3D engine that AI agents drive
Give each smooth metal part a reflection probe of its own (part of issue #167)
Nguyen Xuan Ana5ea7643b12d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6e925f7..8bb110b7 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Show the floor and the other parts in smooth metal (part of issue #167, which stays open). `traceObjectProbes` in `src/probe-trace.js` gives each part with `metallic` of at least 0.5 and `roughness` of at most 0.6 a reflection probe of its own, traced from the middle of the part without it (up to 8 parts, lit by direct light and the environment's diffuse light), and `placeProbes` assigns it. `metal` scores 0.1294 to 0.1036 against Cycles (EEVEE 0.0916), `brushed-film` 0.1149 to 0.1029, `car-paint` 0.1059 to 0.1038, `material-spheres` 0.1312 to 0.1293; every scene without a reflective part is unchanged to four digits and draws the same frame (`metal` 1.51 ms plain, 1.58 ms with four probes). `npm run reference` places them by default; recipes do not yet.+- A renderer no longer draws its shadow map a second time on the first frame when the frame has no assembly; the constructor already drew it. On `mountain-valley` that removes 9.72 million shadow triangles from the first frame, with identical pictures (issue #171). `node bench/reference/profile-scene.mjs <scene>` prints where a scene's time goes, and `frame-time.mjs --plain` measures scenes that are too large for the light bake.- Tell an agent when its scene is a closed room with no bake (issue #163). `scene_inspect` now returns a `closed-room-without-bake` diagnostic when 90 percent or more of 48 rays from the middle of the scene hit a front face, and names `bake`; measured against Cycles a closed room goes from 0.1430 and 0.1436 (`dark-shaft`, `temple-hall`) to 0.0609 and 0.0560 once baked. No frame cost and no schema change; agent scene entry grows 884 bytes gzip. `bakeSkyVisibility` in `light-bake` writes only the occlusion map (0.1021 and 0.0856 in under a second) and is not applied automatically. **A closed room without a bake now shows a warning in `scene_inspect`.**- Clean up docs, media and scripts. Remove stale logs, six unreferenced PNG previews (about 6.1 MB) with their render sidecars, the OpenAI skill metadata and ten scripts that aimed at harness pages that no longer exist. Update the roadmap, the mesh and verification docs and the contributing guide, point the links to unshipped docs at GitHub, and add `npm run check:links`, `smoke:modeling`, `smoke:material-maps` and `benchmark:mesh-query`.diff --git a/bench/reference/README.md b/bench/reference/README.mdindex a8324ecc..3757db69 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -178,6 +178,54 @@ What ships: a `closed-room-without-bake` diagnostic in `scene_inspect` (`src/cloThe no-bake scores of every scene are unchanged: no shader, renderer or scene build code moved, and the full rescore after this change matches the committed `baseline.json`. Size: the agent scene entry grows by 884 bytes gzip and `light-bake` by 158; every budget still holds, so none changed. Whether a cold agent follows the existing rule in the skill without the diagnostic was not measured: the suite's tasks each need a reference recipe and checks, which cost more than the $1 the issue allowed.+## Reflections between objects (2026-11-02, issue #167)++A mirror sphere and a steel cylinder showed only the sky and a flat horizon, where Cycles and EEVEE show the floor and the other objects. Parts now take a probe of their own, and `metal` goes from 0.1294 to 0.1036 against Cycles (EEVEE 0.0916). That recovers 68 percent of the gap to EEVEE and does not reach it.++### Where the `metal` error was++FLIP error by region, before the change, on the existing 960 by 540 renders. The regions are discs projected from the object bounds, so a share of each shadow counts toward the object. The renders used here score 0.1336 against Cycles (the committed baseline said 0.1294), so read the columns against each other and not against the table above. Each cell is the region's share of the whole image mean, mean error times the share of pixels.++| Region | Pixels | 67js before | 67js with probes | EEVEE |+| --- | --- | --- | --- | --- |+| Chrome sphere | 5.6% | 0.0184 | 0.0145 | 0.0116 |+| Gold torus | 1.6% | 0.0016 | 0.0016 | 0.0016 |+| Copper box | 9.4% | 0.0307 | 0.0246 | 0.0248 |+| Steel cylinder | 2.8% | 0.0106 | 0.0078 | 0.0055 |+| Floor | 64.2% | 0.0702 | 0.0639 | 0.0565 |+| Sky | 16.5% | 0.0025 | 0.0025 | 0.0016 |+| Whole image | | 0.1336 | 0.1147 | 0.1014 |++The four reflective parts held 46 percent of the error before and 55 percent of the gap to EEVEE (0.0178 of 0.0322). The sphere's lower half showed sky below the horizon, where Cycles shows the grey floor, and the cylinder reflected no lit floor. The floor itself is not a reflector (roughness 0.8). Its remaining gap to EEVEE (0.0074 after the change, 0.0137 before) is indirect light and shadow softness, which a reflection does not change.++### Options++| Option | What it costs per frame | Score on `metal` | Status |+| --- | --- | --- | --- |+| One probe per reflective part, traced without that part | 1.51 ms plain against 1.58 ms with four probes (RTX 3060, medians of three alternating rounds of 200 frames; the spread between rounds was about 0.2 ms). A scene with no reflective part draws the same frame: no wrapper, no shader change. Once: a CPU trace of 128 by 64 texels per probe and a GPU prefilter on the first draw. | 0.1294 to 0.1036 | Built |+| Screen-space reflections | Not built. Inferred: a depth and colour pass before the reflective parts and a ray march for each reflective pixel, paid only by scenes with smooth metal. It shows only what is on screen, so the floor behind the camera and the back of an object stay missing. | not measured | Not built |+| Planar reflection for flat floors | Not built. A second scene draw for each mirror plane. The `metal` floor is rough, so it has nothing to reflect, and the `metal-room` floor is the only case here. | not measured | Not built |++A probe at the middle of the object and traced without it is the only option the code already supports, it costs no frame in a plain scene, and it gives a Cycles-like reflection of the floor and of other parts up to one bounce of direct light. A first version with one bounce had speckle on the floor (16 samples) and scored 0.1250 on the analysis renders; with no bounce and the sky's diffuse light added to each hit, it scored 0.1147. A first version without the sky light made the floor in the reflection black and scored 0.1457, worse than no probe (0.1336).++### What it does++`traceObjectProbes(parts, lighting, options)` in `src/probe-trace.js` finds the parts with `metallic` of at least 0.5 and `roughness` of at most 0.6, traces one 128 by 64 map at the middle of each one's bounds with that part left out, and returns the same shape as `traceProbes` plus the index of the part. `placeProbes` gives each such part its own probe. More than 8 reflective parts (lamp posts, spires) get none, because they read as shapes and not as mirrors. A trace shades a hit with the direct light, the part's colour (half the colour for metal) and the environment map's diffuse light. A ray that misses reads the environment map.++`npm run reference` places these probes by default on every scene that has no bake and no `--probes` flag; `--no-object-probes` draws the old sky-only reflections, and `--object-probes` with `--probes` names the scenes. There is no recipe field: a recipe scene does not place object probes yet, because the recipe path has no map of the sky to light the floor in the reflection (the procedural sky is a colour gradient), and that is the next piece of work.++### Scores against Cycles (GPU, full rescore, 2026-11-02)++| Scene | Before | After | EEVEE |+| --- | --- | --- | --- |+| `metal` | 0.1294 | 0.1036 | 0.0916 |+| `car-paint` | 0.1059 | 0.1038 | 0.0844 |+| `brushed-film` | 0.1149 | 0.1029 | 0.0984 |+| `material-spheres` | 0.1312 | 0.1293 | 0.1053 |+| `metal-room` | 0.5128 | 0.5076 | 0.5262 |++Every other scene scored the same to four digits, GPU and CPU. `car-paint` has one reflective part, so it gains little: the clearcoat sphere reflects the floor and nothing else. The issue's second box holds (no frame cost without a reflective part); its first box does not (`metal` is 0.012 above EEVEE).+## BaselineMeasured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metric is [FLIP](https://github.com/NVlabs/flip) for LDR images: 0 means identical, and a higher score means a larger visible difference.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 8b3ee0e5..ccedf9a0 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -117,18 +117,18 @@"gpu-vs-cpu": 0.0071},"brushed-film": {- "gpu-vs-cycles": 0.1149,- "gpu-vs-eevee": 0.1004,- "cpu-vs-cycles": 0.1146,- "cpu-vs-eevee": 0.1004,+ "gpu-vs-cycles": 0.1029,+ "gpu-vs-eevee": 0.0855,+ "cpu-vs-cycles": 0.1026,+ "cpu-vs-eevee": 0.0854,"eevee-vs-cycles": 0.0984,- "gpu-vs-cpu": 0.0061+ "gpu-vs-cpu": 0.0062},"car-paint": {- "gpu-vs-cycles": 0.1059,- "gpu-vs-eevee": 0.0679,- "cpu-vs-cycles": 0.1056,- "cpu-vs-eevee": 0.0679,+ "gpu-vs-cycles": 0.1038,+ "gpu-vs-eevee": 0.065,+ "cpu-vs-cycles": 0.1035,+ "cpu-vs-eevee": 0.065,"eevee-vs-cycles": 0.0844,"gpu-vs-cpu": 0.0059},@@ -201,10 +201,10 @@"gpu-vs-cpu": 0.0095},"material-spheres": {- "gpu-vs-cycles": 0.1312,- "gpu-vs-eevee": 0.0748,- "cpu-vs-cycles": 0.131,- "cpu-vs-eevee": 0.0745,+ "gpu-vs-cycles": 0.1293,+ "gpu-vs-eevee": 0.0756,+ "cpu-vs-cycles": 0.1291,+ "cpu-vs-eevee": 0.0753,"eevee-vs-cycles": 0.1053,"gpu-vs-cpu": 0.007},@@ -217,20 +217,20 @@"gpu-vs-cpu": 0.0281},"metal": {- "gpu-vs-cycles": 0.1294,- "gpu-vs-eevee": 0.0952,- "cpu-vs-cycles": 0.1291,- "cpu-vs-eevee": 0.0953,+ "gpu-vs-cycles": 0.1036,+ "gpu-vs-eevee": 0.0782,+ "cpu-vs-cycles": 0.1033,+ "cpu-vs-eevee": 0.0783,"eevee-vs-cycles": 0.0916,- "gpu-vs-cpu": 0.0067+ "gpu-vs-cpu": 0.0064},"metal-room": {- "gpu-vs-cycles": 0.5128,- "gpu-vs-eevee": 0.108,- "cpu-vs-cycles": 0.5124,- "cpu-vs-eevee": 0.1086,+ "gpu-vs-cycles": 0.5076,+ "gpu-vs-eevee": 0.1082,+ "cpu-vs-cycles": 0.5072,+ "cpu-vs-eevee": 0.1088,"eevee-vs-cycles": 0.5262,- "gpu-vs-cpu": 0.0061+ "gpu-vs-cpu": 0.0062},"mountain-valley": {"gpu-vs-cycles": 0.3473,diff --git a/bench/reference/frame-time.mjs b/bench/reference/frame-time.mjsindex 492e3071..985b4b74 100644--- a/bench/reference/frame-time.mjs+++ b/bench/reference/frame-time.mjs@@ -25,8 +25,11 @@ try {// Alternate the order so a drifting machine load does not favor one side. --cascades measures one map and three// cascades, each with a still camera and with a camera that moves every frame.// --plain measures only the plain frame, for scenes with more parts than the light bake takes.+ // --objects measures the plain frame against the frame with one probe for each reflective part.const variants = process.argv.includes('--plain')? [1, 2, 3].map(() => ({ bake: false, probes: false }))+ : process.argv.includes('--objects')+ ? [1, 2, 3].flatMap(round => (round % 2 ? [false, 'objects'] : ['objects', false]).map(probes => ({ bake: false, probes }))): process.argv.includes('--cascades')? [0, 3, 0, 3].flatMap(cascades => [false, true].map(orbit => ({ bake: false, cascades, orbit }))): [1, 2, 3].flatMap(round => (round % 2 ? [[false, false], [true, false], [true, true], [false, true]] : [[false, true], [true, true], [true, false], [false, false]]).map(([bake, probes]) => ({ bake, probes })));diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 6d92cd41..fb4194ed 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -120,13 +120,14 @@ function createSceneRenderer(parts, scene, cascades) {// no automatic probe, so these name one by hand.const PROBE_SPECIFICATIONS = { 'material-spheres': [{ position: [0, 1.6, 0] }], metal: [{ position: [0.2, 1, 0.9] }] };-async function probeScene(scene, id, drawnParts) {- const { placeProbes, traceProbes } = await import('/src/reflection-probes.js');+async function probeScene(scene, id, drawnParts, mode) {+ const { placeProbes, traceObjectProbes, traceProbes } = await import('/src/reflection-probes.js');const { pointLights, keyColor, lightDirection, map } = scene.environment;const started = performance.now();const lighting = { pointLights, keyColor, lightDirection };- const trace = traceProbes(scene.parts, lighting, PROBE_SPECIFICATIONS[id] ?? 'room', { environment: scene.environment, environmentMap: map, rotation: map.rotation });- const placed = placeProbes(drawnParts, trace, { rotation: map.rotation });+ const options = { environment: scene.environment, environmentMap: map, rotation: map?.rotation ?? 0 };+ const trace = mode === 'objects' ? traceObjectProbes(scene.parts, lighting, options) : traceProbes(scene.parts, lighting, PROBE_SPECIFICATIONS[id] ?? 'room', options);+ const placed = placeProbes(drawnParts, trace, { rotation: map?.rotation ?? 0 });return { parts: placed.parts, report: placed.report, seconds: (performance.now() - started) / 1000 };}@@ -135,7 +136,7 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambien// A measurement switch: 0 removes the world's light from every surface, to show how much of a picture comes from it.if (ambient !== null) scene.environment = { ...scene.environment, ambientIntensity: ambient };const baked = bake ? await bakeScene(scene, bake) : null;- const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts) : null;+ const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts, probes) : null;const canvas = document.querySelector('canvas');// backgroundOnly draws the sky alone, so a score can be limited to the pixels the asset covers.const renderer = createSceneRenderer(backgroundOnly ? [] : probed ? probed.parts : baked ? baked.parts : scene.parts, scene, cascades);@@ -160,7 +161,7 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambienasync function measureReferenceFrameTime(id, { bake, probes = false, cascades = 0, orbit = false, warmupFrames = 20, measuredFrames = 200 }) {const scene = await REFERENCE_SCENES[id]();const baked = bake ? await bakeScene(scene, {}) : null;- const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts) : null;+ const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts, probes) : null;const renderer = createSceneRenderer(probed ? probed.parts : baked ? baked.parts : scene.parts, scene, cascades);renderer.resize();const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0, ambientOcclusionRadius: 0.5 } };diff --git a/bench/reference/images/brushed-film.jpg b/bench/reference/images/brushed-film.jpgindex 1d518448..3dbdab84 100644Binary files a/bench/reference/images/brushed-film.jpg and b/bench/reference/images/brushed-film.jpg differdiff --git a/bench/reference/images/car-paint.jpg b/bench/reference/images/car-paint.jpgindex ccf683a4..45f76e61 100644Binary files a/bench/reference/images/car-paint.jpg and b/bench/reference/images/car-paint.jpg differdiff --git a/bench/reference/images/material-spheres.jpg b/bench/reference/images/material-spheres.jpgindex 58400c5f..c4a158d7 100644Binary files a/bench/reference/images/material-spheres.jpg and b/bench/reference/images/material-spheres.jpg differdiff --git a/bench/reference/images/metal-room.jpg b/bench/reference/images/metal-room.jpgindex 06a8d1fc..7a659b32 100644Binary files a/bench/reference/images/metal-room.jpg and b/bench/reference/images/metal-room.jpg differdiff --git a/bench/reference/images/metal.jpg b/bench/reference/images/metal.jpgindex c5770a51..d75f90cf 100644Binary files a/bench/reference/images/metal.jpg and b/bench/reference/images/metal.jpg differdiff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex a3d335cd..02bbdac9 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -53,6 +53,8 @@ const skyOnlyOptions = skyOnlyFlag >= 0 ? { skyOnly: true, texelsPerUnit: skyTexconst probesFlag =argumentsGiven.indexOf('--probes');const probesValue = probesFlag >= 0 ? argumentsGiven[probesFlag + 1] : undefined;const probedSceneIds = probesFlag >= 0 && probesValue && !probesValue.startsWith('--') ? probesValue.split(',') : null;+// --object-probes turns the --probes scenes into one probe per reflective part (traceObjectProbes) instead of a hand placed one.+const objectProbes = argumentsGiven.includes('--object-probes');const cascadesFlag = argumentsGiven.indexOf('--cascades');const cascades = cascadesFlag >= 0 ? Number(argumentsGiven[cascadesFlag + 1]) : 0;const ambientFlag = argumentsGiven.indexOf('--ambient');@@ -83,8 +85,12 @@ async function renderBackend(backend, serverUrl, graphics) {await openHarness();const started = performance.now();const describe = backend === 'gpu';- const probes = probesFlag >= 0 && (probedSceneIds === null || probedSceneIds.includes(id));+ const probesThisScene = probesFlag >= 0 && (probedSceneIds === null || probedSceneIds.includes(id));const bakesThisScene = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id));+ // A scene with no probe of its own and no bake gets one probe per reflective part, the way an engine would place them+ // automatically. --no-object-probes draws the sky-only reflections instead.+ const automaticProbes = !probesThisScene && !bakesThisScene && !argumentsGiven.includes('--no-object-probes');+ const probes = probesThisScene ? (objectProbes ? 'objects' : true) : automaticProbes ? 'objects' : false;const bake = bakesThisScene ? { ...skyOnlyOptions } : null;const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes, ambientScale]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes, ambient: ambientScale }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes, ambient]);if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);diff --git a/src/probe-trace.js b/src/probe-trace.jsindex d947bac7..a04c8787 100644--- a/src/probe-trace.js+++ b/src/probe-trace.js@@ -1,3 +1,4 @@+import { computeIrradianceCoefficients, evaluateIrradiance } from './environment.js';import { createTracer } from './ray-query.js';import {MAX_BAKE_PARTS, averageMapColor, buildWorld, createDirectIrradiance, createGatherer, emittedRadiance, hitNormal, normalizeLights, sceneScale, validatePart, withReach,@@ -16,6 +17,14 @@ const PROBE_BOUNCES = 2;const MAX_PROBE_PIXELS = 65536;+// Object probes: a sharp mirror needs a finer map than a room probe, and one bounce is enough for what a reflection shows.+export const MAXIMUM_OBJECT_PROBES = 8;+const OBJECT_PROBE_WIDTH = 128;+const OBJECT_PROBE_SAMPLES = 16;+const OBJECT_PROBE_BOUNCES = 0;+const OBJECT_PROBE_MINIMUM_METALLIC = 0.5;+const OBJECT_PROBE_MAXIMUM_ROUGHNESS = 0.6;+// A metal part has no diffuse albedo, but a probe that showed it black would hide the one thing a reflection is for.function probeAlbedo(material) {const metallic = material.metallic ?? 0;@@ -32,7 +41,7 @@ function probeAlbedo(material) {* lookup that applies the rotation finds the true direction. Returns `{ data, width, height, hitFraction }` for each* probe; the same input gives the same bytes.*/-export function traceProbeMaps(parts, lighting, positions, { width = 64, samples = 32, bounces = 2, rotation = 0, missRadiance = null, maxSeconds = 60 } = {}) {+export function traceProbeMaps(parts, lighting, positions, { width = 64, samples = 32, bounces = 2, rotation = 0, missRadiance = null, skyIrradiance = null, maxSeconds = 60 } = {}) {const height = width / 2;if (!Number.isInteger(width) || width < 8 || width * height > MAX_PROBE_PIXELS) throw new RangeError(`Probe width must be an even integer from 8 whose map has at most ${MAX_PROBE_PIXELS} pixels.`);if (!Array.isArray(parts) || parts.length === 0 || parts.length > MAX_BAKE_PARTS) throw new RangeError(`Probes take from 1 to ${MAX_BAKE_PARTS} parts.`);@@ -82,8 +91,11 @@ export function traceProbeMaps(parts, lighting, positions, { width = 64, samplesconst owner = world.triangleOwner[hit.nearestTriangle];const direct = directIrradiance(point, normal, owner);gather(point, normal, (probeIndex + 7777) * 1_000_003 + row * width + column, bounced);+ // An open scene's surfaces are lit by the sky too, and the room trace leaves that to the environment map.+ const sky = skyIrradiance ? skyIrradiance(normal) : null;for (let channel = 0; channel < 3; channel++) {- data[target + channel] = emissionOfPart[owner][channel] + albedoOfPart[owner][channel] * (direct[channel] / Math.PI + bounced[channel]);+ const skyLight = sky ? sky[channel] : 0;+ data[target + channel] = emissionOfPart[owner][channel] + albedoOfPart[owner][channel] * (direct[channel] / Math.PI + bounced[channel] + skyLight);}}}@@ -163,6 +175,20 @@ function environmentMissRadiance(map) {};}+// The diffuse light the environment map gives a surface with this normal, turned the way the renderer turns the map.+function environmentSkyIrradiance(map) {+ const coefficients = computeIrradianceCoefficients(map);+ const cosine = Math.cos(map.rotation);+ const sine = Math.sin(map.rotation);+ const mapped = [0, 0, 0];+ return normal => {+ mapped[0] = cosine * normal[0] - sine * normal[2];+ mapped[1] = normal[1];+ mapped[2] = sine * normal[0] + cosine * normal[2];+ return evaluateIrradiance(coefficients, mapped).map(value => value * map.intensity);+ };+}+function skyMissRadiance(environment) {const bottom = environment.skyBottom ?? [0.62, 0.70, 0.67];const top = environment.skyTop ?? [0.20, 0.38, 0.52];@@ -175,6 +201,40 @@ function skyMissRadiance(environment) {};}+/** A part that shows its surroundings: metal with a smooth enough surface for a reflection to read as a picture. */+export function isReflectivePart(material) {+ return (material.metallic ?? 0) >= OBJECT_PROBE_MINIMUM_METALLIC && (material.roughness ?? 1) <= OBJECT_PROBE_MAXIMUM_ROUGHNESS;+}++/**+ * One probe for each reflective part, at the middle of its bounds, traced without that part so it shows the others and+ * the floor and never itself. Each traced entry names its `part` (the index in `parts`). A scene with no reflective part,+ * or only one part, traces nothing.+ */+export function traceObjectProbes(parts, lighting, options = {}) {+ const { environment = {}, environmentMap = null, rotation = 0, samples = OBJECT_PROBE_SAMPLES, bounces = OBJECT_PROBE_BOUNCES, width = OBJECT_PROBE_WIDTH, maxSeconds = 60 } = options;+ const reflective = [];+ parts.forEach((part, index) => {+ if (isReflectivePart(part.material)) reflective.push(index);+ });+ // Many small metal parts (lamp posts, spires) read as shapes and not as mirrors, and each probe costs a trace and a draw batch.+ const wanted = reflective.length > MAXIMUM_OBJECT_PROBES ? [] : reflective;+ const skipped = wanted.length > 0 ? null : reflective.length > 0 ? `more than ${MAXIMUM_OBJECT_PROBES} reflective parts` : 'no reflective part';+ if (wanted.length === 0 || parts.length < 2) {+ return { traced: [], automatic: true, requested: reflective.length, skipped, seconds: 0 };+ }+ const started = performance.now();+ const missRadiance = environmentMap ? environmentMissRadiance(environmentMap) : skyMissRadiance(environment);+ const skyIrradiance = environmentMap ? environmentSkyIrradiance(environmentMap) : null;+ const traced = wanted.map(index => {+ const others = parts.filter((part, other) => other !== index);+ const position = boundsCentre(worldBounds(parts[index]));+ const [map] = traceProbeMaps(others, lighting, [position], { width, samples, bounces, rotation, missRadiance, skyIrradiance, maxSeconds });+ return { position, radius: null, part: index, ...map };+ });+ return { traced, automatic: true, requested: reflective.length, skipped: null, seconds: (performance.now() - started) / 1000 };+}+/*** Traces the probes of `specs`: a list of `{ position, radius? }` (a missing radius reaches the whole scene), or* `'room'` for one probe in the middle of the parts, kept only when the scene is enclosed. `parts` need world `matrix`diff --git a/src/reflection-probes.js b/src/reflection-probes.jsindex ce5ee6d8..edd63aa9 100644--- a/src/reflection-probes.js+++ b/src/reflection-probes.js@@ -6,7 +6,7 @@ import { boundsCentre, traceProbes, worldBounds } from './probe-trace.js';// Reflection probes: the room around a point, traced once and prefiltered like an environment map, so a glossy part// reflects the objects around it and not only the sky. This module is optional. A scene without a probe never loads it,// and the renderer's only link to it is the material field `environmentProbe`, which batches parts by probe.-export { MAXIMUM_PROBES, normalizeProbeList, roomCentreProbe, traceProbes } from './probe-trace.js';+export { MAXIMUM_PROBES, isReflectivePart, normalizeProbeList, roomCentreProbe, traceObjectProbes, traceProbes } from './probe-trace.js';// A probe lights the specular term only. Diffuse light stays with the environment and the light bake, which already hold it.@@ -43,11 +43,13 @@ function probedMaterial(liveMaterial, probeMap, wrappers) {/** Gives each part the nearest probe that reaches it, as a material wrapper that keeps reading the live material. */export function placeProbes(parts, probeTrace, { rotation = 0, wrappers = new Map() } = {}) {- const probes = probeTrace.traced.map(({ position, radius, width, height, data, hitFraction }) => ({- position, radius, hitFraction, map: createEnvironmentMap({ width, height, data, intensity: 1, rotation }),+ const probes = probeTrace.traced.map(({ position, radius, width, height, data, hitFraction, part }) => ({+ position, radius, hitFraction, part, map: createEnvironmentMap({ width, height, data, intensity: 1, rotation }),}));- const probedParts = parts.map(part => {- const probe = selectProbe(probes, boundsCentre(worldBounds(part)));+ const probesByPart = new Map(probes.filter(probe => probe.part !== undefined).map(probe => [probe.part, probe]));+ const sharedProbes = probes.filter(probe => probe.part === undefined);+ const probedParts = parts.map((part, index) => {+ const probe = probesByPart.get(index) ?? selectProbe(sharedProbes, boundsCentre(worldBounds(part)));return probe ? Object.freeze({ ...part, material: probedMaterial(part.material, probe.map, wrappers) }) : part;});const report = {diff --git a/tests/reflection-probes.test.js b/tests/reflection-probes.test.jsindex 564023e5..61753baa 100644--- a/tests/reflection-probes.test.js+++ b/tests/reflection-probes.test.js@@ -1,8 +1,8 @@import test from 'node:test';import assert from 'node:assert/strict';import { box, sphere } from '../src/geometry.js';-import { applyReflectionProbes, normalizeProbeList, selectProbe, roomCentreProbe } from '../src/reflection-probes.js';-import { traceProbeMaps, traceProbes } from '../src/probe-trace.js';+import { applyReflectionProbes, isReflectivePart, normalizeProbeList, placeProbes, selectProbe, roomCentreProbe, traceObjectProbes } from '../src/reflection-probes.js';+import { MAXIMUM_OBJECT_PROBES, traceProbeMaps, traceProbes } from '../src/probe-trace.js';import { createFragmentShader } from '../src/shaders.js';import { normalizeAgentBake } from '../src/agent-bake.js';@@ -108,3 +108,48 @@ test('a probe on a light-mapped part keeps its light map fields and still readslightMapped.material.color = [0.2, 0.3, 0.4];assert.deepEqual(probed.material.color, [0.2, 0.3, 0.4]);});++const openAir = { pointLights: [], keyColor: [0, 0, 0] };++function objectScene() {+ return [+ placed('floor', cube, [0, -0.05, 0], [20, 0.1, 20], { color: [0.5, 0.5, 0.5] }),+ placed('mirror', ball, [-1, 0.5, 0], [0.5, 0.5, 0.5], { metallic: 1, roughness: 0.05 }),+ placed('block', cube, [1, 0.5, 0], [1, 1, 1], { color: [0.9, 0.1, 0.1] }),+ ];+}++test('a reflective part gets a probe of its own, and no other part is probed', () => {+ const parts = objectScene();+ const trace = traceObjectProbes(parts, openAir, { width: 32 });+ assert.equal(trace.traced.length, 1);+ assert.equal(trace.traced[0].part, 1);+ assert.deepEqual(trace.traced[0].position.map(value => Math.round(value * 100) / 100), [-1, 0.5, 0]);+ const result = placeProbes(parts, trace);+ assert.equal(result.report.partsWithProbe, 1);+ assert.equal(result.parts[1].material.environmentProbe, result.probes[0].map);+ assert.equal(result.parts[0].material.environmentProbe, undefined);+ assert.equal(result.parts[2].material.environmentProbe, undefined);+});++test('the probe of a part never hits the part itself and sees the floor and the block', () => {+ const [probe] = traceObjectProbes(objectScene(), openAir, { width: 64 }).traced;+ // The floor fills the lower half of the view and the block part of the upper half; a mirror that traced itself would fill every ray.+ assert.ok(probe.hitFraction > 0.45 && probe.hitFraction < 0.65, `floor and block fill about half the view: ${probe.hitFraction}`);+});++test('a scene with no reflective part, or too many, traces nothing', () => {+ const plain = objectScene().map(part => ({ ...part, material: { ...part.material, metallic: 0 } }));+ assert.equal(traceObjectProbes(plain, openAir).traced.length, 0);+ const crowd = Array.from({ length: MAXIMUM_OBJECT_PROBES + 1 }, (item, index) => placed(`post-${index}`, cube, [index, 1, 0], [0.2, 2, 0.2], { metallic: 1, roughness: 0.3 }));+ const trace = traceObjectProbes(crowd, openAir);+ assert.equal(trace.traced.length, 0);+ assert.match(trace.skipped, /more than 8/);+});++test('rough metal and plain surfaces are not reflective', () => {+ assert.equal(isReflectivePart({ metallic: 1, roughness: 0.3 }), true);+ assert.equal(isReflectivePart({ metallic: 1, roughness: 0.9 }), false);+ assert.equal(isReflectivePart({ metallic: 0.2, roughness: 0.1 }), false);+ assert.equal(isReflectivePart({}), false);+});