Skip to content

3D engine that AI agents drive

Pack baked lightmaps into crucible pack (#2178)

Nguyen Xuan Anb2e3f4c7cbf7
diff --git a/changes/2178-lightmaps.md b/changes/2178-lightmaps.md
new file mode 100644
index 00000000..1070e96f
--- /dev/null
+++ b/changes/2178-lightmaps.md
@@ -0,0 +1 @@
+- `crucible pack` now carries a recipe's baked lightmaps: the bake runs in Node at pack time, the texels travel as bytes, and `<crucible-scene>` draws them with no bake code and no tracing on the page; a bake over 262,144 texels is refused with the field to lower (#2178)
diff --git a/changes/2178-lightmaps.size.md b/changes/2178-lightmaps.size.md
new file mode 100644
index 00000000..61d476fc
--- /dev/null
+++ b/changes/2178-lightmaps.size.md
@@ -0,0 +1 @@
+- entry:crucible-scene: a packed lightmap is plain bytes, and the page must wrap them in the ImageData the renderer uploads (188 bytes gzip); without it a baked pack fails with a texImage2D error in Chrome.
diff --git a/docs/pack.md b/docs/pack.md
index 1bc96db8..1fa5932f 100644
--- a/docs/pack.md
+++ b/docs/pack.md
@@ -2,7 +2,7 @@
`crucible pack` compiles a recipe (`format: "crucible.scene"`) in Node into a compact data file, so a web page loads the renderer and the data but not the recipe compiler. The page uses a `<crucible-scene>` element: it shows a poster picture first, then swaps in live 3D when the scene is ready.
-This is slice 1 of #2178. It packs a still scene. Scroll, hover and click triggers, and baked lightmaps, come in later slices.
+This is slice 1 of #2178. It packs a still scene. Scroll, hover and click triggers come in later slices.
## Pack a scene
@@ -36,6 +36,12 @@ Packing the same recipe twice writes the same `scene.pack` bytes.
`crucible-scene.js` imports no `agent-scene` module. `tests/scene-pack.test.js` checks the import graph.
+## Baked light
+
+A recipe `bake` section runs when you pack, in Node. The lightmaps it writes (one texture per part, one byte per channel) travel in `scene.pack`, and the page draws them: it traces no ray and loads no bake code.
+
+A pack carries at most 262,144 lightmap texels (1 MB of raw bytes), a quarter of what a recipe build may trace, because the page downloads every texel. Past that, pack stops and names `bake.texelsPerUnit`: lower it, set `bake.preset` to `"draft"`, or bake fewer and smaller parts.
+
## What a pack refuses
Pack names the recipe field and what to change. For now it refuses `motion`, `timeline`, `physics`, `cloth`, `particles`, `game`, `postPasses`, `armatures`, `environment.sky`, `environment.hdri`, cascaded shadows, area lights, line art, material snippets and procedural material patterns. Scenes light with `environment.setup`. The automatic floor is not drawn: put a floor in the recipe.
@@ -51,3 +57,14 @@ Measured on `public/recipes/view-transform.json` (a lamp, six parts), Chrome, gz
| Total | 232,182 B | 228,641 B |
The JavaScript halves. The data does not shrink for this scene, because the baked reflection probes of its two metal parts are 196 KB before gzip. A scene without baked probes pays much less data.
+
+A baked room (`tests/fixtures/pack-baked-room.recipe.json` with `bake.preset` set to `"standard"`: six walls, a block, a ball and one lamp; 15,568 lightmap texels), 800 by 600 in GPU Chrome, gzip -9 of each file the page downloaded. This recipe build is bundled with esbuild and every agent-scene module, so its JavaScript is not comparable with the lamp table above:
+
+| | Recipe build | Packed bundle |
+| --- | --- | --- |
+| JavaScript | 644,298 B | 110,728 B |
+| Data | the recipe JSON, 552 B | `scene.pack`, 76,502 B |
+| Total | 644,850 B | 187,230 B |
+| Bake on the page | about 3.8 s of ray tracing in Node | none |
+
+The two stills are pixel identical (RMSE 0, no pixel differs).
diff --git a/src/crucible-scene.js b/src/crucible-scene.js
index 80ffc61c..e45d1555 100644
--- a/src/crucible-scene.js
+++ b/src/crucible-scene.js
@@ -3,6 +3,7 @@
// agent-scene module: the recipe was compiled ahead of time, so the page pays for the renderer and nothing else.
import { decodePack } from './scene-pack-format.js';
import { loadPackShaderModules } from './scene-pack-shaders.js';
+import { partsWithImageData } from './scene-pack-images.js';
export const SCENE_STATES = Object.freeze(['loading', 'live', 'error']);
@@ -40,7 +41,8 @@ async function createLiveRenderer(canvas, scene) {
showBackground: scene.environment.world,
}),
};
- const renderer = new CrucibleRenderer(canvas, scene.parts, {
+ // Baked lightmaps arrive as plain bytes; the renderer uploads ImageData.
+ const renderer = new CrucibleRenderer(canvas, partsWithImageData(scene.parts), {
ground: false,
hdr: true,
depth: true,
diff --git a/src/scene-pack-images.js b/src/scene-pack-images.js
new file mode 100644
index 00000000..d0883e0a
--- /dev/null
+++ b/src/scene-pack-images.js
@@ -0,0 +1,30 @@
+// Gives the texture images of a packed scene back the form the renderer uploads. The pack holds an image as plain
+// { width, height, data } (a baked lightmap is one byte per channel); a browser uploads ImageData, which the recipe build
+// makes through createImage in src/material-texture-kit.js. This module imports nothing, so the runtime stays light.
+
+function isPackedImage(value) {
+ return value !== null && typeof value === 'object' && value.data instanceof Uint8ClampedArray
+ && Number.isInteger(value.width) && Number.isInteger(value.height);
+}
+
+function imageDataOf(image) {
+ return typeof ImageData === 'function' ? new ImageData(image.data, image.width, image.height) : image;
+}
+
+function materialWithImageData(material) {
+ let changed = null;
+ for (const [slot, texture] of Object.entries(material)) {
+ if (texture === null || typeof texture !== 'object' || !isPackedImage(texture.image)) continue;
+ changed ??= { ...material };
+ changed[slot] = { ...texture, image: imageDataOf(texture.image) };
+ }
+ return changed ?? material;
+}
+
+/** The parts with every packed texture image turned into ImageData (a part without textures is returned as it is). */
+export function partsWithImageData(parts) {
+ return parts.map(part => {
+ const material = part.material ? materialWithImageData(part.material) : part.material;
+ return material === part.material ? part : { ...part, material };
+ });
+}
diff --git a/src/scene-pack.js b/src/scene-pack.js
index 82f5b6fc..d1611daa 100644
--- a/src/scene-pack.js
+++ b/src/scene-pack.js
@@ -12,6 +12,11 @@ export const PACK_FILE_NAME = 'scene.pack';
export const PACK_RUNTIME_FILE_NAME = 'crucible-scene.js';
export const PACK_POSTER_EXTENSIONS = Object.freeze(['.webp', '.png', '.jpg', '.jpeg']);
const RECIPE_FORMAT = 'crucible.scene';
+// Lightmap texels one pack may carry: 262,144 is 1 MB of raw RGBA bytes. A recipe build may trace up to 1,000,000 texels,
+// but a page downloads every texel, so a pack holds a quarter of that.
+export const PACK_MAX_LIGHTMAP_TEXELS = 262_144;
+// The bake writes bounced light into the emissive slot (parts with their own emission use the light map slot) and sky visibility into the occlusion slot.
+const LIGHTMAP_SLOTS = Object.freeze(['emissiveMap', 'lightMap', 'occlusionMap']);
// Sections of a recipe that move or simulate. Slice 1 of #2178 packs the scene at time zero only.
const UNSUPPORTED_SECTIONS = Object.freeze(['motion', 'timeline', 'physics', 'cloth', 'particles', 'game', 'postPasses', 'armatures']);
@@ -46,12 +51,35 @@ export function validatePackRecipe(recipe) {
}
}
-/** Compiles a recipe to the bytes of a `.pack` file: its parts, camera, lighting and effects, ready for the runtime. */
-export async function compileRecipeToPack(recipe) {
+/** The texels of every baked light texture on the parts. */
+export function countLightmapTexels(parts) {
+ let texels = 0;
+ for (const part of parts) {
+ for (const slot of LIGHTMAP_SLOTS) {
+ const image = part.material?.[slot]?.image;
+ if (image) texels += image.width * image.height;
+ }
+ }
+ return texels;
+}
+
+function checkLightmapBudget(recipe, parts, maxLightmapTexels) {
+ const texels = countLightmapTexels(parts);
+ if (texels <= maxLightmapTexels) return;
+ const density = recipe.bake?.texelsPerUnit ?? recipe.bake?.preset ?? 'standard';
+ refuse(`recipe.bake.texelsPerUnit: the bake wrote ${texels} lightmap texels, over the ${maxLightmapTexels} one pack carries (the page downloads every texel). Lower bake.texelsPerUnit (now ${density}; 1 to 12), set bake.preset to "draft", or bake fewer and smaller parts.`);
+}
+
+/**
+ * Compiles a recipe to the bytes of a `.pack` file: its parts, camera, lighting and effects, ready for the runtime.
+ * A recipe `bake` runs here, in Node, and its lightmaps travel in the pack as bytes: the page never traces.
+ */
+export async function compileRecipeToPack(recipe, { maxLightmapTexels = PACK_MAX_LIGHTMAP_TEXELS } = {}) {
validatePackRecipe(recipe);
await loadAllAgentSceneModules();
const scene = createAgentScene(recipe);
const environment = scene.environment;
+ if (recipe.bake) checkLightmapBudget(recipe, scene.parts, maxLightmapTexels);
return encodePack({
shaderModules: agentSceneModulesNeeded(recipe).filter(name => Object.hasOwn(PACK_SHADER_MODULES, name)),
camera: scene.camera,
diff --git a/tests/fixtures/pack-baked-room.recipe.json b/tests/fixtures/pack-baked-room.recipe.json
new file mode 100644
index 00000000..e9ea3014
--- /dev/null
+++ b/tests/fixtures/pack-baked-room.recipe.json
@@ -0,0 +1,29 @@
+{
+ "format": "crucible.scene",
+ "schemaVersion": 1,
+ "geometries": [{ "id": "box", "type": "box", "bevel": 0 }, { "id": "ball", "type": "sphere" }],
+ "materials": [
+ { "id": "plaster", "color": [0.8, 0.78, 0.72], "roughness": 1 },
+ { "id": "red", "color": [0.75, 0.12, 0.1], "roughness": 0.9 },
+ { "id": "green", "color": [0.15, 0.6, 0.2], "roughness": 0.9 }
+ ],
+ "nodes": [
+ { "id": "floor", "geometry": "box", "material": "plaster", "translation": [0, -0.1, 0], "scale": [6, 0.2, 6] },
+ { "id": "ceiling", "geometry": "box", "material": "plaster", "translation": [0, 3.1, 0], "scale": [6, 0.2, 6] },
+ { "id": "back", "geometry": "box", "material": "plaster", "translation": [0, 1.5, -3.1], "scale": [6.4, 3.2, 0.2] },
+ { "id": "left", "geometry": "box", "material": "red", "translation": [-3.1, 1.5, 0], "scale": [0.2, 3.2, 6] },
+ { "id": "right", "geometry": "box", "material": "green", "translation": [3.1, 1.5, 0], "scale": [0.2, 3.2, 6] },
+ { "id": "front", "geometry": "box", "material": "plaster", "translation": [0, 1.5, 3.1], "scale": [6.4, 3.2, 0.2] },
+ { "id": "block", "geometry": "box", "material": "plaster", "translation": [-1, 0.6, -0.6], "scale": [1.2, 1.2, 1.2] },
+ { "id": "ball", "geometry": "ball", "material": "plaster", "translation": [1.2, 0.5, 0.4], "scale": [1, 1, 1] }
+ ],
+ "camera": { "eye": [0, 1.5, 2.9], "target": [0, 1.3, -1], "fov": 70 },
+ "environment": {
+ "setup": "studio",
+ "environmentIntensity": 0.05,
+ "keyIntensity": 0,
+ "fillIntensity": 0,
+ "pointLights": [{ "position": [0, 2.8, 0], "color": [1, 0.85, 0.65], "intensity": 18, "radius": 0.1, "range": 9 }]
+ },
+ "bake": { "preset": "draft", "probes": false }
+}
diff --git a/tests/scene-pack-lightmaps.test.js b/tests/scene-pack-lightmaps.test.js
new file mode 100644
index 00000000..0867db7e
--- /dev/null
+++ b/tests/scene-pack-lightmaps.test.js
@@ -0,0 +1,98 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { build } from 'esbuild';
+import { createAgentScene, loadAllAgentSceneModules } from '../src/agent-scene.js';
+import { decodePack } from '../src/scene-pack-format.js';
+import { partsWithImageData } from '../src/scene-pack-images.js';
+import { compileRecipeToPack, countLightmapTexels, PACK_MAX_LIGHTMAP_TEXELS, validatePackRecipe } from '../src/scene-pack.js';
+
+function bakedRoomRecipe() {
+ return JSON.parse(readFileSync(new URL('./fixtures/pack-baked-room.recipe.json', import.meta.url), 'utf8'));
+}
+
+function lightmapOf(part) {
+ return part.material.emissiveMap ?? part.material.lightMap;
+}
+
+test('a packed baked room carries the same lightmap texels as the recipe build, and the page needs no bake', async () => {
+ await loadAllAgentSceneModules();
+ const live = createAgentScene(bakedRoomRecipe());
+ const packed = decodePack(await compileRecipeToPack(bakedRoomRecipe()));
+ assert.equal(packed.parts.length, live.parts.length);
+ assert.ok(countLightmapTexels(live.parts) > 0, 'the fixture bakes light');
+ live.parts.forEach((part, index) => {
+ const expected = lightmapOf(part);
+ const stored = lightmapOf(packed.parts[index]);
+ assert.ok(stored, `${part.name} keeps its lightmap`);
+ assert.equal(stored.image.width, expected.image.width);
+ assert.equal(stored.image.height, expected.image.height);
+ assert.equal(stored.colorSpace, expected.colorSpace);
+ assert.ok(stored.image.data instanceof Uint8ClampedArray, 'texels stay one byte per channel');
+ assert.deepEqual(Buffer.from(stored.image.data), Buffer.from(expected.image.data), `${part.name} texels`);
+ assert.equal(packed.parts[index].material.emission, part.material.emission, `${part.name} keeps the lightmap scale`);
+ assert.deepEqual([...packed.parts[index].geometry.uvs], [...part.geometry.uvs], `${part.name} keeps the lightmap UVs`);
+ });
+});
+
+test('packing a baked recipe twice gives the same bytes', async () => {
+ const first = await compileRecipeToPack(bakedRoomRecipe());
+ const second = await compileRecipeToPack(bakedRoomRecipe());
+ assert.deepEqual(Buffer.from(first), Buffer.from(second));
+});
+
+test('a recipe without a bake packs no lightmap texels', async () => {
+ const recipe = bakedRoomRecipe();
+ delete recipe.bake;
+ const packed = decodePack(await compileRecipeToPack(recipe));
+ assert.equal(countLightmapTexels(packed.parts), 0);
+});
+
+test('a bake over the texel budget is refused with the field and what to lower', async () => {
+ const baked = decodePack(await compileRecipeToPack(bakedRoomRecipe()));
+ const texels = countLightmapTexels(baked.parts);
+ assert.ok(texels < PACK_MAX_LIGHTMAP_TEXELS, 'the fixture fits the default budget');
+ await assert.rejects(
+ compileRecipeToPack(bakedRoomRecipe(), { maxLightmapTexels: texels - 1 }),
+ error => error instanceof TypeError
+ && error.message.startsWith('recipe.bake.texelsPerUnit:')
+ && error.message.includes(`${texels} lightmap texels`)
+ && /Lower bake\.texelsPerUnit/.test(error.message),
+ );
+ await assert.doesNotReject(compileRecipeToPack(bakedRoomRecipe(), { maxLightmapTexels: texels }));
+ assert.doesNotThrow(() => validatePackRecipe(bakedRoomRecipe()), 'a bake no longer needs a refusal');
+});
+
+test('the <crucible-scene> runtime reaches no recipe bake and no agent scene compiler', async () => {
+ const result = await build({ entryPoints: ['src/crucible-scene.js'], bundle: true, write: false, metafile: true, format: 'esm', splitting: true, outdir: 'out', logLevel: 'error' });
+ const inputs = Object.keys(result.metafile.inputs);
+ const forbidden = inputs.filter(path => /src\/(agent-scene(?!-capabilities)|agent-bake|agent-look|agent-apply|scene-pack\.js)/.test(path));
+ assert.deepEqual(forbidden, []);
+ // src/light-bake.js is there already for the probe code of the `reflections` shader module (probe-trace.js imports its
+ // ray helpers). A lightmap is drawn by the renderer from stored bytes and must add no second way in.
+ const lightBakeImporters = inputs.filter(path => result.metafile.inputs[path].imports.some(entry => entry.path === 'src/light-bake.js'));
+ assert.deepEqual(lightBakeImporters, ['src/probe-trace.js']);
+});
+
+test('the runtime turns packed texel bytes into the ImageData a browser uploads, and leaves other parts alone', () => {
+ class FakeImageData {
+ constructor(data, width, height) {
+ Object.assign(this, { data, width, height });
+ }
+ }
+ const lightmap = { image: { width: 2, height: 1, data: new Uint8ClampedArray(8) }, colorSpace: 'srgb' };
+ const bareMaterial = { color: [1, 1, 1] };
+ const parts = [{ name: 'lit', material: { color: [1, 1, 1], emissiveMap: lightmap } }, { name: 'bare', material: bareMaterial }];
+ globalThis.ImageData = FakeImageData;
+ try {
+ const converted = partsWithImageData(parts);
+ assert.ok(converted[0].material.emissiveMap.image instanceof FakeImageData);
+ assert.equal(converted[0].material.emissiveMap.image.data, lightmap.image.data, 'the bytes are not copied');
+ assert.equal(converted[0].material.emissiveMap.colorSpace, 'srgb');
+ assert.equal(converted[1], parts[1], 'a part without textures is returned as it is');
+ assert.ok(!(parts[0].material.emissiveMap.image instanceof FakeImageData), 'the input is not changed');
+ } finally {
+ delete globalThis.ImageData;
+ }
+ assert.equal(partsWithImageData(parts)[0].material.emissiveMap.image, lightmap.image, 'without ImageData (Node) the plain image stays');
+});