3D engine that AI agents drive
Bake each sampled pose when bake.rebake is set (issue 603)
Nguyen Xuan An824fb232050d
diff --git a/docs/light-bake.md b/docs/light-bake.mdindex bc670bab..5a5aad1a 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -155,4 +155,4 @@ The bake is traced at the authored pose and is cached by a key over the bake setMotion is the exception: a motion track can move a light, the sun or a part after the bake was traced, and the baked light stays where it was. When a bake and motion both exist, `scene_inspect` compares the key at the sampled time with the baked key and reports a `bake-stale` diagnostic when they differ. A scene without motion, or at a time where nothing moved, pays nothing and gets no warning. Material animation is not part of the check.-To fix it, bake a pose that stays put (keep lit lights and parts still, or animate only unlit things), or set `bake.rebake` to `true` with `set-bake`. `rebake` skips the cache so every build traces again, and it silences `bake-stale`. It traces the authored pose, so it does not make baked light follow motion; clear it with `set-bake` without the field once the scene is final.+To fix it, bake a pose that stays put (keep lit lights and parts still, or animate only unlit things), or set `bake.rebake` to `true` with `set-bake`. With `rebake`, a frame sampled at a pose whose key differs from the bake in use is lit by a bake traced at that pose: the lights, the sun and the part matrices as motion sets them. The bake is kept by that key for the last 4 poses (least recently used leaves first), so a seek back to a held pose, or a second render at the same time, traces nothing. `bake-stale` is gone because the bake is current, not because it is hidden. The cost is one full bake per new pose: on the closed test room at the `draft` preset, about 0.7 to 0.8 s each on a loaded machine (measured 2026-11-09), so a render that steps through many distinct poses (a moving lamp over 120 frames) pays that every frame; keep rebake for a few key poses or short moves, and leave it off when the scene is final. An edit that does not change the authored pose still reuses the cache.diff --git a/skills/build-67js-scene/references/light.md b/skills/build-67js-scene/references/light.mdindex fb8de257..f4f12723 100644--- a/skills/build-67js-scene/references/light.md+++ b/skills/build-67js-scene/references/light.md@@ -78,9 +78,9 @@ sunlit closed room. It needs `irradianceGrid`; without it the call fails with "bThe bake runs when the scene builds and again only when parts, lights, materials or the bake change.A motion track that moves a light, the sun or a part leaves the baked light behind: `scene_inspect` then reports-`bake-stale`. Keep lit lights and parts still, or set `bake.rebake` true to trace on every build and silence it.+`bake-stale`. Keep lit lights and parts still, or set `bake.rebake` true: each pose motion samples is baked (the last 4 are kept), about 0.7 s each on a small room, so use it for a few poses.`scene_inspect` shows `bake.seconds`, `bake.skipped` (alpha, skins, morphs, hair and cloth are left as they were) and-`bake.used`. It bakes the rest pose, so a light moved by a motion track does not move its baked light. `"bake": null`+`bake.used`. Without rebake it bakes the rest pose, so a light moved by a motion track does not move its baked light. `"bake": null`(`set-bake`) removes it.## Flush faces flicker (z-fighting)diff --git a/src/agent-bake.js b/src/agent-bake.jsindex 59ed8f65..b1f80249 100644--- a/src/agent-bake.js+++ b/src/agent-bake.js@@ -79,19 +79,51 @@ export function lightBakeKey(recipe, generatedGeometryGenerators, environment, w[...worldMatrices].map(([name, matrix]) => [name, Array.from(matrix)])]);}+// The bake inputs at a sampled pose: the lights, sun and part matrices as motion has set them, and the key they give.+function sampledBakeInputs(recipe, sourceRestParts, generators, pose) {+ const environment = pose.movedLook ? motionEnvironment(structuredClone(recipe.environment), pose.movedLook) : recipe.environment;+ const worldMatrices = new Map(sourceRestParts.map(part => [part.name, new Float32Array(pose.graph.getNode(part.name).worldMatrix)]));+ return { environment, worldMatrices, key: lightBakeKey(recipe, generators, environment, worldMatrices) };+}+/** The scene_inspect diagnostics for a bake whose inputs, at the sampled pose, differ from the ones it was traced at. */export function staleBakeProblems(state, generators, bakedKey) {- const environment = state.movedLook ? motionEnvironment(structuredClone(state.recipe.environment), state.movedLook) : state.recipe.environment;- const graph = state.poseGraph ?? state.graph;- const worldMatrices = new Map(state.sourceRestParts.map(part => [part.name, graph.getNode(part.name).worldMatrix]));- return lightBakeKey(state.recipe, generators, environment, worldMatrices) === bakedKey ? [] : [staleBakeDiagnostic()];+ const pose = { graph: state.poseGraph ?? state.graph, movedLook: state.movedLook };+ return sampledBakeInputs(state.recipe, state.sourceRestParts, generators, pose).key === bakedKey ? [] : [staleBakeDiagnostic()];+}++const REBAKE_CACHE_SIZE = 4;++/**+ * bake.rebake: the bake for the pose a frame is sampled at. Returns null while the bake in use already matches that pose;+ * otherwise the bake traced at the sampled lights, sun and part matrices, from the cache (the last 4 poses, least recently+ * used leaves first) or freshly traced. `lightBake.currentKey` is the pose the scene is drawn with.+ */+export function bakeAtSampledPose(lightBake, recipe, generators, pose) {+ const { key, environment, worldMatrices } = sampledBakeInputs(recipe, lightBake.sourceRestParts, generators, pose);+ if (key === lightBake.currentKey) {+ return null;+ }+ let entry = lightBake.cache.get(key);+ const reused = Boolean(entry);+ lightBake.cache.delete(key);+ if (!entry) {+ const baked = bakeAgentParts(lightBake.sourceRestParts, worldMatrices, environment, recipe.bake, generators);+ entry = { parts: baked.parts, report: baked.report };+ }+ lightBake.cache.set(key, entry);+ if (lightBake.cache.size > REBAKE_CACHE_SIZE) {+ lightBake.cache.delete(lightBake.cache.keys().next().value);+ }+ lightBake.currentKey = key;+ return { entry, reused };}function staleBakeDiagnostic() {return {kind: 'bake-stale', severity: 'warning', target: 'bake',message: 'A light, the sun or a part has moved from the pose the bake was traced at, so the baked light no longer matches the frame.',- fix: 'Bounced light does not follow motion. Bake a pose that stays put, or set bake.rebake true (scene_apply set-bake) to trace again on every build and silence this. Material animation is not checked.',+ fix: 'Bounced light does not follow motion. Bake a pose that stays put, or set bake.rebake true (scene_apply set-bake) to bake each sampled pose. Material animation is not checked.',};}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex bce835ec..5608fb31 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -293,7 +293,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({}),// Recipe bake: bounced light written into lightmaps at build time (src/light-bake.js, loaded on demand).bake: Object.freeze({- fields: 'preset, or samples (1-256), bounces (1-8), texelsPerUnit (1-12) over it; irradianceGrid true or 8-48 nodes: a baked grid of bounced diffuse light in place of lightmaps (opt in, static); gridFog true adds the fog (sunlit closed rooms; dark shafts too bright); probes room by default, false for none, or up to 4 {position, radius?}; rebake true traces every build, no bake-stale. Same recipe, same bytes.',+ fields: 'preset, or samples (1-256), bounces (1-8), texelsPerUnit (1-12) over it; irradianceGrid true or 8-48 nodes: a baked grid of bounced diffuse light in place of lightmaps (opt in, static); gridFog true adds the fog (sunlit closed rooms; dark shafts too bright); probes room by default, false for none, or up to 4 {position, radius?}; rebake true bakes each pose motion samples (4 cached), no bake-stale. Same recipe, same bytes.',presets: BAKE_PRESETS,notes: 'Bounced light from point, spot, area and key lights. Reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit (bake.used, bake.reduction); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular. Probes: specular, not in glTF.',limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: MAX_POINT_LIGHTS }),diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 77e526be..f0a57f58 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1288,8 +1288,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {state.sourceRestParts.every((part, index) => part === nextParts[index]);const sourceRestParts = sameParts ? state.sourceRestParts : Object.freeze(nextParts);const lightBakeResult = stageLightBake(recipe, sourceRestParts, graph);- const reflected = stageObjectReflections(recipe, sourceRestParts, lightBakeResult ? lightBakeResult.parts : sourceRestParts, graph);- const restParts = stageCoplanarOffsets(recipe, stageLightLinks(recipe, stageFloorSky(recipe, reflected ? reflected.parts : lightBakeResult ? lightBakeResult.parts : sourceRestParts)));+ const { reflected, restParts } = stageRestParts(recipe, sourceRestParts, lightBakeResult, graph);const stagedState = {recipe, geometryRecords, geometries, graph, materialHandles,// Part identity decides what the next stage reuses, so it compares the parts as built, before any bake.@@ -1348,7 +1347,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {}// The bake no longer matches the frame: motion moved a light, the sun or a part off the pose it was traced at.- // Only a scene with both a bake and motion pays for this check, and bake.rebake turns it off.+ // Only a scene with both a bake and motion pays for this check, and bake.rebake turns it off (it bakes each sampled pose).function staleBakeProblems() {if (!lightBake || !state.recipe.bake || state.recipe.bake.rebake || !state.motionSampler) {return [];@@ -1356,6 +1355,21 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {return agentSceneModule('bake').staleBakeProblems(state, bakeGenerators(state.recipe), lightBake.key);}+ function stageRestParts(recipe, sourceRestParts, lightBakeResult, graph) {+ const reflected = stageObjectReflections(recipe, sourceRestParts, lightBakeResult ? lightBakeResult.parts : sourceRestParts, graph);+ return { reflected, restParts: stageCoplanarOffsets(recipe, stageLightLinks(recipe, stageFloorSky(recipe, reflected ? reflected.parts : lightBakeResult ? lightBakeResult.parts : sourceRestParts))) };+ }++ // bake.rebake: a frame sampled at a pose the bake was not traced at is lit by a bake of that pose, cached by its key.+ function rebakeAtPose(pose) {+ const rebaked = lightBake && state.recipe.bake?.rebake && state.motionSampler && agentSceneModule('bake').bakeAtSampledPose(lightBake, state.recipe, bakeGenerators(state.recipe), pose);+ if (rebaked) {+ rebaked.entry.staged ??= stageRestParts(state.recipe, state.sourceRestParts, rebaked.entry, pose.graph);+ state.restParts = rebaked.entry.staged.restParts;+ state.bakeReport = { ...rebaked.entry.report, reused: rebaked.reused };+ }+ }+// A light bake costs seconds of ray tracing: it runs when the parts, the lights, the materials or the bake fields// change, and every other edit, seek or camera move reuses the last result.function stageLightBake(recipe, sourceRestParts, graph) {@@ -1365,11 +1379,12 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {const worldMatrices = new Map(sourceRestParts.map(part => [part.name, new Float32Array(graph.getNode(part.name).worldMatrix)]));const generatedGeometryGenerators = bakeGenerators(recipe);const key = agentSceneModule('bake').lightBakeKey(recipe, generatedGeometryGenerators, recipe.environment, worldMatrices);- if (!recipe.bake.rebake && lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {+ if (lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {+ lightBake.currentKey = key;return { ...lightBake, reused: true };}const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryGenerators);- lightBake = { key, sourceRestParts, parts: baked.parts, report: baked.report };+ lightBake = { key, currentKey: key, sourceRestParts, parts: baked.parts, report: baked.report, cache: new Map([[key, { parts: baked.parts, report: baked.report }]]) };return { ...lightBake, reused: false };}@@ -1529,7 +1544,9 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {if (time !== null && !state.motionSampler && !state.physicsSampler && !state.clothSampler && !state.particleSampler && !state.assetRuntime.animators.length && !state.sequences.length) {throw new RangeError('This procedural recipe has no motion, physics, cloth or particles, and no placed asset clip.');}- if (publishPose(state, stagePose(state, time))) {+ const pose = stagePose(state, time);+ rebakeAtPose(pose);+ if (publishPose(state, pose)) {topologyRevision++;}return state.motionTime;diff --git a/tests/agent-bake-stale.test.js b/tests/agent-bake-stale.test.jsindex 0edd93b3..8fcc6c83 100644--- a/tests/agent-bake-stale.test.js+++ b/tests/agent-bake-stale.test.js@@ -3,7 +3,7 @@ import './support/load-agent-scene-modules.mjs';import assert from 'node:assert/strict';import test from 'node:test';import { createAgentScene } from '../src/agent-scene.js';-import { closedRoom } from './support/agent-bake-rooms.mjs';+import { closedRoom, lightmapBytesOf } from './support/agent-bake-rooms.mjs';const LIGHT_MOVES = { kind: 'light', id: 'point:0', property: 'position', keyframes: [{ time: 0, value: [0, 2, 0] }, { time: 2, value: [1, 2, 0] }] };@@ -37,12 +37,36 @@ test('an unchanged scene, or one with a bake and no motion, gives no warning', (assert.deepEqual(staleDiagnostics(unmoved), []);});-test('bake.rebake turns the warning off and skips the cache on a rebuild', () => {+const lightMapData = (scene, name) => Array.from(lightmapBytesOf(scene, name));++test('bake.rebake bakes the pose motion samples: the light map at time t equals a fresh bake of the scene posed at t', () => {const scene = createAgentScene(bakedRoom({ rebake: true }));+ const authoredFloor = lightMapData(scene, 'floor');scene.sampleMotion(2);assert.deepEqual(staleDiagnostics(scene), []);- assert.equal(scene.inspect().bake.rebake, true);- const firstBake = scene.inspect().bake.reused;- assert.equal(firstBake, false);+ assert.equal(scene.inspect().bake.reused, false);+ const posed = bakedRoom();+ delete posed.motion;+ posed.environment.pointLights[0].position = [1, 2, 0];+ const fresh = createAgentScene(posed);+ for (const name of ['floor', 'back', 'block']) {+ assert.deepEqual(lightMapData(scene, name), lightMapData(fresh, name), name);+ }+ assert.notDeepEqual(lightMapData(scene, 'floor'), authoredFloor);+ scene.sampleMotion(0);+ assert.deepEqual(lightMapData(scene, 'floor'), authoredFloor);+ assert.equal(scene.inspect().bake.reused, true);+});++test('bake.rebake keeps the bakes of the last 4 poses and traces nothing for a pose it holds', () => {+ const scene = createAgentScene(bakedRoom({ rebake: true }));+ const times = [0.5, 1, 1.5, 2];+ for (const time of times) {+ scene.sampleMotion(time);+ assert.equal(scene.inspect().bake.reused, false, `time ${time}`);+ }+ scene.sampleMotion(2);+ scene.sampleMotion(1.5);+ assert.equal(scene.inspect().bake.reused, true);assert.throws(() => createAgentScene(bakedRoom({ rebake: 'yes' })), /rebake must be a boolean/);});