3D engine that AI agents drive
Bake each sampled pose with bake.rebake instead of re-tracing the authored pose (issue 603)
Nguyen Xuan An58c2221ffb06
diff --git a/changes/603-bake-stale.md b/changes/603-bake-stale.mdindex 9312f40a..537b3983 100644--- a/changes/603-bake-stale.md+++ b/changes/603-bake-stale.md@@ -1 +1 @@-- `scene_inspect` reports a `bake-stale` warning when motion has moved a light, the sun or a part off the pose a light bake was traced at; a scene without motion or without a bake pays nothing. `bake.rebake: true` traces on every build and silences the warning. Material animation is not checked, see docs/light-bake.md (#603)+- `scene_inspect` reports a `bake-stale` warning when motion has moved a light, the sun or a part off the pose a light bake was traced at; a scene without motion or without a bake pays nothing. `bake.rebake: true` bakes each pose a render or seek samples (the last 4 are kept, about 0.7 s each on a small room), so the baked light matches the frame and the warning does not apply. Material animation is not checked, see docs/light-bake.md (#603)diff --git a/changes/603-bake-stale.size.md b/changes/603-bake-stale.size.mdindex 0d45482a..33dfeeca 100644--- a/changes/603-bake-stale.size.md+++ b/changes/603-bake-stale.size.md@@ -1 +1 @@-- scene:agent-scene+lazy: the stale check, the bake key and `bake.rebake` live in the lazy bake chunk, which now imports the motion look code it needs to sample lights; the core bundle shrinks by 7 bytes because the new capability text is paid for by shorter notes.+- scene:agent-scene+lazy: the stale check, the bake key, the pose-keyed rebake cache (last 4 poses) and `bake.rebake` live in the lazy bake chunk, which imports the motion look code it needs to sample lights (+1027 bytes gzip). The core scene:agent-scene bundle shrinks by 10 bytes: the small rebake hook in `sampleMotion` is paid for by shorter capability notes.diff --git a/src/agent-bake.js b/src/agent-bake.jsindex b1f80249..9ba634f7 100644--- a/src/agent-bake.js+++ b/src/agent-bake.js@@ -79,6 +79,18 @@ export function lightBakeKey(recipe, generatedGeometryGenerators, environment, w[...worldMatrices].map(([name, matrix]) => [name, Array.from(matrix)])]);}+/** The nodes whose geometry is built every frame, which no lightmap fits, with what builds each. */+export function bakeGenerators(recipe) {+ const generators = new Map();+ for (const system of recipe.particles?.systems ?? []) {+ generators.set(system.node, 'a hair or particle system');+ }+ for (const sheet of recipe.cloth?.sheets ?? []) {+ generators.set(sheet.node, 'a cloth simulation');+ }+ return generators;+}+// 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;@@ -87,9 +99,12 @@ function sampledBakeInputs(recipe, sourceRestParts, generators, pose) {}/** 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) {+export function staleBakeProblems(state, bakedKey) {+ if (state.recipe.bake.rebake) {+ return [];+ }const pose = { graph: state.poseGraph ?? state.graph, movedLook: state.movedLook };- return sampledBakeInputs(state.recipe, state.sourceRestParts, generators, pose).key === bakedKey ? [] : [staleBakeDiagnostic()];+ return sampledBakeInputs(state.recipe, state.sourceRestParts, bakeGenerators(state.recipe), pose).key === bakedKey ? [] : [staleBakeDiagnostic()];}const REBAKE_CACHE_SIZE = 4;@@ -99,24 +114,23 @@ const REBAKE_CACHE_SIZE = 4;* 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) {+export function bakeAtSampledPose(lightBake, recipe, pose) {+ const generators = bakeGenerators(recipe);const { key, environment, worldMatrices } = sampledBakeInputs(recipe, lightBake.sourceRestParts, generators, pose);if (key === lightBake.currentKey) {return null;}- let entry = lightBake.cache.get(key);+ const cache = lightBake.cache ??= new Map([[lightBake.key, lightBake]]);+ let entry = 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);+ cache.delete(key);+ entry ??= bakeAgentParts(lightBake.sourceRestParts, worldMatrices, environment, recipe.bake, generators);+ cache.set(key, entry);+ if (cache.size > REBAKE_CACHE_SIZE) {+ cache.delete(cache.keys().next().value);}lightBake.currentKey = key;- return { entry, reused };+ return { parts: entry.parts, report: { ...entry.report, reused } };}function staleBakeDiagnostic() {diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 1c24ef32..4ca13ea7 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -165,7 +165,7 @@ export const MESH_ATTRIBUTE_NOTES = Object.freeze({// Shape keys on a recipe mesh. Details stay here so the tool schemas stay small.export const MESH_SHAPE_KEY_NOTES = Object.freeze({- shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices (set_position, displace, sculpt, simple_deform, lattice, hook and so on) run on the finished mesh, after the stack. A key that adds or removes vertices is refused. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes } (0 to 1; keys add up); a GLB export writes the targets, names (mesh.extras.targetNames) and weights. Normals stay the base mesh normals.',+ shapeKeys: 'On a mesh geometry, at most 16: { name, offsets, value } or { name, edits, value }. offsets is a list of { select, offset: [x,y,z], falloff } moves like the translate edit; edits are mesh edits that only move vertices run on the finished mesh, after the stack. A key that adds or removes vertices is refused. value (0, from 0 to 1) is the weight without motion. Each key becomes a glTF morph target. Animate it with a motion track { kind: "morph", id: <key name>, property: "weight", keyframes } (0 to 1; keys add up); a GLB export writes targets, names (mesh.extras.targetNames) and weights.',});// Organic shaping edits. Details stay here so the tool schemas stay small.@@ -179,7 +179,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'cone', 'icoSphere', 'torus', 'lathe', 'extrude', 'tube', 'curve', 'text', 'grid', 'plane', 'circle', 'line', 'terrain', 'mesh']),camera: 'eye, target, up, near, far, then fov (vertical degrees) or focalLength (mm, with sensorWidth mm, default 36; not both). projection orthographic with orthoScale (view height in m, default 4). shift [x, y] moves the frame by a fraction of its width and height. fStop (0.7 to 64) turns on depth of field focused on target; 1.4 or lower is full blur, and effects.depthOfField.blur must stay 0. Orthographic and shifted cameras render with the rasterizer, not the path tracer.',terrain: 'One mesh, x and z from -size/2 to size/2, hills about y = 0. size 40 m (1-2000), resolution 64 cells (2-256), seed 1, amplitude 1 m (0-200), holes up to 16 of {center:[x,z],radius} with no surface inside; radius a few cells or more.',- placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start on a decoded copy of its own; set-motion tracks move the node and scene time seeks the clip. Copies share geometry and materials and draw as one batch. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',+ placedAssets: 'Node field asset:{id,materials?,clip?,drive?} turns a group node into a catalog GLB (id from asset_catalog; scene_create_asset is one asset alone). Its transform places it. materials:[{name,color,metallic,roughness,opacity,emission,emissiveColor}] override source materials by name. clip:{index,start=0,speed=1,loop=true} plays that clip from scene time start on a decoded copy of its own; set-motion tracks move the node and scene time seeks the clip. drive:{path | legs, cruiseSpeed | speed, wheels, lights} drives a car along a path in the placement frame on a decoded copy (fields as motion.drive in an asset recipe, docs/vehicle.md; no tail-light glow). scene_inspect assets adds wheels, rejectedNames and light signals. At most 512 placements, 16 assets, 16 playing a clip or driving. Render jobs do not draw placed assets yet; scene_look does.',navigation: 'scene_inspect path:{ground,from:[x,z],to:[x,z]} returns a route over the ground node around its holes, steep slopes and the nodes in avoid:[ids] (box footprints), as keyframes [{time,value:[x,y,z]}] for a translation track with interpolation LINEAR. radius 0.3 m keeps the walker off holes and avoided nodes; maxSlope 40 degrees; cellSize defaults to radius; give seconds for the whole walk or speed (1.4 m/s); lift raises y (half the walker height). Ground and avoided nodes are read at their authored pose. Errors name an unwalkable or unreachable end.',meshEdits: Object.freeze({ operations: Object.freeze(Object.keys(MESH_EDIT_OPERATIONS)), maxEdits: MAX_MESH_EDITS }),meshStack: Object.freeze({ operations: STACK_OPERATIONS, maxNodes: MAX_STACK_NODES }),@@ -294,9 +294,9 @@ 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 bakes each pose motion samples (4 cached), 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 sampled pose (4 kept).',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.',+ 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 are 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 }),}),motionLook: Object.freeze({diff --git a/src/agent-scene.js b/src/agent-scene.jsindex f0a57f58..7dda81a6 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1335,38 +1335,24 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {return linked;}- function bakeGenerators(recipe) {- const generators = new Map();- for (const system of recipe.particles?.systems ?? []) {- generators.set(system.node, 'a hair or particle system');- }- for (const sheet of recipe.cloth?.sheets ?? []) {- generators.set(sheet.node, 'a cloth simulation');- }- return generators;- }-// 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 (it bakes each sampled pose).function staleBakeProblems() {- if (!lightBake || !state.recipe.bake || state.recipe.bake.rebake || !state.motionSampler) {- return [];- }- return agentSceneModule('bake').staleBakeProblems(state, bakeGenerators(state.recipe), lightBake.key);+ return lightBake && state.recipe.bake && state.motionSampler ? agentSceneModule('bake').staleBakeProblems(state, 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))) };+ const baked = lightBakeResult?.parts ?? sourceRestParts;+ const reflected = stageObjectReflections(recipe, sourceRestParts, baked, graph);+ return { reflected, restParts: stageCoplanarOffsets(recipe, stageLightLinks(recipe, stageFloorSky(recipe, reflected ? reflected.parts : baked))) };}// 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);+ const rebaked = state.recipe.bake?.rebake && agentSceneModule('bake').bakeAtSampledPose(lightBake, 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 };+ state.restParts = stageRestParts(state.recipe, state.sourceRestParts, rebaked, pose.graph).restParts;+ state.bakeReport = rebaked.report;}}@@ -1377,14 +1363,14 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {return null;}const worldMatrices = new Map(sourceRestParts.map(part => [part.name, new Float32Array(graph.getNode(part.name).worldMatrix)]));- const generatedGeometryGenerators = bakeGenerators(recipe);+ const generatedGeometryGenerators = agentSceneModule('bake').bakeGenerators(recipe);const key = agentSceneModule('bake').lightBakeKey(recipe, generatedGeometryGenerators, recipe.environment, worldMatrices);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, currentKey: key, sourceRestParts, parts: baked.parts, report: baked.report, cache: new Map([[key, { parts: baked.parts, report: baked.report }]]) };+ lightBake = { key, currentKey: key, sourceRestParts, parts: baked.parts, report: baked.report };return { ...lightBake, reused: false };}