3D engine that AI agents drive
Skip cloth in the recipe bake, bake spot and area lights, fit presets to a ray work budget
Nguyen Xuan Anf9b6c8045a01
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e11aca4e..89006b7f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Fix three gaps a demo film found in the recipe light bake (part of issue #55). A baked scene with `cloth` failed at render time for every frame after t=0 with "A light map needs lightUvs on rigid geometry, with no skin or morph", because the cloth simulation replaces the sheet's geometry each frame; cloth sheet nodes are now skipped and listed in `report.skipped`. The bake now lights with spot lights (the renderer's cone and soft edge) and area lights (front side only, one deterministic shadow ray to a point of the rectangle per hit), where it ignored both; a scene without them bakes the same bytes. The presets could not finish a normal scene (`standard` passed its 20 s limit on a 56 part room, `fine` hit the 30 s preview limit): a recipe bake now has a ray work budget of 10 million units (texels x samples x bounces x rays per hit), estimated from the unwrap before any ray is traced with no clock involved. A preset is scaled down to fit and `scene_inspect` `bake` reports `used` and `reduced`; explicit `samples`, `bounces` or `texelsPerUnit` are never reduced and fail with a message naming the number that fits. `bakeLightmaps` is now `planLightmaps`, `estimateBake` and `traceLightmaps` (still exported as one call); the schema entry grew by one line, within the total budget.+- Add ragdolls (part of issue #96): `physics.ragdoll` in a recipe with armatures and `physics` in an asset recipe (`set-physics`) bind a capsule body to every bone or joint and play the fall back as the pose of those bones, the same bytes for the same seek. New `src/ragdoll.js`, loaded with the physics code only. New suite task `robot-ragdoll`. The lazy budgets of `agent-scene+lazy` and `agent-asset+lazy` rise by 100 and 800 bytes gzip for it; the core entries did not grow from this. Joints have no swing limits yet.- Add terrain holes and a recipe `terrain` geometry (part of issue #64; layers beyond four and the navmesh are not built). `createTerrain({ holes: [{ center: [x, z], radius }] })` leaves no surface where a cell centre is inside a circle, and `terrain.isHole(x, z)` answers for a point; without `holes` the seeded meshes are byte-identical (a digest test). A recipe geometry `{ type: "terrain", size, resolution, seed, amplitude, holes }` builds one seeded ground mesh with the same holes; it loads on demand through the new `terrain` module (core did not grow), the tool schema entry is one line with the fields in `scene_capabilities` `terrain`, and the schema total budget did not change (scene_create and scene_apply rose by a few hundred bytes, mesh_edit fell by the same amount). New suite task `terrain-hole-walk` (ground with a 3 m opening and a walker that has to go around it) with the checks `groundRelief` and `walkPath`. Measured: Haiku passed it 2 of 2 (9 and 6 tool calls, $0.29 in all) and both exported recipes used the `terrain` geometry; there was no control run without the feature, so this shows agents find it, not how many could do without.- Bake patterned, textured and emissive parts, and skip hair hosts (part of issue #128). A recipe `bake` used to skip every part with a pattern, a map or emission (31 parts, the floor and every wall, in the demo room) and failed `scene_create` with "Textured geometry requires UV channel 0" on a node that hosts hair. Those parts now keep `uvs` and their look and take the bounced light through a new `lightMap` material slot on a second UV set (`geometry.lightUvs`); the fragment shader adds `color * (1 - metallic) * lightMap * lightMapScale`, so a brick pattern tints its own bounced light. Hair and particle host nodes are skipped and listed in `report.skipped`. The shader branch compiles out of scenes with no light map; the renderer carries about 650 bytes of gzip for it in `entry:core` (see `docs/light-bake.md` for the measured sizes). GLB export writes `TEXCOORD_1` and the light map as the emissive texture (an approximation: glTF has no light map slot). The path tracer ignores baked maps by design. New reference scene `brick-room` (a recipe-built closed brick room).diff --git a/docs/light-bake.md b/docs/light-bake.mdindex edbf3250..ec5bb7d1 100644--- a/docs/light-bake.md+++ b/docs/light-bake.md@@ -28,13 +28,25 @@ const renderer = new Renderer67(canvas, bakedParts, rendererOptions);| `standard` (default) | 128 | 2 | 6 || `fine` | 192 | 2 | 7 |-Ranges are 1 to 256 samples, 1 to 3 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake over 20 s fails the edit and leaves the scene as it was. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason) and `reused`. Baked parts read every other material field live, so motion tracks on colour still work; the lightmap itself is fixed at the rest pose.+Ranges are 1 to 256 samples, 1 to 3 bounces and 1 to 12 texels per unit. The bake lights the rest pose with the recipe's point lights and key light (key colour times `keyIntensity`). It runs when the scene builds and again only when a part, its matrix, a light, a material or the bake fields change: camera edits, effects edits, motion seeks and renders reuse the result. A bake over 20 s fails the edit and leaves the scene as it was. The same recipe gives the same lightmap bytes. `scene_inspect` returns `bake`: the resolved fields, `used` (the samples, bounces and texelsPerUnit that were traced), `reduced`, `texels`, `rayWork`, `seconds` (of the run that made the lightmaps), `bakedParts`, `skipped` (name and reason) and `reused`.++### Ray work budget++A recipe bake may trace 10 million units of ray work (texels x samples x bounces x rays per hit, one bounce ray plus a shadow ray for each light). The unwrap gives the texel count before any ray is traced, so the estimate is plain arithmetic: it reads no clock and does not depend on machine speed, and the same recipe always resolves to the same numbers. The budget was measured on a closed 56 part room, where every path bounces to the end, at about 1.3 million units per second (about 8 s of tracing, under the 20 s limit and the 30 s preview deadline). Open scenes run faster.++- A preset (all three fields equal to `draft`, `standard` or `fine`) that is over the budget is scaled down: samples by a fifth and texelsPerUnit by a tenth, repeatedly, until it fits (samples not below 16, texelsPerUnit not below 1). `bake.used` shows the result and `bake.reduced` is `true`. The 56 part demo room at `standard` runs at 40 samples and texelsPerUnit 3.5 instead of 128 and 6.+- Explicit `samples`, `bounces` or `texelsPerUnit` (any combination that is not exactly a preset) are never reduced. Over the budget they fail, and the message names what fits, for example "samples 32 or fewer with texelsPerUnit 12, or texelsPerUnit 4.1 or less with samples 256".+- A scene that cannot fit even 16 samples at texelsPerUnit 1 fails with a message to remove parts or lights.++A node that hosts cloth is skipped like a hair host: the cloth simulation replaces its geometry every frame, so a lightmap built on the rest geometry would not follow it (and the renderer refuses a light map on geometry without `lightUvs`, which failed every frame after t=0). Baked parts read every other material field live, so motion tracks on colour still work; the lightmap itself is fixed at the rest pose.## What it bakesThe bake traces cosine-weighted paths from each texel through up to `bounces` reflections. Each hit adds its own emission and the direct light it receives from the point lights and the sun, with shadow rays. A texel stores that light times its own albedo. Direct light is not baked: it stays live, so shadows and moving lights keep working. The stored light is only what has bounced at least once, so a scene needs the same lights at run time that it gave the bake.-Not baked: spot lights, area lights, the environment map (it already lights every surface at run time), and specular reflection. A metal part reflects no baked light. Fresnel and sheen are ignored.+Spot lights take the cone and soft edge the renderer uses (`angle`, `penumbra`, default 0.15), with `range` and `radius` as for a point light. An area light is a rectangle that emits from its front side only, with the path tracer's `intensity * cosine / distance squared`. A hit is lit by one shadow ray per area light to a point of the rectangle that changes on every call; the sequence is a hash of the call count, so it repeats exactly, and the many paths of a texel average the soft shadow. At most 8 spot and 4 area lights. A scene without spot or area lights bakes the same bytes as before.++Not baked: the environment map (it already lights every surface at run time) and specular reflection. A metal part reflects no baked light. Fresnel and sheen are ignored.## How a part draws it@@ -42,7 +54,7 @@ A baked part is a copy with new geometry and a new material. A plain part (no maA part with texture maps, a pattern, layers or its own emission cannot lend its emissive map or its UV channel 0, so it takes the light through the renderer's `lightMap` slot instead. Its geometry keeps `uvs` (the unwrap splits vertices along its seams, and each new vertex copies the `uvs` and `colors` of the vertex it came from) and gains `lightUvs`, the second UV set. The material keeps every field and gains `lightMap` (`srgb`, linear filter, clamped) and `lightMapScale` (the brightest texel). The texture holds the light that arrives, not the light times an albedo, and the fragment shader adds `color * (1 - metallic) * lightMap * lightMapScale` under the existing shading, so the pattern or texture (box projected or UV mapped) tints it at run time. The renderer uploads the two UV sets as one four-wide attribute; the shader branch, the sampler and the uniforms compile out of any scene with no `lightMap`. The bake traces such a part with its colour times the mean colour of its base map, so a brick wall reflects brick coloured light and not white light.-Skipped, with the reason in `report.skipped`: transparent parts, a material tag that draws its own look (water, fire, foliage), skinned or morphing parts, and a node that hosts a hair or particle system (its geometry is rebuilt every frame and has no UVs; the recipe bake marks these, which fixed `scene_create` failing with "Textured geometry requires UV channel 0"). Skipped parts still block and reflect light.+Skipped, with the reason in `report.skipped`: transparent parts, a material tag that draws its own look (water, fire, foliage), skinned or morphing parts, a cloth sheet, and a node that hosts a hair or particle system (its geometry is rebuilt every frame and has no UVs; the recipe bake marks these, which fixed `scene_create` failing with "Textured geometry requires UV channel 0"). Skipped parts still block and reflect light.GLB export writes `lightUvs` as `TEXCOORD_1` and the light map as the emissive texture on `texCoord` 1, with the base colour factor as `emissiveFactor`. glTF has no light map slot, so a base colour texture does not tint it there: the export is an approximation for viewers, not for reference renders. The path tracer ignores `lightMap` and `emissiveMap` on purpose: it traces indirect light itself, so reading a baked map would count the same light twice.diff --git a/docs/parity.md b/docs/parity.mdindex 16bfffe2..4124b065 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 || Physics > Simulation Nodes | missing | No node graph. | | #43 || Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |-| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets; scene_inspect reports bake seconds and skipped parts), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes, no spot or area lights, no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 |+| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point, spot and area lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets, shrunk deterministically to a ray work budget of 10 million so a preset finishes on a 56 part room; scene_inspect reports what it used, whether it reduced, bake seconds and skipped parts, which include hair, particle and cloth nodes), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes and no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 || Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | || Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 || Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |diff --git a/src/agent-bake.js b/src/agent-bake.jsindex c95b3d5f..3536bda9 100644--- a/src/agent-bake.js+++ b/src/agent-bake.js@@ -1,6 +1,8 @@-import { bakeLightmaps } from './light-bake.js';+import { planLightmaps, estimateBake, traceLightmaps } from './light-bake.js';import { knownKeys, finiteNumber } from './agent-recipe-checks.js';-import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS } from './agent-scene-capabilities.js';+import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS, BAKE_RAY_WORK_BUDGET } from './agent-scene-capabilities.js';++const PRESET_SAMPLES_FLOOR = 16;// Recipe `bake`: bounced light written into lightmaps when the scene builds. This module loads on demand, so scenes// without a bake never download the ray tracer.@@ -32,6 +34,73 @@ export function normalizeAgentBake(input) {return resolved;}+function isPreset(settings) {+ return Object.values(BAKE_PRESETS).some(preset => Object.keys(preset).every(field => preset[field] === settings[field]));+}++function fits(plan, settings) {+ return estimateBake(plan, settings).rayWork <= BAKE_RAY_WORK_BUDGET;+}++// The densest texelsPerUnit, to two decimals, that still fits the budget at the given samples and bounces (0 when none does).+function largestFittingTexelsPerUnit(plan, settings) {+ let fitting = 0;+ let tooMuch = settings.texelsPerUnit;+ for (let step = 0; step < 12; step++) {+ const middle = Math.floor((fitting + tooMuch) / 2 * 100) / 100;+ if (middle <= fitting) {+ break;+ }+ if (fits(plan, { ...settings, texelsPerUnit: middle })) {+ fitting = middle;+ } else {+ tooMuch = middle;+ }+ }+ return fitting >= BAKE_RANGES.texelsPerUnit[0] ? fitting : 0;+}++function overBudgetMessage(plan, settings, rayWork) {+ const fittingSamples = Math.floor(BAKE_RAY_WORK_BUDGET * settings.samples / rayWork);+ const fittingTexelsPerUnit = largestFittingTexelsPerUnit(plan, settings);+ const choices = [];+ if (fittingSamples >= BAKE_RANGES.samples[0]) {+ choices.push(`samples ${fittingSamples} or fewer with texelsPerUnit ${settings.texelsPerUnit}`);+ }+ if (fittingTexelsPerUnit > 0) {+ choices.push(`texelsPerUnit ${fittingTexelsPerUnit} or less with samples ${settings.samples}`);+ }+ const advice = choices.length > 0 ? `At bounces ${settings.bounces} this scene fits ${choices.join(', or ')}.` : 'Remove parts or lights, or lower bounces.';+ return `The bake would need ${rayWork} units of ray work (texels x samples x bounces x rays per hit); the limit is ${BAKE_RAY_WORK_BUDGET}. ${advice}`;+}++/**+ * Keeps a bake inside the ray work budget before any ray is traced. The estimate counts texels, samples, bounces and lights,+ * and reads no clock, so the same recipe always resolves to the same settings. A preset is scaled down (samples first by a+ * fifth, texel density by a tenth, repeatedly); explicit samples or texelsPerUnit are never changed and fail instead.+ */+function fitSettingsToBudget(plan, settings) {+ const { rayWork } = estimateBake(plan, settings);+ if (rayWork <= BAKE_RAY_WORK_BUDGET) {+ return { used: settings, reduced: false };+ }+ if (!isPreset(settings)) {+ throw new RangeError(overBudgetMessage(plan, settings, rayWork));+ }+ let used = settings;+ while (!fits(plan, used)) {+ if (used.samples <= PRESET_SAMPLES_FLOOR && used.texelsPerUnit <= BAKE_RANGES.texelsPerUnit[0]) {+ throw new RangeError(`Even ${PRESET_SAMPLES_FLOOR} samples at texelsPerUnit ${BAKE_RANGES.texelsPerUnit[0]} is over the ray work limit of ${BAKE_RAY_WORK_BUDGET} for this scene. Remove parts or lights, or lower bounces.`);+ }+ used = {+ ...used,+ samples: Math.max(PRESET_SAMPLES_FLOOR, Math.floor(used.samples * 0.8)),+ texelsPerUnit: Math.max(BAKE_RANGES.texelsPerUnit[0], Math.round(used.texelsPerUnit * 0.9 * 100) / 100),+ };+ }+ return { used, reduced: true };+}+// The baked part keeps reading every other material field from the live material, so motion tracks still drive it.function liveBakedMaterial(liveMaterial, bakedMaterial) {const output = {};@@ -47,21 +116,25 @@ function liveBakedMaterial(liveMaterial, bakedMaterial) {* Returns the new parts, which share the originals' matrices so poses still move them, and a report: texels,* rayWork, seconds, skipped parts with reasons.*/-export function bakeAgentParts(parts, worldMatrices, environment, settings, generatedGeometryNames = new Set()) {+export function bakeAgentParts(parts, worldMatrices, environment, settings, generatedGeometryGenerators = new Map()) {const sunScale = environment.keyIntensity ?? 1;const lighting = {pointLights: environment.pointLights,+ spotLights: environment.spotLights,+ areaLights: environment.areaLights,keyColor: Array.from(environment.keyColor, channel => channel * sunScale),lightDirection: environment.lightDirection,};- // A hair or particle host is drawn from geometry built every frame, which has no lightmap UVs.+ // A hair, particle or cloth node is drawn from geometry built every frame, which has no lightmap UVs.const snapshots = parts.map(part => ({...part,matrix: worldMatrices.get(part.name),material: { ...part.material },- generatesGeometry: generatedGeometryNames.has(part.name),+ generatesGeometry: generatedGeometryGenerators.get(part.name) ?? false,}));- const { parts: bakedSnapshots, report } = bakeLightmaps(snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS });+ const plan = planLightmaps(snapshots, lighting, { ...settings, maxSeconds: BAKE_MAXIMUM_SECONDS });+ const { used, reduced } = fitSettingsToBudget(plan, settings);+ const { parts: bakedSnapshots, report } = traceLightmaps(plan, used);const bakedParts = parts.map((part, index) => {if (bakedSnapshots[index] === snapshots[index]) {return part;@@ -69,6 +142,6 @@ export function bakeAgentParts(parts, worldMatrices, environment, settings, geneconst { geometry, material } = bakedSnapshots[index];return Object.freeze({ ...part, geometry, material: liveBakedMaterial(part.material, material) });});- return { parts: Object.freeze(bakedParts), report: { ...settings, texels: report.texels, rayWork: report.rayWork, seconds: report.seconds,+ return { parts: Object.freeze(bakedParts), report: { ...settings, used, reduced, texels: report.texels, rayWork: report.rayWork, seconds: report.seconds,bakedParts: report.parts.length, skipped: report.skipped } };}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 282ede34..e9c22964 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -96,6 +96,11 @@ export const BAKE_PRESETS = Object.freeze({});export const BAKE_RANGES = Object.freeze({ samples: [1, 256], bounces: [1, 3], texelsPerUnit: [1, 12] });export const BAKE_MAXIMUM_SECONDS = 20;+/**+ * Ray work (texels x samples x bounces x rays per hit) a recipe bake may trace. Measured on a closed, 56 part room (every+ * path bounces to the end) at about 1.3 million units per second, so this is about 8 s there, with room under the 20 s limit+ * for a slower machine. A preset is scaled down to fit; explicit samples or texelsPerUnit that do not fit fail. */+export const BAKE_RAY_WORK_BUDGET = 10_000_000;/** Render job output: each side up to 1920 and never more pixels than 1920x1080 (portrait 1080x1920 fits). */export const MAXIMUM_JOB_SIDE = 1920;export const MAXIMUM_JOB_PIXELS = 1920 * 1080;@@ -219,8 +224,8 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({bake: Object.freeze({fields: 'preset, or samples (1-256), bounces (1-3), texelsPerUnit (1-12) over it. Same recipe, same bytes.',presets: BAKE_PRESETS,- notes: 'Bounced light from point lights and the key light, for closed rooms. Reruns only when parts, lights, materials or bake change. Patterns and textures keep their look. Skips alpha, skin, morph, hair hosts (bake.skipped, bake.seconds). Spot and area lights, environment map and specular are not baked. Over 20 s fails the edit.',- limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, maxPointLights: 8 }),+ notes: 'Bounced light from point, spot, area and key lights, for closed rooms. Reruns only when parts, lights, materials or bake change. Patterns and textures keep their look. Skips alpha, skin, morph, hair and cloth nodes (bake.skipped, bake.seconds). A preset shrinks to fit the ray work limit (bake.used, bake.reduced); explicit samples or texelsPerUnit over it fail. Environment map and specular are not baked.',+ limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, maxRayWork: BAKE_RAY_WORK_BUDGET, maxPointLights: 8 }),}),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),});diff --git a/src/agent-scene.js b/src/agent-scene.jsindex e86b7bbd..9847835d 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1026,13 +1026,20 @@ export function createAgentScene(input, inputLimits = {}) {}const worldMatrices = new Map(sourceRestParts.map(part => [part.name, new Float32Array(graph.getNode(part.name).worldMatrix)]));const { pointLights, keyColor, keyIntensity, lightDirection } = recipe.environment;- const generatedGeometryNames = new Set((recipe.particles?.systems ?? []).map(system => system.node));- const key = JSON.stringify([recipe.bake, [...generatedGeometryNames], pointLights, keyColor, keyIntensity, lightDirection, recipe.materials,+ const generatedGeometryGenerators = new Map();+ for (const system of recipe.particles?.systems ?? []) {+ generatedGeometryGenerators.set(system.node, 'a hair or particle system');+ }+ for (const sheet of recipe.cloth?.sheets ?? []) {+ generatedGeometryGenerators.set(sheet.node, 'a cloth simulation');+ }+ const { spotLights, areaLights } = recipe.environment;+ const key = JSON.stringify([recipe.bake, [...generatedGeometryGenerators], pointLights, spotLights, areaLights, keyColor, keyIntensity, lightDirection, recipe.materials,[...worldMatrices].map(([name, matrix]) => [name, Array.from(matrix)])]);if (lightBake?.key === key && lightBake.sourceRestParts === sourceRestParts) {return { ...lightBake, reused: true };}- const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryNames);+ const baked = agentSceneModule('bake').bakeAgentParts(sourceRestParts, worldMatrices, recipe.environment, recipe.bake, generatedGeometryGenerators);lightBake = { key, sourceRestParts, parts: baked.parts, report: baked.report };return { ...lightBake, reused: false };}diff --git a/src/light-bake.js b/src/light-bake.jsindex 5c6712c5..534d8508 100644--- a/src/light-bake.js+++ b/src/light-bake.js@@ -24,6 +24,10 @@ export const MAX_BAKE_TEXELS = 1_000_000;export const MAX_BAKE_TRIANGLES = 200_000;export const MAX_BAKE_PARTS = 256;export const MAX_BAKE_POINT_LIGHTS = 8;+export const MAX_BAKE_SPOT_LIGHTS = 8;+export const MAX_BAKE_AREA_LIGHTS = 4;+// The renderer's own soft edge for a spot light that gives none.+const DEFAULT_SPOT_PENUMBRA = 0.15;const MAP_FIELDS = ['map', 'normalMap', 'metallicRoughnessMap', 'occlusionMap', 'emissiveMap'];const SURFACE_UTILIZATION_FLOOR = 0.05;@@ -53,6 +57,62 @@ function finiteVector(value, length) {return (Array.isArray(value) || ArrayBuffer.isView(value)) && value.length === length && Array.from(value).every(Number.isFinite);}+function normalizedDirection(direction, label) {+ if (!finiteVector(direction, 3) || Math.hypot(...direction) === 0) throw new RangeError(`${label} needs a finite, nonzero direction.`);+ const length = Math.hypot(...direction);+ return Array.from(direction, component => component / length);+}++function checkedLightList(lights, maximum, name) {+ if (!Array.isArray(lights) || lights.length > maximum) throw new RangeError(`Light bake takes at most ${maximum} ${name}.`);+}++function checkedLightBasics(light, label) {+ if (!finiteVector(light.position, 3) || !finiteVector(light.color ?? [1, 1, 1], 3) || !Number.isFinite(light.intensity) || light.intensity < 0) {+ throw new RangeError(`${label} needs a position, a color and a nonnegative intensity.`);+ }+}++/** Spot lights in the form the path tracer uses: a unit axis, the cosine of the outer half angle and the soft edge width. */+function normalizeSpotLights(spotLights) {+ checkedLightList(spotLights, MAX_BAKE_SPOT_LIGHTS, 'spot lights');+ return spotLights.map((light, index) => {+ const label = `Light bake spot light ${index}`;+ checkedLightBasics(light, label);+ const angle = light.angle ?? Math.PI / 4;+ const penumbra = light.penumbra ?? DEFAULT_SPOT_PENUMBRA;+ const range = light.range ?? 0;+ const radius = light.radius ?? 0.05;+ if (![angle, penumbra, range, radius].every(Number.isFinite) || angle <= 0 || angle >= Math.PI || penumbra < 0 || range < 0 || radius < 0) {+ throw new RangeError(`${label} has an invalid angle, penumbra, range or radius.`);+ }+ const cosineHalfAngle = Math.cos(angle);+ return {+ position: Array.from(light.position), color: Array.from(light.color ?? [1, 1, 1]), intensity: light.intensity, range, radius,+ direction: normalizedDirection(light.direction, label), cosineHalfAngle, blend: (1 - cosineHalfAngle) * penumbra,+ };+ });+}++/** Rectangular area lights: a unit normal and the two unit axes that span the rectangle (width along `across`). */+function normalizeAreaLights(areaLights) {+ checkedLightList(areaLights, MAX_BAKE_AREA_LIGHTS, 'area lights');+ return areaLights.map((light, index) => {+ const label = `Light bake area light ${index}`;+ checkedLightBasics(light, label);+ if (!(light.width >= 0) || !(light.height >= 0) || !Number.isFinite(light.width) || !Number.isFinite(light.height)) {+ throw new RangeError(`${label} needs a finite width and height.`);+ }+ const normal = normalizedDirection(light.direction, label);+ const guide = normalizedDirection(light.up ?? [0, 1, 0], label);+ let across = [guide[1] * normal[2] - guide[2] * normal[1], guide[2] * normal[0] - guide[0] * normal[2], guide[0] * normal[1] - guide[1] * normal[0]];+ const acrossLength = Math.hypot(...across);+ across = acrossLength < 1e-3 ? [1, 0, 0] : across.map(component => component / acrossLength);+ const along = [normal[1] * across[2] - normal[2] * across[1], normal[2] * across[0] - normal[0] * across[2], normal[0] * across[1] - normal[1] * across[0]];+ return { position: Array.from(light.position), color: Array.from(light.color ?? [1, 1, 1]), intensity: light.intensity, width: light.width, height: light.height, normal, across, along };+ });+}+function normalizeLights(lighting) {if (lighting === null || typeof lighting !== 'object') throw new TypeError('Light bake needs a lighting object.');const pointLights = lighting.pointLights ?? [];@@ -66,13 +126,15 @@ function normalizeLights(lighting) {if (!Number.isFinite(range) || range < 0 || !Number.isFinite(radius) || radius < 0) throw new RangeError(`Light bake point light ${index} has an invalid range or radius.`);return { position: Array.from(light.position), color: Array.from(light.color ?? [1, 1, 1]), intensity: light.intensity, range, radius };});+ const spotLights = normalizeSpotLights(lighting.spotLights ?? []);+ const areaLights = normalizeAreaLights(lighting.areaLights ?? []);const keyColor = lighting.keyColor ?? [0, 0, 0];const lightDirection = lighting.lightDirection ?? [0, 1, 0];if (!finiteVector(keyColor, 3) || keyColor.some(channel => channel < 0) || !finiteVector(lightDirection, 3)) throw new RangeError('Light bake keyColor and lightDirection must be finite vectors.');const directionLength = Math.hypot(...lightDirection);const hasSun = keyColor.some(channel => channel > 0) && directionLength > 0;const sunDirection = hasSun ? lightDirection.map(component => component / directionLength) : [0, 1, 0];- return { pointLights: normalizedPoints, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection } : null };+ return { pointLights: normalizedPoints, spotLights, areaLights, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection } : null };}function validatePart(part, index) {@@ -94,7 +156,10 @@ function validatePart(part, index) {function skipReason(part) {const material = part.material;- if (part.generatesGeometry) return 'a hair or particle system rebuilds its geometry every frame, so it has no fixed surface to bake';+ if (part.generatesGeometry) {+ const generator = typeof part.generatesGeometry === 'string' ? part.generatesGeometry : 'a hair or particle system';+ return `${generator} rebuilds its geometry every frame, so it has no fixed surface to bake`;+ }if (part.skin || part.morph || part.geometry.skinIndices || part.geometry.morphTargets) return 'skinned or morphing parts move, so a fixed lightmap would not follow';if ((material.tag ?? 'surface') !== 'surface') return `the ${material.tag} material draws its own look`;if (material.opacity !== undefined && material.opacity < 1 || material.alphaMode && material.alphaMode !== 'opaque') return 'it is transparent';@@ -244,6 +309,51 @@ function createDirectIrradiance(tracer, lights, offset, scale) {}const toLight = [0, 0, 0];const power = [0, 0, 0];+ // Aims `toLight` at a light's position and returns the distance, or 0 when the point sits on the light.+ function aimAtPosition(point, lightX, lightY, lightZ) {+ const deltaX = lightX - point[0];+ const deltaY = lightY - point[1];+ const deltaZ = lightZ - point[2];+ const distanceSquared = deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ;+ if (distanceSquared < 1e-12) return { distance: 0, distanceSquared };+ const distance = Math.sqrt(distanceSquared);+ toLight[0] = deltaX / distance;+ toLight[1] = deltaY / distance;+ toLight[2] = deltaZ / distance;+ return { distance, distanceSquared };+ }+ function addSpotLight(point, normal, light) {+ const { distance, distanceSquared } = aimAtPosition(point, light.position[0], light.position[1], light.position[2]);+ if (distance === 0) return;+ const axisCosine = -(light.direction[0] * toLight[0] + light.direction[1] * toLight[1] + light.direction[2] * toLight[2]);+ const inside = axisCosine - light.cosineHalfAngle;+ if (inside <= 0) return;+ const edge = light.blend > 0 && inside < light.blend ? inside / light.blend : 1;+ const mask = edge * edge * (3 - 2 * edge);+ const strength = light.intensity * pointLightFalloff(distanceSquared, light) * mask;+ for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;+ addLight(point, normal, toLight, distance - offset, power);+ }+ // One shadow ray to a point of the rectangle that changes with every call. The sequence depends only on the order of+ // the calls, so a bake repeats exactly and the many paths of a texel average the soft shadow.+ let areaSampleCount = 0;+ function addAreaLight(point, normal, light, lightIndex) {+ areaSampleCount++;+ const across = (hashUnit(areaSampleCount, 17, lightIndex) - 0.5) * light.width;+ const along = (hashUnit(areaSampleCount, 19, lightIndex) - 0.5) * light.height;+ const { distance, distanceSquared } = aimAtPosition(+ point,+ light.position[0] + light.across[0] * across + light.along[0] * along,+ light.position[1] + light.across[1] * across + light.along[1] * along,+ light.position[2] + light.across[2] * across + light.along[2] * along,+ );+ if (distance === 0) return;+ const emitCosine = -(light.normal[0] * toLight[0] + light.normal[1] * toLight[1] + light.normal[2] * toLight[2]);+ if (emitCosine <= 0) return;+ const strength = light.intensity * emitCosine / distanceSquared;+ for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;+ addLight(point, normal, toLight, distance - offset, power);+ }return function directIrradiance(point, normal) {result[0] = 0;result[1] = 0;@@ -262,6 +372,8 @@ function createDirectIrradiance(tracer, lights, offset, scale) {for (let channel = 0; channel < 3; channel++) power[channel] = light.color[channel] * strength;addLight(point, normal, toLight, distance - offset, power);}+ for (const light of lights.spotLights) addSpotLight(point, normal, light);+ for (let index = 0; index < lights.areaLights.length; index++) addAreaLight(point, normal, lights.areaLights[index], index);if (lights.sun) addLight(point, normal, lights.sun.direction, shadowReach, lights.sun.color);return result;};@@ -528,29 +640,32 @@ function lightMappedPart(part, geometry, texture, peak) {/*** Bakes bounced light into the parts and returns new parts (the input is not changed) plus a report.* lighting: { pointLights: [{ position, color, intensity, radius, range }], keyColor, lightDirection }, the same shapes- * the renderer takes. Spot and area lights are not baked.+ * the renderer takes, plus optional spotLights and areaLights in their renderer shapes.* options: maxResolution, texelsPerUnit, samples, bounces, maxSeconds (see BAKE_LIMITS). The time limit throws and* never truncates, so a bake that finishes always has the same bytes.*/export function bakeLightmaps(parts, lighting, options = {}) {+ const plan = planLightmaps(parts, lighting, options);+ return traceLightmaps(plan, plan.settings);+}++/**+ * Everything a bake decides before the first ray: validated options and lights, the unwrap of each bakeable part and the+ * parts that are skipped. It reads no clock to decide anything, so `estimateBake` of one plan is the same on every+ * machine. Pass the plan and the final settings to `traceLightmaps`.+ */+export function planLightmaps(parts, lighting, options = {}) {const settings = normalizeBakeOptions(options);const lights = normalizeLights(lighting);if (!Array.isArray(parts) || parts.length === 0 || parts.length > MAX_BAKE_PARTS) throw new RangeError(`Light bake takes from 1 to ${MAX_BAKE_PARTS} parts.`);parts.forEach(validatePart);+ const triangleTotal = parts.reduce((total, part) => total + part.geometry.indices.length / 3, 0);+ if (triangleTotal > MAX_BAKE_TRIANGLES) throw new RangeError(`Light bake takes at most ${MAX_BAKE_TRIANGLES} triangles in total.`);const started = performance.now();- const world = buildWorld(parts);- const scale = sceneScale(world.positions);- const offset = scale * 1e-4;- const tracer = createTracer(world);- const directIrradiance = createDirectIrradiance(tracer, lights, offset, scale);- const albedoOfPart = parts.map(part => diffuseAlbedo(part.material));- const emissionOfPart = parts.map(part => emittedRadiance(part.material));- const gather = createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples: settings.samples, bounces: settings.bounces });const unwrapCache = new Map();const secondSetCache = new Map();- const plans = [];+ const entries = [];const skipped = [];- let texelTotal = 0;parts.forEach((part, index) => {const reason = skipReason(part);if (reason) {@@ -560,18 +675,43 @@ export function bakeLightmaps(parts, lighting, options = {}) {const slot = usesLightMapSlot(part.material);const cache = slot ? secondSetCache : unwrapCache;if (!cache.has(part.geometry)) cache.set(part.geometry, slot ? unwrapIntoSecondUvSet(part.geometry) : unwrapForLightmap(part.geometry));- const unwrapped = cache.get(part.geometry);- const resolution = lightmapResolution(worldTriangleArea(part), unwrapped.utilization, settings);- texelTotal += resolution * resolution;- plans.push({ part, index, unwrapped, resolution, slot });+ entries.push({ part, index, unwrapped: cache.get(part.geometry), area: worldTriangleArea(part), slot });});- const rayWork = texelTotal * settings.samples * settings.bounces * (1 + lights.pointLights.length + (lights.sun ? 1 : 0));+ return { parts, lights, settings, started, entries, skipped };+}++/** Texels and ray work of a planned bake at the given settings, with no tracing. Ray work counts one bounce ray plus one shadow ray per light. */+export function estimateBake(plan, { samples, bounces, texelsPerUnit }) {+ const resolutionSettings = { texelsPerUnit, maxResolution: plan.settings.maxResolution };+ const texels = plan.entries.reduce((total, { area, unwrapped }) => {+ const resolution = lightmapResolution(area, unwrapped.utilization, resolutionSettings);+ return total + resolution * resolution;+ }, 0);+ const { lights } = plan;+ const raysPerHit = 1 + lights.pointLights.length + lights.spotLights.length + lights.areaLights.length + (lights.sun ? 1 : 0);+ return { texels, rayWork: texels * samples * bounces * raysPerHit };+}++/** Traces a plan with the given settings (samples, bounces, texelsPerUnit, maxSeconds) and returns the baked parts and the report. */+export function traceLightmaps(plan, tracedSettings) {+ const { parts, lights, started, skipped } = plan;+ const settings = { ...plan.settings, ...tracedSettings };+ const { texels: texelTotal, rayWork } = estimateBake(plan, settings);if (texelTotal > MAX_BAKE_TEXELS) throw new RangeError(`Light bake would use ${texelTotal} texels; the limit is ${MAX_BAKE_TEXELS}. Lower maxResolution or texelsPerUnit.`);if (rayWork > MAX_BAKE_RAY_WORK) throw new RangeError(`Light bake would trace about ${rayWork} rays; the limit is ${MAX_BAKE_RAY_WORK}. Lower samples, bounces or texelsPerUnit.`);+ const world = buildWorld(parts);+ const scale = sceneScale(world.positions);+ const offset = scale * 1e-4;+ const tracer = createTracer(world);+ const directIrradiance = createDirectIrradiance(tracer, lights, offset, scale);+ const albedoOfPart = parts.map(part => diffuseAlbedo(part.material));+ const emissionOfPart = parts.map(part => emittedRadiance(part.material));+ const gather = createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples: settings.samples, bounces: settings.bounces });const baked = parts.slice();const partReports = [];const sum = [0, 0, 0];- for (const { part, index, unwrapped, resolution, slot } of plans) {+ for (const { part, index, unwrapped, area, slot } of plan.entries) {+ const resolution = lightmapResolution(area, unwrapped.utilization, settings);const { positions, normals, covered } = rasterizeTexels(unwrapped.geometry, part.matrix, resolution);const radiance = new Float32Array(resolution * resolution * 3);const albedo = albedoOfPart[index];diff --git a/tests/agent-bake.test.js b/tests/agent-bake.test.jsindex 8053a7ca..28ef9f0c 100644--- a/tests/agent-bake.test.js+++ b/tests/agent-bake.test.js@@ -2,7 +2,7 @@ import assert from 'node:assert/strict';import test from 'node:test';import { createAgentScene } from '../src/agent-scene.js';import { normalizeAgentBake } from '../src/agent-bake.js';-import { BAKE_PRESETS } from '../src/agent-scene-capabilities.js';+import { BAKE_PRESETS, BAKE_RAY_WORK_BUDGET, BAKE_MAXIMUM_SECONDS } from '../src/agent-scene-capabilities.js';function closedRoom(extra = {}) {const box = (id, translation, scale, material) => ({ id, geometry: 'box', material, translation, scale });@@ -149,3 +149,102 @@ test('a node that hosts a hair system bakes without an error and is reported asassert.ok(scene.parts.find(part => part.name === 'head').material.emissiveMap);assert.equal(scene.parts.find(part => part.name === 'fur').material.emissiveMap, undefined);});++function roomLitBy(environment) {+ return closedRoom({ environment: { ...environment, keyIntensity: 0, fillIntensity: 0 } });+}++function lightmapBytesOf(scene, name) {+ return lightmapBytes(scene.parts.find(part => part.name === name));+}++test('a spot light that points at the floor bakes the light that bounces off it', () => {+ const recipe = roomLitBy({ spotLights: [{ position: [0, 2.8, 0.5], direction: [0, -1, 0], angle: 0.6, intensity: 30 }] });+ const scene = createAgentScene(recipe);+ assert.ok(scene.parts.find(part => part.name === 'back').material.emissiveMap);+ assert.deepEqual(lightmapBytesOf(createAgentScene(recipe), 'back'), lightmapBytesOf(scene, 'back'));+ const withoutSpot = createAgentScene(roomLitBy({}));+ assert.notDeepEqual(lightmapBytesOf(withoutSpot, 'back'), lightmapBytesOf(scene, 'back'));+});++test('an area light bakes bounced light on its front side only, and a changed spot or area light bakes again', () => {+ const facingDown = roomLitBy({ areaLights: [{ position: [0, 2.9, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: 20 }] });+ const facingUp = roomLitBy({ areaLights: [{ position: [0, 2.9, 0], direction: [0, 1, 0], width: 1, height: 1, intensity: 20 }] });+ const scene = createAgentScene(facingDown);+ assert.ok(scene.parts.find(part => part.name === 'floor').material.emissiveMap);+ assert.deepEqual(lightmapBytesOf(createAgentScene(facingDown), 'floor'), lightmapBytesOf(scene, 'floor'));+ assert.notDeepEqual(lightmapBytesOf(createAgentScene(facingUp), 'floor'), lightmapBytesOf(scene, 'floor'));+ scene.apply([{ type: 'set-environment', environment: { areaLights: [{ position: [0, 2.9, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: 25 }] } }], { expectedRevision: 0 });+ assert.equal(scene.inspect().bake.reused, false);+});++function largeRoom(bake) {+ const recipe = closedRoom({ bake });+ recipe.environment.spotLights = [{ position: [0, 2.8, 0], direction: [0, -1, 0], angle: 1, intensity: 20 }];+ for (let index = 0; index < 48; index++) {+ const column = index % 8;+ const row = Math.floor(index / 8);+ recipe.nodes.push({ id: `crate-${index}`, geometry: 'box', material: 'white', translation: [-1.75 + column * 0.5, 0.3, -1.7 + row * 0.6], scale: [0.4, 0.6, 0.4] });+ }+ return recipe;+}++test('a preset on a 56 part room shrinks to the ray work budget, finishes, and reports what it used', () => {+ const scene = createAgentScene(largeRoom({ preset: 'standard' }));+ const bake = scene.inspect().bake;+ assert.equal(scene.parts.length, 56);+ assert.equal(bake.reduced, true);+ assert.ok(bake.used.samples < BAKE_PRESETS.standard.samples);+ assert.ok(bake.used.texelsPerUnit < BAKE_PRESETS.standard.texelsPerUnit);+ assert.equal(bake.used.bounces, BAKE_PRESETS.standard.bounces);+ assert.ok(bake.rayWork <= BAKE_RAY_WORK_BUDGET);+ assert.ok(bake.seconds < BAKE_MAXIMUM_SECONDS);+ const again = createAgentScene(largeRoom({ preset: 'standard' }));+ assert.deepEqual(again.inspect().bake.used, bake.used);+ assert.deepEqual(lightmapBytesOf(again, 'floor'), lightmapBytesOf(scene, 'floor'));+});++test('a preset that already fits is not reduced', () => {+ const bake = createAgentScene(closedRoom()).inspect().bake;+ assert.equal(bake.reduced, false);+ assert.deepEqual(bake.used, BAKE_PRESETS.draft);+});++test('explicit samples or texelsPerUnit over the budget fail with the number that fits, and that number works', () => {+ const heavy = { preset: 'draft', samples: 256, bounces: 3, texelsPerUnit: 12 };+ let message = '';+ assert.throws(() => createAgentScene(closedRoom({ bake: heavy })), error => {+ message = error.message;+ return /ray work/.test(error.message);+ });+ const fittingSamples = Number(/samples (\d+) or fewer/.exec(message)?.[1]);+ const fittingDensity = Number(/texelsPerUnit ([\d.]+) or less/.exec(message)?.[1]);+ assert.ok(fittingSamples >= 1 && fittingSamples < 256, message);+ assert.ok(fittingDensity >= 1 && fittingDensity < 12, message);+ const withSamples = createAgentScene(closedRoom({ bake: { ...heavy, samples: fittingSamples } })).inspect().bake;+ assert.equal(withSamples.reduced, false);+ assert.equal(withSamples.used.samples, fittingSamples);+ assert.ok(withSamples.rayWork <= BAKE_RAY_WORK_BUDGET);+});++function clothRoom() {+ const recipe = closedRoom({ cloth: { duration: 2, sheets: [{ node: 'flag', pin: ['top'] }] } });+ recipe.geometries.push({ id: 'sheet', type: 'grid', segments: 8 });+ recipe.nodes.push({ id: 'flag', geometry: 'sheet', material: 'white', translation: [0.5, 2, 0], scale: [1, 1, 1] });+ return recipe;+}++test('a cloth sheet is skipped by the bake and still has no lightmap after a seek past t=0', () => {+ const scene = createAgentScene(clothRoom());+ const skipped = scene.inspect().bake.skipped.find(entry => entry.name === 'flag');+ assert.ok(skipped);+ assert.match(skipped.reason, /cloth/);+ scene.sampleMotion(1);+ const flag = scene.parts.find(part => part.name === 'flag');+ assert.equal(flag.material.lightMap, undefined);+ assert.equal(flag.material.emissiveMap, undefined);+ for (const part of scene.parts) {+ assert.ok(!part.material.lightMap || part.geometry.lightUvs, `${part.name} has a light map without lightUvs`);+ }+ assert.ok(scene.parts.find(part => part.name === 'floor').material.emissiveMap);+});diff --git a/tests/light-bake.test.js b/tests/light-bake.test.jsindex eb5b05a0..efb64962 100644--- a/tests/light-bake.test.js+++ b/tests/light-bake.test.js@@ -132,6 +132,23 @@ test('options are validated with their bounds', () => {for (const bad of [null, [], 'fast', 3]) assert.throws(() => normalizeBakeOptions(bad), TypeError);});+test('hostile spot and area lights are refused before any ray is traced', () => {+ const spot = { position: [0, 2, 0], direction: [0, -1, 0], intensity: 5 };+ const area = { position: [0, 2, 0], direction: [0, -1, 0], width: 1, height: 1, intensity: 5 };+ const refused = [+ [{ spotLights: [{ ...spot, direction: [0, 0, 0] }] }, /spot light 0.*direction/],+ [{ spotLights: [{ ...spot, position: [0, Number.NaN, 0] }] }, /spot light 0/],+ [{ spotLights: [{ ...spot, angle: 4 }] }, /spot light 0.*angle/],+ [{ spotLights: Array(9).fill(spot) }, /at most 8 spot lights/],+ [{ areaLights: [{ ...area, width: -1 }] }, /area light 0.*width/],+ [{ areaLights: [{ ...area, intensity: Infinity }] }, /area light 0/],+ [{ areaLights: Array(5).fill(area) }, /at most 4 area lights/],+ ];+ for (const [lights, message] of refused) {+ assert.throws(() => bakeLightmaps(smallRoom(), { ...lamp, ...lights }, fastOptions), message);+ }+});+test('hostile parts and lights are refused before any ray is traced', () => {const withPosition = value => {const parts = smallRoom();