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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
perf(gi): the first build of the field is sliced over frames, and a camera move sends only the rebuilt range - the cards keep their light instead of starting the bounces again every step
yhhe94aca2573dd
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.mdindex 36ff4050b..b74de72f2 100644--- a/docs/GI_LUMEN_DESIGN.md+++ b/docs/GI_LUMEN_DESIGN.md@@ -175,6 +175,12 @@- 安卓上探针行数取 45(1200 高时间距 28)而不是 90,探针数为桌面的 1/4;`u_probeSpacing` 可手动指定。手机上 GI 从 20.5 ms 降到 **约 6.4 ms**(帧 14.1,关 GI 为 7.7)。- 间距变大后画面出现 28 像素的方块:原因不是噪点而是权重在探针集合切换处不连续(最近四个探针之外的、权重还有 0.375 的探针,在跨过 tile 边界时被突然丢掉)。改为最近四个用双线性权重(在 tile 远端恰为 0),只有这四个都不合用时(两面墙的夹角)才用 16 个探针的宽帐篷。方块消失,桌面对 Cycles 的占比不变。+### 5.5.1 首次建场分帧与按范围交接(2026-11-11)++- **首次建场分帧**:新场景(以及任何盒子变化)现在造一个新的 `GlobalSdf`,盒子只放置(`update(instance, true)`),整个窗口排队(`queueAll`),每帧做 3 ms,做完才打包交出。两种模式(单窗口、跟随相机)走同一条路。手机上之前首次建场约 1 s 的停顿(JS 合成三级场)按这个办法拆进帧里。+- **按范围交接**:新绑定 `postprocess_updateGIField(header, sdfOffset, count)`,相机移动后只送重建过的级别(通常只有最细一级,10 MB,不是 30 MB),引擎只上传那一段显存。**更重要的是**:整场交接会把所有卡面的光清零并从第一次反弹重新开始,相机每走一步卡面光照就“回弹”一次;按范围交接不碰卡面,不再回弹。光变化而场没变时只送头部。+- 电脑:相机来回走 12 秒,最坏帧 17.0 ms,无超过 50 ms 的帧;交接 3.4 ms 中位(复制本身便宜,收益主要是不再重置卡面)。**手机上这一版还没测**(手机锁屏进入休眠,按设计不去绕过)。+## 5.4 成本断言(2026-11-11)`node tools/gi/check-gi-cost.mjs`(门禁 `gi-cost`,本地范围)。一帧的成本是“工作量 × 设备上每份工作的代价”,第二个因子是设备的(同一份工作,RTX 3 ms,手机 20 ms),第一个因子是引擎的,在 `DynamicGI` 派发通道的地方计数(`DynamicGIStats`,经 `postprocess_giStats` 读回,页面里是 `window.__estellaGIStats()`),两边一样,所以在 GPU 快得看不出差别的机器上也能拦住回归。diff --git a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts b/sdk/src/ecs/bridge/nativeEngineApi.generated.tsindex cdec0c797..0c9997cc2 100644--- a/sdk/src/ecs/bridge/nativeEngineApi.generated.ts+++ b/sdk/src/ecs/bridge/nativeEngineApi.generated.ts@@ -141,6 +141,7 @@ export interface NativeEngineApi {postprocess_shutdown?(): void;postprocess_supportsCompute?(): boolean;postprocess_takeSkyCapture?(dst: number, bytes: number): boolean;+ postprocess_updateGIField?(headerPtr: number, headerCount: number, sdfPtr: number, sdfOffset: number, sdfCount: number): boolean;probe_volume_create?(resX: number, resY: number, resZ: number, shPtr: number): number;probe_volume_release?(volumeHandle: number): void;probe_volume_setSkyVisibility?(volumeHandle: number, visibilityPtr: number): void;@@ -497,6 +498,7 @@ export function createNativeEngineApi(bind('postprocess_shutdown', 'es_postprocess_shutdown', false);bind('postprocess_supportsCompute', 'es_postprocess_supportsCompute', false);bind('postprocess_takeSkyCapture', 'es_postprocess_takeSkyCapture', false);+ bind('postprocess_updateGIField', 'es_postprocess_updateGIField', false);bind('probe_volume_create', 'es_probe_volume_create', false);bind('probe_volume_release', 'es_probe_volume_release', false);bind('probe_volume_setSkyVisibility', 'es_probe_volume_setSkyVisibility', false);diff --git a/sdk/src/gi/dynamicGISystem.ts b/sdk/src/gi/dynamicGISystem.tsindex 0e1b2b123..888c0e3ae 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, type GPUScene } from './gpuScene';+import { analyticBox, instanceBounds, packGPUScene, type GIInstance, type GILight, type GPUScene } from './gpuScene';import { GlobalSdf } from './globalSdf';import type { PointLight } from './surfaceCache';import { worldUnitsPerMeter } from '../ecs/worldUnits';@@ -152,18 +152,38 @@ type Loader = {/*** 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.+ *+ * The first time, and after a scene change, the whole of it goes. After a camera move only the levels that were rebuilt do (10 MB a level, and the+ * finest is nearly all there is to send), by the range of the field they fill: the engine leaves the cards and the light on them alone.*/-function handOver(m: NonNullable<ReturnType<typeof marshallingCore>>, scene: GPUScene, [instancesMs, fieldMs, packMs]: [number, number, number]): void {+function sendScene(m: NonNullable<ReturnType<typeof marshallingCore>>, field: { sdf: GlobalSdf; sent: number[] | null }, scene: GPUScene,+ full: boolean, [instancesMs, fieldMs, packMs]: [number, number, number]): void {const t = performance.now();+ const levels = field.sdf.levels.slice(0, 3);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);+ if (full || !field.sent || !m.postprocess_updateGIField) {+ 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);+ return;+ }+ let at = 0, sent = 0;+ const headerPtr = put(scene.header);+ levels.forEach((l, k) => {+ if (field.sent![k] !== l.version) {+ m.postprocess_updateGIField!(headerPtr, scene.header.length, put(scene.sdf.subarray(at, at + l.storage.length)), at, l.storage.length);+ sent++;+ }+ at += l.storage.length;+ });+ // Nothing of the field changed (the light did): the header alone.+ if (sent === 0) m.postprocess_updateGIField!(headerPtr, scene.header.length, headerPtr, 0, 0);});+ field.sent = levels.map((l) => l.version);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();@@ -176,10 +196,10 @@ function handOver(m: NonNullable<ReturnType<typeof marshallingCore>>, scene: GPUexport 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 field: { sdf: GlobalSdf; sceneKey: string; cell: number; sent: number[] | null } | 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;+ let waiting: { instances: GIInstance[]; light: GILight | null; lights: PointLight[]; work: number; full: boolean; build: 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 => {@@ -209,7 +229,7 @@ export function dynamicGISystem(app: App) {});};const effect = dynamicGIEffect(volumes);- if (!effect) { lastKey = ''; follow = null; return; }+ if (!effect) { lastKey = ''; field = null; waiting = null; return; }// The web's module, or a device's host (which answers the same heap from its arena): the arrays cross the boundary through it.const m = marshallingCore(app.wasmModule ?? nativeEngineApi());if (!m?.postprocess_setGIScene) return;@@ -257,16 +277,16 @@ export function dynamicGISystem(app: App) {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) {+ if (field && waiting) {const ts = performance.now();- const finished = follow.sdf.step(3);+ const finished = field.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]);+ const w = waiting;waiting = null;+ const tPack = performance.now();+ const done = packGPUScene(w.instances, w.light, { sdf: field.sdf, lights: w.lights });+ if (done) sendScene(m, field, done, w.full, [w.build, w.work, performance.now() - tPack]);}}if (key === lastKey || sceneKey === '') return;@@ -276,30 +296,28 @@ export function dynamicGISystem(app: App) {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;- if (!follow || follow.cell !== cell || follow.instancesKey !== sceneKey) {- const fresh = new GlobalSdf([{ dim: 128, cell }, { dim: 128, cell: cell * 4 }, { dim: 128, cell: cell * 16 }]);- fresh.setCenter(eye!);- instances.forEach((inst, id) => fresh.update({ id, sdf: inst.sdf, worldFromLocal: inst.worldFromLocal }));- follow = { sdf: fresh, instancesKey: sceneKey, cell };+ const cell = following ? effect.cellSize : 0;+ if (!field || field.sceneKey !== sceneKey || field.cell !== cell) {+ // A scene the field has not seen: a new field, over the frames that follow, and the whole of it sent when it is done.+ let sdf: GlobalSdf;+ if (following) {+ sdf = new GlobalSdf([{ dim: 128, cell }, { dim: 128, cell: cell * 4 }, { dim: 128, cell: cell * 16 }]);+ sdf.setCenter(eye!);} else {- // 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;+ const { min, max } = instanceBounds(instances);+ const extent = Math.max(max[0]! - min[0]!, max[1]! - min[1]!, max[2]! - min[2]!);+ sdf = new GlobalSdf([{ dim: 128, cell: (extent * 1.15) / 124 }]);+ sdf.setCenter([(min[0]! + max[0]!) / 2, (min[1]! + max[1]!) / 2, (min[2]! + max[2]!) / 2]);}- sdf = follow.sdf;- } else {- follow = null;+ instances.forEach((inst, id) => sdf.update({ id, sdf: inst.sdf, worldFromLocal: inst.worldFromLocal }, true));+ sdf.queueAll();+ field = { sdf, sceneKey, cell, sent: null };+ waiting = { instances, light, lights: point.slice(0, 8), work: 0, full: true, build: performance.now() - t0 };+ return;}- const t2 = performance.now();- const scene = packGPUScene(instances, light, { sdf, lights: point.slice(0, 8) });- if (!scene) return;- const t3 = performance.now();- handOver(m, scene, [t1 - t0, t2 - t1, t3 - t2]);+ // The same scene: the eye moved (queue the slabs that came into view), or only the light did (nothing to queue). Either way it is sent when whole.+ if (following) field.sdf.setCenter(eye!, true);+ waiting = { instances, light, lights: point.slice(0, 8), work: waiting?.work ?? 0, full: waiting?.full ?? false, build: 0 };},{ name: 'DynamicGISystem', runWhenPaused: true },);diff --git a/sdk/src/gi/globalSdf.ts b/sdk/src/gi/globalSdf.tsindex 714721fea..db8a1c489 100644--- a/sdk/src/gi/globalSdf.ts+++ b/sdk/src/gi/globalSdf.ts@@ -121,11 +121,19 @@ export class GlobalSdf {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 {+ /** Queues the whole of every window to be rebuilt (see `step`): after instances were placed with `update(instance, true)`. */+ queueAll(): void {+ for (const level of this.levels) {+ this.schedule_(level, [level.origin[0]!, level.origin[1]!, level.origin[2]!], [level.origin[0]! + level.dim, level.origin[1]! + level.dim, level.origin[2]! + level.dim], true);+ }+ }++ /** Adds an instance, or moves/replaces the one with its id. With `lazy` it is only placed: the cells round it are for `queueAll` and `step` to do. */+ update(instance: SdfInstance, lazy = false): void {const previous = this.placed_.get(instance.id);const placed = this.place_(instance);this.placed_.set(instance.id, placed);+ if (lazy) return;for (const level of this.levels) {if (previous) this.rebuildBox_(level, previous.min, previous.max);this.rebuildBox_(level, placed.min, placed.max);diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.tsindex 31e51f202..3dd3ccaba 100644--- a/sdk/src/wasm.ts+++ b/sdk/src/wasm.ts@@ -556,6 +556,7 @@ export interface ESEngineModule {postprocess_addComputePass?(name: string, wgsl: string, params: string, workgroupX: number, workgroupY: number): number;postprocess_supportsCompute?(): boolean;postprocess_addNativePass?(name: string, kind: string): number;+ postprocess_updateGIField?(headerPtr: number, headerCount: number, sdfPtr: number, sdfOffset: number, sdfCount: number): boolean;postprocess_setGIScene?(headerPtr: number, headerCount: number, sdfPtr: number, sdfCount: number, instancesPtr: number, instanceCount: number, pixelsPtr: number, pixelCount: number): boolean;postprocess_setPassScale(name: string, scale: number): void;postprocess_setPassContinuesEffect(name: string): void;diff --git a/src/esengine/bindings/PostProcessBindings.cpp b/src/esengine/bindings/PostProcessBindings.cppindex 1502dd8f6..ffd427977 100644--- a/src/esengine/bindings/PostProcessBindings.cpp+++ b/src/esengine/bindings/PostProcessBindings.cpp@@ -100,6 +100,23 @@ bool postprocess_setGIScene(uintptr_t headerPtr, u32 headerCount, uintptr_t sdfPscene.sdf.assign(sdf, sdf + sdfCount);scene.instances.assign(instances, instances + instanceCount);scene.pixels.assign(pixels, pixels + pixelCount);+ scene.full = true;+ ++scene.version;+ return true;+}++bool postprocess_updateGIField(uintptr_t headerPtr, u32 headerCount, uintptr_t sdfPtr, u32 sdfOffset, u32 sdfCount) {+ DynamicGIScene& scene = dynamicGIScene();+ if (scene.sdf.empty() || scene.header.size() < 22 || headerCount != scene.header.size() || static_cast<u64>(sdfOffset) + sdfCount > scene.sdf.size()) return false;+ const f32* header = boundarySpan<f32>(headerPtr, headerCount, "postprocess_updateGIField.header");+ const f32* sdf = boundarySpan<f32>(sdfPtr, sdfCount, "postprocess_updateGIField.sdf");+ if (!header || !sdf) return false;+ std::copy(header, header + headerCount, scene.header.begin());+ std::copy(sdf, sdf + sdfCount, scene.sdf.begin() + sdfOffset);+ if (!scene.full) {+ scene.dirtyBegin = scene.dirtyEnd == scene.dirtyBegin ? sdfOffset : std::min(scene.dirtyBegin, sdfOffset);+ scene.dirtyEnd = std::max(scene.dirtyEnd, sdfOffset + sdfCount);+ }++scene.version;return true;}diff --git a/src/esengine/bindings/PostProcessBindings.hpp b/src/esengine/bindings/PostProcessBindings.hppindex df3778c22..5323cf683 100644--- a/src/esengine/bindings/PostProcessBindings.hpp+++ b/src/esengine/bindings/PostProcessBindings.hpp@@ -33,6 +33,12 @@ u32 postprocess_addNativePass(const std::string& name, const std::string& kind);*/bool postprocess_setGIScene(uintptr_t headerPtr, u32 headerCount, uintptr_t sdfPtr, u32 sdfCount, uintptr_t instancesPtr, u32 instanceCount,uintptr_t pixelsPtr, u32 pixelCount);+/**+ * @brief Updates the scene the dynamic GI traces after the camera moved: the header, and @p sdfCount floats of the field from float @p sdfOffset on.+ * @details Nothing else of the scene changes, and the GPU is sent only that range: the cards keep the light they have. Needs a scene set whole first.+ * @return false when there is no scene yet, or the range falls outside it.+ */+bool postprocess_updateGIField(uintptr_t headerPtr, u32 headerCount, uintptr_t sdfPtr, u32 sdfOffset, u32 sdfCount);/** The project's multisampling request for the scene target; 1 = off. Clamped* by what the device supports — the device answers capability, not policy. */void postprocess_setMsaaSamples(u32 samples);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex 01f5a4bb4..b1113a94d 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -608,6 +608,7 @@ EMSCRIPTEN_BINDINGS(esengine_renderer) {emscripten::function("postprocess_supportsCompute", &esengine::postprocess_supportsCompute);emscripten::function("postprocess_addNativePass", &esengine::postprocess_addNativePass);emscripten::function("postprocess_setGIScene", &esengine::postprocess_setGIScene);+ emscripten::function("postprocess_updateGIField", &esengine::postprocess_updateGIField);emscripten::function("postprocess_setPassScale", &esengine::postprocess_setPassScale);emscripten::function("postprocess_setPassContinuesEffect", &esengine::postprocess_setPassContinuesEffect);emscripten::function("postprocess_requestSkyCapture", &esengine::postprocess_requestSkyCapture);diff --git a/src/esengine/renderer/frame/DynamicGI.cpp b/src/esengine/renderer/frame/DynamicGI.cppindex 08d96ab7e..cf9581cb6 100644--- a/src/esengine/renderer/frame/DynamicGI.cpp+++ b/src/esengine/renderer/frame/DynamicGI.cpp@@ -616,9 +616,17 @@ bool DynamicGI::ensure() {}bool DynamicGI::upload() {- const DynamicGIScene& s = dynamicGIScene();+ DynamicGIScene& s = dynamicGIScene();if (s.header.size() < kHeaderSize || s.sdf.empty() || s.instances.empty() || s.pixels.empty()) return false;if (s.version == uploadedVersion_) return true;+ // A camera moved: only the range of the field that was rewritten goes over. The cards, the instances and the light the cards hold stay as they+ // are (a whole upload zeroes the light and starts the bounces again from the first, which a moving camera would see as a pop every step).+ if (!s.full && sdf_ != BufferHandle::Invalid && sdfBytes_ == std::max(static_cast<u32>(s.sdf.size() * 4), 16u) && s.dirtyEnd <= s.sdf.size()) {+ if (s.dirtyEnd > s.dirtyBegin) device_.updateBuffer(sdf_, s.dirtyBegin * 4u, s.sdf.data() + s.dirtyBegin, (s.dirtyEnd - s.dirtyBegin) * 4u);+ s.dirtyBegin = s.dirtyEnd = 0;+ uploadedVersion_ = s.version;+ return true;+ }const auto put = [&](BufferHandle& buffer, u32& have, const void* data, u32 bytes) {bytes = std::max(bytes, 16u);if (buffer == BufferHandle::Invalid || have != bytes) {@@ -650,6 +658,8 @@ bool DynamicGI::upload() {device_.updateBuffer(radiance_[0], 0, zero.data(), radianceBytes);frame_ = 0;uploadedVersion_ = s.version;+ s.full = false;+ s.dirtyBegin = s.dirtyEnd = 0;return true;}diff --git a/src/esengine/renderer/frame/DynamicGI.hpp b/src/esengine/renderer/frame/DynamicGI.hppindex 30ddafff0..52e2ad78b 100644--- a/src/esengine/renderer/frame/DynamicGI.hpp+++ b/src/esengine/renderer/frame/DynamicGI.hpp@@ -60,6 +60,10 @@ struct DynamicGIScene {/// 4 words a card pixel.std::vector<u32> pixels;u32 version = 0;+ /// What changed since the GPU copy was made: everything (a whole scene was set), or only the floats [dirtyBegin, dirtyEnd) of the field and the header+ /// (a camera moved; the cards and their light are the same, and are not touched).+ bool full = true;+ u32 dirtyBegin = 0, dirtyEnd = 0;};/**