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.

feat(gi): the dynamic GI reads material emission and baked meshes - cards carry the emissive colour, a mesh brings its distance field and cards through the cook, checked on the lab rooms as meshes

yhh38c76af58940
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.md
index 47e0712eb..1f08d4616 100644
--- a/docs/GI_LUMEN_DESIGN.md
+++ b/docs/GI_LUMEN_DESIGN.md
@@ -113,7 +113,7 @@
|---|---|---|
| P0 | 网格 SDF 烘焙 + `.esmeshsdf` 资源类型与加载器 + 全局距离场 clipmap + 公共 WGSL 追踪 | 球、盒、薄墙的距离和追踪与闭式解比对;WGSL 追踪由 `tools/gi/check-sdf-wgsl.mjs` 在无头 WebGPU 上校验。**已落地(2026-11-11)**:`pipeline/src/assets/meshSdf.ts`、`MeshSdfAssetLoader`、`sdk/src/gi/globalSdf.ts`;导入设置 `dynamicGI`(默认关)。**未做**:clipmap 接到渲染帧的网格实例、上传 GPU 存储缓冲、编辑器导入开关 |
| P1 | 表面缓存:card 烘焙、直接光 + 自发光、命中点取光 | 卡面亮度与 Lambert 闭式值一致,SDF 遮挡产生阴影,自发光出现在命中点取光里。**CPU 参考已落地(2026-11-11)**:`pipeline/src/assets/meshCards.ts`(`.esmeshcards`,6 个轴向 card)、`MeshCardsAssetLoader`、`sdk/src/gi/surfaceCache.ts`(`light`、`lookup`)、`pipeline/tests/surface-cache.test.ts`。**未做**:基色贴图不读(只用材质基色与顶点色)、图集分配、GPU 刷新通道 |
-| P2 | 屏幕探针 + SDF 追踪 + 时间/空间滤波,单次反弹 | `gi_leak` 为 0;`gi_room` 阴影区 0.6–1.1。**CPU 参考已落地并对 Cycles 验证(2026-11-11)**:`sdk/src/gi/screenProbes.ts`(8×8 八面体探针、半球积分、多次反弹迭代),`pipeline/tests/gi-lab.test.ts`。实测:`gi_leak` 室内最亮 0(体素 GI 为 0.005);`gi_room` 与 `gi_away` 为 Cycles 的 0.46–1.89 倍,屏幕内外一致(体素 GI 是 0.1–1.7 与 0.31–0.52)。**未做**:GPU 通道(探针追踪/插值到像素/时间滤波)、渲染帧实例接入;精度偏差(天花板 1.9、侧墙 0.5)主要来自 25 cm 的 card 和每探针 64 条光线 | **GPU 通道已落地(2026-11-11)**:`DynamicGI.cpp`(卡面光照、8×8 探针、应用三个 compute 通道)、`postprocess_setGIScene` 绑定、`dynamicGISystem.ts`(把 MeshRenderer 的内置立方体喂给 GPU)、后效 `dynamicGI`。无头 WebGPU(swiftshader)上对 Cycles 实测:`gi_leak` 室内 0;`gi_room` 阴影区 0.54–1.08(遮挡面 0.6,体素 GI 为 0.1);`gi_away` 0.54–0.86(体素 GI 为 0.31–0.52)。**未做**:材质自发光进 card(`gi_emissive` 为 0)、带 `.esmeshsdf/.esmeshcards` 的网格接入、多级 clipmap、点光/聚光、时间重投影、手机成本
+| P2 | 屏幕探针 + SDF 追踪 + 时间/空间滤波,单次反弹 | `gi_leak` 为 0;`gi_room` 阴影区 0.6–1.1。**CPU 参考已落地并对 Cycles 验证(2026-11-11)**:`sdk/src/gi/screenProbes.ts`(8×8 八面体探针、半球积分、多次反弹迭代),`pipeline/tests/gi-lab.test.ts`。实测:`gi_leak` 室内最亮 0(体素 GI 为 0.005);`gi_room` 与 `gi_away` 为 Cycles 的 0.46–1.89 倍,屏幕内外一致(体素 GI 是 0.1–1.7 与 0.31–0.52)。**未做**:GPU 通道(探针追踪/插值到像素/时间滤波)、渲染帧实例接入;精度偏差(天花板 1.9、侧墙 0.5)主要来自 25 cm 的 card 和每探针 64 条光线 | **GPU 通道已落地(2026-11-11)**:`DynamicGI.cpp`(卡面光照、8×8 探针、应用三个 compute 通道)、`postprocess_setGIScene` 绑定、`dynamicGISystem.ts`(把 MeshRenderer 的内置立方体喂给 GPU)、后效 `dynamicGI`。无头 WebGPU(swiftshader)上对 Cycles 实测:`gi_leak` 室内 0;`gi_room` 阴影区 0.54–1.08(遮挡面 0.6,体素 GI 为 0.1);`gi_away` 0.54–0.86(体素 GI 为 0.31–0.52)。**随后补上(2026-11-11)**:材质 `u_emissive` 进 card(`gi_emissive` 从 0 到 Cycles 的 0.9–1.14 倍);带 `.esmeshsdf/.esmeshcards` 的网格接入(`buildInstances`,打包时由依赖扫描随网格带上,运行时按创作路径找旁文件;`gi_oracle.py --methods dgim` 用网格版房间验证,0.5–1.4 倍、`gi_leak` 为 0)。**未做**:多级 clipmap、点光/聚光、时间重投影、手机成本
| P3 | 表面缓存吃上一帧间接光(多次反弹)+ 世界辐射缓存 | `gi_room` 0.8–1.1;`gi_away` ≥ 0.8;`gi_emissive` ≥ 0.8 |
| P4 | 成本:自适应探针、光线预算、QualityConfig 档位、手机与桌面实测 | 帧时间达标;gate 内加成本断言(同阴影通道做法) |
| P5 | 编辑器:设置面板、调试视图(SDF、card、探针)、文档;`esengine/fx-gi` 分组与包体 | 编辑器检查;包体断言 |
diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.ts
index 3db81cf41..695579662 100644
--- a/pipeline/src/assets/assetDb.ts
+++ b/pipeline/src/assets/assetDb.ts
@@ -375,7 +375,7 @@ async function computeDeps(
const byPath = new Map(entries.map((e) => [e.path, e]));
const uuids = new Set(entries.map((e) => e.uuid));
const refEntries = (targets ?? entries).filter(
- (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT
+ (e) => JSON_REF_TYPES.has(e.type) || e.type === BITMAP_FONT || e.type === 'mesh'
|| SKELETAL_ATLAS_TYPES.has(getEditorType(e.path)),
);
type DepResult = { uuid: string; refs: string[] } | { warning: string };
@@ -405,7 +405,15 @@ async function computeDeps(
const isBitmapFont = entry.type === BITMAP_FONT;
try {
const refs = new Set<string>();
- if (isBitmapFont) {
+ if (entry.type === 'mesh') {
+ // A mesh is binary and names nothing; the files the dynamic GI reads are its siblings, kept whenever the mesh is (an import with
+ // `dynamicGI` on wrote them, and the runtime asks for them by the mesh's own path).
+ const stem = entry.path.replace(/\.esmesh$/i, '');
+ for (const ext of ['.esmeshsdf', '.esmeshcards']) {
+ const dep = byPath.get(stem + ext);
+ if (dep) refs.add(dep.uuid);
+ }
+ } else if (isBitmapFont) {
const content = await readTextInRoot(path.join(root, entry.path));
for (const m of content.matchAll(FNT_PAGE)) {
const dep = byPath.get(normalizeRefPath(resolveRelativePath(entry.path, m[1])));
diff --git a/pipeline/tests/gpu-scene.test.ts b/pipeline/tests/gpu-scene.test.ts
new file mode 100644
index 000000000..11af959a4
--- /dev/null
+++ b/pipeline/tests/gpu-scene.test.ts
@@ -0,0 +1,131 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file gpu-scene.test.ts
+ * @brief The scene the dynamic GI feeds the engine: which renderers become instances, and the arrays packed for the compute passes.
+ */
+import { describe, it, expect } from 'vitest';
+import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';
+import { bakeMeshCards } from '../src/assets/meshCards';
+import { bakeMeshSdf } from '../src/assets/meshSdf';
+import { buildInstances, type GIEntry } from '../../sdk/src/gi/dynamicGISystem';
+import { packGPUScene, GI_HEADER_FLOATS, GI_INSTANCE_FLOATS } from '../../sdk/src/gi/gpuScene';
+
+function box(h: [number, number, number]): MeshData {
+ const p: number[] = [];
+ for (let i = 0; i < 8; i++) p.push((i & 1 ? 1 : -1) * h[0], (i & 2 ? 1 : -1) * h[1], (i & 4 ? 1 : -1) * h[2]);
+ const idx: number[] = [];
+ for (const [a, b, c, d] of [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]] as [number, number, number, number][]) {
+ const pa = p.slice(a * 3, a * 3 + 3), pb = p.slice(b * 3, b * 3 + 3), pc = p.slice(c * 3, c * 3 + 3);
+ const u = pb.map((v, k) => v - pa[k]!), w = pc.map((v, k) => v - pa[k]!);
+ const n = [u[1]! * w[2]! - u[2]! * w[1]!, u[2]! * w[0]! - u[0]! * w[2]!, u[0]! * w[1]! - u[1]! * w[0]!];
+ idx.push(...(n[0]! * pa[0]! + n[1]! * pa[1]! + n[2]! * pa[2]! > 0 ? [a, b, c, a, c, d] : [a, c, b, a, d, c]));
+ }
+ const vertices = new Uint8Array(8 * 12), view = new DataView(vertices.buffer);
+ p.forEach((v, i) => view.setFloat32(i * 4, v, true));
+ return { channels: [{ semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 }], vertexStride: 12, vertexCount: 8, vertices,
+ indices: new Uint32Array(idx), aabbMin: [-h[0], -h[1], -h[2]], aabbMax: h };
+}
+
+const transform = (position: [number, number, number], scale: [number, number, number] = [1, 1, 1], rotation = { x: 0, y: 0, z: 0, w: 1 }) => ({
+ position: { x: 0, y: 0, z: 0 }, rotation: { x: 0, y: 0, z: 0, w: 1 }, scale: { x: 1, y: 1, z: 1 },
+ worldPosition: { x: position[0], y: position[1], z: position[2] }, worldRotation: rotation, worldScale: { x: scale[0], y: scale[1], z: scale[2] },
+});
+const entry = (mesh: number, t: ReturnType<typeof transform>, path: string | null = null, emissive: [number, number, number] = [0, 0, 0]): GIEntry =>
+ ({ mesh, transform: t, colour: [0.5, 0.5, 0.5], emissive, path });
+
+const CUBE = 7;
+const mesh = box([50, 50, 50]);
+const baked = { sdf: bakeMeshSdf(mesh, { cellSize: 10 })!, cards: bakeMeshCards(mesh, { cell: 25, baseColor: [0.2, 0.4, 0.6], emissive: [0, 1, 0] })! };
+
+describe('which renderers become instances', () => {
+ it('takes a built-in cube as a box of its world scale, and a baked mesh with its files placed by its transform', () => {
+ const { instances } = buildInstances([
+ entry(CUBE, transform([0, 0, 0], [4, 1, 1])),
+ entry(9, transform([300, 0, 0], [2, 2, 2]), 'assets/rock.esmesh'),
+ ], CUBE, (p) => (p === 'assets/rock.esmesh' ? baked : null));
+ expect(instances.length).toBe(2);
+ expect(instances[0]!.cards.aabbMax).toEqual([200, 50, 50]);
+ // The baked mesh is scaled by 2 about its own origin and moved to x = 300.
+ const m = instances[1]!.worldFromLocal;
+ expect([m[0], m[5], m[10], m[12]]).toEqual([2, 2, 2, 300]);
+ expect(instances[1]!.cards).toBe(baked.cards);
+ });
+
+ it('leaves out a mesh with no baked files, one scaled unevenly, and anything that is not drawn by a mesh', () => {
+ const { instances } = buildInstances([
+ entry(9, transform([0, 0, 0]), 'assets/none.esmesh'),
+ entry(9, transform([0, 0, 0], [1, 2, 1]), 'assets/rock.esmesh'),
+ entry(9, transform([0, 0, 0]), null),
+ ], CUBE, (p) => (p === 'assets/rock.esmesh' ? baked : null));
+ expect(instances.length).toBe(0);
+ });
+
+ it('carries a material emissive colour onto the cards of a cube, and rotates it with the entity', () => {
+ const turn = { x: 0, y: Math.SQRT1_2, z: 0, w: Math.SQRT1_2 }; // 90 degrees about y
+ const { instances } = buildInstances([entry(CUBE, transform([10, 0, 0], [1, 1, 1], turn), null, [4, 2, 0])], CUBE, () => null);
+ expect(instances[0]!.cards.emissiveScale).toBe(4);
+ expect(Array.from(instances[0]!.cards.cards[2]!.emissive.slice(0, 3))).toEqual([255, 128, 0]);
+ const m = instances[0]!.worldFromLocal;
+ expect(Math.abs(m[2]! + 1)).toBeLessThan(1e-6); // local x now points along world -z
+ });
+
+ it('changes its key when anything that matters moves, and not when nothing does', () => {
+ const a = buildInstances([entry(CUBE, transform([0, 0, 0]))], CUBE, () => null).key;
+ expect(buildInstances([entry(CUBE, transform([0, 0, 0]))], CUBE, () => null).key).toBe(a);
+ expect(buildInstances([entry(CUBE, transform([1, 0, 0]))], CUBE, () => null).key).not.toBe(a);
+ expect(buildInstances([entry(CUBE, transform([0, 0, 0]), null, [1, 0, 0])], CUBE, () => null).key).not.toBe(a);
+ });
+});
+
+describe('the packed scene', () => {
+ const { instances } = buildInstances([entry(CUBE, transform([0, 150, 0], [4, 3, 5])), entry(CUBE, transform([300, 0, 0]))], CUBE, () => null);
+ const scene = packGPUScene(instances, { toLight: [0, 1, 0], radiance: [1, 1, 1] })!;
+
+ it('lays the header, the field, the instances and the card pixels out as the engine reads them', () => {
+ expect(scene.header.length).toBe(GI_HEADER_FLOATS);
+ const [dim, cell, , , , reach, count, pixels] = scene.header;
+ expect(dim).toBe(128);
+ expect(scene.sdf.length).toBe(128 ** 3);
+ expect(reach).toBeCloseTo(cell! * 6, 4);
+ expect(count).toBe(2);
+ expect(scene.instances.length).toBe(2 * GI_INSTANCE_FLOATS);
+ expect(scene.pixels.length).toBe(pixels! * 4);
+ expect(Array.from(scene.header.slice(8, 12))).toEqual([0, 1, 0, 1]);
+ });
+
+ it('numbers the faces of each instance one after the other through the pixel array', () => {
+ let expected = 0;
+ for (let i = 0; i < 2; i++) for (let face = 0; face < 6; face++) {
+ const at = i * GI_INSTANCE_FLOATS + 44 + face * 4;
+ expect(scene.instances[at + 2]).toBe(expected);
+ expected += scene.instances[at]! * scene.instances[at + 1]!;
+ }
+ expect(expected).toBe(scene.header[7]);
+ // Every pixel names its instance and face (word 3).
+ const w3 = scene.pixels[3]!;
+ expect([w3 >> 3, w3 & 7]).toEqual([0, 0]);
+ const last = scene.pixels[(scene.header[7]! - 1) * 4 + 3]!;
+ expect([last >> 3, last & 7]).toEqual([1, 5]);
+ });
+
+ it('stores the world box and the scale where the kernels look for them, and the inverse that undoes the placement', () => {
+ const b = 0;
+ expect(Array.from(scene.instances.slice(b + 28, b + 31))).toEqual([-200, 0, -250]);
+ expect(Array.from(scene.instances.slice(b + 32, b + 35))).toEqual([200, 300, 250]);
+ expect(scene.instances[b + 31]).toBe(1);
+ // World to local at the entity's centre is the origin: row . (0, 150, 0) + w = 0 for the y row.
+ expect(scene.instances[b + 16 + 4 + 1]! * 150 + scene.instances[b + 16 + 4 + 3]!).toBeCloseTo(0, 5);
+ });
+
+ it('packs a normal and a colour into the words the kernels unpack', () => {
+ // Pixel 0 is face 0 (+x) of the first box: normal (127, 0, 0), albedo 0.5 grey.
+ const w0 = scene.pixels[0]!, w1 = scene.pixels[1]!;
+ expect([w0 & 0xffff, (w0 >> 16) & 255, (w0 >> 24) & 255, w1 & 255]).toEqual([0, 127, 0, 0]);
+ expect([(w1 >> 8) & 255, (w1 >> 16) & 255, (w1 >>> 24) & 255]).toEqual([128, 128, 128]);
+ });
+
+ it('is nothing for a scene with nothing in it', () => {
+ expect(packGPUScene([], null)).toBeNull();
+ });
+});
diff --git a/pipeline/tests/mesh-sidecar-deps.test.ts b/pipeline/tests/mesh-sidecar-deps.test.ts
new file mode 100644
index 000000000..966ddc6bd
--- /dev/null
+++ b/pipeline/tests/mesh-sidecar-deps.test.ts
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A mesh keeps the distance field and surface cards written beside it in the cook: they are named by nothing, so the dependency scan
+ * links them from the mesh, and a build ships them whenever it ships the mesh.
+ */
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { scanAssetDatabase } from '../src/assets/assetDb';
+
+let root: string;
+const MESH = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa', SDF = 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', CARDS = 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', OTHER = 'dddddddd-dddd-4ddd-8ddd-dddddddddddd';
+
+function writeAsset(rel: string, type: string, uuid: string): void {
+ const abs = path.join(root, rel);
+ mkdirSync(path.dirname(abs), { recursive: true });
+ writeFileSync(abs, 'x');
+ writeFileSync(`${abs}.meta`, JSON.stringify({ uuid, version: '2.0', type, importer: {} }));
+}
+
+beforeAll(() => {
+ root = mkdtempSync(path.join(tmpdir(), 'estella-meshdeps-'));
+ writeAsset('assets/rock.esmesh', 'mesh', MESH);
+ writeAsset('assets/rock.esmeshsdf', 'meshSdf', SDF);
+ writeAsset('assets/rock.esmeshcards', 'meshCards', CARDS);
+ writeAsset('assets/tree.esmesh', 'mesh', OTHER);
+});
+afterAll(() => { rmSync(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });
+
+describe('the files beside a mesh', () => {
+ it('are dependencies of the mesh, and a mesh with none has no dependencies', async () => {
+ const { index } = await scanAssetDatabase(root);
+ expect(index.deps[MESH]).toEqual([SDF, CARDS].sort());
+ expect(index.deps[OTHER]).toBeUndefined();
+ });
+});
diff --git a/sdk/src/gi/dynamicGISystem.ts b/sdk/src/gi/dynamicGISystem.ts
index 371c75e9f..c224c99fb 100644
--- a/sdk/src/gi/dynamicGISystem.ts
+++ b/sdk/src/gi/dynamicGISystem.ts
@@ -4,13 +4,13 @@
* @file dynamicGISystem.ts
* @brief Feeds the dynamic GI the scene (docs/GI_LUMEN_DESIGN.md): the instances in the world, composed and handed to the engine when they change.
*
- * @details Runs only while a PostProcessVolume carries an enabled `dynamicGI` effect. What it sees of the scene is the MeshRenderers whose mesh
- * is the built-in cube: each is a box of its world scale, with its colour, and a box needs no baked file (analyticBox). A mesh
- * with a baked `.esmeshsdf` / `.esmeshcards` beside it is the next step; until then it is not in the GI's scene.
- * The sun is the first enabled directional light.
+ * @details Runs only while a PostProcessVolume carries an enabled `dynamicGI` effect. A MeshRenderer whose mesh is the built-in cube is a box of
+ * its world scale, with its colour and the emissive colour of its material, and needs no baked file (analyticBox). Any other mesh is the
+ * `.esmeshsdf` and `.esmeshcards` the import wrote beside it (the `dynamicGI` import setting), placed with the entity's transform; a
+ * mesh without them is not in the GI's scene. The sun is the first enabled directional light.
*
* Composition is JavaScript work on the cells the instances touch and runs when the scene changes (a key of the instances'
- * transforms and colours and the sun), not every frame.
+ * transforms, colours and emission, and the sun), not every frame.
*/
import type { App } from '../app/app';
import { defineSystem } from '../ecs/system';
@@ -20,20 +20,65 @@ import { LightType } from '../wasm/wasm.generated';
import { Assets } from '../asset/AssetPlugin';
import type { Entity } from '../types';
import { withScratch } from '../wasm/wasmScratch';
+import { Material } from '../render/material';
import { analyticBox, packGPUScene, type GIInstance, type GILight } from './gpuScene';
+import type { MeshSdf } from './meshSdfFormat';
+import type { MeshCards } from './cardFormat';
const CUBE = 100; // the built-in cube is 100 units across
-function matrixOf(t: TransformData): number[] {
+function matrixOf(t: TransformData, scale = 1): number[] {
const { x, y, z, w } = t.worldRotation, p = t.worldPosition;
return [
- 1 - 2 * (y * y + z * z), 2 * (x * y + z * w), 2 * (x * z - y * w), 0,
- 2 * (x * y - z * w), 1 - 2 * (x * x + z * z), 2 * (y * z + x * w), 0,
- 2 * (x * z + y * w), 2 * (y * z - x * w), 1 - 2 * (x * x + y * y), 0,
+ (1 - 2 * (y * y + z * z)) * scale, 2 * (x * y + z * w) * scale, 2 * (x * z - y * w) * scale, 0,
+ 2 * (x * y - z * w) * scale, (1 - 2 * (x * x + z * z)) * scale, 2 * (y * z + x * w) * scale, 0,
+ 2 * (x * z + y * w) * scale, 2 * (y * z - x * w) * scale, (1 - 2 * (x * x + y * y)) * scale, 0,
p.x, p.y, p.z, 1,
];
}
+/** What the system reads of one MeshRenderer: enough to place it in the GI scene. */
+export interface GIEntry {
+ mesh: number;
+ transform: TransformData;
+ colour: readonly [number, number, number];
+ emissive: readonly [number, number, number];
+ /** The asset path of the mesh, where it has one (a built-in cube has none the GI needs). */
+ path: string | null;
+}
+
+export interface GISidecars { sdf: MeshSdf; cards: MeshCards }
+
+/**
+ * The instances of the GI scene from the renderers: a built-in cube is a box of its world scale (with its colour and emission); any other
+ * mesh is the baked `.esmeshsdf` and `.esmeshcards` beside it, when it has them and is scaled the same along every axis (a distance field
+ * does not survive a stretch). Everything else is not in the GI scene.
+ */
+export function buildInstances(entries: readonly GIEntry[], cube: number, sidecars: (path: string) => GISidecars | null): { instances: GIInstance[]; key: string } {
+ const instances: GIInstance[] = [];
+ let key = '';
+ const extent = Math.max(1, ...entries.filter((e) => e.mesh === cube).flatMap((e) => [e.transform.worldScale.x, e.transform.worldScale.y, e.transform.worldScale.z].map((v) => v * CUBE)));
+ for (const e of entries) {
+ const s = e.transform.worldScale, p = e.transform.worldPosition, q = e.transform.worldRotation;
+ const pose = `${[p.x, p.y, p.z, q.x, q.y, q.z, q.w, s.x, s.y, s.z].map((v) => v.toFixed(3)).join(',')};${e.colour.join(',')};${e.emissive.join(',')}`;
+ if (e.mesh === cube) {
+ const size: [number, number, number] = [s.x * CUBE, s.y * CUBE, s.z * CUBE];
+ // A box with a cell fine enough that a wall a tenth of a metre thick is still more than one.
+ const { cards, ...sdf } = analyticBox(size, e.colour, Math.max(extent / 60, 1e-3), extent / 20, 24, e.emissive);
+ instances.push({ sdf, cards, worldFromLocal: matrixOf({ ...e.transform, worldScale: { x: 1, y: 1, z: 1 } }) });
+ key += `|c${pose}`;
+ } else if (e.path) {
+ const found = sidecars(e.path);
+ if (!found) continue;
+ const lo = Math.min(s.x, s.y, s.z), hi = Math.max(s.x, s.y, s.z);
+ if (lo <= 0 || hi / lo > 1.05) continue;
+ instances.push({ sdf: found.sdf, cards: found.cards, worldFromLocal: matrixOf(e.transform, (s.x + s.y + s.z) / 3) });
+ key += `|m${e.path};${pose}`;
+ }
+ }
+ return { instances, key };
+}
+
function wantsDynamicGI(volumes: Iterable<[Entity, PostProcessVolumeData]>): boolean {
for (const [, v] of volumes) {
for (const e of v.effects as Array<{ type: string; enabled?: boolean }>) if (e.type === 'dynamicGI' && e.enabled !== false) return true;
@@ -41,8 +86,38 @@ function wantsDynamicGI(volumes: Iterable<[Entity, PostProcessVolumeData]>): boo
return false;
}
+/** The emissive colour of a material, black where it has none. */
+export function emissiveOf(material: number): [number, number, number] {
+ if (material === 0) return [0, 0, 0];
+ const v = Material.getUniform(material as never, 'u_emissive') as unknown;
+ if (Array.isArray(v)) return [Number(v[0]) || 0, Number(v[1]) || 0, Number(v[2]) || 0];
+ const o = v as { x?: number; y?: number; z?: number; r?: number; g?: number; b?: number } | undefined;
+ if (!o || typeof o !== 'object') return [0, 0, 0];
+ return [o.x ?? o.r ?? 0, o.y ?? o.g ?? 0, o.z ?? o.b ?? 0];
+}
+
+type Loader = {
+ loadTyped?(type: string, ref: string): Promise<unknown>;
+ pathForHandle?(kind: string, handle: number): string | null;
+ catalog?: { addressOf?(path: string): string | null };
+};
+
export function dynamicGISystem(app: App) {
let cube = 0, loading = false, lastKey = '';
+ // 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 => {
+ if (sidecars.has(path) || !app.hasResource(Assets)) return;
+ sidecars.set(path, null);
+ const assets = app.getResource(Assets) as unknown as Loader;
+ // A packaged build renames every asset to its hash; the files beside the mesh are named from where it was authored.
+ const authored = assets.catalog?.addressOf?.(path) ?? path;
+ const base = authored.replace(/\.esmesh$/, '');
+ if (!assets.loadTyped || base === authored) return;
+ void Promise.all([assets.loadTyped('meshSdf', `${base}.esmeshsdf`), assets.loadTyped('meshCards', `${base}.esmeshcards`)]).then(
+ ([sdf, cards]) => { sidecars.set(path, { sdf: sdf as MeshSdf, cards: cards as MeshCards }); lastKey = ''; },
+ () => { /* a mesh with no baked files is simply not in the scene */ });
+ };
return defineSystem(
[Query(MeshRenderer, Transform), Query(Light, Transform), Query(PostProcessVolume)],
(meshes: Iterable<[Entity, MeshRendererData, TransformData]>, lights: Iterable<[Entity, LightData, TransformData]>,
@@ -67,25 +142,21 @@ export function dynamicGISystem(app: App) {
light = { toLight: [-ax / n, -ay / n, -az / n], radiance: [l.color.r * l.intensity, l.color.g * l.intensity, l.color.b * l.intensity] };
break;
}
- const boxes: Array<{ matrix: number[]; size: [number, number, number]; colour: [number, number, number] }> = [];
- let key = light ? `${light.toLight.join(',')}|${light.radiance.join(',')}` : 'dark';
+ const assets = app.hasResource(Assets) ? app.getResource(Assets) as unknown as Loader : null;
+ const entries: GIEntry[] = [];
for (const [, r, t] of meshes) {
- if (!r.enabled || r.mesh !== cube) continue;
- const s = t.worldScale, matrix = matrixOf(t);
- const size: [number, number, number] = [s.x * CUBE, s.y * CUBE, s.z * CUBE];
- const colour: [number, number, number] = [r.color.r, r.color.g, r.color.b];
- boxes.push({ matrix, size, colour });
- key += `|${matrix.slice(0, 3).concat(matrix.slice(12, 15)).map((v) => v.toFixed(3)).join(',')};${size.join(',')};${colour.join(',')}`;
+ if (!r.enabled) continue;
+ let path: string | null = null;
+ if (r.mesh !== cube && r.mesh !== 0) {
+ path = assets?.pathForHandle?.('mesh', r.mesh) ?? null;
+ if (path) request(path);
+ }
+ entries.push({ mesh: r.mesh, transform: t, colour: [r.color.r, r.color.g, r.color.b], emissive: emissiveOf(r.material), path });
}
- if (key === lastKey || boxes.length === 0) return;
+ const { instances, key: sceneKey } = buildInstances(entries, cube, (p) => sidecars.get(p) ?? null);
+ const key = (light ? `${light.toLight.join(',')}|${light.radiance.join(',')}` : 'dark') + sceneKey;
+ if (key === lastKey || instances.length === 0) return;
lastKey = key;
- const extent = Math.max(...boxes.flatMap((b) => b.size));
- const instances: GIInstance[] = boxes.map((b) => {
- // A box of the field's own cell size: fine enough that a wall a tenth of a metre thick is still more than a cell.
- const cell = Math.max(extent / 60, 1e-3);
- const { cards, ...sdf } = analyticBox(b.size, b.colour, cell, extent / 20);
- return { sdf, cards, worldFromLocal: b.matrix };
- });
const scene = packGPUScene(instances, light);
if (!scene) return;
withScratch(m, (alloc) => {
diff --git a/sdk/src/gi/gpuScene.ts b/sdk/src/gi/gpuScene.ts
index 09acc12db..03ed20715 100644
--- a/sdk/src/gi/gpuScene.ts
+++ b/sdk/src/gi/gpuScene.ts
@@ -44,7 +44,7 @@ export const GI_HEADER_FLOATS = 24;
export const GI_INSTANCE_FLOATS = 80;
/** A box of the given size centred on the origin, as a distance field and as cards, without any mesh: what a primitive is to the GI. */
-export function analyticBox(size: readonly [number, number, number], colour: readonly [number, number, number], cell: number, cardCell: number, maxResolution = 24): GIInstance['sdf'] & { cards: MeshCards } {
+export function analyticBox(size: readonly [number, number, number], colour: readonly [number, number, number], cell: number, cardCell: number, maxResolution = 24, emissive: readonly [number, number, number] = [0, 0, 0]): GIInstance['sdf'] & { cards: MeshCards } {
const h = size.map((s) => s / 2);
const inflate = 0.5 * cell, pad = 2;
const dims = size.map((s) => Math.max(Math.ceil(s / cell), 1) + 2 * pad) as [number, number, number];
@@ -55,16 +55,19 @@ export function analyticBox(size: readonly [number, number, number], colour: rea
const d = Math.hypot(Math.max(q[0]!, 0), Math.max(q[1]!, 0), Math.max(q[2]!, 0)) + Math.min(Math.max(q[0]!, q[1]!, q[2]!), 0);
distance[x + y * dims[0] + z * dims[0] * dims[1]] = d - inflate;
}
- const cards: MeshCards = { aabbMin: h.map((v) => -v) as [number, number, number], aabbMax: h as [number, number, number], cell: cardCell, emissiveScale: 1, cards: [] };
+ const cards: MeshCards = { aabbMin: h.map((v) => -v) as [number, number, number], aabbMax: h as [number, number, number], cell: cardCell, emissiveScale: Math.max(emissive[0], emissive[1], emissive[2], 1e-6), cards: [] };
const cap = Math.max(...size) / maxResolution, px = Math.max(cardCell, cap);
for (const { axis, sign, u, v } of CARD_AXES) {
const width = Math.max(1, Math.min(maxResolution, Math.ceil(size[u]! / px))), height = Math.max(1, Math.min(maxResolution, Math.ceil(size[v]! / px)));
- const n = width * height, normal = new Int8Array(n * 3), albedo = new Uint8Array(n * 3);
+ const n = width * height, normal = new Int8Array(n * 3), albedo = new Uint8Array(n * 3), emit = new Uint8Array(n * 3);
for (let i = 0; i < n; i++) {
normal[i * 3 + axis] = 127 * sign;
- for (let k = 0; k < 3; k++) albedo[i * 3 + k] = Math.round(Math.min(Math.max(colour[k]!, 0), 1) * 255);
+ for (let k = 0; k < 3; k++) {
+ albedo[i * 3 + k] = Math.round(Math.min(Math.max(colour[k]!, 0), 1) * 255);
+ emit[i * 3 + k] = Math.round(Math.min(Math.max(emissive[k]! / cards.emissiveScale, 0), 1) * 255);
+ }
}
- cards.cards.push({ width, height, depth: new Uint16Array(n), normal, albedo, emissive: new Uint8Array(n * 3) });
+ cards.cards.push({ width, height, depth: new Uint16Array(n), normal, albedo, emissive: emit });
}
return { dims, cell, origin, distance, inflate, cards };
}
diff --git a/tools/render-lab/gi_oracle.py b/tools/render-lab/gi_oracle.py
index 712f22463..0698dd012 100644
--- a/tools/render-lab/gi_oracle.py
+++ b/tools/render-lab/gi_oracle.py
@@ -31,6 +31,8 @@ METHODS = {
'baked': {'BAKE': '1', 'BOUNCES': '8'},
'vgi': {'EFFECTS': json.dumps([{'type': 'voxelGI', 'enabled': True, 'uniforms': {}}])},
'dgi': {'BACKEND': 'webgpu', 'HEADLESS_GPU': '1', 'EFFECTS': json.dumps([{'type': 'dynamicGI', 'enabled': True, 'uniforms': {}}])},
+ # The same, with every box a mesh and the `.esmeshsdf` / `.esmeshcards` an import with `dynamicGI` on writes beside it (make_mesh_boxes.mjs).
+ 'dgim': {'BACKEND': 'webgpu', 'HEADLESS_GPU': '1', 'MESH_BOXES': '1', 'EFFECTS': json.dumps([{'type': 'dynamicGI', 'enabled': True, 'uniforms': {}}])},
}
# The share of Cycles' light, per region, each method is allowed (measured 2026-11-11). A region the sun lights directly reads about 1 for all.
@@ -45,6 +47,11 @@ BANDS = {
('gi_room', 'dgi'): (0.45, 1.25),
('gi_away', 'dgi'): (0.45, 1.00),
('gi_leak', 'dgi'): ('zero', 0.0005),
+ ('gi_emissive', 'dgi'): (0.75, 1.35),
+ ('gi_room', 'dgim'): (0.45, 1.45),
+ ('gi_away', 'dgim'): (0.45, 1.30),
+ ('gi_leak', 'dgim'): ('zero', 0.0005),
+ ('gi_emissive', 'dgim'): (0.75, 1.50),
}
# Wrong today, on purpose written down: the lightmap baker has no notion of an emissive surface (tools/lightmap-wasm/kernel.cpp carries albedo
# and the sun, nothing that emits), so a room lit only by a glowing panel bakes black. The region shares are asserted to stay under this.
@@ -54,7 +61,6 @@ BANDS = {
KNOWN_GAP = {
('gi_emissive', 'baked'): ('the lightmap baker does not light from emissive surfaces', 0.05),
('gi_leak', 'vgi'): ('the voxel method lets the sun through thin walls', 0.008),
- ('gi_emissive', 'dgi'): ('the dynamic GI does not read the emissive colour of a material into its cards yet', 0.05),
}
diff --git a/tools/render-lab/gi_project.py b/tools/render-lab/gi_project.py
index aea9cebf8..ee40a23c8 100644
--- a/tools/render-lab/gi_project.py
+++ b/tools/render-lab/gi_project.py
@@ -36,14 +36,22 @@ if 'emission' in spec:
json.dump({'uuid': mid, 'version': '2.0', 'type': 'material', 'importer': {}}, open(proj + '/assets/materials/panel.esmaterial.meta', 'w'), indent=2)
panel_material = '@uuid:' + mid
+MESH_BOXES = os.environ.get('MESH_BOXES') == '1'
+if MESH_BOXES:
+ # Each box a mesh with the files the dynamic GI reads beside it, as an import with `dynamicGI` on would write them.
+ import subprocess
+ boxes = [{'size': list(b[2]), 'colour': list(b[3]), 'emissive': [spec.get('emission', 0)] * 3 if b[0] == 'panel' else [0, 0, 0]} for b in spec['boxes']]
+ json.dump(boxes, open(proj + '/boxes.json', 'w'))
+ subprocess.check_call(['node', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'make_mesh_boxes.mjs'), proj, proj + '/boxes.json'])
+
for i, (name, centre, size, colour) in enumerate(spec['boxes']):
- mr = {'mesh': 'builtin:cube', 'lit': True, 'opaque': True, 'cullBackfaces': True,
+ mr = {'mesh': 'assets/meshes/box_%d.esmesh' % i if MESH_BOXES else 'builtin:cube', 'lit': True, 'opaque': True, 'cullBackfaces': True,
'color': {'r': colour[0], 'g': colour[1], 'b': colour[2], 'a': 1}}
if name == 'panel' and panel_material:
mr['material'] = panel_material
entities.append({'id': 10 + i, 'name': name, 'parent': None, 'children': [], 'visible': True, 'components': [
{'type': 'Transform', 'data': {'position': {'x': centre[0], 'y': centre[1], 'z': centre[2]},
- 'scale': {'x': size[0] / 100.0, 'y': size[1] / 100.0, 'z': size[2] / 100.0}}},
+ 'scale': {'x': 1, 'y': 1, 'z': 1} if MESH_BOXES else {'x': size[0] / 100.0, 'y': size[1] / 100.0, 'z': size[2] / 100.0}}},
{'type': 'MeshRenderer', 'data': mr}]})
if spec['sun']:
diff --git a/tools/render-lab/make_mesh_boxes.mjs b/tools/render-lab/make_mesh_boxes.mjs
new file mode 100644
index 000000000..03e91fe05
--- /dev/null
+++ b/tools/render-lab/make_mesh_boxes.mjs
@@ -0,0 +1,55 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The GI lab's boxes as meshes with the files the dynamic GI reads beside them: for each box in <boxes.json>, `assets/meshes/box_<i>.esmesh`
+ * (the built-in cube scaled to the box), `.esmeshsdf` and `.esmeshcards` — what an import with `dynamicGI` on writes.
+ *
+ * node tools/render-lab/make_mesh_boxes.mjs <projectDir> <boxes.json> boxes.json: [{ size: [x, y, z], colour: [r, g, b], emissive: [r, g, b] }]
+ */
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+import { build } from 'esbuild';
+
+const root = path.resolve(import.meta.dirname, '../..');
+const [project, boxesFile] = process.argv.slice(2);
+const boxes = JSON.parse(readFileSync(boxesFile, 'utf8'));
+
+// Beside the pipeline, whose node_modules resolve `esengine`; removed once loaded.
+const out = path.join(root, 'pipeline', '.make-boxes.mjs');
+await build({
+ stdin: {
+ contents: `
+ export { builtinMeshTemplate } from ${JSON.stringify(path.join(root, 'sdk/src/asset/builtinMeshes.ts'))};
+ export { encodeMesh } from ${JSON.stringify(path.join(root, 'sdk/src/asset/meshFormat.ts'))};
+ export { bakeMeshSdf, encodeMeshSdf } from ${JSON.stringify(path.join(root, 'pipeline/src/assets/meshSdf.ts'))};
+ export { bakeMeshCards } from ${JSON.stringify(path.join(root, 'pipeline/src/assets/meshCards.ts'))};
+ export { encodeMeshCards } from ${JSON.stringify(path.join(root, 'sdk/src/gi/cardFormat.ts'))};
+ `,
+ resolveDir: root, loader: 'ts',
+ },
+ bundle: true, platform: 'node', format: 'esm', outfile: out, external: ['esengine'], logLevel: 'error',
+});
+const T = await import(pathToFileURL(out).href);
+rmSync(out, { force: true });
+
+const dir = path.join(project, 'assets', 'meshes');
+mkdirSync(dir, { recursive: true });
+boxes.forEach((b, i) => {
+ const cube = T.builtinMeshTemplate('builtin:cube').build();
+ const view = new DataView(cube.vertices.buffer, cube.vertices.byteOffset, cube.vertices.byteLength);
+ const position = cube.channels.find((c) => c.semantic === 0);
+ // The built-in cube is 100 across; the box is its size, so the vertices are scaled by size / 100 about the origin.
+ for (let v = 0; v < cube.vertexCount; v++) {
+ for (let k = 0; k < 3; k++) {
+ const at = v * cube.vertexStride + position.offset + k * 4;
+ view.setFloat32(at, view.getFloat32(at, true) * (b.size[k] / 100), true);
+ }
+ }
+ cube.aabbMin = b.size.map((s) => -s / 2);
+ cube.aabbMax = b.size.map((s) => s / 2);
+ const name = `box_${i}`;
+ writeFileSync(path.join(dir, `${name}.esmesh`), T.encodeMesh(cube));
+ writeFileSync(path.join(dir, `${name}.esmeshsdf`), T.encodeMeshSdf(T.bakeMeshSdf(cube, { cellSize: 10 })));
+ writeFileSync(path.join(dir, `${name}.esmeshcards`), T.encodeMeshCards(T.bakeMeshCards(cube, { cell: 25, maxResolution: 24, baseColor: b.colour, emissive: b.emissive })));
+});