Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

perf(gi): a camera that moves rebuilds the following field a few milliseconds a frame - boxes built only when the scene changes, levels repacked only when they changed, slabs queued; measured with a walking camera

yhhb5b12443a2b7
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.md
index 42b93263c..36ff4050b 100644
--- a/docs/GI_LUMEN_DESIGN.md
+++ b/docs/GI_LUMEN_DESIGN.md
@@ -189,6 +189,22 @@
它不能说明的:绝对毫秒。手机上约 15 ms 与光线数无关,那一块是带宽和附件,这里只能管住“被迫多写多少字节”和“每像素读几次”,不能说多少毫秒;每个通道的时间仍要在手机上量。
+## 5.5 相机移动的成本(2026-11-11)
+
+`node tools/gi/measure-camera-move.mjs`:导出带相机来回走动脚本的实验室(`CAM_MOVE=1`),三级场(`u_cellSize` 2.5),无头跑在本机 GPU 上,读页面的帧间隔与系统自己记的每次重建的耗时。相机每走 8 个细格(20 单位)重建一次。
+
+| | 重建一次(桌面,中位 / 最坏) | 12 秒内帧 |
+|---|---|---|
+| 起点 | 49 / 70 ms(盒子 6 + 场 15 + 打包 23 + 交接 4) | 5 帧超过 50 ms,最坏 67 ms |
+| 盒子只在场景变化时建 | | |
+| 只重打包变了的级别、属主字直接在场里维护 | 20 / 38 ms | 0 帧超过 50 ms,最坏 33 ms |
+| 按实例遍历周围的格子(而不是逐格问所有实例)| 17 / 33 ms | |
+| 新进入的薄片排队,每帧做 3 ms,做完再一次打包交出 | 一次性部分约 6 ms(打包 2 + 交接 4)| **最坏帧 16.9 ms,无卡顿** |
+
+- 排队期间引擎追踪的是上一次交出的场(窗口落后相机一点,别无坏处);`GlobalSdf.setCenter(p, true)` 排队,`step(ms)` 做,`pending` 为假时才打包,所以不会读到环形寻址里远端旧内容。
+- 手机(同一台,移动相机的实验室):帧 p50 15.1、p90 17.6 ms;系统的重建工作每次 47–73 ms,分摊在帧里;**第一次建场约 1 s**(JS 在手机上合成三级场),是加载时的一次停顿。
+- 还要做:交接的 30 MB 复制与上传(桌面 4–8 ms,手机上更多)可以只送变了的级别;第一次建场可以分帧。
+
## 6. 分期
每期独立可验收、可回退,期间旧 `voxelGI` 一直可用。
diff --git a/sdk/src/gi/dynamicGISystem.ts b/sdk/src/gi/dynamicGISystem.ts
index 5e6119498..0e1b2b123 100644
--- a/sdk/src/gi/dynamicGISystem.ts
+++ b/sdk/src/gi/dynamicGISystem.ts
@@ -23,7 +23,7 @@ import { withScratch } from '../wasm/wasmScratch';
import { marshallingCore } from '../asset/loaders/engineCore';
import { nativeEngineApi } from '../ecs/bridge/engineApi';
import { Material } from '../render/material';
-import { analyticBox, packGPUScene, type GIInstance, type GILight } from './gpuScene';
+import { analyticBox, packGPUScene, type GIInstance, type GILight, type GPUScene } from './gpuScene';
import { GlobalSdf } from './globalSdf';
import type { PointLight } from './surfaceCache';
import { worldUnitsPerMeter } from '../ecs/worldUnits';
@@ -149,10 +149,37 @@ type Loader = {
catalog?: { addressOf?(path: string): string | null };
};
+/**
+ * Gives the engine a packed scene, and records what the rebuild behind it cost (for tools/gi/measure-camera-move.mjs): the milliseconds of the
+ * boxes, of the field and of the pack, then the hand-over's own. Said to the device log every 8 rebuilds, where that is the only place to read it.
+ */
+function handOver(m: NonNullable<ReturnType<typeof marshallingCore>>, scene: GPUScene, [instancesMs, fieldMs, packMs]: [number, number, number]): void {
+ const t = performance.now();
+ withScratch(m, (alloc) => {
+ const put = (data: ArrayBufferView): number => {
+ const ptr = alloc(data.byteLength);
+ m.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength), ptr);
+ return ptr;
+ };
+ m.postprocess_setGIScene!(put(scene.header), scene.header.length, put(scene.sdf), scene.sdf.length,
+ put(scene.instances), scene.instances.length, put(scene.pixels), scene.pixels.length);
+ });
+ const record = ((globalThis as { __estellaGIBuild?: { ms: number[][] } }).__estellaGIBuild ??= { ms: [] });
+ record.ms.push([instancesMs, fieldMs, packMs, performance.now() - t, scene.sdf.byteLength / 1048576]);
+ if (record.ms.length > 256) record.ms.shift();
+ if (record.ms.length % 8 === 0) {
+ const totals = record.ms.slice(-8).map((r) => r[0]! + r[1]! + r[2]! + r[3]!).sort((x, y) => x - y);
+ console.log(`[gi] last 8 rebuilds: median ${totals[4]!.toFixed(1)} ms, worst ${totals[7]!.toFixed(1)} ms (${scene.sdf.byteLength >> 20} MB of field)`);
+ }
+}
+
export function dynamicGISystem(app: App) {
let cube = 0, loading = false, lastKey = '';
// The field that follows the camera, kept between frames so that a camera that moves rebuilds only the slabs that came into view.
let follow: { sdf: GlobalSdf; instancesKey: string; cell: number } | null = null;
+ let built: { sceneKey: string; instances: GIInstance[] } | null = null;
+ // A camera that moved while the field is still being rebuilt for the last move: what is waiting to be packed and sent when it is done.
+ let waiting: { instances: GIInstance[]; light: GILight | null; lights: PointLight[]; work: number } | null = null;
// The baked files beside a mesh, by its path: null while loading and for a mesh that has none.
const sidecars = new Map<string, GISidecars | null>();
const request = (path: string): void => {
@@ -228,10 +255,28 @@ export function dynamicGISystem(app: App) {
const snap = following ? effect.cellSize * 8 : 1;
const eyeKey = following ? eye!.map((v) => Math.floor(v / snap)).join(',') : '';
const key = (light ? `${light.toLight.join(',')}|${light.radiance.join(',')}` : 'dark') + sceneKey + '#' + lightKey + '#' + effect.cellSize + eyeKey;
+ // The rebuild a camera move asked for goes on a few milliseconds a frame, and is handed to the engine when it is whole: until then
+ // the engine traces the field as it was, which is a window a little behind the eye and nothing worse.
+ if (follow && waiting) {
+ const ts = performance.now();
+ const finished = follow.sdf.step(3);
+ waiting.work += performance.now() - ts;
+ if (finished) {
+ const { instances: held, light: heldLight, lights: heldLights, work } = waiting;
+ const tPack = performance.now();
+ const done = packGPUScene(held, heldLight, { sdf: follow.sdf, lights: heldLights });
+ if (done) handOver(m, done, [0, work, performance.now() - tPack]);
+ waiting = null;
+ }
+ }
if (key === lastKey || sceneKey === '') return;
lastKey = key;
- const { instances } = buildInstances(entries, cube, (p) => sidecars.get(p) ?? null);
+ const t0 = performance.now();
+ // The boxes are built when the scene changes, not when only the eye did: a camera that walks changes the key every few steps.
+ if (!built || built.sceneKey !== sceneKey) built = { sceneKey, instances: buildInstances(entries, cube, (p) => sidecars.get(p) ?? null).instances };
+ const instances = built.instances;
if (instances.length === 0) return;
+ const t1 = performance.now();
let sdf: GlobalSdf | undefined;
if (following) {
const cell = effect.cellSize;
@@ -241,23 +286,20 @@ export function dynamicGISystem(app: App) {
instances.forEach((inst, id) => fresh.update({ id, sdf: inst.sdf, worldFromLocal: inst.worldFromLocal }));
follow = { sdf: fresh, instancesKey: sceneKey, cell };
} else {
- follow.sdf.setCenter(eye!);
+ // Only the eye moved: queue the slabs and let the frames do them (see above); the scene is sent when they are done.
+ follow.sdf.setCenter(eye!, true);
+ waiting = { instances, light, lights: point.slice(0, 8), work: 0 };
+ return;
}
sdf = follow.sdf;
} else {
follow = null;
}
+ const t2 = performance.now();
const scene = packGPUScene(instances, light, { sdf, lights: point.slice(0, 8) });
if (!scene) return;
- withScratch(m, (alloc) => {
- const put = (data: ArrayBufferView): number => {
- const ptr = alloc(data.byteLength);
- m.HEAPU8.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength), ptr);
- return ptr;
- };
- m.postprocess_setGIScene!(put(scene.header), scene.header.length, put(scene.sdf), scene.sdf.length,
- put(scene.instances), scene.instances.length, put(scene.pixels), scene.pixels.length);
- });
+ const t3 = performance.now();
+ handOver(m, scene, [t1 - t0, t2 - t1, t3 - t2]);
},
{ name: 'DynamicGISystem', runWhenPaused: true },
);
diff --git a/sdk/src/gi/globalSdf.ts b/sdk/src/gi/globalSdf.ts
index 5aa98b32e..714721fea 100644
--- a/sdk/src/gi/globalSdf.ts
+++ b/sdk/src/gi/globalSdf.ts
@@ -46,8 +46,15 @@ interface Level {
/** The window's first cell, in whole cells of the level. */
origin: [number, number, number];
data: Float32Array;
- /** Per cell, 1 + the id of the instance nearest to it (127 for an id past 125), 0 where nothing is within reach. */
- owner: Uint8Array;
+ /**
+ * One array holding the field and then, in the same memory, the instance nearest each cell (1 + its id, 127 for an id past 125, 0 where
+ * nothing is within reach; four cells to a word of seven-bit ids, since a word with a top bit set could read as a NaN and a device is free
+ * to change those). `data` and `ownerWords` are views of it: what the engine reads is this array, as it is.
+ */
+ storage: Float32Array;
+ ownerWords: Uint32Array;
+ /** Counts the rebuilds that touched the level, so a packer can leave a level that did not change where it is. */
+ version: number;
}
export class GlobalSdf {
@@ -59,7 +66,8 @@ export class GlobalSdf {
constructor(levels: readonly GlobalSdfLevel[]) {
this.levels = levels.map((l) => {
if ((l.dim & (l.dim - 1)) !== 0 || l.dim < 2) throw new Error(`a clipmap level is a power of two cells across, got ${l.dim}`);
- const level: Level = { dim: l.dim, cell: l.cell, origin: [0, 0, 0], data: new Float32Array(l.dim ** 3), owner: new Uint8Array(l.dim ** 3) };
+ const cells = l.dim ** 3, storage = new Float32Array(cells + cells / 4);
+ const level: Level = { dim: l.dim, cell: l.cell, origin: [0, 0, 0], data: storage.subarray(0, cells), storage, ownerWords: new Uint32Array(storage.buffer, cells * 4, cells / 4), version: 0 };
level.data.fill(l.cell * GlobalSdf.REACH_CELLS);
return level;
});
@@ -68,14 +76,19 @@ export class GlobalSdf {
reach(level: Level): number { return level.cell * GlobalSdf.REACH_CELLS; }
/** Moves every window so it is centred on `p`, to whole cells: only the slabs that came into view are rebuilt. */
- setCenter(p: readonly [number, number, number]): void {
+ /**
+ * With `lazy`, the slabs that came into view are queued, not rebuilt: `step` does them a few milliseconds a frame. The windows move at once
+ * (what a trace reads is whatever the caller last packed, and it should not pack until `pending` is false: the cells of the new edge hold
+ * what the far side of the torus held).
+ */
+ setCenter(p: readonly [number, number, number], lazy = false): void {
for (const level of this.levels) {
const target = [0, 1, 2].map((k) => Math.floor(p[k]! / level.cell) - level.dim / 2) as [number, number, number];
const move = [0, 1, 2].map((k) => target[k]! - level.origin[k]!);
if (move.every((m) => m === 0)) continue;
const old = level.origin;
level.origin = target;
- if (move.some((m) => Math.abs(m) >= level.dim)) { this.rebuild_(level, [target[0]!, target[1]!, target[2]!], [target[0]! + level.dim, target[1]! + level.dim, target[2]! + level.dim]); continue; }
+ if (move.some((m) => Math.abs(m) >= level.dim)) { this.schedule_(level, [target[0]!, target[1]!, target[2]!], [target[0]! + level.dim, target[1]! + level.dim, target[2]! + level.dim], lazy); continue; }
// One slab per axis that moved: [new edge].
for (let k = 0; k < 3; k++) {
const m = move[k]!;
@@ -83,11 +96,31 @@ export class GlobalSdf {
const lo = [...target] as [number, number, number], hi = [target[0]! + level.dim, target[1]! + level.dim, target[2]! + level.dim] as [number, number, number];
if (m > 0) lo[k] = old[k]! + level.dim; else hi[k] = old[k]!;
lo[k] = Math.max(lo[k]!, target[k]!); hi[k] = Math.min(hi[k]!, target[k]! + level.dim);
- this.rebuild_(level, lo, hi);
+ this.schedule_(level, lo, hi, lazy);
}
}
}
+ private jobs_: Array<{ level: Level; lo: [number, number, number]; hi: [number, number, number] }> = [];
+
+ /** Whether slabs are still waiting to be rebuilt (see `setCenter`). */
+ get pending(): boolean { return this.jobs_.length > 0; }
+
+ /** Rebuilds queued slabs until `budgetMs` has gone; true when none is left. A slab is cut into pieces of 16 layers so a budget can stop between them. */
+ step(budgetMs: number): boolean {
+ const start = performance.now();
+ while (this.jobs_.length > 0 && performance.now() - start < budgetMs) {
+ const job = this.jobs_.shift()!;
+ this.rebuild_(job.level, job.lo, job.hi);
+ }
+ return this.jobs_.length === 0;
+ }
+
+ private schedule_(level: Level, lo: [number, number, number], hi: [number, number, number], lazy: boolean): void {
+ if (!lazy) { this.rebuild_(level, lo, hi); return; }
+ for (let z = lo[2]!; z < hi[2]!; z += 16) this.jobs_.push({ level, lo: [lo[0]!, lo[1]!, z], hi: [hi[0]!, hi[1]!, Math.min(z + 16, hi[2]!)] });
+ }
+
/** Adds an instance, or moves/replaces the one with its id. */
update(instance: SdfInstance): void {
const previous = this.placed_.get(instance.id);
@@ -197,6 +230,7 @@ export class GlobalSdf {
private rebuild_(level: Level, lo: [number, number, number], hi: [number, number, number]): void {
const a = [0, 1, 2].map((k) => Math.max(lo[k]!, level.origin[k]!)), b = [0, 1, 2].map((k) => Math.min(hi[k]!, level.origin[k]! + level.dim));
if (a.some((v, k) => v >= b[k]!)) return;
+ level.version++;
const reach = this.reach(level);
const near: Placed[] = [];
for (const placed of this.placed_.values()) {
@@ -206,20 +240,28 @@ export class GlobalSdf {
}
if (overlaps) near.push(placed);
}
- const mask = level.dim - 1;
+ const mask = level.dim - 1, dim = level.dim, cell = level.cell;
+ // Every cell of the region starts as "nothing within reach", then each instance writes the cells round it: the work follows the surfaces, not the
+ // volume, so a room of a few boxes costs its walls and not its air.
for (let z = a[2]!; z < b[2]!; z++) for (let y = a[1]!; y < b[1]!; y++) for (let x = a[0]!; x < b[0]!; x++) {
- const p: [number, number, number] = [(x + 0.5) * level.cell, (y + 0.5) * level.cell, (z + 0.5) * level.cell];
- let d = reach, owner = 0;
- for (const placed of near) {
- // An instance further from the cell than the reach (outside its own box grown by it) cannot be what the cell remembers.
+ const at = (x & mask) + (y & mask) * dim + (z & mask) * dim * dim;
+ level.data[at] = reach;
+ level.ownerWords[at >> 2] = (level.ownerWords[at >> 2]! & ~(255 << ((at & 3) * 8))) >>> 0;
+ }
+ const p: [number, number, number] = [0, 0, 0];
+ for (const placed of near) {
+ const owner = placed.instance.id < 126 ? placed.instance.id + 1 : 127;
+ // The cells within the reach of this instance box, inside the region.
+ const lo2 = [0, 1, 2].map((k) => Math.max(a[k]!, Math.floor((placed.min[k]! - reach) / cell))), hi2 = [0, 1, 2].map((k) => Math.min(b[k]!, Math.ceil((placed.max[k]! + reach) / cell)));
+ for (let z = lo2[2]!; z < hi2[2]!; z++) for (let y = lo2[1]!; y < hi2[1]!; y++) for (let x = lo2[0]!; x < hi2[0]!; x++) {
+ p[0] = (x + 0.5) * cell; p[1] = (y + 0.5) * cell; p[2] = (z + 0.5) * cell;
if (p[0] < placed.min[0]! - reach || p[0] > placed.max[0]! + reach || p[1] < placed.min[1]! - reach || p[1] > placed.max[1]! + reach
|| p[2] < placed.min[2]! - reach || p[2] > placed.max[2]! + reach) continue;
- const v = this.distanceTo_(placed, p);
- if (v < d) { d = v; owner = placed.instance.id < 126 ? placed.instance.id + 1 : 127; }
+ const v = this.distanceTo_(placed, p), at = (x & mask) + (y & mask) * dim + (z & mask) * dim * dim;
+ if (v >= level.data[at]!) continue;
+ level.data[at] = Math.max(v, -reach);
+ level.ownerWords[at >> 2] = ((level.ownerWords[at >> 2]! & ~(255 << ((at & 3) * 8))) | (owner << ((at & 3) * 8))) >>> 0;
}
- const at = (x & mask) + (y & mask) * level.dim + (z & mask) * level.dim * level.dim;
- level.data[at] = Math.max(d, -reach);
- level.owner[at] = owner;
}
}
diff --git a/sdk/src/gi/gpuScene.ts b/sdk/src/gi/gpuScene.ts
index 908e43777..c55cf368e 100644
--- a/sdk/src/gi/gpuScene.ts
+++ b/sdk/src/gi/gpuScene.ts
@@ -79,6 +79,9 @@ export function analyticBox(size: readonly [number, number, number], colour: rea
const scaleOf = (m: ArrayLike<number>): number => Math.hypot(m[0]!, m[1]!, m[2]!);
+/** What a pack of a field left behind: the packed array and the version of each level it holds (see `Level.version`). */
+const packCache = new WeakMap<GlobalSdf, { packed: Float32Array; versions: number[] }>();
+
export interface PackOptions {
dim?: number;
sky?: readonly [number, number, number];
@@ -176,19 +179,20 @@ export function packGPUScene(instances: readonly GIInstance[], light: GILight |
set(8, ...(light?.toLight ?? [0, 1, 0]), light ? 1 : 0, ...(light?.radiance ?? [0, 0, 0]), bias, extent * 2.5, tolerance);
set(18, ...(options.sky ?? [0, 0, 0]), 0.25);
set(22, levels.length);
- // The field of every level, each followed by its owner words (four cells to a word of seven-bit ids; a word with a top bit set could
- // read as a NaN, and a device is free to change those). Level 0 sits first, so the header's offsets for it are 0 and dim^3.
+ // The field of every level, each followed by its owner words, level 0 first (so the header's offsets for it are 0 and dim^3). A level is
+ // copied into the packed array only if it changed since the last pack of this field: a camera that moves rebuilds the finest level
+ // nearly every step and the others once in a long while, and the copy is 10 MB a level.
let floats = 0;
- for (const l of levels) floats += l.data.length + l.data.length / 4;
- const packed = new Float32Array(floats);
+ for (const l of levels) floats += l.storage.length;
+ let cache = packCache.get(sdf);
+ if (!cache || cache.packed.length !== floats) { cache = { packed: new Float32Array(floats), versions: levels.map(() => -1) }; packCache.set(sdf, cache); }
+ const packed = cache.packed;
let at = 0;
levels.forEach((l, k) => {
const cells = l.data.length;
- packed.set(l.data, at);
- const words = new Uint32Array(packed.buffer, (at + cells) * 4, cells / 4);
- for (let i = 0; i < cells; i++) words[i >> 2]! |= l.owner[i]! << ((i & 3) * 8);
+ if (cache!.versions[k] !== l.version) { packed.set(l.storage, at); cache!.versions[k] = l.version; }
if (k > 0) set(24 + (k - 1) * 8, l.dim, l.cell, l.origin[0]!, l.origin[1]!, l.origin[2]!, l.cell * GlobalSdf.REACH_CELLS, at, at + cells);
- at += cells + cells / 4;
+ at += l.storage.length;
});
const lights = (options.lights ?? []).slice(0, GI_MAX_LIGHTS);
set(23, lights.length);
diff --git a/sdk/tests/global-sdf.test.ts b/sdk/tests/global-sdf.test.ts
index 3a5dc41a1..be3e61248 100644
--- a/sdk/tests/global-sdf.test.ts
+++ b/sdk/tests/global-sdf.test.ts
@@ -89,6 +89,28 @@ describe('the scene distance field', () => {
}
});
+ it('queues the slabs of a lazy move and, stepped to the end, leaves the same field as an eager one', () => {
+ const build = (lazy: boolean) => {
+ const g = field();
+ g.setCenter([0, 0, 0]);
+ g.update(instance(1, sphereSdf(1, 0.1), [3, 0, 0]));
+ g.update(instance(2, sphereSdf(1, 0.1), [12, 1, 0]));
+ g.setCenter([5, 1, 2], lazy);
+ return g;
+ };
+ const eager = build(false), lazy = build(true);
+ expect(lazy.pending).toBe(true);
+ expect(eager.pending).toBe(false);
+ let guard = 0;
+ while (!lazy.step(2)) expect(++guard).toBeLessThan(10000);
+ expect(lazy.pending).toBe(false);
+ for (let l = 0; l < eager.levels.length; l++) {
+ expect(Array.from(lazy.levels[l]!.data.subarray(0, 4096))).toEqual(Array.from(eager.levels[l]!.data.subarray(0, 4096)));
+ expect(lazy.levels[l]!.version).toBeGreaterThan(0);
+ }
+ for (const p of [[3, 0.5, 0], [11, 1, 0.5], [5, 5, 5]] as const) expect(lazy.sample(p)).toBe(eager.sample(p));
+ });
+
it('falls back to a coarser level where the finer window ends', () => {
const g = field(); // fine window is 16 across, coarse 64
g.setCenter([0, 0, 0]);
diff --git a/tools/gi/measure-camera-move.mjs b/tools/gi/measure-camera-move.mjs
new file mode 100644
index 000000000..86b598412
--- /dev/null
+++ b/tools/gi/measure-camera-move.mjs
@@ -0,0 +1,58 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * What a camera moving through the dynamic GI scene costs: the frames it hitches and what each rebuild of the following distance field spends.
+ *
+ * node tools/gi/measure-camera-move.mjs [seconds=12] env CELL (default 2.5): the finest cell of the three levels
+ *
+ * Exports the GI lab with a script that walks the camera back and forth (CAM_MOVE), runs it headless on the machine GPU, and reads the frame
+ * intervals the page saw and the system's own record of each rebuild (instances, field, pack, hand-over to the engine, megabytes of field).
+ */
+import { spawnSync } from 'node:child_process';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const root = path.resolve(import.meta.dirname, '../..');
+const seconds = Number(process.argv[2] ?? 12), cell = Number(process.env.CELL ?? 2.5);
+const work = mkdtempSync(path.join(tmpdir(), 'gi-move-'));
+const project = path.join(work, 'project'), web = path.join(work, 'web');
+const env = { ...process.env, BACKEND: 'webgpu', CAM_MOVE: '1', EFFECTS: JSON.stringify([{ type: 'dynamicGI', enabled: true, uniforms: { u_cellSize: cell } }]) };
+let r = spawnSync('python', [path.join(root, 'tools/render-lab/gi_project.py'), project, 'gi_room'], { env, encoding: 'utf8' });
+if (r.status !== 0) { console.error(r.stderr); process.exit(1); }
+spawnSync('node', [path.join(root, 'tools/asset-meta.js'), path.join(project, 'assets')], { encoding: 'utf8' });
+r = spawnSync('node', [path.join(root, 'pipeline/bin/estella.mjs'), 'export', project, '--out', web], { encoding: 'utf8', cwd: root });
+if (r.status !== 0) { console.error((r.stdout + r.stderr).slice(-600)); process.exit(1); }
+
+const { chromium } = await import(pathToFileURL(path.join(root, 'node_modules/playwright/index.mjs')).href);
+const { serveHost } = await import(pathToFileURL(path.join(root, 'tools/lib/staticServer.mjs')).href);
+const server = await serveHost(web);
+const browser = await chromium.launch({ channel: 'chromium', headless: true, args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--mute-audio'] });
+try {
+ const page = await browser.newPage({ viewport: { width: 1280, height: 720 }, deviceScaleFactor: 1 });
+ await page.addInitScript(() => {
+ window.__frames = [];
+ let last = performance.now();
+ const tick = (now) => { window.__frames.push(now - last); last = now; requestAnimationFrame(tick); };
+ requestAnimationFrame(tick);
+ });
+ await page.goto(`http://127.0.0.1:${server.address().port}/`, { waitUntil: 'load' });
+ await page.waitForTimeout(8000); // load, the first build, settle
+ await page.evaluate(() => { window.__frames.length = 0; if (window.__estellaGIBuild) window.__estellaGIBuild.ms.length = 0; });
+ await page.waitForTimeout(seconds * 1000);
+ const { frames, builds } = await page.evaluate(() => ({ frames: window.__frames.slice(), builds: window.__estellaGIBuild ? window.__estellaGIBuild.ms.slice() : [] }));
+ const pct = (xs, p) => [...xs].sort((a, b) => a - b)[Math.min(xs.length - 1, Math.floor(xs.length * p))];
+ console.log(`frames: ${frames.length} in ${seconds}s, median ${pct(frames, 0.5).toFixed(1)} ms, p99 ${pct(frames, 0.99).toFixed(1)} ms, worst ${Math.max(...frames).toFixed(1)} ms, over 50 ms: ${frames.filter((f) => f > 50).length}`);
+ console.log(`rebuilds: ${builds.length}`);
+ if (builds.length > 0) {
+ const col = (i) => builds.map((b) => b[i]);
+ const sum = builds.map((b) => b[0] + b[1] + b[2] + b[3]);
+ const m = (i) => `${pct(col(i), 0.5).toFixed(1)} / ${Math.max(...col(i)).toFixed(1)}`;
+ console.log(` per rebuild (median / worst ms): instances ${m(0)}, field ${m(1)}, pack ${m(2)}, hand-over ${m(3)}; total ${pct(sum, 0.5).toFixed(1)} / ${Math.max(...sum).toFixed(1)}; ${builds[0][4].toFixed(1)} MB of field`);
+ }
+} finally {
+ await browser.close();
+ server.close();
+ rmSync(work, { recursive: true, force: true, maxRetries: 5 });
+}
diff --git a/tools/render-lab/gi_project.py b/tools/render-lab/gi_project.py
index 5d68dc7b8..a72fac535 100644
--- a/tools/render-lab/gi_project.py
+++ b/tools/render-lab/gi_project.py
@@ -82,6 +82,16 @@ if os.environ.get('BAKE') == '1':
{'type': 'BakedLighting', 'data': {'atlasSize': 1024, 'texelsPerUnit': float(os.environ.get('TPU', '0.2')), 'bounces': int(os.environ.get('BOUNCES', '4')),
'samples': int(os.environ.get('BAKE_SAMPLES', '256')), 'probeSamples': 128}}]})
+if os.environ.get('CAM_MOVE') == '1':
+ # A script that walks the camera back and forth along z, 200 units over a few seconds: a camera moving through the room, for the cost of moving it.
+ os.makedirs(proj + '/src', exist_ok=True)
+ open(proj + '/src/main.ts', 'w').write("""import { addSystemToSchedule, defineSystem, Query, Mut, Res, Time, Transform, Camera, Schedule } from 'esengine';
+let t = 0;
+addSystemToSchedule(Schedule.PostUpdate, defineSystem([Query(Mut(Transform), Camera), Res(Time)], (cameras, time) => {
+ t += time.delta;
+ for (const [, transform] of cameras) transform.position.z = -235 + 100 * (1 - Math.cos(t * 0.6));
+}, { name: 'CameraWalk' }));
+""")
effects = json.loads(os.environ.get('EFFECTS', '[]'))
if effects:
entities[0]['components'].append({'type': 'PostProcessVolume', 'data': {'isGlobal': True, 'weight': 1, 'priority': 0, 'effects': effects}})