Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add reflection probes behind bake.probes and a metal-room reference scene (Part of #55)

Nguyen Xuan An3bde6296ce01
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6b960022..ca1549a7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add reflection probes and a `metal-room` reference scene (part of issue #55, which stays open). `bake.probes` ('room' or up to 4 `{ position, radius? }`) traces the room around a point once, prefilters it through `createEnvironmentResources` and lets nearby parts reflect it (specular only, no parallax, not in GLB). Off by default: without a bake the rooms score 0.02 to 0.06 better against Cycles, but with a bake the picture did not change and open scenes score worse. Core growth is 48 bytes gzip (`lit-box`). `npm run reference -- --probes` and `frame-time.mjs` take the new variant.
+
- Darken the automatic floor and measure the default look with a blind pairwise judge (part of issue #53). `bench/agent-modeling/default-judge.mjs` draws the six cold recipes under two defaults from the three-quarter view and the recipe camera (what `scene_look` draws), shows a Sonnet judge both in a seeded random order and reports wins with an exact binomial p. The current default beats no floor 18 of 18 (p 0.0000076, 9 of 9 in each position); the control, one image against itself, picks "first" 17 of 18, so a tie goes to the first. The floor colour goes from 0.6, 0.6, 0.58 to 0.22, 0.22, 0.21 because the judge named a floor too close to the backdrop: it beats the old floor 18 of 18, while 0.38 won 13 of 18 (p 0.096) and was dropped. Only recipes that get the automatic floor change; the judge spend was $4.50, above its $4 plan. Core did not change.
- Import `SheenChair` and score it (part of issue #51). A glTF normal map may now carry its own `KHR_texture_transform` offset and positive scale (same rotation) on top of the transform the other maps share: the importer bakes the shared one into the UVs and stores the remainder as `uvTransform` on the normal map descriptor, and the `normalMapTransform` shader feature in `addons/material-layer-shaders` applies it (a scene without such a normal map compiles the same shader as before). Any other difference between the maps of one material still fails the import, and an extension `texCoord` equal to the texture's own is no longer refused. Core grew by 25 bytes gzip (`lit-box` 60,179 to 60,204): a hook in the normal map lookup, one feature line and the `bind` argument; the glTF importer grew by about 370.
diff --git a/bench/reference/README.md b/bench/reference/README.md
index afb2351e..c1edecd3 100644
--- a/bench/reference/README.md
+++ b/bench/reference/README.md
@@ -40,6 +40,8 @@ Light bake (issue #55): `npm run reference -- --bake lit-interior` bakes bounced
`brushed-film` (issue #51) holds a brushed gold sphere (`anisotropy` 0.8), a dark sphere with a thin film (`iridescence`, IOR 1.3, 400 nm) and a silver sphere with the same film. `render-blender.py` maps the glTF anisotropy model onto Blender's aspect ratio (alpha along the tangent is `mix(alpha, 1, strength^2)`, so Blender gets Anisotropic = (1 - alpha / alpha_tangent) / 0.9 and the geometric-mean roughness) and feeds a UV-map Tangent node, because Blender's default tangent is a different field: with the default tangent the first run scored 0.1673 against Cycles and the highlight ran in rings where 67js had bands; with the UV tangent it scores 0.1613 and the highlight direction matches. Thin film goes to Principled Thin Film Thickness and IOR. EEVEE draws no thin film, so its sphere stays black. The two models are not the same: Blender's film is its own Fresnel integration, 67js uses Belcour and Barla at the view angle, so match the colours by eye in the image, not by the score alone. Measured 2026-11-01 on the RTX 3060 and SwiftShader. Before and after adding anisotropy and iridescence, every older scene scored the same against Cycles and EEVEE to four digits (largest change 0.0000, limit 0.002), because their shaders compile the two layers out.
+`metal-room` (issue #55) is the `lit-interior` room with a mirror sphere, a gold sphere and a glossy floor, to show what reflection probes do: 0.5128 against Cycles without a probe and 0.4520 with one (`npm run reference -- --skip-blender --probes metal-room`; with `--bake` the score is 0.1754 either way). `--probes [ids]` adds probes to the named scenes; open scenes use a hand placed probe from `PROBE_SPECIFICATIONS` in `harness.js`, and score worse (`metal` 0.1868 to 0.2246, `material-spheres` 0.1598 to 0.1740). Every scene without a probe re-scored within 0.0001 of its earlier baseline.
+
The mean against Cycles is 0.198 for 67js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.
EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In `lit-interior` and `fog`, EEVEE scores no better than 67js. Those two scenes depend on indirect light, and this suite does not use EEVEE light probes. A low score does not mean a good picture on its own, so read each score with its image in `images/`.
diff --git a/bench/reference/baseline.json b/bench/reference/baseline.json
index 07cc4cc9..dddb70a5 100644
--- a/bench/reference/baseline.json
+++ b/bench/reference/baseline.json
@@ -3,68 +3,72 @@
"blenderVersion": "5.2.2 LTS",
"seconds": {
"brick-flat": {
- "cycles": 24.4,
- "eevee": 6.4
+ "cycles": 57.7,
+ "eevee": 6.8
},
"brick-graph": {
- "cycles": 25.9,
- "eevee": 29.8
+ "cycles": 50.6,
+ "eevee": 1.4
},
"brick-room": {
- "cycles": 122.6,
- "eevee": 2.9
+ "cycles": 27.3,
+ "eevee": 2.8
},
"brushed-film": {
- "cycles": 28.7,
- "eevee": 0.6
+ "cycles": 16.4,
+ "eevee": 3.9
},
"car-paint": {
- "cycles": 46.9,
- "eevee": 2.3
+ "cycles": 11.7,
+ "eevee": 7.4
},
"character": {
- "cycles": 27.8,
- "eevee": 1.7
+ "cycles": 16.4,
+ "eevee": 3.0
},
"fog": {
- "cycles": 186.7,
- "eevee": 1.3
+ "cycles": 31.8,
+ "eevee": 3.5
},
"foliage": {
- "cycles": 44.8,
- "eevee": 0.6
+ "cycles": 36.0,
+ "eevee": 9.0
},
"glass": {
- "cycles": 15.1,
- "eevee": 0.5
+ "cycles": 30.0,
+ "eevee": 2.5
},
"light-linking": {
- "cycles": 21.3,
- "eevee": 1.0
+ "cycles": 29.4,
+ "eevee": 1.4
},
"lit-interior": {
- "cycles": 64.2,
- "eevee": 12.1
+ "cycles": 43.6,
+ "eevee": 0.9
},
"long-street": {
- "cycles": 50.7,
- "eevee": 0.6
+ "cycles": 7.3,
+ "eevee": 0.7
},
"material-spheres": {
- "cycles": 15.2,
- "eevee": 0.7
+ "cycles": 13.5,
+ "eevee": 3.4
},
- "metal": {
- "cycles": 52.5,
+ "metal-room": {
+ "cycles": 33.0,
"eevee": 1.0
},
+ "metal": {
+ "cycles": 19.9,
+ "eevee": 1.7
+ },
"outdoor-hdri": {
- "cycles": 11.5,
- "eevee": 0.8
+ "cycles": 18.6,
+ "eevee": 2.0
},
"spot-area": {
- "cycles": 18.4,
- "eevee": 0.7
+ "cycles": 33.5,
+ "eevee": 3.6
}
},
"graphics": {
@@ -109,7 +113,7 @@
"gpu-vs-eevee": 0.1323,
"cpu-vs-cycles": 0.152,
"cpu-vs-eevee": 0.1323,
- "eevee-vs-cycles": 0.082,
+ "eevee-vs-cycles": 0.0819,
"gpu-vs-cpu": 0.0055
},
"character": {
@@ -124,13 +128,13 @@
"gpu-vs-cycles": 0.2612,
"gpu-vs-eevee": 0.0542,
"cpu-vs-cycles": 0.2608,
- "cpu-vs-eevee": 0.0542,
- "eevee-vs-cycles": 0.2661,
+ "cpu-vs-eevee": 0.0543,
+ "eevee-vs-cycles": 0.2662,
"gpu-vs-cpu": 0.0085
},
"foliage": {
"gpu-vs-cycles": 0.1594,
- "gpu-vs-eevee": 0.1387,
+ "gpu-vs-eevee": 0.1386,
"cpu-vs-cycles": 0.159,
"cpu-vs-eevee": 0.1384,
"eevee-vs-cycles": 0.0783,
@@ -165,7 +169,7 @@
"gpu-vs-eevee": 0.1396,
"cpu-vs-cycles": 0.1554,
"cpu-vs-eevee": 0.1396,
- "eevee-vs-cycles": 0.0975,
+ "eevee-vs-cycles": 0.0976,
"gpu-vs-cpu": 0.0098
},
"material-spheres": {
@@ -184,6 +188,14 @@
"eevee-vs-cycles": 0.0934,
"gpu-vs-cpu": 0.0063
},
+ "metal-room": {
+ "gpu-vs-cycles": 0.5128,
+ "gpu-vs-eevee": 0.108,
+ "cpu-vs-cycles": 0.5124,
+ "cpu-vs-eevee": 0.1086,
+ "eevee-vs-cycles": 0.5262,
+ "gpu-vs-cpu": 0.0061
+ },
"outdoor-hdri": {
"gpu-vs-cycles": 0.0676,
"gpu-vs-eevee": 0.052,
diff --git a/bench/reference/frame-time.mjs b/bench/reference/frame-time.mjs
index 2bc11f6c..20a15a1a 100644
--- a/bench/reference/frame-time.mjs
+++ b/bench/reference/frame-time.mjs
@@ -1,4 +1,5 @@
-// Frame time of a reference scene with and without the light bake: node bench/reference/frame-time.mjs [scene-id] [gpu|cpu]
+// Frame time of a reference scene: plain, with the light bake, with reflection probes, and with both.
+// node bench/reference/frame-time.mjs [scene-id] [gpu|cpu]
import { constants, setPriority } from 'node:os';
import { chromium } from 'playwright';
import { createServer } from 'vite';
@@ -25,7 +26,7 @@ try {
// cascades, each with a still camera and with a camera that moves every frame.
const variants = process.argv.includes('--cascades')
? [0, 3, 0, 3].flatMap(cascades => [false, true].map(orbit => ({ bake: false, cascades, orbit })))
- : [false, true, false, true].map(bake => ({ bake }));
+ : [[false, false], [true, false], [true, true], [false, true], [false, false], [true, false], [true, true], [false, true]].map(([bake, probes]) => ({ bake, probes }));
for (const variant of variants) {
results.push({ ...variant, ...(await page.evaluate(([id, options]) => window.measureReferenceFrameTime(id, options), [sceneId, variant])) });
}
diff --git a/bench/reference/harness.js b/bench/reference/harness.js
index df4e7743..d87cc439 100644
--- a/bench/reference/harness.js
+++ b/bench/reference/harness.js
@@ -85,12 +85,27 @@ function createSceneRenderer(parts, scene, cascades) {
});
}
-async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false }) {
+// Probes are traced from the original parts and placed on whichever parts the scene draws (baked or not). An open scene has
+// 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');
+ 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 });
+ return { parts: placed.parts, report: placed.report, seconds: (performance.now() - started) / 1000 };
+}
+
+async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0, backgroundOnly = false, probes = false }) {
const scene = await SCENES[id]();
const baked = bake ? await bakeScene(scene, bake) : null;
+ const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts) : 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 ? [] : baked ? baked.parts : scene.parts, scene, cascades);
+ const renderer = createSceneRenderer(backgroundOnly ? [] : 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, ambientOcclusionRadius } };
renderer.render(frame);
@@ -102,16 +117,18 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambien
graphics: renderer.context.getParameter(debug ? debug.UNMASKED_RENDERER_WEBGL : renderer.context.RENDERER),
description: describe ? describeScene(id, scene) : null,
bake: baked ? { seconds: baked.seconds, report: baked.report } : null,
+ probes: probed ? { seconds: probed.seconds, report: probed.report } : null,
};
renderer.dispose();
return result;
}
// Frame time of one scene with and without the light bake: a bake only adds an emissive map to each part, so this shows what it costs to draw.
-async function measureReferenceFrameTime(id, { bake, cascades = 0, orbit = false, warmupFrames = 20, measuredFrames = 200 }) {
+async 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 renderer = createSceneRenderer(baked ? baked.parts : scene.parts, scene, cascades);
+ const probed = probes ? await probeScene(scene, id, baked ? baked.parts : scene.parts) : 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 } };
// With orbit the camera moves a little every frame, so cascaded maps have to be redrawn each time, as in a camera move.
@@ -133,7 +150,7 @@ async function measureReferenceFrameTime(id, { bake, cascades = 0, orbit = false
renderer.dispose();
frameMilliseconds.sort((first, second) => first - second);
const total = frameMilliseconds.reduce((sum, value) => sum + value, 0);
- return { baked: Boolean(bake), frames: measuredFrames, meanMilliseconds: total / measuredFrames,
+ return { baked: Boolean(bake), probes: Boolean(probes), frames: measuredFrames, meanMilliseconds: total / measuredFrames,
medianMilliseconds: frameMilliseconds[Math.floor(measuredFrames / 2)], p95Milliseconds: frameMilliseconds[Math.floor(measuredFrames * 0.95)] };
}
diff --git a/bench/reference/images/brick-flat.jpg b/bench/reference/images/brick-flat.jpg
index ac30b9ed..08a3c07e 100644
Binary files a/bench/reference/images/brick-flat.jpg and b/bench/reference/images/brick-flat.jpg differ
diff --git a/bench/reference/images/brick-graph.jpg b/bench/reference/images/brick-graph.jpg
index 6c5022de..0e4f116c 100644
Binary files a/bench/reference/images/brick-graph.jpg and b/bench/reference/images/brick-graph.jpg differ
diff --git a/bench/reference/images/brick-room.jpg b/bench/reference/images/brick-room.jpg
index 4bf6c81f..5c0363c6 100644
Binary files a/bench/reference/images/brick-room.jpg and b/bench/reference/images/brick-room.jpg differ
diff --git a/bench/reference/images/brushed-film.jpg b/bench/reference/images/brushed-film.jpg
index 6b8e82a1..ea7791b7 100644
Binary files a/bench/reference/images/brushed-film.jpg and b/bench/reference/images/brushed-film.jpg differ
diff --git a/bench/reference/images/car-paint.jpg b/bench/reference/images/car-paint.jpg
index c4574da3..337bd214 100644
Binary files a/bench/reference/images/car-paint.jpg and b/bench/reference/images/car-paint.jpg differ
diff --git a/bench/reference/images/character.jpg b/bench/reference/images/character.jpg
index e30c8646..db4d7977 100644
Binary files a/bench/reference/images/character.jpg and b/bench/reference/images/character.jpg differ
diff --git a/bench/reference/images/fog.jpg b/bench/reference/images/fog.jpg
index 77e97c5d..b86bbe69 100644
Binary files a/bench/reference/images/fog.jpg and b/bench/reference/images/fog.jpg differ
diff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpg
index ce69fec3..ae174fb9 100644
Binary files a/bench/reference/images/foliage.jpg and b/bench/reference/images/foliage.jpg differ
diff --git a/bench/reference/images/glass.jpg b/bench/reference/images/glass.jpg
index 8134e8a5..764314f2 100644
Binary files a/bench/reference/images/glass.jpg and b/bench/reference/images/glass.jpg differ
diff --git a/bench/reference/images/light-linking.jpg b/bench/reference/images/light-linking.jpg
index e1c815fa..c0d4a0df 100644
Binary files a/bench/reference/images/light-linking.jpg and b/bench/reference/images/light-linking.jpg differ
diff --git a/bench/reference/images/lit-interior.jpg b/bench/reference/images/lit-interior.jpg
index b5ccf1f6..47d17430 100644
Binary files a/bench/reference/images/lit-interior.jpg and b/bench/reference/images/lit-interior.jpg differ
diff --git a/bench/reference/images/long-street.jpg b/bench/reference/images/long-street.jpg
index ad11befa..a492eb94 100644
Binary files a/bench/reference/images/long-street.jpg and b/bench/reference/images/long-street.jpg differ
diff --git a/bench/reference/images/material-spheres.jpg b/bench/reference/images/material-spheres.jpg
index 8a1cf5d1..9918aaca 100644
Binary files a/bench/reference/images/material-spheres.jpg and b/bench/reference/images/material-spheres.jpg differ
diff --git a/bench/reference/images/metal-room.jpg b/bench/reference/images/metal-room.jpg
new file mode 100644
index 00000000..ede47cf8
Binary files /dev/null and b/bench/reference/images/metal-room.jpg differ
diff --git a/bench/reference/images/metal.jpg b/bench/reference/images/metal.jpg
index e6a5b756..09332444 100644
Binary files a/bench/reference/images/metal.jpg and b/bench/reference/images/metal.jpg differ
diff --git a/bench/reference/images/outdoor-hdri.jpg b/bench/reference/images/outdoor-hdri.jpg
index f6d2b29a..99682236 100644
Binary files a/bench/reference/images/outdoor-hdri.jpg and b/bench/reference/images/outdoor-hdri.jpg differ
diff --git a/bench/reference/images/spot-area.jpg b/bench/reference/images/spot-area.jpg
index 62462bed..41dce0b4 100644
Binary files a/bench/reference/images/spot-area.jpg and b/bench/reference/images/spot-area.jpg differ
diff --git a/bench/reference/run.mjs b/bench/reference/run.mjs
index 8c3e7ccf..afef0bd1 100644
--- a/bench/reference/run.mjs
+++ b/bench/reference/run.mjs
@@ -2,6 +2,7 @@
// --ambient-occlusion <strength> [--ambient-occlusion-radius <units>] turns occlusion on (off by default).
// --bake [<id>,<id>] bakes bounced light into the named scenes (every scene when no ids follow) before 67js draws them;
// Blender still gets the plain scene.
+// --probes [<id>,<id>] adds reflection probes (src/reflection-probes.js) to the named scenes, on top of --bake when both are given.
// --path-tracer [--samples <n>] [--noise-threshold <n>] [--scene <id>] draws the scenes with the offline path tracer (src/path-tracer.js) instead, keeps the
// Cycles renders of an earlier run, and scores them into path-tracer.json. Nothing in baseline.json or images/ changes.
// Use --score-only to score existing renders, --skip-blender to keep them, and --scene <id> for one scene.
@@ -40,6 +41,9 @@ const ambientOcclusionRadius = radiusFlag >= 0 ? Number(argumentsGiven[radiusFla
const bakeFlag = argumentsGiven.indexOf('--bake');
const bakeValue = bakeFlag >= 0 ? argumentsGiven[bakeFlag + 1] : undefined;
const bakedSceneIds = bakeFlag >= 0 && bakeValue && !bakeValue.startsWith('--') ? bakeValue.split(',') : null;
+const probesFlag = argumentsGiven.indexOf('--probes');
+const probesValue = probesFlag >= 0 ? argumentsGiven[probesFlag + 1] : undefined;
+const probedSceneIds = probesFlag >= 0 && probesValue && !probesValue.startsWith('--') ? probesValue.split(',') : null;
const cascadesFlag = argumentsGiven.indexOf('--cascades');
const cascades = cascadesFlag >= 0 ? Number(argumentsGiven[cascadesFlag + 1]) : 0;
const pathTracerFlag = argumentsGiven.includes('--path-tracer');
@@ -63,8 +67,9 @@ async function renderBackend(backend, serverUrl, graphics) {
if (onlyScene && id !== onlyScene) continue;
const started = performance.now();
const describe = backend === 'gpu';
+ const probes = probesFlag >= 0 && (probedSceneIds === null || probedSceneIds.includes(id));
const bake = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id)) ? {} : null;
- const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades]);
+ const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions, cascadeCount, withProbes]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions, cascades: cascadeCount, probes: withProbes }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake, cascades, probes]);
if (result.glError !== 0) throw new Error(`${id} on ${backend} gave WebGL error ${result.glError}.`);
graphics[backend] = result.graphics;
await writeFile(`${WORK_DIRECTORY}/${id}-${backend}.png`, Buffer.from(result.image, 'base64'));
@@ -74,7 +79,8 @@ async function renderBackend(backend, serverUrl, graphics) {
await writeFile(`${WORK_DIRECTORY}/${id}-background.png`, Buffer.from(background.image, 'base64'));
}
const bakeNote = result.bake ? `, bake ${result.bake.seconds.toFixed(1)} s, ${result.bake.report.texels} texels` : '';
- console.log(`${id} on ${backend}: ${Math.round(performance.now() - started)} ms${bakeNote}`);
+ const probeNote = result.probes ? `, probes ${result.probes.report.placed.length} on ${result.probes.report.partsWithProbe} parts` : '';
+ console.log(`${id} on ${backend}: ${Math.round(performance.now() - started)} ms${bakeNote}${probeNote}`);
}
if (errors.length) throw new Error(errors.join('\n'));
} finally {
diff --git a/bench/reference/scenes.js b/bench/reference/scenes.js
index 4fc83d81..78245f40 100644
--- a/bench/reference/scenes.js
+++ b/bench/reference/scenes.js
@@ -214,6 +214,34 @@ export const REFERENCE_SCENES = {
};
},
+ // The lit-interior room with a mirror sphere, a gold sphere and a glossy floor: what a reflection probe is for.
+ async 'metal-room'() {
+ const lighting = constantLighting(0.02);
+ const wall = { color: [0.7, 0.68, 0.62], roughness: 0.9 };
+ const cube = box(0, 1);
+ const parts = [
+ part('room-floor', cube, [0, -0.05, 0], [8, 0.1, 8], { color: [0.35, 0.3, 0.27], roughness: 0.25 }),
+ part('room-ceiling', cube, [0, 3.05, 0], [8, 0.1, 8], wall),
+ part('room-back', cube, [0, 1.5, -4.05], [8, 3.2, 0.1], wall),
+ part('room-left', cube, [-4.05, 1.5, 0], [0.1, 3.2, 8], { ...wall, color: [0.55, 0.25, 0.2] }),
+ part('room-right', cube, [4.05, 1.5, 0], [0.1, 3.2, 8], { ...wall, color: [0.2, 0.35, 0.5] }),
+ part('room-front', cube, [0, 1.5, 4.05], [8, 3.2, 0.1], wall),
+ part('table', cube, [0, 0.7, -1], [2.4, 0.1, 1.2], { color: [0.3, 0.18, 0.1], roughness: 0.4 }),
+ part('mirror', sphere(64, 40), [-0.6, 1.05, -1], [0.3, 0.3, 0.3], { color: [0.95, 0.95, 0.95], metallic: 1, roughness: 0.04 }),
+ part('gold', sphere(64, 40), [0.6, 1.05, -1], [0.3, 0.3, 0.3], { color: [1, 0.77, 0.34], metallic: 1, roughness: 0.25 }),
+ ];
+ const pointLights = [
+ { position: [0, 2.6, -0.5], color: [1, 0.9, 0.75], intensity: 8, radius: 0.05, castShadow: true },
+ { position: [-2.5, 1.5, 1.5], color: [1, 0.6, 0.4], intensity: 2, radius: 0.05, castShadow: true },
+ { position: [2.5, 1.5, 1.5], color: [0.5, 0.7, 1], intensity: 2, radius: 0.05, castShadow: true },
+ ];
+ return {
+ parts, blenderWorld: lighting.blenderWorld,
+ environment: environment(lighting, { pointLights }),
+ camera: { eye: [0, 1.5, 3.9], target: [0, 1, -1], up: [0, 1, 0], fov: 50, near: 0.05, far: 50 },
+ };
+ },
+
// A closed room built from a recipe, with brick walls: the bake has to give a patterned wall bounced light and keep its bricks.
async 'brick-room'() {
const lighting = constantLighting(0.02);
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index fc0fb879..4ac5f12b 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 289090,
- "gzip": 82703,
- "brotli": 70463
+ "min": 289306,
+ "gzip": 82774,
+ "brotli": 70473
},
"entry:model": {
"min": 40093,
@@ -39,14 +39,14 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 158507,
- "gzip": 48584,
- "brotli": 42047
+ "min": 159468,
+ "gzip": 48943,
+ "brotli": 42391
},
"entry:gltf+lazy": {
- "min": 169480,
- "gzip": 51789,
- "brotli": 44979
+ "min": 170759,
+ "gzip": 52270,
+ "brotli": 45429
},
"entry:modeling": {
"min": 21149,
@@ -129,14 +129,14 @@
"brotli": 4675
},
"entry:light-bake": {
- "min": 73438,
- "gzip": 26713,
- "brotli": 23608
+ "min": 73639,
+ "gzip": 26808,
+ "brotli": 23679
},
"entry:path-tracer": {
- "min": 33435,
- "gzip": 13479,
- "brotli": 11838
+ "min": 35311,
+ "gzip": 14226,
+ "brotli": 12466
},
"entry:texture-set": {
"min": 1837,
@@ -144,24 +144,24 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 214722,
- "gzip": 66960,
- "brotli": 58652
+ "min": 222460,
+ "gzip": 69591,
+ "brotli": 60978
},
"entry:agent-scene+lazy": {
- "min": 677234,
- "gzip": 233780,
- "brotli": 206588
+ "min": 692879,
+ "gzip": 239495,
+ "brotli": 211708
},
"entry:agent-asset": {
- "min": 309821,
- "gzip": 98589,
- "brotli": 86642
+ "min": 317572,
+ "gzip": 101036,
+ "brotli": 88777
},
"entry:agent-asset+lazy": {
- "min": 714100,
- "gzip": 245447,
- "brotli": 216586
+ "min": 729753,
+ "gzip": 250974,
+ "brotli": 221437
},
"entry:hdri": {
"min": 8075,
@@ -179,44 +179,44 @@
"brotli": 1425
},
"entry:material-layer-shaders": {
- "min": 76556,
- "gzip": 19687,
- "brotli": 17305
+ "min": 76919,
+ "gzip": 19827,
+ "brotli": 17421
},
"entry:light-linking": {
- "min": 67970,
- "gzip": 18132,
- "brotli": 15941
+ "min": 68011,
+ "gzip": 18153,
+ "brotli": 15963
},
"entry:cascaded-shadows": {
- "min": 95719,
- "gzip": 26679,
- "brotli": 22674
+ "min": 95760,
+ "gzip": 26701,
+ "brotli": 22773
},
"scene:lit-box": {
- "min": 218641,
- "gzip": 60179,
- "brotli": 51428
+ "min": 218857,
+ "gzip": 60252,
+ "brotli": 51463
},
"scene:gltf-box": {
- "min": 280223,
- "gzip": 80810,
- "brotli": 70295
+ "min": 281359,
+ "gzip": 81225,
+ "brotli": 70600
},
"scene:gltf-box+lazy": {
- "min": 291196,
- "gzip": 84016,
- "brotli": 73226
+ "min": 292645,
+ "gzip": 84550,
+ "brotli": 73645
},
"scene:agent-scene": {
- "min": 326356,
- "gzip": 97862,
- "brotli": 85183
+ "min": 327796,
+ "gzip": 98464,
+ "brotli": 85766
},
"scene:agent-scene+lazy": {
- "min": 788868,
- "gzip": 264689,
- "brotli": 233118
+ "min": 798215,
+ "gzip": 268369,
+ "brotli": 236379
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index bfc45622..b3925f53 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -6,13 +6,13 @@
"agent-scene": 100000
},
"budgets": {
- "entry:core": 84400,
+ "entry:core": 84500,
"entry:model": 14400,
"entry:nature": 13200,
"entry:motion": 13600,
"entry:canvas2d": 9400,
- "entry:gltf": 49600,
- "entry:gltf+lazy": 52900,
+ "entry:gltf": 50000,
+ "entry:gltf+lazy": 53400,
"entry:modeling": 8700,
"entry:sculpt": 2500,
"entry:surface": 10100,
@@ -29,23 +29,23 @@
"entry:terrain": 3400,
"entry:grass": 4400,
"entry:clutter": 5300,
- "entry:light-bake": 27300,
- "entry:path-tracer": 14400,
+ "entry:light-bake": 27400,
+ "entry:path-tracer": 14600,
"entry:texture-set": 900,
- "entry:agent-scene": 68300,
- "entry:agent-scene+lazy": 238500,
- "entry:agent-asset": 100600,
- "entry:agent-asset+lazy": 250400,
+ "entry:agent-scene": 71000,
+ "entry:agent-scene+lazy": 244300,
+ "entry:agent-asset": 103100,
+ "entry:agent-asset+lazy": 256000,
"entry:hdri": 3300,
"entry:camera-effects": 8600,
"entry:render-passes": 1700,
- "entry:material-layer-shaders": 20100,
- "entry:light-linking": 18500,
+ "entry:material-layer-shaders": 20300,
+ "entry:light-linking": 18600,
"entry:cascaded-shadows": 27300,
- "scene:lit-box": 61400,
- "scene:gltf-box": 82500,
- "scene:gltf-box+lazy": 85700,
- "scene:agent-scene": 99900,
- "scene:agent-scene+lazy": 270000
+ "scene:lit-box": 61500,
+ "scene:gltf-box": 82900,
+ "scene:gltf-box+lazy": 86300,
+ "scene:agent-scene": 100500,
+ "scene:agent-scene+lazy": 273800
}
}
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 2d2c73d9..12a2d2c5 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,5 +1,5 @@
{
- "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades",
+ "measured": "2026-10-31, from scripts/measure-tool-cost.mjs; raised by 800 total and 150 for scene_apply for branch and labels fields (no new tool); raised by 650 total and 80 for scene_apply for clip layers, bone masks and retargeting through MCP; raised by 20 for scene_create and 20 for the scene_capabilities result after merging the expression language with the material graph; was 373388 schema bytes before shared IDs and recipe references; trimmed after the render-passes merge: material graph, depth of field, motion blur and passes details moved to scene_capabilities, budgets set to the measured value plus 0.5% (total 188267, scene_capabilities result 5167); raised by 95 for scene_apply and 690 for the scene_capabilities result for node relations; curve and text geometry entries shortened to a pointer at scene_capabilities curveText, budgets set to the measured value plus 0.5% (total 189468, scene_capabilities result 6399); then six modifier ops (weld, triangulate, edge_split, smooth, simple_deform, cast) added as one compact schema entry with details in scene_capabilities meshModifiers, entry and mesh_stack description shortened: total 190382 (budget unchanged at 190420), mesh_edit 34216 (budget 34220), scene_capabilities result 7042 (budget 7050); mesh_stack 11682 (budget 11690); after merging imported mesh topology with the modifier ops: raised the total to 190480 (measured 190471), mesh_edit to 34300 (measured 34293) and the scene_capabilities result to 7520 (measured 7512) for imported mesh edits; then cloth (recipe cloth, set-cloth, grid geometry) added with the total unchanged at 190480 (measured 189159): physics descriptions shortened and set-physics now takes the same record reference as set-motion, scene_create raised to 62150 and scene_apply lowered to 44130, scene_capabilities result raised to 8190 (measured 8176) for the cloth details; then particles and hair (recipe `particles`, set-particles) added with the total unchanged at 190480 (measured 189642, scene_create raised to 62350 and scene_apply to 44370 for the recipe particles reference and set-particles): the section is one record reference described in scene_capabilities, so the scene_capabilities result rose to 9570 (measured 9523) for the particle and hair fields; after merging the film timeline (recipe timeline, set-timeline) with particles: total 190719 (budget 190730), scene_create 62464, scene_apply 44620, scene_capabilities result 9902; then the path tracer renderer setting (drop z.int bounds, integers still checked by the job validator): total raised to 190830 (measured 190818); after merging the render limits and light bake with the path tracer: measured total 190013, scene_create raised to 62680 (measured 62667), scene_apply to 44860 (measured 44852) and the scene_capabilities result to 10620 (measured 10613) for the bake section and job size limits; then material layers anisotropy and iridescence (issue #51): the 16 layer fields take one short line each in the schema and their ranges and notes moved to scene_capabilities scene.materialLayers, so the scene_capabilities result rose to 12230 (measured 12168); then the worker bake limit added workerMaxSeconds to the bake limits (result 13361, budget raised to 13370); then the sculpt and shrinkwrap mesh edits (issue #47) with the total unchanged at 190830 (measured 190612): the face rule and tag prefix descriptions shortened (the face rule text repeats in every select field), so mesh_edit rose to 33980 (measured 33960) and mesh_stack fell to 11030 (measured 11014), and the scene_capabilities result rose to 13350 (measured 13338) for the meshSculpt notes; then recipe light links and shadow cascades (issue #52): environment fields added to the shared environment schema with the total unchanged at 190830 (measured 190507) by shortening its descriptions, and the scene_capabilities result raised to 13870 (measured 13865) for lightLinking and shadowCascades; then reflection probes (issue #55): 100 more for the bake.probes line (measured 13963)",
"schemaTotalBytes": 190830,
"schemaToolBytes": {
"scene_create": 62930,
@@ -10,7 +10,7 @@
},
"schemaOtherToolBytes": 4000,
"resultBytes": {
- "scene_capabilities": 13870,
+ "scene_capabilities": 13970,
"scene_create": 1400,
"scene_inspect": 1400,
"mesh_inspect": 1200,
diff --git a/docs/light-bake.md b/docs/light-bake.md
index 7be76884..4b2a66e1 100644
--- a/docs/light-bake.md
+++ b/docs/light-bake.md
@@ -57,6 +57,21 @@ Skipped, with the reason in `report.skipped`: transparent parts, a material tag
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.
+## Reflection probes
+
+A probe is the room around a point, traced once and prefiltered like an environment map (`createEnvironmentResources`), so a glossy part reflects the room and not only the sky. `src/reflection-probes.js` holds placement and the renderer link; `src/probe-trace.js` traces on the CPU with the bake's ray tracer (direct light, bounced light, emission; a ray that leaves the scene reads the environment map or the sky colours), 64 by 32 texels, 32 samples and 2 bounces, deterministic, about 0.2 to 0.3 s per probe. A part takes the nearest probe whose `radius` reaches the middle of its bounds, else the environment. A probe lights the specular term only: diffuse stays with the environment and the bake. No parallax correction (not built: a probe at the centre of a room is wrong near the walls).
+
+```js
+import { applyReflectionProbes } from '67js/addons/reflection-probes';
+const { parts: probedParts } = applyReflectionProbes(parts, lighting, [{ position: [0, 1.5, 0], radius: 6 }], { environment, environmentMap: environment.map, rotation: environment.map.rotation });
+```
+
+In a recipe, `bake.probes` is `'room'` (one probe in the middle of the parts' bounds, kept only when at least 90 percent of its rays hit a part, so an open scene gets none) or a list of up to 4 `{ position, radius? }`; absent or `false` means none. It is off by default because the measurement below does not show it helping a baked room. The report has `bake.probes` (placed probes, `partsWithProbe`, `skipped`, `glb`). A probe is not written to GLB: glTF has no standard for it.
+
+Cost: a scene without a probe loads none of this and its fragment shader is unchanged (the renderer links through the material field `environmentProbe`, which batches parts by probe, and one shader slot that only a probe scene fills). With a probe the prefilter runs once when the first batch that uses it draws, and nothing after.
+
+Measured against Cycles (FLIP, GPU; `npm run reference -- --skip-blender --probes ...`, 2026-11-01): `lit-interior` 0.5055 to 0.4791, `brick-room` 0.5102 to 0.4828, `metal-room` 0.5128 to 0.4520. Open scenes get worse with a hand placed probe: `material-spheres` 0.1598 to 0.1740, `metal` 0.1868 to 0.2246 (the probe sits among the objects and each sphere reflects itself where it should reflect the others). With the bake on, the picture was byte identical with and without probes in all three rooms (0.1444, 0.1515, 0.1754): the reason is not found, so the combination is unproven.
+
## Limits
| Option | Default | Range | Meaning |
diff --git a/docs/parity.md b/docs/parity.md
index f1cecba3..5f71e35f 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -186,7 +186,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Physics > Collision | partial | Rapier collisions with sensors (enter and leave events) and 16 collision layers with masks, in code and recipes. `scene_inspect` reports contacts and resting state. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
| 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 > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. Reflection probes exist behind `bake.probes` (specular only, no parallax; [light-bake](light-bake.md)); no irradiance or box 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 (issue #129) and runs about 2.8 times faster per thread, and 3.5 to 3.9 times with the shadow-ray change (inferred from 8,360 to about 30,000 paths per second on the demo room), than at that table, whose scores and seconds predate both (the second table in the reference README has the current ones); it draws them on box-projected materials too, can stop converged pixels on request (`noiseThreshold`, off by default because it costs `spot-area` score, see the reference README), and finishes a 1920 by 1080 still of a 181,708 triangle room at 64 samples in 246 s on 8 threads with `noiseThreshold` 0.03 (about 8 to 9 minutes with every sample, inferred) under a job limit now 600 s; it does not trace volume fog, translucent leaves, occlusion or emissive maps or light linking, and it is not Cycles parity (its floor is darker than Cycles' in `character` and `outdoor-hdri`, cause not found). `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 |
diff --git a/src/agent-bake.js b/src/agent-bake.js
index 679840da..36be2d90 100644
--- a/src/agent-bake.js
+++ b/src/agent-bake.js
@@ -1,5 +1,7 @@
import { planLightmaps, estimateBake, traceLightmaps } from './light-bake.js';
import { runKernel } from './kernel-offload.js';
+import { normalizeProbeList, traceProbes } from './probe-trace.js';
+import { placeProbes } from './reflection-probes.js';
import { knownKeys, finiteNumber } from './agent-recipe-checks.js';
import { BAKE_PRESETS, BAKE_RANGES, BAKE_MAXIMUM_SECONDS, BAKE_WORKER_MAXIMUM_SECONDS, BAKE_PRESET_PATH_WORK, BAKE_EXPLICIT_PATH_WORK_LIMIT } from './agent-scene-capabilities.js';
@@ -8,7 +10,7 @@ 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.
-const BAKE_FIELDS = ['preset', 'samples', 'bounces', 'texelsPerUnit'];
+const BAKE_FIELDS = ['preset', 'samples', 'bounces', 'texelsPerUnit', 'probes'];
const BAKED_MATERIAL_FIELDS = ['emission', 'emissiveColor', 'emissiveMap', 'lightMap', 'lightMapScale'];
/** Validates a recipe bake section and returns the plain, resolved form stored in the recipe (null clears it). */
@@ -27,6 +29,10 @@ export function normalizeAgentBake(input) {
}
resolved[field] = finiteNumber(input[field], `Bake ${field}`, minimum, maximum);
}
+ // Absent or false: no probes. 'room' puts one in the middle of an enclosed room; a list places them.
+ if (input.probes !== undefined) {
+ resolved.probes = input.probes === false || input.probes === 'room' ? input.probes : normalizeProbeList(input.probes);
+ }
for (const field of ['samples', 'bounces']) {
if (!Number.isInteger(resolved[field])) {
throw new RangeError(`Bake ${field} must be an integer.`);
@@ -176,6 +182,8 @@ export function bakeAgentParts(parts, worldMatrices, environment, settings, gene
spotLights: environment.spotLights,
areaLights: environment.areaLights,
keyColor: Array.from(environment.keyColor, channel => channel * sunScale),
+ skyTop: environment.skyTop,
+ skyBottom: environment.skyBottom,
lightDirection: environment.lightDirection,
};
// A hair, particle or cloth node is drawn from geometry built every frame, which has no lightmap UVs.
@@ -186,6 +194,9 @@ export function bakeAgentParts(parts, worldMatrices, environment, settings, gene
generatesGeometry: generatedGeometryGenerators.get(part.name) ?? false,
}));
const { changed, report, used, reduced } = runKernel('lightBake', [snapshots, lighting, settings], bakeChangedParts);
+ // Probes see the unbaked parts, as the bake does, and are traced as a kernel of their own so a worker can take them too.
+ const probeTrace = !settings.probes ? null
+ : runKernel('probeTrace', [snapshots, lighting, settings.probes, { environment: lighting, maxSeconds: bakeSecondsLimit() }], traceProbes);
const bakedSnapshots = snapshots.slice();
for (const [index, part] of changed) {
bakedSnapshots[index] = part;
@@ -197,6 +208,8 @@ export function bakeAgentParts(parts, worldMatrices, environment, settings, gene
const { geometry, material } = bakedSnapshots[index];
return Object.freeze({ ...part, geometry, material: liveBakedMaterial(part.material, material) });
});
- return { parts: Object.freeze(bakedParts), report: { ...settings, used, reduced, texels: report.texels, rayWork: report.rayWork, seconds: report.seconds,
+ // Probes are placed here, on the page, because they build maps and materials; their trace ran above.
+ const placed = probeTrace ? placeProbes(bakedParts, probeTrace) : null;
+ return { parts: Object.freeze(placed ? placed.parts : bakedParts), report: { ...(placed ? { probes: placed.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.js
index 337f6cf5..006235db 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -239,9 +239,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-3), texelsPerUnit (1-12) over it. Same recipe, same bytes.',
+ fields: 'preset, or samples (1-256), bounces (1-3), texelsPerUnit (1-12) over it; probes room or up to 4 {position, radius?}. Same recipe, same bytes.',
presets: BAKE_PRESETS,
- notes: 'Bounced light from point, spot, area and key lights. Reruns when parts, lights, materials or bake change. Skips alpha, skin, morph, hair, cloth (bake.skipped). A preset shrinks to fit (bake.used, bake.reduced); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular.',
+ 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.reduced); explicit settings fail over maxPathWork or past maxSeconds. No environment map or specular. Probes (off by default): specular only, none in glTF.',
limits: Object.freeze({ maxSeconds: BAKE_MAXIMUM_SECONDS, workerMaxSeconds: BAKE_WORKER_MAXIMUM_SECONDS, maxPathWork: BAKE_EXPLICIT_PATH_WORK_LIMIT, maxPointLights: 8 }),
}),
motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),
diff --git a/src/kernel-registry.js b/src/kernel-registry.js
index fc59a9bb..00aa7951 100644
--- a/src/kernel-registry.js
+++ b/src/kernel-registry.js
@@ -1,12 +1,14 @@
import { bakeChangedParts } from './agent-bake.js';
import { bakeCloth } from './cloth.js';
import { bakeMaterialPattern } from './material-patterns.js';
+import { traceProbes } from './probe-trace.js';
import { unwrapUv } from './mesh-uv.js';
// The kernels a worker can run, by the name the call sites give `runKernel`. Each is the same function the call site
// computes inline with, so the worker and the inline path return identical data.
const KERNELS = {
lightBake: bakeChangedParts,
+ probeTrace: traceProbes,
cloth: bakeCloth,
pattern: bakeMaterialPattern,
uvUnwrap: unwrapUv,
diff --git a/src/light-bake.js b/src/light-bake.js
index 63f315af..75efdba6 100644
--- a/src/light-bake.js
+++ b/src/light-bake.js
@@ -122,7 +122,7 @@ function withAffects(normalizedLights, sourceLights) {
* A light limited by `affects` adds nothing at a surface of a part it skips, as in the renderer, so a part that a
* light does not reach is not lit by it even as the bounce of another part.
*/
-function withReach(lights, parts) {
+export function withReach(lights, parts) {
const reachOf = (light) => {
if (light.affects === null) return null;
const names = new Set(light.affects);
@@ -136,7 +136,7 @@ function lightReaches(light, owner) {
return light.reach === null || light.reach[owner] === 1;
}
-function normalizeLights(lighting) {
+export function normalizeLights(lighting) {
if (lighting === null || typeof lighting !== 'object') throw new TypeError('Light bake needs a lighting object.');
const pointLights = lighting.pointLights ?? [];
if (!Array.isArray(pointLights) || pointLights.length > MAX_BAKE_POINT_LIGHTS) throw new RangeError(`Light bake takes at most ${MAX_BAKE_POINT_LIGHTS} point lights.`);
@@ -162,7 +162,7 @@ function normalizeLights(lighting) {
return { pointLights: withAffects(normalizedPoints, pointLights), spotLights, areaLights, sun: hasSun ? { color: Array.from(keyColor), direction: sunDirection, affects: lighting.keyAffects ?? null } : null };
}
-function validatePart(part, index) {
+export function validatePart(part, index) {
const { geometry, matrix } = part ?? {};
const label = `Light bake part ${index}`;
if (!geometry || !(geometry.positions instanceof Float32Array) || geometry.positions.length === 0 || geometry.positions.length % 3 !== 0) throw new TypeError(`${label} needs Float32 positions.`);
@@ -205,7 +205,7 @@ function srgbToLinear(byte) {
}
/** Mean linear colour of a base color map on a fixed grid of samples, or white when the image bytes are not readable. */
-function averageMapColor(map) {
+export function averageMapColor(map) {
const image = map?.image;
if (!image?.data || !(image.width > 0) || !(image.height > 0)) return [1, 1, 1];
const sum = [0, 0, 0];
@@ -225,14 +225,14 @@ function diffuseAlbedo(material) {
return material.color.map((channel, index) => Math.max(channel, 0) * keep * mapAverage[index]);
}
-function emittedRadiance(material) {
+export function emittedRadiance(material) {
const strength = material.emission ?? 0;
if (strength <= 0) return [0, 0, 0];
return (material.emissiveColor ?? material.color).map(channel => channel * strength);
}
/** All parts in world space as one triangle soup: positions, indices, and the part each triangle belongs to. */
-function buildWorld(parts) {
+export function buildWorld(parts) {
let vertexTotal = 0;
let indexTotal = 0;
for (const part of parts) {
@@ -265,7 +265,7 @@ function buildWorld(parts) {
return { positions, indices, triangleOwner, bvh: buildTriangleBvh(positions, indices) };
}
-function sceneScale(positions) {
+export function sceneScale(positions) {
let largest = 0;
for (let index = 0; index < positions.length; index++) largest = Math.max(largest, Math.abs(positions[index]));
return Math.max(largest, 1e-3);
@@ -319,7 +319,7 @@ function cosineDirection(normal, firstUnit, secondUnit, out) {
* Builds the function that returns the irradiance (light power per area, before the albedo and 1/pi of a diffuse
* surface) of the direct lights at a point, with shadow rays against the world.
*/
-function createDirectIrradiance(tracer, lights, offset, scale) {
+export function createDirectIrradiance(tracer, lights, offset, scale) {
const result = [0, 0, 0];
const shadowReach = scale * 1e6;
function addLight(point, normal, toLight, distance, power) {
@@ -409,7 +409,7 @@ function createDirectIrradiance(tracer, lights, offset, scale) {
};
}
-function hitNormal(world, triangleId, direction, out) {
+export function hitNormal(world, triangleId, direction, out) {
readTriangle(world.positions, world.indices, triangleId, SCRATCH_TRIANGLE);
const firstX = SCRATCH_TRIANGLE[3] - SCRATCH_TRIANGLE[0];
const firstY = SCRATCH_TRIANGLE[4] - SCRATCH_TRIANGLE[1];
@@ -435,7 +435,7 @@ const SCRATCH_TRIANGLE = new Float64Array(9);
* The mean radiance arriving at one texel from other surfaces: cosine-weighted paths of up to `bounces` reflections,
* each hit adding its own emission and its direct light. The caller multiplies by the texel's albedo.
*/
-function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples, bounces }) {
+export function createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples, bounces }) {
const direction = [0, 0, 0];
const origin = [0, 0, 0];
const normal = [0, 0, 0];
diff --git a/src/material-layer-shaders.js b/src/material-layer-shaders.js
index 6be7d88e..7cbe3258 100644
--- a/src/material-layer-shaders.js
+++ b/src/material-layer-shaders.js
@@ -319,7 +319,10 @@ const IDENTITY_NORMAL_MAP_TRANSFORM = [1, 1, 0, 0];
const MAP_STATE_NORMAL_MAP = 1;
const MAP_STATE_LAYER_MAPS = 18;
+// Other optional features (reflection probes) also bind per batch, so this keeps whatever was registered first.
+const previousBind = layerTextureSupport.bind;
layerTextureSupport.bind = (renderer, mapState) => {
+ previousBind?.(renderer, mapState);
if (!renderer.shaderFeatures) return;
const context = renderer.context;
const layerMaps = mapState[MAP_STATE_LAYER_MAPS];
diff --git a/src/probe-trace.js b/src/probe-trace.js
new file mode 100644
index 00000000..d947bac7
--- /dev/null
+++ b/src/probe-trace.js
@@ -0,0 +1,206 @@
+import { createTracer } from './ray-query.js';
+import {
+ MAX_BAKE_PARTS, averageMapColor, buildWorld, createDirectIrradiance, createGatherer, emittedRadiance, hitNormal, normalizeLights, sceneScale, validatePart, withReach,
+} from './light-bake.js';
+
+// The half of reflection probes that needs no GPU and no renderer: validating a probe list, placing the automatic probe
+// and tracing the maps. It is pure data in and out, so a bake worker can run it. reflection-probes.js turns the traces
+// into maps and gives parts their probe.
+
+export const MAXIMUM_PROBES = 4;
+export const PROBE_MAP_WIDTH = 64;
+// An automatic probe is only worth placing in a room: below this share of rays hitting a part the scene is open air.
+export const ENCLOSED_HIT_FRACTION = 0.9;
+const PROBE_SAMPLES = 32;
+const PROBE_BOUNCES = 2;
+
+const MAX_PROBE_PIXELS = 65536;
+
+// 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;
+ const keep = 1 - metallic * 0.5;
+ const mapAverage = averageMapColor(material.map);
+ return material.color.map((channel, index) => Math.max(channel, 0) * keep * mapAverage[index]);
+}
+
+/**
+ * The radiance seen from each probe position, as one equirectangular map per probe (rows from straight up, the centre
+ * looking toward -Z, the layout of `createEnvironmentMap`). A ray that hits a part returns its emission plus the direct
+ * light and the bounced light it receives, shaded as the bake shades a texel; a ray that leaves the scene returns
+ * `missRadiance(direction, out)`. `rotation` stores the map the way an environment of that rotation expects it, so a
+ * 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 } = {}) {
+ 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.`);
+ parts.forEach(validatePart);
+ const lights = normalizeLights(lighting);
+ const world = buildWorld(parts);
+ const scale = sceneScale(world.positions);
+ const offset = scale * 1e-4;
+ const tracer = createTracer(world);
+ const directIrradiance = createDirectIrradiance(tracer, withReach(lights, parts), offset, scale);
+ const albedoOfPart = parts.map(part => probeAlbedo(part.material));
+ const emissionOfPart = parts.map(part => emittedRadiance(part.material));
+ const gather = createGatherer({ world, tracer, albedoOfPart, emissionOfPart, directIrradiance, offset, samples, bounces });
+ const started = performance.now();
+ const rotationCosine = Math.cos(rotation);
+ const rotationSine = Math.sin(rotation);
+ const direction = [0, 0, 0];
+ const point = [0, 0, 0];
+ const normal = [0, 0, 0];
+ const bounced = [0, 0, 0];
+ const missed = [0, 0, 0];
+ return positions.map((position, probeIndex) => {
+ const data = new Float32Array(width * height * 3);
+ let hits = 0;
+ for (let row = 0; row < height; row++) {
+ const polar = (row + 0.5) / height * Math.PI;
+ for (let column = 0; column < width; column++) {
+ if (performance.now() - started > maxSeconds * 1000) throw new Error(`Probe trace passed maxSeconds (${maxSeconds}).`);
+ const azimuth = ((column + 0.5) / width - 0.5) * 2 * Math.PI;
+ const mappedX = Math.sin(polar) * Math.sin(azimuth);
+ const mappedZ = -Math.sin(polar) * Math.cos(azimuth);
+ direction[0] = rotationCosine * mappedX + rotationSine * mappedZ;
+ direction[1] = Math.cos(polar);
+ direction[2] = -rotationSine * mappedX + rotationCosine * mappedZ;
+ const target = (row * width + column) * 3;
+ const hit = tracer.trace(position[0], position[1], position[2], direction[0], direction[1], direction[2], Infinity, false);
+ if (hit.nearestTriangle < 0) {
+ if (missRadiance) {
+ missRadiance(direction, missed);
+ data.set(missed, target);
+ }
+ continue;
+ }
+ hits++;
+ for (let axis = 0; axis < 3; axis++) point[axis] = position[axis] + direction[axis] * hit.nearestDistance;
+ hitNormal(world, hit.nearestTriangle, direction, normal);
+ const owner = world.triangleOwner[hit.nearestTriangle];
+ const direct = directIrradiance(point, normal, owner);
+ gather(point, normal, (probeIndex + 7777) * 1_000_003 + row * width + column, bounced);
+ for (let channel = 0; channel < 3; channel++) {
+ data[target + channel] = emissionOfPart[owner][channel] + albedoOfPart[owner][channel] * (direct[channel] / Math.PI + bounced[channel]);
+ }
+ }
+ }
+ return { data, width, height, hitFraction: hits / (width * height) };
+ });
+}
+
+/** Validates the probe list of a recipe: up to MAXIMUM_PROBES of `{ position, radius? }`. */
+export function normalizeProbeList(list) {
+ if (!Array.isArray(list) || list.length > MAXIMUM_PROBES) {
+ throw new RangeError(`bake.probes must be false or a list of at most ${MAXIMUM_PROBES} probes.`);
+ }
+ return list.map((probe, index) => {
+ const label = `bake.probes[${index}]`;
+ const validPosition = Array.isArray(probe?.position) && probe.position.length === 3 && probe.position.every(value => Number.isFinite(value) && Math.abs(value) <= 1e6);
+ if (!validPosition) {
+ throw new TypeError(`${label} needs position [x, y, z].`);
+ }
+ for (const key of Object.keys(probe)) {
+ if (key !== 'position' && key !== 'radius') {
+ throw new TypeError(`${label} has an unknown field ${key}; use position and radius.`);
+ }
+ }
+ if (probe.radius !== undefined && !(Number.isFinite(probe.radius) && probe.radius > 0 && probe.radius <= 1e6)) {
+ throw new RangeError(`${label}.radius must be a number above 0.`);
+ }
+ return { position: [...probe.position], ...(probe.radius === undefined ? {} : { radius: probe.radius }) };
+ });
+}
+
+export function worldBounds(part) {
+ const { positions } = part.geometry;
+ const { matrix } = part;
+ const minimum = [Infinity, Infinity, Infinity];
+ const maximum = [-Infinity, -Infinity, -Infinity];
+ for (let vertex = 0; vertex < positions.length; vertex += 3) {
+ for (let axis = 0; axis < 3; axis++) {
+ const value = matrix[axis] * positions[vertex] + matrix[4 + axis] * positions[vertex + 1] + matrix[8 + axis] * positions[vertex + 2] + matrix[12 + axis];
+ minimum[axis] = Math.min(minimum[axis], value);
+ maximum[axis] = Math.max(maximum[axis], value);
+ }
+ }
+ return { minimum, maximum };
+}
+
+export function boundsCentre({ minimum, maximum }) {
+ return minimum.map((value, axis) => (value + maximum[axis]) / 2);
+}
+
+/** The probe a room gets by default: the middle of the parts' bounds, reaching every corner of it. */
+export function roomCentreProbe(parts) {
+ const total = { minimum: [Infinity, Infinity, Infinity], maximum: [-Infinity, -Infinity, -Infinity] };
+ for (const part of parts) {
+ const bounds = worldBounds(part);
+ for (let axis = 0; axis < 3; axis++) {
+ total.minimum[axis] = Math.min(total.minimum[axis], bounds.minimum[axis]);
+ total.maximum[axis] = Math.max(total.maximum[axis], bounds.maximum[axis]);
+ }
+ }
+ const diagonal = Math.hypot(...total.maximum.map((value, axis) => value - total.minimum[axis]));
+ return { position: boundsCentre(total), radius: diagonal / 2 };
+}
+
+// A ray that leaves the scene reads the environment map the scene is lit by, turned the way the renderer turns it.
+function environmentMissRadiance(map) {
+ const cosine = Math.cos(map.rotation);
+ const sine = Math.sin(map.rotation);
+ return (direction, out) => {
+ const mappedX = cosine * direction[0] - sine * direction[2];
+ const mappedZ = sine * direction[0] + cosine * direction[2];
+ const column = Math.min(map.width - 1, Math.floor((Math.atan2(mappedX, -mappedZ) / (2 * Math.PI) + 0.5) * map.width));
+ const row = Math.min(map.height - 1, Math.floor(Math.acos(Math.min(Math.max(direction[1], -1), 1)) / Math.PI * map.height));
+ const offset = (row * map.width + column) * map.channels;
+ for (let channel = 0; channel < 3; channel++) {
+ out[channel] = map.data[offset + channel] * 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];
+ return (direction, out) => {
+ const blend = Math.min(Math.max((direction[1] + 0.15) / 0.85, 0), 1);
+ const smooth = blend * blend * (3 - 2 * blend);
+ for (let channel = 0; channel < 3; channel++) {
+ out[channel] = bottom[channel] + (top[channel] - bottom[channel]) * smooth;
+ }
+ };
+}
+
+/**
+ * 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`
+ * values. Returns `{ traced, automatic, requested, skipped, seconds }`, where each traced probe holds its position,
+ * radius, equirectangular `data` and the share of rays that hit a part. The same input gives the same bytes.
+ */
+export function traceProbes(parts, lighting, specs, options = {}) {
+ const { environment = {}, environmentMap = null, rotation = 0, samples = PROBE_SAMPLES, bounces = PROBE_BOUNCES, maxSeconds = 60 } = options;
+ const automatic = specs === 'room';
+ const requested = automatic ? [roomCentreProbe(parts)] : normalizeProbeList(specs);
+ const sceneRadius = roomCentreProbe(parts).radius * 2;
+ const started = performance.now();
+ const positions = requested.map(probe => probe.position);
+ const maps = requested.length === 0 ? [] : traceProbeMaps(parts, lighting, positions, { width: PROBE_MAP_WIDTH, samples, bounces, rotation, missRadiance: environmentMap ? environmentMissRadiance(environmentMap) : skyMissRadiance(environment), maxSeconds });
+ const traced = [];
+ requested.forEach((spec, index) => {
+ if (automatic && maps[index].hitFraction < ENCLOSED_HIT_FRACTION) {
+ return;
+ }
+ traced.push({ position: spec.position, radius: spec.radius ?? sceneRadius, ...maps[index] });
+ });
+ return {
+ traced,
+ automatic,
+ requested: requested.length,
+ skipped: automatic && traced.length === 0 ? 'open scene: under 90 percent of rays from the room centre hit a part' : null,
+ seconds: (performance.now() - started) / 1000,
+ };
+}
diff --git a/src/reflection-probes.js b/src/reflection-probes.js
new file mode 100644
index 00000000..ce5ee6d8
--- /dev/null
+++ b/src/reflection-probes.js
@@ -0,0 +1,158 @@
+import { createEnvironmentMap, createEnvironmentResources } from './environment.js';
+import { fullscreenVertex } from './gl-program.js';
+import { layerTextureSupport, registerShaderFeatureCode } from './shaders.js';
+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';
+
+// A probe lights the specular term only. Diffuse light stays with the environment and the light bake, which already hold it.
+
+const MAP_STATE_PROBE = 19;
+
+/** The nearest probe whose radius reaches the point, or null; a tie goes to the earlier probe. */
+export function selectProbe(probes, point) {
+ let nearest = null;
+ let nearestDistance = Infinity;
+ for (const probe of probes) {
+ const distance = Math.hypot(point[0] - probe.position[0], point[1] - probe.position[1], point[2] - probe.position[2]);
+ if (distance <= probe.radius && distance < nearestDistance) {
+ nearest = probe;
+ nearestDistance = distance;
+ }
+ }
+ return nearest;
+}
+
+// A part wrapped once per probe keeps reading every other field from the live material, so motion on colour still works.
+function probedMaterial(liveMaterial, probeMap, wrappers) {
+ const byProbe = wrappers.get(liveMaterial) ?? new Map();
+ wrappers.set(liveMaterial, byProbe);
+ if (!byProbe.has(probeMap)) {
+ const wrapper = {};
+ for (const field of Object.keys(liveMaterial)) {
+ Object.defineProperty(wrapper, field, { enumerable: true, get: () => liveMaterial[field] });
+ }
+ Object.defineProperty(wrapper, 'environmentProbe', { enumerable: true, value: probeMap });
+ byProbe.set(probeMap, Object.freeze(wrapper));
+ }
+ return byProbe.get(probeMap);
+}
+
+/** 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 probedParts = parts.map(part => {
+ const probe = selectProbe(probes, boundsCentre(worldBounds(part)));
+ return probe ? Object.freeze({ ...part, material: probedMaterial(part.material, probe.map, wrappers) }) : part;
+ });
+ const report = {
+ automatic: probeTrace.automatic,
+ requested: probeTrace.requested,
+ placed: probes.map(({ position, radius, hitFraction }) => ({ position, radius, hitFraction })),
+ skipped: probeTrace.skipped,
+ glb: probes.length > 0 ? 'Probes are not written to GLB: glTF has no standard for them.' : null,
+ partsWithProbe: probedParts.filter((part, index) => part !== parts[index]).length,
+ };
+ return { parts: Object.freeze(probedParts), probes, report };
+}
+
+/** Traces the probes (see traceProbes) and places them: for code that holds parts and lights and no recipe. */
+export function applyReflectionProbes(parts, lighting, specs, options = {}) {
+ return placeProbes(parts, traceProbes(parts, lighting, specs, options), options);
+}
+
+registerShaderFeatureCode('probe', Object.freeze({
+ declarations: 'uniform float probeEnabled;\n',
+ // Divides out the world-mode weight the surroundings get below, because a probe's radiance is already the real light.
+ probeSurroundings: ' if (probeEnabled > 0.5) surroundings = environmentRadiance(reflected, roughness * environmentLevelMax) / max(mix(1.0, 0.5 * daylight, worldMode), 0.05);\n',
+}));
+
+const rendererStates = new WeakMap();
+
+function stateOf(renderer) {
+ if (!rendererStates.has(renderer)) {
+ const enabledLocation = renderer.context.getUniformLocation(renderer.program, 'probeEnabled');
+ rendererStates.set(renderer, { resources: new Map(), enabledLocation, bound: false });
+ }
+ return rendererStates.get(renderer);
+}
+
+// Prefiltering draws into framebuffers, so the state a draw call depends on is put back after it.
+function prefilterProbe(renderer, map) {
+ const context = renderer.context;
+ const framebuffer = context.getParameter(context.FRAMEBUFFER_BINDING);
+ const viewport = context.getParameter(context.VIEWPORT);
+ const program = context.getParameter(context.CURRENT_PROGRAM);
+ const vertexArray = context.getParameter(context.VERTEX_ARRAY_BINDING);
+ const activeUnit = context.getParameter(context.ACTIVE_TEXTURE);
+ context.activeTexture(context.TEXTURE0);
+ const firstUnitTexture = context.getParameter(context.TEXTURE_BINDING_2D);
+ const enabled = [context.DEPTH_TEST, context.CULL_FACE, context.BLEND, context.SCISSOR_TEST].map(capability => [capability, context.isEnabled(capability)]);
+ const compileProgram = (gl, vertexSource, fragmentSource) => renderer.compileEnvironmentProgram(gl, vertexSource, fragmentSource);
+ const resources = createEnvironmentResources(context, map, { compileProgram, fullscreenVertex });
+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
+ context.viewport(...viewport);
+ context.useProgram(program);
+ context.bindVertexArray(vertexArray);
+ context.bindTexture(context.TEXTURE_2D, firstUnitTexture);
+ context.activeTexture(activeUnit);
+ for (const [capability, wasEnabled] of enabled) {
+ if (wasEnabled) {
+ context.enable(capability);
+ } else {
+ context.disable(capability);
+ }
+ }
+ context.deleteTexture(resources.brdfTexture);
+ // The renderer deletes everything in its texture table when it is disposed.
+ renderer.textures.set(Symbol('reflection-probe'), resources.specularTexture);
+ return resources;
+}
+
+function bindProbe(renderer, mapState) {
+ if (!renderer.shaderFeatures?.has('probe')) {
+ return;
+ }
+ const state = stateOf(renderer);
+ const context = renderer.context;
+ const probeMap = mapState[MAP_STATE_PROBE];
+ const globalMap = renderer.activeMap;
+ if (!probeMap) {
+ if (!state.bound) {
+ return;
+ }
+ state.bound = false;
+ renderer.activateEnvironment(globalMap);
+ if (globalMap) {
+ renderer.applyEnvironmentUniforms(globalMap);
+ }
+ context.uniform1f(state.enabledLocation, 0);
+ return;
+ }
+ if (!state.resources.has(probeMap.data)) {
+ state.resources.set(probeMap.data, prefilterProbe(renderer, probeMap));
+ }
+ const resources = state.resources.get(probeMap.data);
+ const uniforms = renderer.uniforms;
+ state.bound = true;
+ renderer.bindEnvironmentTextures(resources.specularTexture, renderer.environmentResources?.brdfTexture ?? renderer.whiteTexture);
+ context.uniform1f(uniforms.environmentIntensity, 1);
+ context.uniform2f(uniforms.environmentRotation, Math.cos(probeMap.rotation), Math.sin(probeMap.rotation));
+ context.uniform1f(uniforms.environmentLevelMax, resources.levelCount - 1);
+ if (globalMap && renderer.environmentResources) {
+ // The environment's irradiance still lights the diffuse term, and the intensity uniform is now 1.
+ context.uniform3fv(uniforms['environmentIrradiance[0]'], renderer.environmentResources.irradiance.map(value => value * globalMap.intensity));
+ }
+ context.uniform1f(state.enabledLocation, 1);
+}
+
+const previousBind = layerTextureSupport.bind;
+layerTextureSupport.bind = (renderer, mapState) => {
+ previousBind?.(renderer, mapState);
+ bindProbe(renderer, mapState);
+};
diff --git a/src/renderer.js b/src/renderer.js
index f3111020..572d25ff 100644
--- a/src/renderer.js
+++ b/src/renderer.js
@@ -55,6 +55,7 @@ function shaderFeaturesOfParts(parts) {
if (material[field]) features.add(MAP_SHADER_FEATURES[index]);
});
if (material.lightMap) features.add('lightMap');
+ if (material.environmentProbe) features.add('probe');
if (material.normalMap?.uvTransform) features.add('normalMapTransform');
Object.keys(material.layerMaps ?? {}).forEach(name => features.add(name));
if (material.layers) features.add('splat');
@@ -149,7 +150,7 @@ function materialMapState(material) {
const occlusionStrength = material.occlusionStrength ?? 1;
validateSplatMaterial(material);
if (material.layers && PROCEDURAL_MATERIAL_TAGS.has(material.tag)) throw new Error('Splat layers require a standard PBR material tag.');
- return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material), material.layerMaps ?? null];
+ return [...MATERIAL_MAPS.map(field => material[field] ?? null), normalScale[0], normalScale[1], occlusionStrength, ...mossState(material), material.boxMapScale ?? 0, material.boxMapAxis ?? 1, ...lightMapState(material), ...splatBatchState(material), material.layerMaps ?? null, material.environmentProbe ?? null];
}
// A baked light map reads the second UV set, so it is only drawn for parts that cannot be skinned or morphed.
@@ -1453,6 +1454,7 @@ export class Renderer67 {
// Binds the prefiltered textures for this frame and returns the active map, or null for the built-in studio lighting.
activateEnvironment(map) {
+ this.activeMap = this.benchmark ? null : map;
if (this.benchmark || !map) {
this.bindEnvironmentTextures(this.whiteTexture, this.whiteTexture);
return null;
@@ -1584,6 +1586,7 @@ export class Renderer67 {
}
drawTranslucent(frame, environment, assemblyAmount, environmentMap) {
+ this.activateEnvironment(environmentMap);
const liquids = this.batches.filter(batch => batchPass(batch) === 'liquid');
const foams = this.batches.filter(batch => batchPass(batch) === 'foam');
if (liquids.length === 0 && foams.length === 0) return;
diff --git a/src/shaders.js b/src/shaders.js
index e777ebd8..396768c0 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -873,7 +873,7 @@ ${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;
// Outdoors the surroundings are sky and haze; reflecting the studio softboxes there lit grazing leaves white and cyan.
vec3 reflected = reflect(-viewDirection, specularNormal);
vec3 surroundings = worldMode > 0.5 ? mix(fogColor * 0.8, vec3(0.20, 0.38, 0.52) * 1.6, smoothstep(-0.15, 0.7, reflected.y)) : studio(reflected, roughness);
- radiance += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;
+${featureCode("probeSurroundings")} radiance += surroundings * reflectance * skyReflection * (1.0 - roughness * 0.55) * mix(1.0, 0.5 * daylight, worldMode) * occlusion * ambientIntensity;
radiance += color * (1.0 - metallic) * mix(vec3(0.16, 0.20, 0.22), vec3(0.19, 0.25, 0.30) * max(daylight, 0.08), worldMode) * (0.45 + 0.55 * max(normal.y, 0.0)) * occlusion * ambientIntensity;
}
// Baked bounced light arrives as irradiance, so the surface colour (pattern and texture included) tints it here.
diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.js
index 42ce3094..0e58e57e 100644
--- a/tests/reference-baseline.test.js
+++ b/tests/reference-baseline.test.js
@@ -4,7 +4,7 @@ import test from 'node:test';
const REFERENCE_DIRECTORY = new URL('../bench/reference/', import.meta.url);
const baseline = JSON.parse(readFileSync(new URL('baseline.json', REFERENCE_DIRECTORY), 'utf8'));
-const EXPECTED_SCENES = ['brick-flat', 'brick-graph', 'brick-room', 'brushed-film', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'light-linking', 'lit-interior', 'long-street', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];
+const EXPECTED_SCENES = ['brick-flat', 'brick-graph', 'brick-room', 'brushed-film', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'light-linking', 'lit-interior', 'long-street', 'material-spheres', 'metal', 'metal-room', 'outdoor-hdri', 'spot-area'];
const EXPECTED_SCORES = ['cpu-vs-cycles', 'cpu-vs-eevee', 'eevee-vs-cycles', 'gpu-vs-cpu', 'gpu-vs-cycles', 'gpu-vs-eevee'];
test('the render baseline scores every scene with every renderer pair', () => {
diff --git a/tests/reflection-probes.test.js b/tests/reflection-probes.test.js
new file mode 100644
index 00000000..9567b034
--- /dev/null
+++ b/tests/reflection-probes.test.js
@@ -0,0 +1,98 @@
+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 { createFragmentShader } from '../src/shaders.js';
+import { normalizeAgentBake } from '../src/agent-bake.js';
+
+const cube = box(0, 1);
+const ball = sphere(16, 12);
+
+function placed(name, geometry, translation, scale, material = {}) {
+ const matrix = new Float32Array([scale[0], 0, 0, 0, 0, scale[1], 0, 0, 0, 0, scale[2], 0, translation[0], translation[1], translation[2], 1]);
+ return { name, geometry, matrix, material: { tag: 'surface', color: [0.7, 0.7, 0.7], metallic: 0, roughness: 0.8, emission: 0, ...material } };
+}
+
+function closedRoom() {
+ return [
+ placed('floor', cube, [0, -0.05, 0], [6, 0.1, 6]),
+ placed('ceiling', cube, [0, 3.05, 0], [6, 0.1, 6]),
+ placed('back', cube, [0, 1.5, -3.05], [6, 3.2, 0.1], { color: [0.8, 0.1, 0.1] }),
+ placed('left', cube, [-3.05, 1.5, 0], [0.1, 3.2, 6]),
+ placed('right', cube, [3.05, 1.5, 0], [0.1, 3.2, 6]),
+ placed('front', cube, [0, 1.5, 3.05], [6, 3.2, 0.1]),
+ placed('mirror', ball, [1.5, 0.5, 0], [0.5, 0.5, 0.5], { metallic: 1, roughness: 0.05 }),
+ ];
+}
+
+const lamp = { pointLights: [{ position: [0, 2.6, 0], color: [1, 1, 1], intensity: 8, radius: 0.05 }], keyColor: [0, 0, 0] };
+
+test('an enclosed room gets one automatic probe at its centre', () => {
+ const result = applyReflectionProbes(closedRoom(), lamp, 'room');
+ assert.equal(result.report.placed.length, 1);
+ assert.deepEqual(result.report.placed[0].position.map(value => Math.round(value * 100) / 100), [0, 1.5, 0]);
+ assert.ok(result.report.placed[0].hitFraction >= 0.9);
+ assert.equal(result.report.partsWithProbe, 7);
+ assert.ok(result.parts.every(part => part.material.environmentProbe === result.probes[0].map));
+});
+
+test('an open scene gets no automatic probe and says why', () => {
+ const openParts = [placed('floor', cube, [0, -0.05, 0], [6, 0.1, 6]), placed('post', cube, [2, 1, 0], [0.2, 2, 0.2])];
+ const result = applyReflectionProbes(openParts, lamp, 'room');
+ assert.equal(result.probes.length, 0);
+ assert.match(result.report.skipped, /open scene/);
+ assert.equal(result.report.partsWithProbe, 0);
+});
+
+test('a probe sees the coloured wall it faces and is lit by the lamp', () => {
+ const [probe] = traceProbeMaps(closedRoom(), lamp, [[0, 1.5, 0]], { width: 32, samples: 8 });
+ // Row 8 of 16 looks at the horizon; the middle column looks toward -Z, where the red wall is.
+ const offset = (8 * 32 + 16) * 3;
+ const [red, green] = [probe.data[offset], probe.data[offset + 1]];
+ assert.ok(red > 0.05 && red > green * 3, `wall seen as red ${red} ${green}`);
+ assert.equal(probe.hitFraction, 1);
+});
+
+test('the same input traces the same bytes', () => {
+ const first = traceProbes(closedRoom(), lamp, 'room', { samples: 8 });
+ const second = traceProbes(closedRoom(), lamp, 'room', { samples: 8 });
+ assert.deepEqual(Array.from(first.traced[0].data), Array.from(second.traced[0].data));
+});
+
+test('a part takes the nearest probe in range, else none', () => {
+ const near = { position: [0, 0, 0], radius: 2 };
+ const far = { position: [10, 0, 0], radius: 2 };
+ assert.equal(selectProbe([far, near], [0.5, 0, 0]), near);
+ assert.equal(selectProbe([far, near], [9, 0, 0]), far);
+ assert.equal(selectProbe([far, near], [5, 0, 0]), null);
+ const overlapping = { position: [1, 0, 0], radius: 2 };
+ assert.equal(selectProbe([near, overlapping], [0.4, 0, 0]), near);
+ assert.equal(selectProbe([overlapping, near], [0.6, 0, 0]), overlapping);
+});
+
+test('explicit probes with a radius leave distant parts without one', () => {
+ const room = closedRoom();
+ const result = applyReflectionProbes(room, lamp, [{ position: [1.5, 1, 0], radius: 1.2 }], { samples: 4 });
+ assert.deepEqual(result.parts.filter(part => part.material.environmentProbe).map(part => part.name), ['mirror']);
+});
+
+test('probe lists are validated', () => {
+ assert.throws(() => normalizeProbeList(Array.from({ length: 5 }, () => ({ position: [0, 0, 0] }))), /at most 4/);
+ assert.throws(() => normalizeProbeList([{ position: [0, 0] }]), /position/);
+ assert.throws(() => normalizeProbeList([{ position: [0, 0, 0], size: 1 }]), /unknown field/);
+ assert.throws(() => normalizeProbeList([{ position: [0, 0, 0], radius: 0 }]), /radius/);
+ assert.deepEqual(roomCentreProbe(closedRoom()).position.map(Math.round), [0, 2, 0]);
+});
+
+test('bake.probes accepts false, room, a list or nothing', () => {
+ assert.equal(normalizeAgentBake({}).probes, undefined);
+ assert.equal(normalizeAgentBake({ probes: false }).probes, false);
+ assert.equal(normalizeAgentBake({ probes: 'room' }).probes, 'room');
+ assert.deepEqual(normalizeAgentBake({ probes: [{ position: [0, 1, 0] }] }).probes, [{ position: [0, 1, 0] }]);
+});
+
+test('the probe shader code compiles in only when asked for', () => {
+ assert.doesNotMatch(createFragmentShader(), /probeEnabled/);
+ assert.match(createFragmentShader(['probe']), /probeEnabled > 0.5\) surroundings/);
+});