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): mesh distance fields load as assets, import can bake them, and the scene field composes them into clipmaps with a sphere trace checked on WebGPU

yhhb0a3793ec7ff
diff --git a/docs/GI_LUMEN_DESIGN.md b/docs/GI_LUMEN_DESIGN.md
index 8cf11c218..5ec0616cf 100644
--- a/docs/GI_LUMEN_DESIGN.md
+++ b/docs/GI_LUMEN_DESIGN.md
@@ -111,7 +111,7 @@
| 期 | 内容 | 验收 |
|---|---|---|
-| P0 | 网格 SDF 烘焙(pipeline,**烘焙器 `pipeline/src/assets/meshSdf.ts` 已落地并有闭式测试**;`.esmeshsdf` 资源类型和运行时加载器同批接入,避免先注册一个无人读取的资源类型)+ 全局距离场 clipmap + `sphereTrace`/`occlusion` 公共 WGSL | 新 oracle 场景:球、盒、薄墙的距离值和闭式解比对(`tools/oracle`);薄墙 10 cm 在 0.1 m 格下 `occlusion` 为真 |
+| P0 | 网格 SDF 烘焙(pipeline)+ `.esmeshsdf` 资源类型与加载器 + 全局距离场。**已落地(2026-11-11)**:烘焙器 `pipeline/src/assets/meshSdf.ts`;导入设置 `distanceField`(默认关);`MeshSdfAssetLoader`;CPU 合成的 clipmap `sdk/src/gi/globalSdf.ts`(环形寻址、按脏区重建、`sphereTrace`/`occluded`);WGSL 追踪 `GLOBAL_SDF_WGSL`,由 `tools/gi/check-sdf-wgsl.mjs` 在无头 WebGPU 上与球的闭式解比对。**未做**:clipmap 接到渲染帧的网格实例、上传 GPU 存储缓冲、编辑器里的导入开关+ 全局距离场 clipmap + `sphereTrace`/`occlusion` 公共 WGSL | 新 oracle 场景:球、盒、薄墙的距离值和闭式解比对(`tools/oracle`);薄墙 10 cm 在 0.1 m 格下 `occlusion` 为真 |
| P1 | 表面缓存:card 烘焙、图集分配、直接光 + 自发光刷新 | 卡面亮度与 `shade()` 参考一致;自发光面板出现在命中点取光里 |
| P2 | 屏幕探针 + SDF 追踪 + 时间/空间滤波,单次反弹 | `gi_leak` 为 0;`gi_room` 阴影区 0.6–1.1 |
| P3 | 表面缓存吃上一帧间接光(多次反弹)+ 世界辐射缓存 | `gi_room` 0.8–1.1;`gi_away` ≥ 0.8;`gi_emissive` ≥ 0.8 |
diff --git a/pipeline/src/assets/importModelFile.ts b/pipeline/src/assets/importModelFile.ts
index dc25397d8..4357e3ce0 100644
--- a/pipeline/src/assets/importModelFile.ts
+++ b/pipeline/src/assets/importModelFile.ts
@@ -20,6 +20,7 @@ import {
type ImportedMesh, type ImportedNode, type SpecularMapReading,
} from './modelImport';
import { modelStem, readModelSource } from './readModelSource';
+import { bakeMeshSdf, encodeMeshSdf } from './meshSdf';
import { parseManifest } from '../project/format';
export interface ModelImportSettings {
@@ -30,6 +31,8 @@ export interface ModelImportSettings {
lodMinTriangles: number;
characters: boolean;
springBones: boolean;
+ /** Bake a signed distance field beside each mesh (`<name>.esmeshsdf`), which the dynamic GI traces against. */
+ distanceField: boolean;
}
export interface ImportedModel {
@@ -63,7 +66,7 @@ export interface ImportModelOptions {
}
const DEFAULTS: ModelImportSettings = {
- scale: 1, lightmapUV: false, specularMap: 'color', lodLevels: 0, lodMinTriangles: 256, characters: false, springBones: false,
+ scale: 1, lightmapUV: false, specularMap: 'color', lodLevels: 0, lodMinTriangles: 256, characters: false, springBones: false, distanceField: false,
};
/** What a model's `.meta` asks of the import; the schema's defaults where it is silent or unreadable. One read, because two would be two chances to disagree. */
@@ -71,7 +74,7 @@ export function modelSettings(absSource: string): ModelImportSettings {
try {
const meta = JSON.parse(readFileSync(`${absSource}.meta`, 'utf8')) as
{ importer?: { scale?: unknown; lightmapUV?: unknown; specularMap?: unknown;
- lodLevels?: unknown; lodMinTriangles?: unknown; characterMaterials?: unknown; springBones?: unknown } };
+ lodLevels?: unknown; lodMinTriangles?: unknown; characterMaterials?: unknown; springBones?: unknown; distanceField?: unknown } };
const imp = meta.importer;
const scale = imp?.scale;
const levels = imp?.lodLevels;
@@ -84,6 +87,7 @@ export function modelSettings(absSource: string): ModelImportSettings {
lodMinTriangles: typeof minTriangles === 'number' && minTriangles >= 0 ? minTriangles : 256,
characters: imp?.characterMaterials === 'auto',
springBones: imp?.springBones === 'auto',
+ distanceField: imp?.distanceField === true,
};
} catch {
return { ...DEFAULTS };
@@ -123,7 +127,7 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importe
const sourceDir = opts.originDir ?? path.dirname(absSource);
const stem = modelStem(absSource);
const projectRef = (abs: string): string => path.relative(path.resolve(root), abs).split(path.sep).join('/');
- const { scale, lightmapUV, specularMap, lodLevels, lodMinTriangles, characters, springBones } = { ...modelSettings(absSource), ...opts.settings };
+ const { scale, lightmapUV, specularMap, lodLevels, lodMinTriangles, characters, springBones, distanceField } = { ...modelSettings(absSource), ...opts.settings };
const { meshes, textures, nodes, animations, externalFiles, warnings } = await readModelSource(
new Uint8Array(readFileSync(absSource)), stem,
@@ -254,6 +258,11 @@ export async function importModelFile(opts: ImportModelOptions): Promise<Importe
for (const [i, lodBytes] of levels.entries()) {
await write(`${lodName(mesh, i + 1)}.esmesh`, lodBytes);
}
+ // A skinned or morphing mesh moves its surface: a field baked from the bind pose would be a wrong wall.
+ if (distanceField && !mesh.data.inverseBindMatrices && !mesh.data.morph) {
+ const field = bakeMeshSdf(mesh.data, { cellSize: (0.1 * projectUnitsPerMeter(root)) / Math.max(scale, 1e-6) });
+ if (field) await write(`${mesh.name}.esmeshsdf`, encodeMeshSdf(field));
+ }
}
}
for (const texture of textures) await write(texture.name, texture.bytes);
diff --git a/pipeline/src/assets/meshSdf.ts b/pipeline/src/assets/meshSdf.ts
index b804b570f..d8b96e00f 100644
--- a/pipeline/src/assets/meshSdf.ts
+++ b/pipeline/src/assets/meshSdf.ts
@@ -33,17 +33,9 @@ export interface MeshSdfOptions {
inflate?: number;
}
-export interface MeshSdf {
- dims: [number, number, number];
- /** Edge of one cell, in mesh units. */
- cell: number;
- /** The world-space position of the first cell's CORNER; cell (i, j, k) is centred at `origin + (i + 0.5, j + 0.5, k + 0.5) * cell`. */
- origin: [number, number, number];
- /** Signed distance per cell, x fastest, in mesh units. */
- distance: Float32Array;
- /** The growth already applied, in mesh units. */
- inflate: number;
-}
+import type { MeshSdf } from '../../../sdk/src/gi/meshSdfFormat';
+export type { MeshSdf } from '../../../sdk/src/gi/meshSdfFormat';
+export { encodeMeshSdf, decodeMeshSdf, sampleMeshSdf, toHalf, fromHalf } from '../../../sdk/src/gi/meshSdfFormat';
const BAND = 3;
const INF = 1e30;
@@ -196,76 +188,3 @@ export function bakeMeshSdf(data: MeshData, options: MeshSdfOptions): MeshSdf |
}
return { dims, cell, origin, distance: out, inflate };
}
-
-/** The value a half-float holds nearest to `v` (IEEE 754 binary16, round to nearest even, no NaN). */
-export function toHalf(v: number): number {
- if (!(Math.abs(v) < 65504)) return v < 0 ? 0xfbff : 0x7bff;
- const f = new Float32Array([v]), u = new Uint32Array(f.buffer)[0]!;
- const sign = (u >>> 16) & 0x8000;
- let exp = ((u >>> 23) & 0xff) - 127 + 15;
- let man = u & 0x7fffff;
- if (exp <= 0) {
- if (exp < -10) return sign;
- man = (man | 0x800000) >>> (1 - exp);
- return sign | ((man + 0x1000) >>> 13);
- }
- const rounded = (man + 0xfff + ((man >>> 13) & 1)) >>> 13;
- return sign | (((exp << 10) + rounded) & 0xffff);
-}
-
-export function fromHalf(h: number): number {
- const sign = h & 0x8000 ? -1 : 1, exp = (h >>> 10) & 0x1f, man = h & 0x3ff;
- if (exp === 0) return sign * man * 2 ** -24;
- if (exp === 31) return sign * 65504;
- return sign * (1 + man / 1024) * 2 ** (exp - 15);
-}
-
-/** `.esmeshsdf`: 'ESDF', version 1, dims x3 (u32), cell, origin x3, inflate (f32), then the distances as half floats, x fastest. */
-export const MESH_SDF_MAGIC = 0x46445345;
-export const MESH_SDF_HEADER_BYTES = 4 * (2 + 3 + 1 + 3 + 1);
-
-export function encodeMeshSdf(sdf: MeshSdf): Uint8Array {
- const count = sdf.distance.length, bytes = new Uint8Array(MESH_SDF_HEADER_BYTES + count * 2 + (count & 1) * 2);
- const view = new DataView(bytes.buffer);
- let o = 0;
- const u32 = (v: number) => { view.setUint32(o, v, true); o += 4; };
- const f32 = (v: number) => { view.setFloat32(o, v, true); o += 4; };
- u32(MESH_SDF_MAGIC); u32(1);
- sdf.dims.forEach(u32);
- f32(sdf.cell);
- sdf.origin.forEach(f32);
- f32(sdf.inflate);
- for (let i = 0; i < count; i++) view.setUint16(o + i * 2, toHalf(sdf.distance[i]!), true);
- return bytes;
-}
-
-export function decodeMeshSdf(bytes: Uint8Array): MeshSdf {
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
- if (view.getUint32(0, true) !== MESH_SDF_MAGIC) throw new Error('not a mesh distance field');
- if (view.getUint32(4, true) !== 1) throw new Error(`unsupported mesh distance field version ${view.getUint32(4, true)}`);
- const dims: [number, number, number] = [view.getUint32(8, true), view.getUint32(12, true), view.getUint32(16, true)];
- const cell = view.getFloat32(20, true);
- const origin: [number, number, number] = [view.getFloat32(24, true), view.getFloat32(28, true), view.getFloat32(32, true)];
- const inflate = view.getFloat32(36, true);
- const count = dims[0] * dims[1] * dims[2], distance = new Float32Array(count);
- for (let i = 0; i < count; i++) distance[i] = fromHalf(view.getUint16(MESH_SDF_HEADER_BYTES + i * 2, true));
- return { dims, cell, origin, distance, inflate };
-}
-
-/**
- * The field's value at a point: trilinear between cell centres inside the grid, and beyond its edge the edge value plus how far the point
- * is from the grid (the nearest surface is at least that much further, so a trace may step that far).
- */
-export function sampleMeshSdf(sdf: MeshSdf, point: readonly [number, number, number]): number {
- const g = [0, 1, 2].map((k) => Math.min(Math.max((point[k]! - sdf.origin[k]!) / sdf.cell - 0.5, 0), sdf.dims[k]! - 1 - 1e-6));
- const i0 = g.map(Math.floor) as number[], f = g.map((v, k) => v - i0[k]!);
- const beyond = Math.hypot(...[0, 1, 2].map((k) => Math.max(sdf.origin[k]! + 0.5 * sdf.cell - point[k]!, point[k]! - (sdf.origin[k]! + (sdf.dims[k]! - 0.5) * sdf.cell), 0)));
- const at = (x: number, y: number, z: number) => sdf.distance[x + y * sdf.dims[0] + z * sdf.dims[0] * sdf.dims[1]]!;
- let sum = 0;
- for (let c = 0; c < 8; c++) {
- const dx = c & 1, dy = (c >> 1) & 1, dz = (c >> 2) & 1;
- const w = (dx ? f[0]! : 1 - f[0]!) * (dy ? f[1]! : 1 - f[1]!) * (dz ? f[2]! : 1 - f[2]!);
- sum += w * at(i0[0]! + dx, i0[1]! + dy, i0[2]! + dz);
- }
- return sum + beyond;
-}
diff --git a/pipeline/tests/model-distance-field.test.ts b/pipeline/tests/model-distance-field.test.ts
new file mode 100644
index 000000000..74def4bb6
--- /dev/null
+++ b/pipeline/tests/model-distance-field.test.ts
@@ -0,0 +1,67 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A model imported with `distanceField` on gets a `.esmeshsdf` beside each mesh; without it, none.
+ */
+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { afterAll, describe, expect, it } from 'vitest';
+import { importModelFile } from '../src/assets/importModelFile';
+import { decodeMeshSdf, sampleMeshSdf } from '../src/assets/meshSdf';
+
+/** A cube of half extent 50 (units), glTF with outward winding. */
+function cubeGltf(): string {
+ const p: number[] = [];
+ for (let i = 0; i < 8; i++) p.push((i & 1 ? 1 : -1) * 50, (i & 2 ? 1 : -1) * 50, (i & 4 ? 1 : -1) * 50);
+ const quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
+ const idx: number[] = [];
+ for (const [a, b, c, d] of quads 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 positions = new Float32Array(p), indices = new Uint16Array(idx);
+ const bytes = Buffer.concat([Buffer.from(positions.buffer), Buffer.from(indices.buffer)]);
+ return JSON.stringify({
+ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: 'cube' }],
+ meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1 }] }],
+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${bytes.toString('base64')}` }],
+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: positions.byteLength, target: 34962 }, { buffer: 0, byteOffset: positions.byteLength, byteLength: indices.byteLength, target: 34963 }],
+ accessors: [
+ { bufferView: 0, componentType: 5126, count: 8, type: 'VEC3', min: [-50, -50, -50], max: [50, 50, 50] },
+ { bufferView: 1, componentType: 5123, count: idx.length, type: 'SCALAR' },
+ ],
+ });
+}
+
+describe('importing a model with a distance field', () => {
+ const roots: string[] = [];
+ afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true, maxRetries: 10, retryDelay: 50 }); });
+
+ async function run(distanceField: boolean) {
+ const root = mkdtempSync(path.join(tmpdir(), 'model-sdf-'));
+ roots.push(root);
+ const dir = path.join(root, 'assets', 'models');
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(path.join(dir, 'cube.gltf'), cubeGltf());
+ const result = await importModelFile({ root, destDir: 'assets/models', absSource: path.join(dir, 'cube.gltf'), settings: { distanceField } });
+ return { result, dir, files: readdirSync(dir) };
+ }
+
+ it('writes a field that measures the mesh it sits beside', async () => {
+ const { result, dir, files } = await run(true);
+ const name = files.find((f) => f.endsWith('.esmeshsdf'));
+ expect(name).toBeDefined();
+ expect(result.products.some((p) => p.endsWith('.esmeshsdf'))).toBe(true);
+ const sdf = decodeMeshSdf(new Uint8Array(readFileSync(path.join(dir, name!))));
+ expect(sampleMeshSdf(sdf, [0, 0, 0])).toBeLessThan(-40);
+ expect(sampleMeshSdf(sdf, [80, 0, 0])).toBeGreaterThan(20);
+ });
+
+ it('writes none unless it is asked to', async () => {
+ const { files } = await run(false);
+ expect(files.some((f) => f.endsWith('.esmeshsdf'))).toBe(false);
+ });
+});
diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.ts
index 6cf526ca6..22295f6e3 100644
--- a/sdk/src/asset/Assets.ts
+++ b/sdk/src/asset/Assets.ts
@@ -41,6 +41,7 @@ import { nativeEngineApi, type EngineApi } from '../ecs/bridge/engineApi';
import { isBuiltinMeshRef } from './builtinMeshes';
import { EnvironmentAssetLoader } from './loaders/EnvironmentAssetLoader';
import { ProbeVolumeAssetLoader } from './loaders/ProbeVolumeAssetLoader';
+import { MeshSdfAssetLoader } from './loaders/MeshSdfAssetLoader';
import { FontAssetLoader } from './loaders/FontAssetLoader';
import { AudioAssetLoader } from './loaders/AudioAssetLoader';
import { AnimClipAssetLoader } from './loaders/AnimClipAssetLoader';
@@ -2691,6 +2692,7 @@ export class Assets {
this.register(new MeshAssetLoader(core));
this.register(new EnvironmentAssetLoader(core));
this.register(new ProbeVolumeAssetLoader(core));
+ this.register(new MeshSdfAssetLoader());
// The audio loader needs the AudioAPI outside load() too (unload /
// invalidate have no LoadContext), so it shares Assets' lazy accessor.
this.register(new AudioAssetLoader(() => this.getAudio_()));
diff --git a/sdk/src/asset/loaders/MeshSdfAssetLoader.ts b/sdk/src/asset/loaders/MeshSdfAssetLoader.ts
new file mode 100644
index 000000000..238a3e1cc
--- /dev/null
+++ b/sdk/src/asset/loaders/MeshSdfAssetLoader.ts
@@ -0,0 +1,26 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+import type { AssetLoader, LoadContext } from '../AssetLoader';
+import { decodeMeshSdf, type MeshSdf } from '../../gi/meshSdfFormat';
+
+/**
+ * Loads `.esmeshsdf` — the signed distance field baked beside a mesh at import. Plain memory: the dynamic GI composes it into its
+ * clipmaps, so nothing here belongs to the GPU and unloading has nothing to free.
+ */
+export class MeshSdfAssetLoader implements AssetLoader<MeshSdf> {
+ readonly type = 'meshSdf';
+ readonly extensions = ['.esmeshsdf'];
+
+ async load(path: string, ctx: LoadContext): Promise<MeshSdf> {
+ const bytes = new Uint8Array(await ctx.loadBinary(ctx.catalog.getBuildPath(path)));
+ try {
+ return decodeMeshSdf(bytes);
+ } catch (err) {
+ throw new Error(`${path}: ${err instanceof Error ? err.message : String(err)}`);
+ }
+ }
+
+ unload(): void {
+ // Decoded distances are ordinary arrays the caller may still hold.
+ }
+}
diff --git a/sdk/src/gi/globalSdf.ts b/sdk/src/gi/globalSdf.ts
new file mode 100644
index 000000000..4d970e214
--- /dev/null
+++ b/sdk/src/gi/globalSdf.ts
@@ -0,0 +1,298 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file globalSdf.ts
+ * @brief The scene's distance field: mesh fields composed into clipmaps that follow the camera (docs/GI_LUMEN_DESIGN.md, 3.2).
+ *
+ * @details Each level is a cube of cells addressed toroidally, so when the window moves only the slabs that came into it are rebuilt.
+ * A cell holds the distance from its centre to the nearest surface, negative inside, clamped to +-`reach` (a cell further
+ * than that from everything is "empty for `reach`", which is all a trace needs of it and is why the cube can be small).
+ *
+ * The composition is CPU work on the cells an instance touches. A static scene pays it once, at load; a moved instance pays
+ * the cells under its old and new boxes. Its result is one `Float32Array` per level, laid out for a storage buffer; the
+ * trace in {@link GLOBAL_SDF_WGSL} reads that and `sphereTrace` below is its twin, so the same rays can be checked on the CPU.
+ *
+ * An instance is uniformly scaled: the field is a distance, and a non-uniform scale does not preserve one.
+ */
+import { sampleMeshSdf, type MeshSdf } from './meshSdfFormat';
+
+export interface SdfInstance {
+ /** Stable identity: moving an instance is `update` with the same id. */
+ id: number;
+ sdf: MeshSdf;
+ /** Column-major 4x4, local to world. Rotation, translation and one uniform scale. */
+ worldFromLocal: ArrayLike<number>;
+}
+
+export interface GlobalSdfLevel {
+ /** Cells along each axis (a power of two). */
+ dim: number;
+ /** World size of one cell. */
+ cell: number;
+}
+
+interface Placed {
+ instance: SdfInstance;
+ scale: number;
+ /** World from local, and its inverse (rigid, so a transpose and a negated translation, over the scale). */
+ inverse: Float64Array;
+ min: [number, number, number];
+ max: [number, number, number];
+}
+
+interface Level {
+ dim: number;
+ cell: number;
+ /** The window's first cell, in whole cells of the level. */
+ origin: [number, number, number];
+ data: Float32Array;
+}
+
+export class GlobalSdf {
+ readonly levels: Level[];
+ /** How far a cell remembers a surface: +-reach cells of the level. */
+ static readonly REACH_CELLS = 6;
+ private placed_ = new Map<number, Placed>();
+
+ 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) };
+ level.data.fill(l.cell * GlobalSdf.REACH_CELLS);
+ return level;
+ });
+ }
+
+ 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 {
+ 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; }
+ // One slab per axis that moved: [new edge].
+ for (let k = 0; k < 3; k++) {
+ const m = move[k]!;
+ if (m === 0) continue;
+ 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);
+ }
+ }
+ }
+
+ /** Adds an instance, or moves/replaces the one with its id. */
+ update(instance: SdfInstance): void {
+ const previous = this.placed_.get(instance.id);
+ const placed = this.place_(instance);
+ this.placed_.set(instance.id, placed);
+ for (const level of this.levels) {
+ if (previous) this.rebuildBox_(level, previous.min, previous.max);
+ this.rebuildBox_(level, placed.min, placed.max);
+ }
+ }
+
+ remove(id: number): void {
+ const previous = this.placed_.get(id);
+ if (!previous) return;
+ this.placed_.delete(id);
+ for (const level of this.levels) this.rebuildBox_(level, previous.min, previous.max);
+ }
+
+ /** The finest level that holds `p` away from its border, or null. */
+ levelAt(p: readonly [number, number, number], margin = 2): Level | null {
+ for (const level of this.levels) {
+ let inside = true;
+ for (let k = 0; k < 3; k++) {
+ const c = p[k]! / level.cell - level.origin[k]!;
+ if (c < margin || c > level.dim - margin) { inside = false; break; }
+ }
+ if (inside) return level;
+ }
+ return null;
+ }
+
+ /** The field at a world point: trilinear in the finest level that holds it; null outside every window. */
+ sample(p: readonly [number, number, number]): number | null {
+ const level = this.levelAt(p, 1);
+ return level ? this.sampleLevel_(level, p) : null;
+ }
+
+ /**
+ * Sphere trace from `origin` along unit `dir`. Returns the distance to the first surface within `maxT`, or null when the ray reaches
+ * `maxT` (or leaves every window) without one. A step is the field's value, never less than a fraction of a cell, so a ray
+ * grazing a surface still moves; a hit is a value under `hitFraction` of the cell.
+ */
+ sphereTrace(origin: readonly [number, number, number], dir: readonly [number, number, number], maxT: number, hitFraction = 0.25): number | null {
+ let t = 0;
+ for (let i = 0; i < 256 && t < maxT; i++) {
+ const p: [number, number, number] = [origin[0]! + dir[0]! * t, origin[1]! + dir[1]! * t, origin[2]! + dir[2]! * t];
+ const level = this.levelAt(p, 1);
+ if (!level) return null;
+ const d = this.sampleLevel_(level, p);
+ if (d < level.cell * hitFraction) return t;
+ t += Math.max(d, level.cell * 0.25);
+ }
+ return null;
+ }
+
+ /** Whether anything stands between two points (a short hop back from the target, so the surface the target is on does not count). */
+ occluded(a: readonly [number, number, number], b: readonly [number, number, number]): boolean {
+ const d = [b[0]! - a[0]!, b[1]! - a[1]!, b[2]! - a[2]!], length = Math.hypot(...d);
+ if (length < 1e-6) return false;
+ const hit = this.sphereTrace(a, d.map((v) => v / length) as [number, number, number], length * 0.98);
+ return hit !== null;
+ }
+
+ private place_(instance: SdfInstance): Placed {
+ const m = instance.worldFromLocal;
+ const scale = Math.hypot(m[0]!, m[1]!, m[2]!);
+ // Rigid part: columns / scale. Inverse = [R^T | -R^T t] / scale.
+ const r = [0, 1, 2].map((c) => [0, 1, 2].map((row) => m[c * 4 + row]! / scale));
+ const t = [m[12]!, m[13]!, m[14]!];
+ const inverse = new Float64Array(16);
+ for (let row = 0; row < 3; row++) {
+ for (let col = 0; col < 3; col++) inverse[col * 4 + row] = r[row]![col]! / scale;
+ inverse[12 + row] = -(r[row]![0]! * t[0]! + r[row]![1]! * t[1]! + r[row]![2]! * t[2]!) / scale;
+ }
+ inverse[15] = 1;
+ const { sdf } = instance;
+ const lo = sdf.origin, hi = [0, 1, 2].map((k) => sdf.origin[k]! + sdf.dims[k]! * sdf.cell);
+ const min: [number, number, number] = [Infinity, Infinity, Infinity], max: [number, number, number] = [-Infinity, -Infinity, -Infinity];
+ for (let c = 0; c < 8; c++) {
+ const local = [c & 1 ? hi[0]! : lo[0], c & 2 ? hi[1]! : lo[1], c & 4 ? hi[2]! : lo[2]];
+ for (let k = 0; k < 3; k++) {
+ const w = m[k]! * local[0]! + m[4 + k]! * local[1]! + m[8 + k]! * local[2]! + m[12 + k]!;
+ min[k] = Math.min(min[k], w); max[k] = Math.max(max[k], w);
+ }
+ }
+ return { instance, scale, inverse, min, max };
+ }
+
+ private distanceTo_(placed: Placed, p: readonly [number, number, number]): number {
+ const i = placed.inverse;
+ const local: [number, number, number] = [
+ i[0]! * p[0]! + i[4]! * p[1]! + i[8]! * p[2]! + i[12]!,
+ i[1]! * p[0]! + i[5]! * p[1]! + i[9]! * p[2]! + i[13]!,
+ i[2]! * p[0]! + i[6]! * p[1]! + i[10]! * p[2]! + i[14]!,
+ ];
+ return sampleMeshSdf(placed.instance.sdf, local) * placed.scale;
+ }
+
+ private rebuildBox_(level: Level, min: readonly number[], max: readonly number[]): void {
+ const reach = this.reach(level);
+ const lo = [0, 1, 2].map((k) => Math.floor((min[k]! - reach) / level.cell)) as [number, number, number];
+ const hi = [0, 1, 2].map((k) => Math.ceil((max[k]! + reach) / level.cell)) as [number, number, number];
+ this.rebuild_(level, lo, hi);
+ }
+
+ /** Rebuilds the cells [lo, hi) (in level cells) that are inside the window from every instance that reaches them. */
+ 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;
+ const reach = this.reach(level);
+ const near: Placed[] = [];
+ for (const placed of this.placed_.values()) {
+ let overlaps = true;
+ for (let k = 0; k < 3; k++) {
+ if (placed.max[k]! + reach < a[k]! * level.cell || placed.min[k]! - reach > b[k]! * level.cell) { overlaps = false; break; }
+ }
+ if (overlaps) near.push(placed);
+ }
+ const mask = level.dim - 1;
+ 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;
+ for (const placed of near) d = Math.min(d, this.distanceTo_(placed, p));
+ level.data[(x & mask) + (y & mask) * level.dim + (z & mask) * level.dim * level.dim] = Math.max(d, -reach);
+ }
+ }
+
+ private sampleLevel_(level: Level, p: readonly [number, number, number]): number {
+ const mask = level.dim - 1;
+ const g = [0, 1, 2].map((k) => p[k]! / level.cell - 0.5);
+ const i0 = g.map(Math.floor), f = g.map((v, k) => v - i0[k]!);
+ let sum = 0;
+ for (let c = 0; c < 8; c++) {
+ const dx = c & 1, dy = (c >> 1) & 1, dz = (c >> 2) & 1;
+ const w = (dx ? f[0]! : 1 - f[0]!) * (dy ? f[1]! : 1 - f[1]!) * (dz ? f[2]! : 1 - f[2]!);
+ sum += w * level.data[((i0[0]! + dx) & mask) + ((i0[1]! + dy) & mask) * level.dim + ((i0[2]! + dz) & mask) * level.dim * level.dim]!;
+ }
+ return sum;
+ }
+}
+
+/**
+ * The trace as the GPU runs it: the same walk as `GlobalSdf.sphereTrace`, over the levels as one storage array (each level's cells in
+ * toroidal order, one after another). `sdfLevels[i]` says where level i starts and how it is addressed. Included by a kernel that
+ * declares `sdfData : array<f32>` and `sdfParams`.
+ */
+export const GLOBAL_SDF_WGSL = /* wgsl */ `
+struct SdfLevel {
+ origin : vec3i, // the window's first cell
+ dim : u32, // cells per axis, a power of two
+ cell : f32, // world size of one cell
+ offset : u32, // where this level starts in sdfData
+ pad0 : u32,
+ pad1 : u32,
+};
+struct SdfParams {
+ count : u32,
+ pad0 : u32,
+ pad1 : u32,
+ pad2 : u32,
+ levels : array<SdfLevel, 4>,
+};
+
+fn sdfCell(level : SdfLevel, c : vec3i) -> f32 {
+ let m = vec3i(i32(level.dim) - 1);
+ let w = c & m;
+ return sdfData[level.offset + u32(w.x) + u32(w.y) * level.dim + u32(w.z) * level.dim * level.dim];
+}
+
+fn sdfLevelSample(level : SdfLevel, p : vec3f) -> f32 {
+ let g = p / level.cell - vec3f(0.5);
+ let i0 = vec3i(floor(g));
+ let f = g - vec3f(i0);
+ let c000 = sdfCell(level, i0);
+ let c100 = sdfCell(level, i0 + vec3i(1, 0, 0));
+ let c010 = sdfCell(level, i0 + vec3i(0, 1, 0));
+ let c110 = sdfCell(level, i0 + vec3i(1, 1, 0));
+ let c001 = sdfCell(level, i0 + vec3i(0, 0, 1));
+ let c101 = sdfCell(level, i0 + vec3i(1, 0, 1));
+ let c011 = sdfCell(level, i0 + vec3i(0, 1, 1));
+ let c111 = sdfCell(level, i0 + vec3i(1, 1, 1));
+ return mix(mix(mix(c000, c100, f.x), mix(c010, c110, f.x), f.y), mix(mix(c001, c101, f.x), mix(c011, c111, f.x), f.y), f.z);
+}
+
+// The finest level holding p at least one cell from its border, or -1.
+fn sdfLevelAt(p : vec3f) -> i32 {
+ for (var i = 0u; i < sdfParams.count; i = i + 1u) {
+ let level = sdfParams.levels[i];
+ let c = p / level.cell - vec3f(level.origin);
+ if (all(c >= vec3f(1.0)) && all(c <= vec3f(f32(level.dim) - 1.0))) { return i32(i); }
+ }
+ return -1;
+}
+
+// Distance along dir to the first surface within maxT, or -1.
+fn sdfTrace(origin : vec3f, dir : vec3f, maxT : f32) -> f32 {
+ var t = 0.0;
+ for (var i = 0; i < 128; i = i + 1) {
+ if (t >= maxT) { return -1.0; }
+ let p = origin + dir * t;
+ let li = sdfLevelAt(p);
+ if (li < 0) { return -1.0; }
+ let level = sdfParams.levels[li];
+ let d = sdfLevelSample(level, p);
+ if (d < level.cell * 0.25) { return t; }
+ t = t + max(d, level.cell * 0.25);
+ }
+ return -1.0;
+}
+`;
diff --git a/sdk/src/gi/meshSdfFormat.ts b/sdk/src/gi/meshSdfFormat.ts
new file mode 100644
index 000000000..5ac37e8fe
--- /dev/null
+++ b/sdk/src/gi/meshSdfFormat.ts
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file meshSdfFormat.ts
+ * @brief `.esmeshsdf`: a mesh's baked signed distance field, and how to read one (docs/GI_LUMEN_DESIGN.md, 3.1).
+ *
+ * @details The baker is the pipeline's (pipeline/src/assets/meshSdf.ts); the runtime reads it here. Distances are in the mesh's own
+ * units, negative inside, already grown by `inflate` so a wall thinner than a cell is still a body.
+ */
+
+export interface MeshSdf {
+ dims: [number, number, number];
+ /** Edge of one cell, in mesh units. */
+ cell: number;
+ /** The world-space position of the first cell's CORNER; cell (i, j, k) is centred at `origin + (i + 0.5, j + 0.5, k + 0.5) * cell`. */
+ origin: [number, number, number];
+ /** Signed distance per cell, x fastest, in mesh units. */
+ distance: Float32Array;
+ /** The growth already applied, in mesh units. */
+ inflate: number;
+}
+
+/** The value a half-float holds nearest to `v` (IEEE 754 binary16, round to nearest even, no NaN). */
+export function toHalf(v: number): number {
+ if (!(Math.abs(v) < 65504)) return v < 0 ? 0xfbff : 0x7bff;
+ const f = new Float32Array([v]), u = new Uint32Array(f.buffer)[0]!;
+ const sign = (u >>> 16) & 0x8000;
+ let exp = ((u >>> 23) & 0xff) - 127 + 15;
+ let man = u & 0x7fffff;
+ if (exp <= 0) {
+ if (exp < -10) return sign;
+ man = (man | 0x800000) >>> (1 - exp);
+ return sign | ((man + 0x1000) >>> 13);
+ }
+ const rounded = (man + 0xfff + ((man >>> 13) & 1)) >>> 13;
+ return sign | (((exp << 10) + rounded) & 0xffff);
+}
+
+export function fromHalf(h: number): number {
+ const sign = h & 0x8000 ? -1 : 1, exp = (h >>> 10) & 0x1f, man = h & 0x3ff;
+ if (exp === 0) return sign * man * 2 ** -24;
+ if (exp === 31) return sign * 65504;
+ return sign * (1 + man / 1024) * 2 ** (exp - 15);
+}
+
+/** `.esmeshsdf`: 'ESDF', version 1, dims x3 (u32), cell, origin x3, inflate (f32), then the distances as half floats, x fastest. */
+export const MESH_SDF_MAGIC = 0x46445345;
+export const MESH_SDF_HEADER_BYTES = 4 * (2 + 3 + 1 + 3 + 1);
+
+export function encodeMeshSdf(sdf: MeshSdf): Uint8Array {
+ const count = sdf.distance.length, bytes = new Uint8Array(MESH_SDF_HEADER_BYTES + count * 2 + (count & 1) * 2);
+ const view = new DataView(bytes.buffer);
+ let o = 0;
+ const u32 = (v: number) => { view.setUint32(o, v, true); o += 4; };
+ const f32 = (v: number) => { view.setFloat32(o, v, true); o += 4; };
+ u32(MESH_SDF_MAGIC); u32(1);
+ sdf.dims.forEach(u32);
+ f32(sdf.cell);
+ sdf.origin.forEach(f32);
+ f32(sdf.inflate);
+ for (let i = 0; i < count; i++) view.setUint16(o + i * 2, toHalf(sdf.distance[i]!), true);
+ return bytes;
+}
+
+export function decodeMeshSdf(bytes: Uint8Array): MeshSdf {
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (view.getUint32(0, true) !== MESH_SDF_MAGIC) throw new Error('not a mesh distance field');
+ if (view.getUint32(4, true) !== 1) throw new Error(`unsupported mesh distance field version ${view.getUint32(4, true)}`);
+ const dims: [number, number, number] = [view.getUint32(8, true), view.getUint32(12, true), view.getUint32(16, true)];
+ const cell = view.getFloat32(20, true);
+ const origin: [number, number, number] = [view.getFloat32(24, true), view.getFloat32(28, true), view.getFloat32(32, true)];
+ const inflate = view.getFloat32(36, true);
+ const count = dims[0] * dims[1] * dims[2], distance = new Float32Array(count);
+ for (let i = 0; i < count; i++) distance[i] = fromHalf(view.getUint16(MESH_SDF_HEADER_BYTES + i * 2, true));
+ return { dims, cell, origin, distance, inflate };
+}
+
+/**
+ * The field's value at a point: trilinear between cell centres inside the grid, and beyond its edge the edge value plus how far the point
+ * is from the grid (the nearest surface is at least that much further, so a trace may step that far).
+ */
+export function sampleMeshSdf(sdf: MeshSdf, point: readonly [number, number, number]): number {
+ const g = [0, 1, 2].map((k) => Math.min(Math.max((point[k]! - sdf.origin[k]!) / sdf.cell - 0.5, 0), sdf.dims[k]! - 1 - 1e-6));
+ const i0 = g.map(Math.floor) as number[], f = g.map((v, k) => v - i0[k]!);
+ const beyond = Math.hypot(...[0, 1, 2].map((k) => Math.max(sdf.origin[k]! + 0.5 * sdf.cell - point[k]!, point[k]! - (sdf.origin[k]! + (sdf.dims[k]! - 0.5) * sdf.cell), 0)));
+ const at = (x: number, y: number, z: number) => sdf.distance[x + y * sdf.dims[0] + z * sdf.dims[0] * sdf.dims[1]]!;
+ let sum = 0;
+ for (let c = 0; c < 8; c++) {
+ const dx = c & 1, dy = (c >> 1) & 1, dz = (c >> 2) & 1;
+ const w = (dx ? f[0]! : 1 - f[0]!) * (dy ? f[1]! : 1 - f[1]!) * (dz ? f[2]! : 1 - f[2]!);
+ sum += w * at(i0[0]! + dx, i0[1]! + dy, i0[2]! + dz);
+ }
+ return sum + beyond;
+}
diff --git a/sdk/tests/global-sdf.test.ts b/sdk/tests/global-sdf.test.ts
new file mode 100644
index 000000000..3a5dc41a1
--- /dev/null
+++ b/sdk/tests/global-sdf.test.ts
@@ -0,0 +1,104 @@
+import { describe, it, expect } from 'vitest';
+import { GlobalSdf, type SdfInstance } from '../src/gi/globalSdf';
+import type { MeshSdf } from '../src/gi/meshSdfFormat';
+
+/** A mesh field built from a closed-form distance, over [-half - pad, half + pad] in local units. */
+function analytic(distance: (p: [number, number, number]) => number, half: number, cell: number, inflate = 0): MeshSdf {
+ const pad = 2 * cell, n = Math.ceil((2 * half + 2 * pad) / cell);
+ const origin: [number, number, number] = [-half - pad, -half - pad, -half - pad];
+ const field = new Float32Array(n * n * n);
+ for (let z = 0; z < n; z++) for (let y = 0; y < n; y++) for (let x = 0; x < n; x++) {
+ field[x + y * n + z * n * n] = distance([origin[0] + (x + 0.5) * cell, origin[1] + (y + 0.5) * cell, origin[2] + (z + 0.5) * cell]) - inflate;
+ }
+ return { dims: [n, n, n], cell, origin, distance: field, inflate };
+}
+const sphereSdf = (r: number, cell: number) => analytic((p) => Math.hypot(...p) - r, r, cell);
+const boxDistance = (p: number[], h: number[]) => {
+ const q = p.map((v, k) => Math.abs(v) - h[k]!);
+ return Math.hypot(...q.map((v) => Math.max(v, 0))) + Math.min(Math.max(...q), 0);
+};
+const matrix = (t: [number, number, number], s = 1): number[] => [s, 0, 0, 0, 0, s, 0, 0, 0, 0, s, 0, t[0], t[1], t[2], 1];
+const instance = (id: number, sdf: MeshSdf, t: [number, number, number], s = 1): SdfInstance => ({ id, sdf, worldFromLocal: matrix(t, s) });
+const field = () => new GlobalSdf([{ dim: 64, cell: 0.25 }, { dim: 64, cell: 1 }]);
+
+describe('the scene distance field', () => {
+ it('reads a placed, scaled sphere as its closed-form distance', () => {
+ const g = field();
+ g.setCenter([5, 0, 0]);
+ g.update(instance(1, sphereSdf(1, 0.1), [5, 0, 0], 2)); // radius 2 in the world
+ for (const p of [[5, 0, 0], [6, 0.5, 0], [7.4, 0, 0], [5, 3, 0.5]] as const) {
+ const truth = Math.hypot(p[0] - 5, p[1], p[2]) - 2;
+ // A cell remembers a surface only to +-6 cells (1.5 here), the rest reads as that far.
+ expect(Math.abs(g.sample(p)! - Math.min(Math.max(truth, -1.5), 1.5))).toBeLessThan(0.15);
+ }
+ });
+
+ it('never reads further than the truth outside the box of an instance (a trace may step what it reads)', () => {
+ const g = field();
+ g.setCenter([5, 0, 0]);
+ g.update(instance(1, sphereSdf(1, 0.1), [5, 0, 0], 2));
+ for (const p of [[2.5, -1, 1], [8, 2, 2], [5, 4, 1]] as const) expect(g.sample(p)!).toBeLessThanOrEqual(Math.hypot(p[0] - 5, p[1], p[2]) - 2 + 0.15);
+ });
+
+ it('traces a ray to the sphere it hits, and past one it misses', () => {
+ const g = field();
+ g.setCenter([0, 0, 0]);
+ g.update(instance(1, sphereSdf(1, 0.1), [0, 0, 6]));
+ const hit = g.sphereTrace([0, 0, 0], [0, 0, 1], 20)!;
+ expect(Math.abs(hit - 5)).toBeLessThan(0.2);
+ expect(g.sphereTrace([0, 3, 0], [0, 0, 1], 20)).toBeNull();
+ });
+
+ it('treats a wall thinner than a cell as a wall: a ray across it is blocked, the room beside it is not', () => {
+ const cell = 0.2, halfs = [3, 2, 0.05];
+ const wall = analytic((p) => boxDistance(p, halfs), 3, cell, 0.5 * cell); // a 0.1 thick wall, grown by half a cell as the baker does
+ const g = field();
+ g.setCenter([0, 0, 0]);
+ g.update(instance(1, wall, [0, 0, 0]));
+ expect(g.occluded([0, 0, -1], [0, 0, 1])).toBe(true);
+ expect(g.occluded([0, 0, 1], [0, 0, 3])).toBe(false);
+ expect(g.occluded([4.5, 0, -1], [4.5, 0, 1])).toBe(false); // round the end of it
+ });
+
+ it('forgets an instance that moved or was removed', () => {
+ const g = field();
+ g.setCenter([0, 0, 0]);
+ g.update(instance(1, sphereSdf(1, 0.1), [0, 0, 5]));
+ expect(g.sphereTrace([0, 0, 0], [0, 0, 1], 20)).not.toBeNull();
+ g.update(instance(1, sphereSdf(1, 0.1), [0, 6, 5]));
+ expect(g.sphereTrace([0, 0, 0], [0, 0, 1], 20)).toBeNull();
+ expect(g.sphereTrace([0, 0, 0], [0, 1, 0.8], 20)).not.toBeNull();
+ g.remove(1);
+ expect(g.sphereTrace([0, 0, 0], [0, 1, 0.8], 20)).toBeNull();
+ });
+
+ it('rebuilds only what came into view when the window moves, and agrees with a field built there', () => {
+ const stepped = field();
+ stepped.setCenter([0, 0, 0]);
+ stepped.update(instance(1, sphereSdf(1, 0.1), [3, 0, 0]));
+ stepped.update(instance(2, sphereSdf(1, 0.1), [12, 1, 0]));
+ for (const c of [[2, 0, 0], [9, 0, 0], [9, 3, 1], [-4, 0, 0]] as const) stepped.setCenter([...c]);
+ const fresh = field();
+ fresh.setCenter([-4, 0, 0]);
+ fresh.update(instance(1, sphereSdf(1, 0.1), [3, 0, 0]));
+ fresh.update(instance(2, sphereSdf(1, 0.1), [12, 1, 0]));
+ for (const p of [[0, 0, 0], [3, 0.5, 0], [-10, 2, 3], [8, 1, 0]] as const) {
+ const a = stepped.sample(p), b = fresh.sample(p);
+ expect(a).not.toBeNull();
+ expect(Math.abs(a! - b!)).toBeLessThan(1e-4);
+ }
+ });
+
+ 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]);
+ g.update(instance(1, sphereSdf(1, 0.1), [30, 0, 0]));
+ expect(g.sphereTrace([0, 0, 0], [1, 0, 0], 60)).not.toBeNull();
+ expect(g.levelAt([40, 0, 0])).toBeNull();
+ expect(g.levelAt([10, 0, 0])).toBe(g.levels[1]);
+ });
+
+ it('refuses a level whose size is not a power of two', () => {
+ expect(() => new GlobalSdf([{ dim: 48, cell: 1 }])).toThrow();
+ });
+});
diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.js
index 40e82bd69..c02d09d50 100644
--- a/tools/assetMetaTable.js
+++ b/tools/assetMetaTable.js
@@ -87,6 +87,7 @@ export const EXT_TO_TYPE = Object.freeze({
'.esenv': 'environment',
'.esprobes': 'probeVolume',
'.esmesh': 'mesh',
+ '.esmeshsdf': 'meshSdf',
// A model as the steps that build it. Never shipped: saving one bakes the sibling
// `.esmesh`, and that is what a scene references. Typed for the same reason
// `.esmatgraph` is, and apart from `model` because nothing imports it.
diff --git a/tools/gi/check-sdf-wgsl.mjs b/tools/gi/check-sdf-wgsl.mjs
new file mode 100644
index 000000000..b6bd18012
--- /dev/null
+++ b/tools/gi/check-sdf-wgsl.mjs
@@ -0,0 +1,122 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * The scene distance field's trace (GLOBAL_SDF_WGSL in sdk/src/gi/globalSdf.ts) run on a real WebGPU device, headless, against the
+ * closed-form distance to a sphere: the WGSL has to compile, and its rays have to land where the maths says.
+ *
+ * node tools/gi/check-sdf-wgsl.mjs
+ *
+ * Exits 2 (not 1) when this machine offers no WebGPU adapter, so a caller can tell "could not run" from "ran and failed".
+ */
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import { pathToFileURL } from 'node:url';
+
+const root = path.resolve(import.meta.dirname, '../..');
+const source = readFileSync(path.join(root, 'sdk/src/gi/globalSdf.ts'), 'utf8');
+const wgsl = source.match(/GLOBAL_SDF_WGSL = \/\* wgsl \*\/ `([\s\S]*?)`;/)?.[1];
+if (!wgsl) throw new Error('GLOBAL_SDF_WGSL not found');
+
+// Two levels: fine (dim 32, cell 0.25: 8 across) and coarse (dim 32, cell 1: 32 across), both centred on the origin.
+const levels = [{ dim: 32, cell: 0.25 }, { dim: 32, cell: 1 }];
+const sphere = { c: [3, 0.2, 0.1], r: 1.5 };
+const reachOf = (cell) => cell * 6;
+const data = [];
+const params = new ArrayBuffer(16 + 4 * 32);
+const pv = new DataView(params);
+pv.setUint32(0, levels.length, true);
+levels.forEach((l, i) => {
+ const origin = [0, 1, 2].map(() => Math.floor(0 / l.cell) - l.dim / 2);
+ const offset = data.length;
+ const cells = new Float32Array(l.dim ** 3);
+ const mask = l.dim - 1;
+ for (let z = origin[2]; z < origin[2] + l.dim; z++) for (let y = origin[1]; y < origin[1] + l.dim; y++) for (let x = origin[0]; x < origin[0] + l.dim; x++) {
+ const d = Math.hypot((x + 0.5) * l.cell - sphere.c[0], (y + 0.5) * l.cell - sphere.c[1], (z + 0.5) * l.cell - sphere.c[2]) - sphere.r;
+ cells[(x & mask) + (y & mask) * l.dim + (z & mask) * l.dim * l.dim] = Math.min(Math.max(d, -reachOf(l.cell)), reachOf(l.cell));
+ }
+ data.push(...cells);
+ const base = 16 + i * 32;
+ origin.forEach((o, k) => pv.setInt32(base + k * 4, o, true));
+ pv.setUint32(base + 12, l.dim, true);
+ pv.setFloat32(base + 16, l.cell, true);
+ pv.setUint32(base + 20, offset, true);
+});
+
+// Rays from the origin toward points around the sphere: some hit, some pass.
+const rays = [];
+const expected = [];
+for (let i = 0; i < 64; i++) {
+ const a = (i / 64) * Math.PI * 0.5 - 0.2, b = ((i * 7) % 64 / 64) * 0.8 - 0.4;
+ const dir = [Math.cos(a) * Math.cos(b), Math.sin(b) * 0.5, Math.sin(a) * Math.cos(b)];
+ const len = Math.hypot(...dir);
+ const d = dir.map((v) => v / len);
+ // Ray/sphere: |o + t d - c|^2 = r^2 with o = 0.
+ const oc = [-sphere.c[0], -sphere.c[1], -sphere.c[2]];
+ const bq = oc[0] * d[0] + oc[1] * d[1] + oc[2] * d[2], cq = oc[0] ** 2 + oc[1] ** 2 + oc[2] ** 2 - sphere.r ** 2, disc = bq * bq - cq;
+ expected.push(disc >= 0 && -bq - Math.sqrt(disc) > 0 ? -bq - Math.sqrt(disc) : -1);
+ rays.push(...d, 0);
+}
+
+const kernel = `
+@group(0) @binding(0) var<storage, read> sdfData : array<f32>;
+@group(0) @binding(1) var<uniform> sdfParams : SdfParams;
+@group(0) @binding(2) var<storage, read> rays : array<vec4f>;
+@group(0) @binding(3) var<storage, read_write> hits : array<f32>;
+${wgsl}
+@compute @workgroup_size(64)
+fn main(@builtin(global_invocation_id) id : vec3u) {
+ hits[id.x] = sdfTrace(vec3f(0.0), rays[id.x].xyz, 30.0);
+}`;
+
+const { chromium } = await import(pathToFileURL(path.join(root, 'node_modules/playwright/index.mjs')).href);
+const browser = await chromium.launch({ channel: 'chromium', headless: true, args: ['--enable-unsafe-webgpu', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader', '--mute-audio'] });
+try {
+ const page = await browser.newPage();
+ // WebGPU exists only in a secure context; a loopback address is one.
+ await page.route('http://127.0.0.1:9/', (route) => route.fulfill({ body: '<html></html>', contentType: 'text/html' }));
+ await page.goto('http://127.0.0.1:9/');
+ const result = await page.evaluate(async ({ kernel, data, params, rays }) => {
+ if (!navigator.gpu) return { error: 'no navigator.gpu' };
+ const adapter = await navigator.gpu.requestAdapter();
+ if (!adapter) return { error: 'no adapter' };
+ const device = await adapter.requestDevice();
+ const module = device.createShaderModule({ code: kernel });
+ const info = await module.getCompilationInfo();
+ const errors = info.messages.filter((m) => m.type === 'error').map((m) => `${m.lineNum}:${m.linePos} ${m.message}`);
+ if (errors.length) return { error: 'wgsl: ' + errors.join(' | ') };
+ const make = (usage, bytes) => { const b = device.createBuffer({ size: Math.max(bytes.byteLength, 16), usage: usage | GPUBufferUsage.COPY_DST }); device.queue.writeBuffer(b, 0, bytes); return b; };
+ const dataBuffer = make(GPUBufferUsage.STORAGE, new Float32Array(data));
+ const paramBuffer = make(GPUBufferUsage.UNIFORM, new Uint8Array(params));
+ const rayBuffer = make(GPUBufferUsage.STORAGE, new Float32Array(rays));
+ const count = rays.length / 4;
+ const out = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.STORAGE | GPUBufferUsage.COPY_SRC });
+ const read = device.createBuffer({ size: count * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ });
+ const pipeline = device.createComputePipeline({ layout: 'auto', compute: { module, entryPoint: 'main' } });
+ const group = device.createBindGroup({ layout: pipeline.getBindGroupLayout(0), entries: [dataBuffer, paramBuffer, rayBuffer, out].map((buffer, binding) => ({ binding, resource: { buffer } })) });
+ const encoder = device.createCommandEncoder();
+ const pass = encoder.beginComputePass();
+ pass.setPipeline(pipeline); pass.setBindGroup(0, group); pass.dispatchWorkgroups(Math.ceil(count / 64)); pass.end();
+ encoder.copyBufferToBuffer(out, 0, read, 0, count * 4);
+ device.queue.submit([encoder.finish()]);
+ await read.mapAsync(GPUMapMode.READ);
+ return { hits: Array.from(new Float32Array(read.getMappedRange().slice(0))) };
+ }, { kernel, data, params: Array.from(new Uint8Array(params)), rays });
+ if (result.error) {
+ console.error('check-sdf-wgsl:', result.error);
+ process.exit(result.error.startsWith('wgsl') ? 1 : 2);
+ }
+ let worst = 0, hitCount = 0, wrong = 0;
+ result.hits.forEach((h, i) => {
+ const e = expected[i];
+ if (e < 0 && h < 0) return;
+ if ((e < 0) !== (h < 0)) { wrong++; return; }
+ hitCount++;
+ worst = Math.max(worst, Math.abs(h - e));
+ });
+ console.log(`rays ${result.hits.length}, hits ${hitCount}, hit/miss disagreements ${wrong}, worst distance error ${worst.toFixed(3)}`);
+ // A trace stops within a quarter of a cell of the surface: 0.0625 on the fine level, 0.25 on the coarse one.
+ if (wrong > 2 || worst > 0.3 || hitCount < 8) { console.error('check-sdf-wgsl: FAILED'); process.exit(1); }
+ console.log('check-sdf-wgsl: passed');
+} finally {
+ await browser.close();
+}