3D engine that AI agents drive
Add cascaded sun shadows and light linking as on-demand addons
Nguyen Xuan An9f6f2f176425
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7db86578..d390c4b6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add cascaded sun shadows and light linking (part of issue #52; recipes do not reach either, and `lit-interior` was already improved by the light bake, not by this work). `addons/cascaded-shadows`: `new Renderer67(canvas, parts, { shadowCascades: createCascadedShadows({ count: 3 }) })` fits up to four depth maps to slices of the camera's view, with sphere fitting and texel snapping so edges do not crawl; on the new `long-street` reference scene the score against Cycles goes from 0.1555 to 0.1398 for about 0.2 ms more a frame on an RTX 3060 (+25 percent on SwiftShader) when the camera moves. `addons/light-linking`: `applyLightLinks(parts, environment)` limits a light to the parts named in its `affects` list (`environment.keyAffects` for the sun) through a per-part mask in `material.lightMask`; the new `light-linking` reference scene scores 0.0998 against Cycles with the same lists as Blender receiver collections. Both keep their GLSL out of the core bundle (`registerShaderFeatureCode`, new slots `sunVisibility`, `linkSun`, `linkPoint`, `linkSpot` and `linkArea`), and `npm run reference -- --cascades <n>` and `frame-time.mjs <scene> <backend> --cascades` measure them. No earlier reference scene moved.+- Fix three gaps a demo film found in the recipe light bake (part of issue #55). A baked scene with `cloth` failed at render time for every frame after t=0 with "A light map needs lightUvs on rigid geometry, with no skin or morph", because the cloth simulation replaces the sheet's geometry each frame; cloth sheet nodes are now skipped and listed in `report.skipped`. The bake now lights with spot lights (the renderer's cone and soft edge) and area lights (front side only, one deterministic shadow ray to a point of the rectangle per hit), where it ignored both; a scene without them bakes the same bytes. The presets could not finish a normal scene (`standard` passed its 20 s limit on a 56 part room, `fine` hit the 30 s preview limit): a recipe bake now has a ray work budget of 10 million units (texels x samples x bounces x rays per hit), estimated from the unwrap before any ray is traced with no clock involved. A preset is scaled down to fit and `scene_inspect` `bake` reports `used` and `reduced`; explicit `samples`, `bounces` or `texelsPerUnit` are never reduced and fail with a message naming the number that fits. `bakeLightmaps` is now `planLightmaps`, `estimateBake` and `traceLightmaps` (still exported as one call). `entry:core` did not change; `entry:light-bake` grew by 1,033 bytes gzip (budget 25,900 to 26,900) and the lazy agent entries by about 1,580; the schema stayed within its total budget (the capability notes were shortened to fit).- Add `sculpt` and `shrinkwrap` mesh edits (part of issue #47; surface patches and a stack form are not built). `sculpt` applies up to 32 inflate, displace and smooth strokes to the vertices of the selected faces; `shrinkwrap` moves them onto a primitive, to the nearest point or projected along a direction, with an offset. Both are in `scene_capabilities` (`meshSculpt`) and in the `mesh_edit` schema, with the tool schema total unchanged (the face rule and tag prefix descriptions were shortened to pay for them). The stroke maths moved to `src/sculpt-strokes.js` and serves `sculptGeometry` too. Four Blender golden cases (two Shrinkwrap modifier comparisons; the sculpt reference runs the same brush formula on Blender's mesh), hostile input tests, and the suite task `ball-badge`, which needs a plate bent onto a ball.diff --git a/bench/reference/README.md b/bench/reference/README.mdindex 08deb697..6c6f0f3a 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -1,6 +1,6 @@# Reference renders-This suite scores how close a 67js render is to Blender on 12 fixed scenes. Later work uses these scores as its starting point.+This suite scores how close a 67js render is to Blender on 15 fixed scenes. Later work uses these scores as its starting point.## Run it@@ -32,6 +32,8 @@ Rows are the baseline taken before shadows for point lights. The `lit-interior`Light bake (issue #55): `npm run reference -- --bake lit-interior` bakes bounced light into the room with `addons/light-bake` (defaults: 128 samples, 2 bounces, 25,648 texels, about 6 s on this machine) and leaves the scene itself unchanged; Blender still gets the plain scene. Measured 2026-10-31 on the RTX 3060: `lit-interior` against Cycles goes from 0.5055 to 0.1444 (SwiftShader 0.5051 to 0.1439), and against EEVEE from 0.0923 to 0.4739, because EEVEE has no indirect light here and the bake adds it. No other scene moved by more than 0.002 (the largest change was 0.0001, `car-paint` against EEVEE). The committed baseline rows and images are not rewritten. The remaining gap shows in the FLIP image as faint blotches on the walls, which is bake noise at 128 samples; at 48 samples the blotches were plain to see and the score was 0.1688.+`long-street` and `light-linking` (issue #52) were added on 2026-11-01. `long-street` is a 140 m street under the sun with 24 buildings, 14 lamp posts and four cars near the camera; one 2048 x 2048 sun map covers 170 m, so its texels are 8 cm wide. Against Cycles it scores 0.1555 with one map and 0.1398 with three cascades (`npm run reference -- --cascades 3`; SwiftShader 0.1554 and 0.1399; against EEVEE 0.1396 and 0.1147; EEVEE against Cycles 0.0975). Frame time on the RTX 3060 (960x540, 4 samples, 200 frames read back, median of two runs of each, `node bench/reference/frame-time.mjs long-street gpu --cascades`): 1.04 ms with one map and a still camera, 1.02 ms with a camera that moves every frame, 1.09 ms with three cascades and a still camera, 1.24 ms with three cascades and a moving camera, so the cascades cost about 0.2 ms (20 percent) in a camera move and next to nothing while the camera is still. On SwiftShader (median, `cpu`): 241 ms, 240 ms, 282 ms and 299 ms, so +17 percent still and +25 percent moving, because the cascade lookup is 36 texture fetches per pixel and the depth passes run on the CPU. The cascades earn their cost where a shadow has to be sharp near the camera and long at the same time; a scene that fits one map in a few metres gains nothing and should not use them. The remaining gap in `long-street` is Cycles' sky and bounce light, not the shadows. `light-linking` has three point lights that each light only some parts (`affects` lists); it scores 0.0998 against Cycles, with the same lists given to Blender as receiver collections. Every scene that existed before kept its score to four digits (`lit-interior` is still 0.5055 against Cycles, 0.0923 against EEVEE), and the committed images of those scenes are unchanged.+`brick-room` (issue #128) is a closed room built from a recipe (`createAgentScene`) with three brick pattern walls, two point lights and a table with a vase. Blender gets the box projection as UVs (`boxProjectedGeometry`) and the baked brick map, but not the bump or the roughness map. Measured 2026-11-01 on the RTX 3060: against Cycles 0.5102 without the bake and 0.1515 with it (`npm run reference -- --bake brick-room`; SwiftShader 0.5096 and 0.1503; EEVEE against Cycles 0.5020); the bake took 14.4 s for 28,576 texels while another session loaded the machine. `lit-interior` stayed at 0.1444 with the bake, and every scene without a bake kept its earlier score to four digits (largest change 0.0000).`brick-graph` (issue #50) is a wall of bricks written as one material graph (triangle waves for the joints, half a brick of shift on every second course, noise through a colour ramp, height as bump) on a quad with UVs, so it uses `mapping: "uv"`. `render-blender.py` translates the same graph JSON into Blender nodes (Math, Map Range, Noise Texture, Color Ramp, Mix and Bump), so each side evaluates its own nodes. It measured 0.2269 against Cycles and 0.1440 for EEVEE on 2026-10-31. A first run scored 0.4027 and showed a black wall in 67js: the `min` and `max` nodes returned NaN. The scene found that bug. The other rows were re-measured in the same run; `glass` against Cycles moved from 0.1450 to 0.1326 and `lit-interior` to the with-shadows numbers described above, and no other score moved by more than 0.002.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 21e8feba..eeb3ff86 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -1,168 +1,192 @@{- "metric": "FLIP (LDR), mean error, lower is better",- "blenderVersion": "5.2.2 LTS",- "seconds": {- "brick-graph": {- "cycles": 8.9,- "eevee": 15.2- },- "brick-room": {- "cycles": 56.7,- "eevee": 7.1- },- "brushed-film": {- "cycles": 7.6,- "eevee": 7.4- },- "car-paint": {- "cycles": 35.4,- "eevee": 82.5- },- "character": {- "cycles": 19.2,- "eevee": 4.5- },- "fog": {- "cycles": 63.5,- "eevee": 36.3- },- "foliage": {- "cycles": 39.5,- "eevee": 27.4- },- "glass": {- "cycles": 29.5,- "eevee": 13.7- },- "lit-interior": {- "cycles": 77.4,- "eevee": 2.6- },- "material-spheres": {- "cycles": 25,- "eevee": 60.5- },- "metal": {- "cycles": 42.2,- "eevee": 30.4- },- "outdoor-hdri": {- "cycles": 42.9,- "eevee": 12.9- },- "spot-area": {- "cycles": 28.5,- "eevee": 10.1- }- },- "graphics": {- "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)",- "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)"- },- "scores": {- "brick-graph": {- "gpu-vs-cycles": 0.2269,- "gpu-vs-eevee": 0.148,- "cpu-vs-cycles": 0.2268,- "cpu-vs-eevee": 0.1479,- "eevee-vs-cycles": 0.144,- "gpu-vs-cpu": 0.0074- },- "brick-room": {- "gpu-vs-cycles": 0.5102,- "gpu-vs-eevee": 0.071,- "cpu-vs-cycles": 0.5096,- "cpu-vs-eevee": 0.0713,- "eevee-vs-cycles": 0.502,- "gpu-vs-cpu": 0.0071- },- "brushed-film": {- "gpu-vs-cycles": 0.1613,- "gpu-vs-eevee": 0.1601,- "cpu-vs-cycles": 0.1613,- "cpu-vs-eevee": 0.1601,- "eevee-vs-cycles": 0.0939,- "gpu-vs-cpu": 0.0058- },- "car-paint": {- "gpu-vs-cycles": 0.1521,- "gpu-vs-eevee": 0.1323,- "cpu-vs-cycles": 0.152,- "cpu-vs-eevee": 0.1323,- "eevee-vs-cycles": 0.0819,- "gpu-vs-cpu": 0.0055- },- "character": {- "gpu-vs-cycles": 0.0995,- "gpu-vs-eevee": 0.0833,- "cpu-vs-cycles": 0.099,- "cpu-vs-eevee": 0.0826,- "eevee-vs-cycles": 0.074,- "gpu-vs-cpu": 0.0068- },- "fog": {- "gpu-vs-cycles": 0.2612,- "gpu-vs-eevee": 0.0542,- "cpu-vs-cycles": 0.2608,- "cpu-vs-eevee": 0.0542,- "eevee-vs-cycles": 0.2662,- "gpu-vs-cpu": 0.0085- },- "foliage": {- "gpu-vs-cycles": 0.1594,- "gpu-vs-eevee": 0.1386,- "cpu-vs-cycles": 0.159,- "cpu-vs-eevee": 0.1384,- "eevee-vs-cycles": 0.0783,- "gpu-vs-cpu": 0.0096- },- "glass": {- "gpu-vs-cycles": 0.1326,- "gpu-vs-eevee": 0.1471,- "cpu-vs-cycles": 0.1323,- "cpu-vs-eevee": 0.1474,- "eevee-vs-cycles": 0.115,- "gpu-vs-cpu": 0.0075- },- "lit-interior": {- "gpu-vs-cycles": 0.5055,- "gpu-vs-eevee": 0.0923,- "cpu-vs-cycles": 0.5051,- "cpu-vs-eevee": 0.0928,- "eevee-vs-cycles": 0.5159,- "gpu-vs-cpu": 0.0062- },- "material-spheres": {- "gpu-vs-cycles": 0.1598,- "gpu-vs-eevee": 0.1196,- "cpu-vs-cycles": 0.1595,- "cpu-vs-eevee": 0.1194,- "eevee-vs-cycles": 0.1006,- "gpu-vs-cpu": 0.0069- },- "metal": {- "gpu-vs-cycles": 0.1868,- "gpu-vs-eevee": 0.1565,- "cpu-vs-cycles": 0.1867,- "cpu-vs-eevee": 0.1565,- "eevee-vs-cycles": 0.0934,- "gpu-vs-cpu": 0.0063- },- "outdoor-hdri": {- "gpu-vs-cycles": 0.0676,- "gpu-vs-eevee": 0.052,- "cpu-vs-cycles": 0.0672,- "cpu-vs-eevee": 0.0515,- "eevee-vs-cycles": 0.0384,- "gpu-vs-cpu": 0.0058- },- "spot-area": {- "gpu-vs-cycles": 0.1242,- "gpu-vs-eevee": 0.1707,- "cpu-vs-cycles": 0.1242,- "cpu-vs-eevee": 0.1709,- "eevee-vs-cycles": 0.1935,- "gpu-vs-cpu": 0.0032- }+ "metric": "FLIP (LDR), mean error, lower is better",+ "blenderVersion": "5.2.2 LTS",+ "seconds": {+ "brick-graph": {+ "cycles": 16.4,+ "eevee": 8.5+ },+ "brick-room": {+ "cycles": 29.1,+ "eevee": 2.2+ },+ "brushed-film": {+ "cycles": 15.9,+ "eevee": 2.0+ },+ "car-paint": {+ "cycles": 13.8,+ "eevee": 3.4+ },+ "character": {+ "cycles": 17.6,+ "eevee": 3.8+ },+ "fog": {+ "cycles": 40.9,+ "eevee": 3.9+ },+ "foliage": {+ "cycles": 28.1,+ "eevee": 9.9+ },+ "glass": {+ "cycles": 22.2,+ "eevee": 16.7+ },+ "light-linking": {+ "cycles": 12.1,+ "eevee": 4.0+ },+ "lit-interior": {+ "cycles": 21.8,+ "eevee": 4.7+ },+ "long-street": {+ "cycles": 12.8,+ "eevee": 4.8+ },+ "material-spheres": {+ "cycles": 18.4,+ "eevee": 4.4+ },+ "metal": {+ "cycles": 32.5,+ "eevee": 4.6+ },+ "outdoor-hdri": {+ "cycles": 9.4,+ "eevee": 5.0+ },+ "spot-area": {+ "cycles": 12.0,+ "eevee": 2.2+ }+ },+ "graphics": {+ "gpu": "ANGLE (NVIDIA, NVIDIA GeForce RTX 3060 (0x00002487) Direct3D11 vs_5_0 ps_5_0, D3D11)",+ "cpu": "ANGLE (Google, Vulkan 1.3.0 (SwiftShader Device (Subzero) (0x0000C0DE)), SwiftShader driver)"+ },+ "scores": {+ "brick-graph": {+ "gpu-vs-cycles": 0.2269,+ "gpu-vs-eevee": 0.148,+ "cpu-vs-cycles": 0.2268,+ "cpu-vs-eevee": 0.1479,+ "eevee-vs-cycles": 0.144,+ "gpu-vs-cpu": 0.0074+ },+ "brick-room": {+ "gpu-vs-cycles": 0.5102,+ "gpu-vs-eevee": 0.071,+ "cpu-vs-cycles": 0.5096,+ "cpu-vs-eevee": 0.0713,+ "eevee-vs-cycles": 0.502,+ "gpu-vs-cpu": 0.0071+ },+ "brushed-film": {+ "gpu-vs-cycles": 0.1613,+ "gpu-vs-eevee": 0.1601,+ "cpu-vs-cycles": 0.1613,+ "cpu-vs-eevee": 0.1601,+ "eevee-vs-cycles": 0.0939,+ "gpu-vs-cpu": 0.0058+ },+ "car-paint": {+ "gpu-vs-cycles": 0.1521,+ "gpu-vs-eevee": 0.1324,+ "cpu-vs-cycles": 0.152,+ "cpu-vs-eevee": 0.1324,+ "eevee-vs-cycles": 0.082,+ "gpu-vs-cpu": 0.0055+ },+ "character": {+ "gpu-vs-cycles": 0.0995,+ "gpu-vs-eevee": 0.0833,+ "cpu-vs-cycles": 0.099,+ "cpu-vs-eevee": 0.0826,+ "eevee-vs-cycles": 0.074,+ "gpu-vs-cpu": 0.0068+ },+ "fog": {+ "gpu-vs-cycles": 0.2612,+ "gpu-vs-eevee": 0.0542,+ "cpu-vs-cycles": 0.2608,+ "cpu-vs-eevee": 0.0542,+ "eevee-vs-cycles": 0.2662,+ "gpu-vs-cpu": 0.0085+ },+ "foliage": {+ "gpu-vs-cycles": 0.1594,+ "gpu-vs-eevee": 0.1386,+ "cpu-vs-cycles": 0.159,+ "cpu-vs-eevee": 0.1384,+ "eevee-vs-cycles": 0.0783,+ "gpu-vs-cpu": 0.0096+ },+ "glass": {+ "gpu-vs-cycles": 0.1326,+ "gpu-vs-eevee": 0.1472,+ "cpu-vs-cycles": 0.1323,+ "cpu-vs-eevee": 0.1474,+ "eevee-vs-cycles": 0.115,+ "gpu-vs-cpu": 0.0075+ },+ "light-linking": {+ "gpu-vs-cycles": 0.0998,+ "gpu-vs-eevee": 0.1122,+ "cpu-vs-cycles": 0.0993,+ "cpu-vs-eevee": 0.1127,+ "eevee-vs-cycles": 0.1558,+ "gpu-vs-cpu": 0.0027+ },+ "lit-interior": {+ "gpu-vs-cycles": 0.5055,+ "gpu-vs-eevee": 0.0923,+ "cpu-vs-cycles": 0.5051,+ "cpu-vs-eevee": 0.0928,+ "eevee-vs-cycles": 0.5159,+ "gpu-vs-cpu": 0.0062+ },+ "long-street": {+ "gpu-vs-cycles": 0.1555,+ "gpu-vs-eevee": 0.1396,+ "cpu-vs-cycles": 0.1554,+ "cpu-vs-eevee": 0.1396,+ "eevee-vs-cycles": 0.0975,+ "gpu-vs-cpu": 0.0098+ },+ "material-spheres": {+ "gpu-vs-cycles": 0.1598,+ "gpu-vs-eevee": 0.1196,+ "cpu-vs-cycles": 0.1595,+ "cpu-vs-eevee": 0.1194,+ "eevee-vs-cycles": 0.1006,+ "gpu-vs-cpu": 0.0069+ },+ "metal": {+ "gpu-vs-cycles": 0.1868,+ "gpu-vs-eevee": 0.1565,+ "cpu-vs-cycles": 0.1867,+ "cpu-vs-eevee": 0.1565,+ "eevee-vs-cycles": 0.0934,+ "gpu-vs-cpu": 0.0063+ },+ "outdoor-hdri": {+ "gpu-vs-cycles": 0.0676,+ "gpu-vs-eevee": 0.052,+ "cpu-vs-cycles": 0.0672,+ "cpu-vs-eevee": 0.0515,+ "eevee-vs-cycles": 0.0383,+ "gpu-vs-cpu": 0.0058+ },+ "spot-area": {+ "gpu-vs-cycles": 0.1242,+ "gpu-vs-eevee": 0.1707,+ "cpu-vs-cycles": 0.1242,+ "cpu-vs-eevee": 0.1709,+ "eevee-vs-cycles": 0.1935,+ "gpu-vs-cpu": 0.0032}+ }}diff --git a/bench/reference/frame-time.mjs b/bench/reference/frame-time.mjsindex 104dc988..2bc11f6c 100644--- a/bench/reference/frame-time.mjs+++ b/bench/reference/frame-time.mjs@@ -21,9 +21,13 @@ try {await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });await page.waitForFunction(() => window.measureReferenceFrameTime, null, { timeout: PAGE_LOAD_TIMEOUT });const results = [];- // Alternate the order so a drifting machine load does not favor one side.- for (const bake of [false, true, false, true]) {- results.push(await page.evaluate(([id, shouldBake]) => window.measureReferenceFrameTime(id, { bake: shouldBake }), [sceneId, bake]));+ // 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.+ 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 }));+ for (const variant of variants) {+ results.push({ ...variant, ...(await page.evaluate(([id, options]) => window.measureReferenceFrameTime(id, options), [sceneId, variant])) });}console.log(JSON.stringify({ sceneId, backend, results }, null, 1));} finally {diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 28d37874..6c881484 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -4,6 +4,8 @@ import { REFERENCE_SCENES } from './scenes.js';import { skinnedGeometry } from '/src/path-tracer-scene.js';import { boxProjectedGeometry } from '/src/export-box-uv.js';import '/src/material-layer-shaders.js';+import { createCascadedShadows } from '/src/cascaded-shadows.js';+import { applyLightLinks } from '/src/light-linking.js';function encodeBytes(typedArray) {const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);@@ -70,14 +72,19 @@ async function bakeScene(scene, bakeOptions) {return { parts: baked.parts, report: baked.report, seconds: (performance.now() - started) / 1000 };}-async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null }) {+// The 67js renderer for a scene: light linking from the lights' affects lists, and cascaded sun shadows when asked for.+function createSceneRenderer(parts, scene, cascades) {+ return new Renderer67(document.querySelector('canvas'), applyLightLinks(parts, scene.environment), {+ ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,+ environment: scene.environment, shadowBounds: scene.shadow, shadowCascades: cascades ? createCascadedShadows({ count: cascades }) : null,+ });+}++async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambientOcclusionRadius = 0.5, bake = null, cascades = 0 }) {const scene = await REFERENCE_SCENES[id]();const baked = bake ? await bakeScene(scene, bake) : null;const canvas = document.querySelector('canvas');- const renderer = new Renderer67(canvas, baked ? baked.parts : scene.parts, {- ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,- environment: scene.environment, shadowBounds: scene.shadow,- });+ const renderer = createSceneRenderer(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);@@ -95,26 +102,25 @@ async function renderReferenceScene(id, { describe, ambientOcclusion = 0, ambien}// 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, warmupFrames = 20, measuredFrames = 200 }) {+async function measureReferenceFrameTime(id, { bake, cascades = 0, orbit = false, warmupFrames = 20, measuredFrames = 200 }) {const scene = await REFERENCE_SCENES[id]();const baked = bake ? await bakeScene(scene, {}) : null;- const renderer = new Renderer67(document.querySelector('canvas'), baked ? baked.parts : scene.parts, {- ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, world: true,- environment: scene.environment, shadowBounds: scene.shadow,- });+ const renderer = createSceneRenderer(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.+ const orbitedEye = index => [scene.camera.eye[0] + Math.sin(index * 0.05) * 0.5, scene.camera.eye[1], scene.camera.eye[2]];// finish() returns before a hardware GPU is done, so reading one pixel back is what waits for the frame.const pixel = new Uint8Array(4);const finishDrawing = () => renderer.context.readPixels(0, 0, 1, 1, renderer.context.RGBA, renderer.context.UNSIGNED_BYTE, pixel);for (let index = 0; index < warmupFrames; index++) {- renderer.render(frame);+ renderer.render(orbit ? { ...frame, eye: orbitedEye(index) } : frame);finishDrawing();}const frameMilliseconds = [];for (let index = 0; index < measuredFrames; index++) {const started = performance.now();- renderer.render(frame);+ renderer.render(orbit ? { ...frame, eye: orbitedEye(index) } : frame);finishDrawing();frameMilliseconds.push(performance.now() - started);}diff --git a/bench/reference/images/light-linking.jpg b/bench/reference/images/light-linking.jpgnew file mode 100644index 00000000..0bc74bb8Binary files /dev/null and b/bench/reference/images/light-linking.jpg differdiff --git a/bench/reference/images/long-street.jpg b/bench/reference/images/long-street.jpgnew file mode 100644index 00000000..503a2f20Binary files /dev/null and b/bench/reference/images/long-street.jpg differdiff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.pyindex 97a4ee3a..13170032 100644--- a/bench/reference/render-blender.py+++ b/bench/reference/render-blender.py@@ -413,6 +413,17 @@ def build_world(scene, world_description, root):background.inputs[1].default_value = world_description["intensity"]+def link_receivers(light_object, names):+ # Light linking: a light with an affects list lights only those parts, as a receiver collection does. Shadows still+ # come from every part, which is also what 67js does.+ if names is None:+ return+ receivers = bpy.data.collections.new(f"{light_object.name}-receivers")+ for name in names:+ receivers.objects.link(bpy.data.objects[name])+ light_object.light_linking.receiver_collection = receivers++def build_lights(scene, environment):key = environment["keyColor"]if max(key) > 0:@@ -426,6 +437,7 @@ def build_lights(scene, environment):sun.rotation_mode = "QUATERNION"sun.rotation_quaternion = toward_light.to_track_quat("Z", "Y")scene.collection.objects.link(sun)+ link_receivers(sun, environment.get("keyAffects"))for index, point in enumerate(environment["pointLights"]):light = bpy.data.lights.new(f"Point-{index}", "POINT")light.energy = point["intensity"] * WATTS_PER_INTENSITY@@ -434,6 +446,7 @@ def build_lights(scene, environment):point_object = bpy.data.objects.new(f"Point-{index}", light)point_object.location = to_blender(point["position"])scene.collection.objects.link(point_object)+ link_receivers(point_object, point.get("affects"))for index, spot in enumerate(environment.get("spotLights", [])):build_spot_light(scene, index, spot)for index, area in enumerate(environment.get("areaLights", [])):@@ -455,6 +468,7 @@ def build_spot_light(scene, index, spot):direction = Vector(to_blender(spot["direction"])).normalized()spot_object.rotation_quaternion = direction.to_track_quat("-Z", "Y")scene.collection.objects.link(spot_object)+ link_receivers(spot_object, spot.get("affects"))def build_area_light(scene, index, area):diff --git a/bench/reference/run.mjs b/bench/reference/run.mjsindex 193200e1..3b8bf55b 100644--- a/bench/reference/run.mjs+++ b/bench/reference/run.mjs@@ -37,6 +37,8 @@ const ambientOcclusionRadius = radiusFlag >= 0 ? Number(argumentsGiven[radiusFlaconst bakeFlag = argumentsGiven.indexOf('--bake');const bakeValue = bakeFlag >= 0 ? argumentsGiven[bakeFlag + 1] : undefined;const bakedSceneIds = bakeFlag >= 0 && bakeValue && !bakeValue.startsWith('--') ? bakeValue.split(',') : null;+const cascadesFlag = argumentsGiven.indexOf('--cascades');+const cascades = cascadesFlag >= 0 ? Number(argumentsGiven[cascadesFlag + 1]) : 0;const pathTracerFlag = argumentsGiven.includes('--path-tracer');const samplesFlag = argumentsGiven.indexOf('--samples');const pathTracerSamples = samplesFlag >= 0 ? Number(argumentsGiven[samplesFlag + 1]) : 64;@@ -48,6 +50,7 @@ async function renderBackend(backend, serverUrl, graphics) {const page = await browser.newPage({ viewport: { width: WIDTH, height: HEIGHT } });const errors = [];page.on('pageerror', error => errors.push(error.message));+ page.on('console', message => message.text().includes('GL_') && console.log('PAGE', message.text().slice(0, 200)));await page.goto(`${serverUrl}/bench/reference/harness.html`, { timeout: PAGE_LOAD_TIMEOUT });await page.waitForFunction(() => window.renderReferenceScene, null, { timeout: PAGE_LOAD_TIMEOUT });const sceneIds = await page.evaluate(() => window.referenceSceneIds);@@ -56,7 +59,7 @@ async function renderBackend(backend, serverUrl, graphics) {const started = performance.now();const describe = backend === 'gpu';const bake = bakeFlag >= 0 && (bakedSceneIds === null || bakedSceneIds.includes(id)) ? {} : null;- const result = await page.evaluate(([sceneId, shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bakeOptions]) => window.renderReferenceScene(sceneId, { describe: shouldDescribe, ambientOcclusion, ambientOcclusionRadius, bake: bakeOptions }), [id, describe, ambientOcclusion, ambientOcclusionRadius, bake]);+ 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]);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'));diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 6c86b9a7..2a444cce 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -199,6 +199,62 @@ export const REFERENCE_SCENES = {};},+ // A street 140 m long under the sun. A single shadow map has to cover the whole street, so its texels are about 8 cm wide;+ // cascades give the cars and lamp posts near the camera 1 to 2 cm texels. harness.js draws it with one map by default and+ // with cascades when run.mjs gets --cascades <count>.+ async 'long-street'() {+ const lighting = constantLighting(0.25);+ const cube = box(0, 1);+ const parts = [part('street-ground', cube, [0, -0.05, -10], [60, 0.1, 160], { color: [0.32, 0.32, 0.33], roughness: 0.9 })];+ const facade = { color: [0.62, 0.55, 0.48], roughness: 0.85 };+ for (let block = 0; block < 12; block++) {+ const z = 55 - block * 12;+ const height = 5 + ((block * 7) % 5) * 2;+ parts.push(part(`building-west-${block}`, cube, [-10.5, height / 2, z], [6, height, 10], facade));+ parts.push(part(`building-east-${block}`, cube, [10.5, (height + 3) / 2, z], [6, height + 3, 10], { color: [0.55, 0.58, 0.62], roughness: 0.85 }));+ }+ for (let post = 0; post < 14; post++) {+ const z = 52 - post * 10;+ parts.push(part(`lamp-post-${post}`, cube, [-4.6, 2.2, z], [0.16, 4.4, 0.16], { color: [0.15, 0.15, 0.16], roughness: 0.4, metallic: 0.8 }));+ parts.push(part(`lamp-arm-${post}`, cube, [-4.1, 4.3, z], [1.1, 0.12, 0.12], { color: [0.15, 0.15, 0.16], roughness: 0.4, metallic: 0.8 }));+ }+ const carColors = [[0.7, 0.1, 0.1], [0.1, 0.25, 0.6], [0.85, 0.8, 0.7], [0.1, 0.4, 0.2]];+ carColors.forEach((color, index) => {+ parts.push(part(`car-body-${index}`, cube, [2.4, 0.55, 44 - index * 9], [1.8, 0.7, 4.2], { color, roughness: 0.35 }));+ parts.push(part(`car-roof-${index}`, cube, [2.4, 1.15, 44.3 - index * 9], [1.5, 0.5, 2.2], { color: [0.12, 0.14, 0.17], roughness: 0.2 }));+ });+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { keyColor: SUN_COLOR, lightDirection: [-0.7, 0.8, 0.35] }),+ camera: { eye: [-1.5, 1.7, 56], target: [0, 2.2, -40], up: [0, 1, 0], fov: 50, near: 0.1, far: 200 },+ shadow: { eye: [-58, 66, 30], target: [0, 0, -10], up: [0, 1, 0], extent: 85, near: 1, far: 260 },+ };+ },++ // Three point lights that each light only some parts (light linking). Without linking the red light would tint the right+ // sphere too. Blender gets the same lists as light-linking receiver collections.+ async 'light-linking'() {+ const lighting = constantLighting(0.01);+ const cube = box(0, 1);+ const parts = [+ part('stage-floor', cube, [0, -0.05, 0], [10, 0.1, 10], { color: [0.6, 0.6, 0.6], roughness: 0.8 }),+ part('stage-back', cube, [0, 1.5, -3.05], [10, 3.2, 0.1], { color: [0.7, 0.7, 0.7], roughness: 0.9 }),+ part('sphere-left', sphere(48, 32), [-1.2, 0.6, -0.5], [0.6, 0.6, 0.6], { color: [0.8, 0.8, 0.8], roughness: 0.4 }),+ part('sphere-right', sphere(48, 32), [1.2, 0.6, -0.5], [0.6, 0.6, 0.6], { color: [0.8, 0.8, 0.8], roughness: 0.4 }),+ part('block-center', cube, [0, 0.4, -1.5], [0.8, 0.8, 0.8], { color: [0.8, 0.8, 0.8], roughness: 0.6 }),+ ];+ const pointLights = [+ { position: [-1.8, 2.4, 1.2], color: [1, 0.35, 0.2], intensity: 14, radius: 0.1, affects: ['sphere-left', 'block-center'] },+ { position: [1.8, 2.4, 1.2], color: [0.25, 0.45, 1], intensity: 14, radius: 0.1, affects: ['sphere-right'] },+ { position: [0, 3, 2.5], color: [1, 1, 1], intensity: 6, radius: 0.1, affects: ['stage-floor', 'stage-back'] },+ ];+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { pointLights }),+ camera: { eye: [0, 1.6, 4.6], target: [0, 0.6, -0.8], up: [0, 1, 0], fov: 50, near: 0.05, far: 50 },+ };+ },+async character() {const lighting = await skyLighting();const response = await fetch(`/${ROBOT_FILE}`);diff --git a/bench/size/baseline.json b/bench/size/baseline.jsonindex 87410f8f..96b2ad1c 100644--- a/bench/size/baseline.json+++ b/bench/size/baseline.json@@ -14,9 +14,9 @@},"bundles": {"entry:core": {- "min": 287420,- "gzip": 82181,- "brotli": 70138+ "min": 287946,+ "gzip": 82334,+ "brotli": 70195},"entry:model": {"min": 40093,@@ -39,14 +39,14 @@"brotli": 7331},"entry:gltf": {- "min": 156342,- "gzip": 47981,- "brotli": 41563+ "min": 156410,+ "gzip": 48011,+ "brotli": 41568},"entry:gltf+lazy": {- "min": 162775,- "gzip": 49970,- "brotli": 43374+ "min": 162843,+ "gzip": 50001,+ "brotli": 43377},"entry:modeling": {"min": 21149,@@ -144,24 +144,24 @@"brotli": 762},"entry:agent-scene": {- "min": 211468,- "gzip": 65703,- "brotli": 57500+ "min": 211531,+ "gzip": 65730,+ "brotli": 57520},"entry:agent-scene+lazy": {- "min": 656357,- "gzip": 225836,- "brotli": 199349+ "min": 656420,+ "gzip": 225855,+ "brotli": 199379},"entry:agent-asset": {- "min": 306775,- "gzip": 97383,- "brotli": 85592+ "min": 306838,+ "gzip": 97409,+ "brotli": 85574},"entry:agent-asset+lazy": {- "min": 693431,- "gzip": 237556,- "brotli": 209425+ "min": 693494,+ "gzip": 237573,+ "brotli": 209454},"entry:hdri": {"min": 8075,@@ -179,34 +179,44 @@"brotli": 1425},"entry:material-layer-shaders": {- "min": 71833,- "gzip": 18658,- "brotli": 16359+ "min": 71897,+ "gzip": 18688,+ "brotli": 16369+ },+ "entry:light-linking": {+ "min": 67458,+ "gzip": 17938,+ "brotli": 15753+ },+ "entry:cascaded-shadows": {+ "min": 95474,+ "gzip": 26574,+ "brotli": 22646},"scene:lit-box": {- "min": 217804,- "gzip": 59861,- "brotli": 51117+ "min": 218221,+ "gzip": 59990,+ "brotli": 51264},"scene:gltf-box": {- "min": 277431,- "gzip": 79898,- "brotli": 69584+ "min": 277847,+ "gzip": 80037,+ "brotli": 69616},"scene:gltf-box+lazy": {- "min": 283864,- "gzip": 81888,- "brotli": 71399+ "min": 284280,+ "gzip": 82027,+ "brotli": 71422},"scene:agent-scene": {- "min": 322662,- "gzip": 96484,- "brotli": 84041+ "min": 323076,+ "gzip": 96616,+ "brotli": 84154},"scene:agent-scene+lazy": {- "min": 767546,- "gzip": 256611,- "brotli": 225945+ "min": 767960,+ "gzip": 256743,+ "brotli": 226045}}}diff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 6ad39dc4..14b41fe4 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -30,6 +30,8 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:light-bake": 26900,+ "entry:light-linking": 18400,+ "entry:cascaded-shadows": 27100,"entry:path-tracer": 13800,"entry:texture-set": 900,"entry:agent-scene": 66500,diff --git a/docs/lighting.md b/docs/lighting.mdindex 9077201e..b2952617 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -93,7 +93,35 @@ Method: representative point, not a light-transform lookup table. The closest poShadows reach `range`, or 30 units when `range` is zero; farther surfaces are lit. Filtering is one bilinear 2 x 2 comparison, and the receiver is moved off its surface by about two texels, so edges are slightly hard and a very thin wall can leak. The atlas is drawn again only when a light moves, a shadow-casting part changes or sways, so a static scene pays the depth passes once. A scene with no shadow casting lights allocates nothing and compiles none of this code.-Cascaded directional shadows are not part of this work: the directional light still uses one 2048 x 2048 map.+## Cascaded sun shadows++The directional light uses one 2048 x 2048 map over the box that `shadowBounds` gives. In a scene as long as a street that box is 100 m or more across, so a texel is 6 to 8 cm and a lamp post near the camera is two texels wide. Cascades cut the camera's view into up to four slices by depth and fit one map to each, so the slice near the camera has texels of about 1 cm.++```js+import { Renderer67 } from '@codepawlhq/67js';+import { createCascadedShadows } from '@codepawlhq/67js/addons/cascaded-shadows';++const renderer = new Renderer67(canvas, parts, {+ world: true,+ shadowBounds, // still gives the light direction (eye minus target)+ shadowCascades: createCascadedShadows({ count: 3 }),+});+```++Options: `count` (1 to 4, default 3), `resolution` (256 to 4096, default 2048), `maximumDistance` (default 150 m; farther surfaces are lit), `splitLambda` (0 uniform to 1 logarithmic, default 0.7) and `casterReach` (how far toward the light a caster may stand, default 200 m). Each slice is a bounding sphere, so turning the camera does not change its size, and its centre snaps to whole texels, so edges do not crawl. The last tenth of a slice blends into the next. The slice maps are drawn again when the camera, the light or a caster moves, so a still camera pays the depth passes once and a moving one pays `count` passes per frame; the measured cost is in `bench/reference/README.md`. Three slices of 2048 x 2048 are a 48 MiB depth array. The single map is still drawn for volume fog and water, which do not read the cascades. A scene without cascades compiles none of this code, and recipes do not reach it yet.++## Light linking++A light can be limited to some parts, as Blender's receiver collection does. Give a light an `affects` list of part names (and `environment.keyAffects` for the sun) and pass the parts through `applyLightLinks`:++```js+import { applyLightLinks } from '@codepawlhq/67js/addons/light-linking';++const environment = { pointLights: [{ position: [-1.8, 2.4, 1.2], intensity: 14, affects: ['sphere-left'] }], keyAffects: ['floor'] };+const renderer = new Renderer67(canvas, applyLightLinks(parts, environment), { environment });+```++A part gets a bit mask in `material.lightMask` (bit 0 the sun, bits 1 to 8 the point lights, 9 to 16 the spot lights, 17 to 20 the area lights, in list order); the shader skips a light whose bit is clear. Linking changes what a light adds, not what it shadows: a part a light does not reach still blocks that light for the others, and in Blender too. Parts with different masks are different batches. The path tracer and the light bake ignore linking, and recipes do not reach it yet (`lightLinking: false` in `scene_capabilities`). A scene without links compiles none of this code. The reference scene `light-linking` is the measured case.## Animation and resourcesdiff --git a/docs/parity.md b/docs/parity.mdindex c63cbf1f..283bf40b 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -190,8 +190,8 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Rendering > Render Engines > Cycles | partial | A CPU path tracer (`addons/path-tracer`, or `settings.renderer` on an image render job; [path-tracer](path-tracer.md)) draws diffuse, GGX metal, clear coat, glass, maps, cutouts, the sun, point, spot and area lights with soft shadows and the environment map, with a denoiser. At 32 samples its FLIP score against Cycles is better than the rasterizer's on 7 of the 11 reference scenes and worse on `outdoor-hdri`, `character`, `fog` (no volume fog) and `foliage` (equal to 0.0003); the mean is 0.171 against 0.189 (`npm run reference -- --path-tracer`, [bench/reference/path-tracer.json](../bench/reference/path-tracer.json)). It draws normal and metallic-roughness maps on UV-mapped materials (issue #129) and runs about 2.8 times faster per thread than at that table, so its scores and seconds there predate both; it does not trace volume fog, translucent leaves or maps on box-projected materials, a 1080p still of a 181,708 triangle room at 64 samples still does not finish inside the 240 s job limit, and it is not Cycles parity. `addons/light-bake` bakes bounced light from point, spot and area lights and the sun into a lightmap for each part, on the CPU with ray tracing; recipes reach it through the `bake` section and `set-bake` (draft, standard or fine presets, shrunk deterministically to a ray work budget of 10 million so a preset finishes on a 56 part room; scene_inspect reports what it used, whether it reduced, bake seconds and skipped parts, which include hair, particle and cloth nodes), patterned, textured and emissive parts bake through a second UV set and a `lightMap` slot, GLB export writes the map approximately as `TEXCOORD_1` emissive, but there are no reflection probes and no baked AO. On `lit-interior` it brings the score against Cycles from 0.5055 to 0.1444 (`npm run reference -- --bake lit-interior`). | [light-bake](../tests/light-bake.test.js), [path-tracer](../tests/path-tracer.test.js), [recipe bake](../tests/agent-bake.test.js), [frame time](../bench/reference/frame-time.mjs), [lit-interior scene](../bench/reference/scenes.js) | #55, #57, #128 || Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | || Rendering > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |-| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |-| Rendering > Lights > Light Linking | missing | No light linking. | | #52 |+| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer; recipes do not reach it): scene `long-street` scores 0.1555 against Cycles with one map and 0.1398 with three cascades, for about 0.2 ms more a frame on an RTX 3060 when the camera moves. | [lighting](../tests/lighting.test.js), [cascades](../tests/cascaded-shadows.test.js), `npm run reference` scenes `spot-area` and `long-street` | #52 |+| Rendering > Lights > Light Linking | partial | `addons/light-linking`: a light's `affects` list (and `environment.keyAffects` for the sun) limits it to the named parts through `applyLightLinks`, as a Blender receiver collection does; the shader skips a light whose bit in the part's mask is clear. Linking changes what a light adds, not what it shadows. The path tracer and the light bake ignore it, recipes do not reach it (`lightLinking: false` in `scene_capabilities`) and there is no blocker list. Scene `light-linking` scores 0.0998 against Cycles. | [light-linking](../tests/light-linking.test.js), `npm run reference` scene `light-linking` | #52 || Rendering > Lights > World Environment | partial | Recipes pick a named setup (`daylight`, `overcast`, `sunset`, `studio`) that carries a procedural environment map, with opt-in screen-space ambient occlusion. Code can load any HDRI; recipes reach only the named maps, with no URLs or files. No reflections between objects yet. | [environment](../tests/environment.test.js), [default look](../tests/default-look.test.js) | #53 || Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps, a clear coat, transmission with thickness, attenuation and IOR, sheen, and specular weight and tint. Anisotropic highlights and a thin-film iridescence layer, as in the glTF extensions, are compiled in only when a part uses them. There is no subsurface scattering, volume material or displacement. | [texture-set](../tests/texture-set.test.js), [material-layers](../tests/material-layers.test.js) | #50, #51 || Rendering > Materials > Assignment | done | A node names one material. | [agent-scene](../tests/agent-scene.test.js) | |diff --git a/package.json b/package.jsonindex b2cb18c6..be612d49 100644--- a/package.json+++ b/package.json@@ -79,6 +79,8 @@"./addons/camera-effects": "./build/camera-effects.js","./addons/render-passes": "./build/render-passes.js","./addons/material-layer-shaders": "./build/material-layer-shaders.js",+ "./addons/light-linking": "./build/light-linking.js",+ "./addons/cascaded-shadows": "./build/cascaded-shadows.js","./package.json": "./package.json"},"scripts": {diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 7579fdaf..dcf5a848 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -69,7 +69,7 @@ Local `environment.pointLights` support eight world-space sources with inverse-sEach light provides `position` and optional `color`, `intensity`, `radius`, `range` and `castShadow`.`environment.spotLights` (eight) take `position`, `direction`, and optional `angle` (outer half angle in radians, default 0.785), `penumbra` (0 to 1, default 0.15), `color`, `intensity`, `radius`, `range` and `castShadow`. Intensity is candela, the same unit as a point light.`environment.areaLights` (four) are rectangles with `position`, `direction` (the side that emits), `width`, `height`, optional `up`, `color` and `intensity` (candela seen head on). They cast no shadow.-`castShadow: true` on a point light uses 6 of the 24 shadow tiles, on a spot light 1. Past 24 the edit is rejected. Shadows reach `range`, or 30 units when `range` is 0. Set `castShadow` on the few lights that show a visible shadow, because each one adds a depth pass.+`castShadow: true` on a point light uses 6 of the 24 shadow tiles, on a spot light 1. Past 24 the edit is rejected. Shadows reach `range`, or 30 units when `range` is 0. Set `castShadow` on the few lights that show a visible shadow, because each one adds a depth pass. Recipes cannot link a light to some parts or cascade the sun shadow (`lightLinking` is false in `scene_capabilities`); those are engine options for code that builds its own `Renderer67` (`addons/light-linking`, `addons/cascaded-shadows`; see docs/lighting.md).`keyIntensity`, `fillIntensity` and `ambientIntensity` independently scale existing lighting.Read the checkout's `docs/lighting.md` for defaults, numeric limits and frame overrides.Point lights currently cast no local shadows. Radius limits attenuation without creating an area emitter.diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 7c30037c..c88188f3 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -181,7 +181,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,ambientOcclusion: Object.freeze({ default: DEFAULT_AMBIENT_OCCLUSION, defaultRadius: 0.5, off: 0 }),// Local lights: spot and rectangular area lights. Shadows share one 2048 x 3072 depth atlas of 24 tiles; a shadowed- // point light uses 6 tiles and a shadowed spot light 1. Area lights cast no shadow. Light linking is not supported.+ // point light uses 6 tiles and a shadowed spot light 1. Area lights cast no shadow. Light linking (addons/light-linking) and cascaded sun shadows (addons/cascaded-shadows) are engine options that recipes do not reach; lightLinking stays false here.maxSpotLights: 8, maxAreaLights: 4,localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),lightLinking: false,diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.jsnew file mode 100644index 00000000..08abb0d4--- /dev/null+++ b/src/cascaded-shadows.js@@ -0,0 +1,271 @@+import { mat4, vec3 } from 'gl-matrix';+import { registerShaderFeatureCode } from './shaders.js';++// Cascaded sun shadows. The camera frustum is cut into up to four slices by view depth; each slice gets its own depth+// map, fitted to a bounding sphere of the slice, so a shadow near the camera is sharp and a far one is coarse. Pass+// `shadowCascades: createCascadedShadows({ count: 3 })` to the Renderer. The code lives here, not in the renderer, so a+// scene without cascades never downloads it. The classic single map is still drawn for volume fog and water.+// The GLSL has no comments, because comments ship to every page:+// - cascadeMatrices take a world position to the clip space of each slice, cascadeSplits holds the view depth where each+// slice ends, cascadeTexels the world size of one shadow texel and cascadeRanges the depth range in metres, and+// cascadeFrame the camera forward axis with the slice count.+// - The receiver is pushed off its surface by 1.5 texels and the depth bias is one texel, as the local shadows do.+// - The last tenth of each slice blends into the next, so no seam shows.+// - The final #define makes the main shader's shadowVisibility(normal) call read the cascades; the classic map stays unused.++export const MAXIMUM_CASCADES = 4;+const DEFAULT_RESOLUTION = 2048;+const DEFAULT_MAXIMUM_DISTANCE = 150;+const DEFAULT_SPLIT_LAMBDA = 0.7;+const DEFAULT_CASTER_REACH = 200;+// A sampler that a program never sets reads unit 0, and the cascade array lives on unit 0, so the main program's other+// samplers are pinned to their own units here. These are the units renderer.js uses: the five maps on 1 to 5, the light map on 6, the local shadow atlas on 15.+const MAIN_SAMPLER_UNITS = { baseMap: 1, normalMap: 2, metallicRoughnessMap: 3, occlusionMap: 4, emissiveMap: 5, lightMap: 6, localShadowAtlas: 15 };+// The light direction when the renderer's shadowBounds do not give one, as renderer.js defaults it.+const DEFAULT_LIGHT_VIEWS = { world: { eye: [-25, 60, 30], target: [0, 2, -10] }, studio: { eye: [-3, 6, 4], target: [0, 1, 0] } };+const NDC_CORNERS = [[-1, -1], [1, -1], [-1, 1], [1, 1]];++const CASCADE_DECLARATIONS = `uniform highp sampler2DArray cascadeShadowMap;+uniform mat4 cascadeMatrices[4];+uniform vec4 cascadeSplits;+uniform vec4 cascadeTexels;+uniform vec4 cascadeRanges;+uniform vec4 cascadeFrame;+float cascadeTap(int layer, vec2 coordinates, float receiverDepth, ivec2 dimensions) {+ vec2 pixel = coordinates * vec2(dimensions) - 0.5;+ ivec2 origin = ivec2(floor(pixel));+ vec2 blend = fract(pixel);+ ivec2 maximum = dimensions - 1;+ float lowerLeft = step(receiverDepth, texelFetch(cascadeShadowMap, ivec3(clamp(origin, ivec2(0), maximum), layer), 0).r);+ float lowerRight = step(receiverDepth, texelFetch(cascadeShadowMap, ivec3(clamp(origin + ivec2(1, 0), ivec2(0), maximum), layer), 0).r);+ float upperLeft = step(receiverDepth, texelFetch(cascadeShadowMap, ivec3(clamp(origin + ivec2(0, 1), ivec2(0), maximum), layer), 0).r);+ float upperRight = step(receiverDepth, texelFetch(cascadeShadowMap, ivec3(clamp(origin + ivec2(1, 1), ivec2(0), maximum), layer), 0).r);+ return mix(mix(lowerLeft, lowerRight, blend.x), mix(upperLeft, upperRight, blend.x), blend.y);+}+float cascadeLayerVisibility(int layer, vec3 normal) {+ vec3 shifted = worldPosition + normal * (cascadeTexels[layer] * 1.5);+ vec3 projected = (cascadeMatrices[layer] * vec4(shifted, 1.0)).xyz * 0.5 + 0.5;+ if (projected.z > 1.0 || projected.z < 0.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 1.0;+ float bias = cascadeTexels[layer] / cascadeRanges[layer] * (1.0 + 2.0 * (1.0 - dot(normal, normalize(lightDirection))));+ ivec2 dimensions = textureSize(cascadeShadowMap, 0).xy;+ vec2 texel = 1.0 / vec2(dimensions);+ float visibility = 0.0;+ for (int row = -1; row <= 1; row++) {+ for (int column = -1; column <= 1; column++) {+ visibility += mix(0.18, 1.0, cascadeTap(layer, projected.xy + vec2(column, row) * texel * 2.5, projected.z - bias, dimensions));+ }+ }+ return visibility / 9.0;+}+float cascadeVisibility(vec3 normal) {+ float viewDepth = dot(worldPosition - eye, cascadeFrame.xyz);+ int count = int(cascadeFrame.w);+ for (int layer = 0; layer < 4; layer++) {+ if (layer >= count) break;+ float split = cascadeSplits[layer];+ if (viewDepth >= split) continue;+ float visibility = cascadeLayerVisibility(layer, normal);+ float previousSplit = layer > 0 ? cascadeSplits[layer - 1] : 0.0;+ float blendStart = split - (split - previousSplit) * 0.1;+ if (layer + 1 < count && viewDepth > blendStart) {+ visibility = mix(visibility, cascadeLayerVisibility(layer + 1, normal), smoothstep(blendStart, split, viewDepth));+ }+ return visibility;+ }+ return 1.0;+}+#define shadowVisibility(normal) cascadeVisibility(normal)+`;++registerShaderFeatureCode('cascadedShadows', { declarations: CASCADE_DECLARATIONS });++function integerInRange(value, minimum, maximum, name) {+ if (!Number.isInteger(value) || value < minimum || value > maximum) {+ throw new RangeError(`${name} must be a whole number between ${minimum} and ${maximum}`);+ }+ return value;+}++function numberInRange(value, minimum, maximum, name) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {+ throw new RangeError(`${name} must be between ${minimum} and ${maximum}`);+ }+ return value;+}++/** View depth where each slice ends: a blend of a uniform and a logarithmic split, as in practical split schemes. */+export function cascadeSplitDistances(count, near, far, lambda = DEFAULT_SPLIT_LAMBDA) {+ const distances = [];+ for (let index = 1; index <= count; index++) {+ const fraction = index / count;+ const logarithmic = near * (far / near) ** fraction;+ const uniform = near + (far - near) * fraction;+ distances.push(lambda * logarithmic + (1 - lambda) * uniform);+ }+ distances[count - 1] = far;+ return distances;+}++// The eight corners of the camera frustum, near plane first, from the inverse view-projection matrix.+function frustumCorners(inverseViewProjection) {+ const corners = [];+ for (const ndcDepth of [-1, 1]) {+ for (const [ndcX, ndcY] of NDC_CORNERS) {+ corners.push(vec3.transformMat4(vec3.create(), [ndcX, ndcY, ndcDepth], inverseViewProjection));+ }+ }+ return corners;+}++// The slice of the frustum between two fractions of the way from the near plane to the far plane.+function frustumSlice(corners, startFraction, endFraction) {+ const slice = [];+ for (const fraction of [startFraction, endFraction]) {+ for (let corner = 0; corner < 4; corner++) {+ slice.push(vec3.lerp(vec3.create(), corners[corner], corners[corner + 4], fraction));+ }+ }+ return slice;+}++function viewDepthOf(point, view) {+ return -vec3.transformMat4(vec3.create(), point, view)[2];+}++function boundingSphere(points) {+ const center = vec3.create();+ points.forEach(point => vec3.add(center, center, point));+ vec3.scale(center, center, 1 / points.length);+ const radius = Math.max(...points.map(point => vec3.distance(center, point)));+ return { center, radius };+}++/**+ * Writes the world to clip matrix of one slice into `target`. The slice is covered by a sphere, so turning the camera+ * does not change its size, and the sphere centre is snapped to whole texels so the shadow edges do not crawl.+ * Returns the world size of a texel and the depth range in metres.+ */+export function writeCascadeMatrix(target, { center, radius }, towardLight, resolution, casterReach) {+ const rotation = mat4.lookAt(mat4.create(), [0, 0, 0], [-towardLight[0], -towardLight[1], -towardLight[2]], Math.abs(towardLight[1]) > 0.99 ? [0, 0, 1] : [0, 1, 0]);+ const lightSpaceCenter = vec3.transformMat4(vec3.create(), center, rotation);+ const texel = (2 * radius) / resolution;+ const snappedX = Math.round(lightSpaceCenter[0] / texel) * texel;+ const snappedY = Math.round(lightSpaceCenter[1] / texel) * texel;+ const snappedZ = Math.round(lightSpaceCenter[2] / texel) * texel;+ const near = -(snappedZ + casterReach);+ const far = -(snappedZ - radius);+ const projection = mat4.ortho(mat4.create(), snappedX - radius, snappedX + radius, snappedY - radius, snappedY + radius, near, far);+ mat4.multiply(target, projection, rotation);+ return { texel, range: far - near };+}++export class CascadedShadows {+ constructor({ count = 3, resolution = DEFAULT_RESOLUTION, maximumDistance = DEFAULT_MAXIMUM_DISTANCE, splitLambda = DEFAULT_SPLIT_LAMBDA, casterReach = DEFAULT_CASTER_REACH } = {}) {+ this.count = integerInRange(count, 1, MAXIMUM_CASCADES, 'cascade count');+ this.resolution = integerInRange(resolution, 256, 4096, 'cascade resolution');+ this.maximumDistance = numberInRange(maximumDistance, 1, 1e5, 'cascade maximumDistance');+ this.splitLambda = numberInRange(splitLambda, 0, 1, 'cascade splitLambda');+ this.casterReach = numberInRange(casterReach, 1, 1e5, 'cascade casterReach');+ this.shaderFeature = 'cascadedShadows';+ this.matrices = new Float32Array(MAXIMUM_CASCADES * 16);+ this.previousMatrices = new Float32Array(MAXIMUM_CASCADES * 16);+ this.splits = new Float32Array(MAXIMUM_CASCADES).fill(1e9);+ this.texels = new Float32Array(MAXIMUM_CASCADES).fill(1);+ this.ranges = new Float32Array(MAXIMUM_CASCADES).fill(1);+ this.forward = new Float32Array(4);+ this.texture = null;+ this.framebuffer = null;+ this.drawCount = 0;+ this.locations = null;+ this.locationProgram = null;+ }++ allocate(context) {+ this.texture = context.createTexture();+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D_ARRAY, this.texture);+ context.texImage3D(context.TEXTURE_2D_ARRAY, 0, context.DEPTH_COMPONENT24, this.resolution, this.resolution, this.count, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MIN_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_MAG_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D_ARRAY, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ this.framebuffer = context.createFramebuffer();+ }++ // Fits every slice to the current camera. Returns the number of slices whose matrix moved.+ fitToCamera(renderer) {+ const light = { ...DEFAULT_LIGHT_VIEWS[renderer.world ? 'world' : 'studio'], ...renderer.shadowBounds };+ const towardLight = vec3.normalize(vec3.create(), vec3.subtract(vec3.create(), light.eye, light.target));+ const corners = frustumCorners(renderer.inverseViewProjection);+ const nearDistance = viewDepthOf(corners[0], renderer.view);+ const planeFarDistance = viewDepthOf(corners[4], renderer.view);+ const farDistance = Math.min(planeFarDistance, this.maximumDistance);+ const splits = cascadeSplitDistances(this.count, nearDistance, farDistance, this.splitLambda);+ const planeSpan = planeFarDistance - nearDistance;+ let previousFraction = 0;+ splits.forEach((split, layer) => {+ const endFraction = Math.min((split - nearDistance) / planeSpan, 1);+ const sphere = boundingSphere(frustumSlice(corners, previousFraction, endFraction));+ const fitted = writeCascadeMatrix(this.matrices.subarray(layer * 16, layer * 16 + 16), sphere, towardLight, this.resolution, this.casterReach);+ this.splits[layer] = split;+ this.texels[layer] = fitted.texel;+ this.ranges[layer] = fitted.range;+ previousFraction = endFraction;+ });+ this.forward.set([...renderer.viewForward, this.count]);+ return this.matrices.some((value, index) => value !== this.previousMatrices[index]);+ }++ /** Redraws the slice maps when the camera, the light or a caster moved. Call once a frame after the camera is set. */+ update(renderer, casterChanged) {+ const context = renderer.context;+ if (!this.texture) this.allocate(context);+ const moved = this.fitToCamera(renderer);+ if (!moved && !casterChanged && this.drawCount > 0) return;+ this.previousMatrices.set(this.matrices);+ this.drawCount++;+ context.bindFramebuffer(context.FRAMEBUFFER, this.framebuffer);+ context.drawBuffers([context.NONE]);+ context.readBuffer(context.NONE);+ context.viewport(0, 0, this.resolution, this.resolution);+ context.enable(context.DEPTH_TEST);+ context.enable(context.CULL_FACE);+ for (let layer = 0; layer < this.count; layer++) {+ context.framebufferTextureLayer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, this.texture, 0, layer);+ context.clear(context.DEPTH_BUFFER_BIT);+ renderer.drawShadowCasters(this.matrices.subarray(layer * 16, layer * 16 + 16));+ }+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ }++ /** Uploads the slice matrices and binds the depth array to unit 0, which the main pass reads. */+ bindUniforms(renderer) {+ const context = renderer.context;+ if (this.locationProgram !== renderer.program) {+ const names = ['cascadeShadowMap', 'cascadeMatrices[0]', 'cascadeSplits', 'cascadeTexels', 'cascadeRanges', 'cascadeFrame'];+ this.locations = Object.fromEntries(names.map(name => [name, context.getUniformLocation(renderer.program, name)]));+ this.locationProgram = renderer.program;+ for (const [name, unit] of Object.entries(MAIN_SAMPLER_UNITS)) context.uniform1i(context.getUniformLocation(renderer.program, name), unit);+ }+ context.activeTexture(context.TEXTURE0);+ context.bindTexture(context.TEXTURE_2D_ARRAY, this.texture);+ context.uniform1i(this.locations.cascadeShadowMap, 0);+ context.uniformMatrix4fv(this.locations['cascadeMatrices[0]'], false, this.matrices);+ context.uniform4fv(this.locations.cascadeSplits, this.splits);+ context.uniform4fv(this.locations.cascadeTexels, this.texels);+ context.uniform4fv(this.locations.cascadeRanges, this.ranges);+ context.uniform4fv(this.locations.cascadeFrame, this.forward);+ }++ dispose(context) {+ if (this.texture) context.deleteTexture(this.texture);+ if (this.framebuffer) context.deleteFramebuffer(this.framebuffer);+ this.texture = null;+ this.framebuffer = null;+ }+}++/** Options: count (1 to 4 slices, default 3), resolution (default 2048), maximumDistance (default 150 m), splitLambda, casterReach. */+export function createCascadedShadows(options) {+ return new CascadedShadows(options);+}diff --git a/src/light-linking.js b/src/light-linking.jsnew file mode 100644index 00000000..826598cb--- /dev/null+++ b/src/light-linking.js@@ -0,0 +1,68 @@+import { registerShaderFeatureCode } from './shaders.js';+import { ALL_LIGHTS_MASK } from './material-layers.js';++// Light linking: a light can be limited to the parts it lights, as Blender's receiver collection does. A part carries+// a bit mask in `material.lightMask`; the shader skips a light whose bit is clear. The code lives here, not in the+// renderer, so a scene without linking never downloads it and its shader has no mask test.+// Bit 0 is the sun (the key light), bits 1 to 8 the point lights, 9 to 16 the spot lights and 17 to 20 the area lights,+// in the order of the environment lists. Linking changes what a light adds, not what it shadows: a part that a light+// does not reach still blocks that light for the others. The path tracer and the light bake ignore linking.+// The GLSL has no comments, because comments ship to every page.++export const SUN_BIT = 0;+export const POINT_FIRST_BIT = 1;+export const SPOT_FIRST_BIT = 9;+export const AREA_FIRST_BIT = 17;++registerShaderFeatureCode('lightLinking', {+ declarations: `uniform int lightLinkMask;+bool lightLinked(int bit) {+ return ((lightLinkMask >> bit) & 1) != 0;+}+`,+ linkSun: ' * float(lightLinked(0))',+ linkPoint: ' if (!lightLinked(1 + index)) continue;\n',+ linkSpot: ' if (!lightLinked(9 + index)) continue;\n',+ linkArea: ' if (!lightLinked(17 + index)) continue;\n',+});++const LIGHT_LISTS = [['pointLights', POINT_FIRST_BIT], ['spotLights', SPOT_FIRST_BIT], ['areaLights', AREA_FIRST_BIT]];++function affectedNames(affects, label) {+ if (affects === undefined) return null;+ if (!Array.isArray(affects) || affects.some(name => typeof name !== 'string')) {+ throw new TypeError(`${label} affects must be a list of part names`);+ }+ return new Set(affects);+}++/** The light mask of one part, from [bit, names] pairs where names is null for "every part". */+export function lightMaskFor(partName, links) {+ let mask = 0;+ for (const [bit, names] of links) {+ if (names === null || names.has(partName)) mask |= 1 << bit;+ }+ return mask;+}++function collectLinks(environment) {+ const links = [[SUN_BIT, affectedNames(environment.keyAffects, 'environment keyAffects')]];+ for (const [field, firstBit] of LIGHT_LISTS) {+ (environment[field] ?? []).forEach((light, index) => links.push([firstBit + index, affectedNames(light.affects, `${field}[${index}]`)]));+ }+ return links;+}++/**+ * Parts with the light masks that the lights' `affects` lists ask for: a light with `affects: ['name', ...]` lights only+ * those parts, a light without it lights every part. `environment.keyAffects` does the same for the sun. A part that+ * every light reaches is returned unchanged, so a scene without links keeps its batches.+ */+export function applyLightLinks(parts, environment) {+ const links = collectLinks(environment);+ if (links.every(([, names]) => names === null)) return parts;+ return parts.map((part) => {+ const mask = lightMaskFor(part.name, links);+ return mask === ALL_LIGHTS_MASK ? part : { ...part, material: { ...part.material, lightMask: mask } };+ });+}diff --git a/src/material-layers.js b/src/material-layers.jsindex f14a5001..e9b85613 100644--- a/src/material-layers.js+++ b/src/material-layers.js@@ -3,6 +3,9 @@const UNIT = Object.freeze([0, 1]);+// Bit 0 is the sun, bits 1 to 8 the point lights, 9 to 16 the spot lights and 17 to 20 the area lights (light-linking.js).+export const ALL_LIGHTS_MASK = 0x1fffff;+export const MATERIAL_LAYER_DEFAULTS = Object.freeze({clearcoat: 0,clearcoatRoughness: 0,@@ -108,7 +111,7 @@ export function dielectricReflectance(material) {/*** Plain values the renderer batches by: dielectric F0 (3), coat (2), sheen (4), transmission (4), attenuation colour (3),- * anisotropy strength and rotation (2), iridescence factor, film IOR and film thickness in nanometres (3).+ * anisotropy strength and rotation (2), iridescence factor, film IOR and film thickness in nanometres (3), light mask (1).*/export function materialLayerState(material) {validateMaterialLayers(material);@@ -128,7 +131,8 @@ export function materialLayerState(material) {materialLayerValue(material, 'iridescence'),materialLayerValue(material, 'iridescenceIor'),materialLayerValue(material, 'iridescenceThickness'),+ material.lightMask ?? ALL_LIGHTS_MASK,];}-export const MATERIAL_LAYER_STATE_LENGTH = 21;+export const MATERIAL_LAYER_STATE_LENGTH = 22;diff --git a/src/renderer.js b/src/renderer.jsindex e93059ba..5006de7f 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -58,6 +58,7 @@ function shaderFeaturesOfParts(parts) {if (material.layers) features.add('splat');if (material.moss > 0) features.add('moss');if (material.anisotropy > 0) features.add('anisotropy');+ if (material.lightMask !== undefined) features.add('lightLinking');if (material.iridescence > 0) features.add('iridescence');if ((material.alphaMode ?? 'opaque') !== 'opaque') features.add('alphaMode');if (TAG_SHADER_FEATURES.has(material.tag)) features.add(material.tag);@@ -364,7 +365,7 @@ function allFinite(values) {}export class Renderer67 {- constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, culling = true, lodPixelError = 1, createGpuTimer = null } = {}) {+ constructor(canvas, parts, { batching = true, pixelRatio = 1.5, benchmark = false, world = false, ground = true, transparent = false, samples = 4, hdr = false, depth = false, memoryBudgetMiB = 256, environment = {}, shadowBounds = {}, shadowCascades = null, culling = true, lodPixelError = 1, createGpuTimer = null } = {}) {this.canvas = canvas;// `createGpuTimer` from adaptive-quality.js is passed in, which keeps the timer code out of scenes that do not time frames.this.createGpuTimer = createGpuTimer;@@ -389,6 +390,7 @@ export class Renderer67 {this.world = world;this.environment = environment;this.shadowBounds = shadowBounds;+ this.shadowCascades = shadowCascades;this.memoryBudgetMiB = memoryBudgetMiB;this.hdr = Boolean(hdr && !benchmark && this.context.getExtension('EXT_color_buffer_float'));if (volume.density > 0 && !this.hdr) throw new Error('Volume fog requires EXT_color_buffer_float for HDR rendering');@@ -484,6 +486,7 @@ export class Renderer67 {this.inverseViewProjection = mat4.create();this.shaderFeatures = shaderFeaturesOfParts(groups.flat());shaderFeaturesOfLighting(this.lighting).forEach(feature => this.shaderFeatures.add(feature));+ if (shadowCascades) this.shaderFeatures.add(shadowCascades.shaderFeature);const pending = {main: this.startMainProgram(),depth: startProgram(this.context, depthVertexShader, depthFragmentShader),@@ -552,7 +555,7 @@ export class Renderer67 {finishMainProgram(pendingProgram) {this.program = finishProgram(this.context, pendingProgram);- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', 'materialAnisotropy', 'materialIridescence', 'lightLinkMask', 'boxMapScale', 'boxMapAxis', 'lightMap', 'lightMapScale', 'hasLightMap', 'viewProjection', 'lightProjection', 'eye', 'armorColor', 'armorSurface', 'exposure', 'inspection', 'shadowMap', ...MAP_UNIFORMS, ...MAP_FLAGS, ...SKIN_UNIFORMS, ...MORPH_UNIFORMS, 'normalScale', 'occlusionStrength', 'materialMoss', ...SPLAT_UNIFORMS, 'hdrEnabled', 'time', 'wind', 'worldMode', 'daylight', 'fogColor', 'lightDirection', 'fogDensity', 'waterRipple', 'rippleTime', 'explosionProgress', 'explosionCenter', 'assemblyAmount', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));for (const name of LIGHT_UNIFORMS) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);}@@ -1798,6 +1801,7 @@ export class Renderer67 {this.context.uniform4f(this.uniforms.materialSheen, layers[5], layers[6], layers[7], layers[8]);this.context.uniform2f(this.uniforms.materialAnisotropy, layers[16], layers[17]);this.context.uniform3f(this.uniforms.materialIridescence, layers[18], layers[19], layers[20]);+ this.context.uniform1i(this.uniforms.lightLinkMask, layers[21]);this.context.uniform1f(this.uniforms.boxMapScale, batch.mapState[12]);this.context.uniform1i(this.uniforms.boxMapAxis, batch.mapState[13]);this.bindSplat(batch.splat);@@ -1859,6 +1863,7 @@ export class Renderer67 {mat4.invert(this.inverseViewProjection, this.viewProjection);extractFrustumPlanes(this.viewProjection, this.frustumPlanes);this.viewForward = [-this.view[2], -this.view[6], -this.view[10]];+ this.shadowCascades?.update(this, casterChanged);context.bindFramebuffer(context.FRAMEBUFFER, passMode ? this.passSupport.framebuffer : this.benchmark ? null : this.multisampleFramebuffer);context.viewport(0, 0, this.canvas.width, this.canvas.height);if (passMode) {@@ -1877,6 +1882,7 @@ export class Renderer67 {context.uniformMatrix4fv(this.uniforms.viewProjection, false, this.viewProjection);context.uniformMatrix4fv(this.uniforms.lightProjection, false, this.lightProjection);context.uniform3fv(this.uniforms.eye, eye);+ this.shadowCascades?.bindUniforms(this);context.uniform3fv(this.uniforms.armorColor, armorColor);context.uniform2fv(this.uniforms.armorSurface, armorSurface);context.uniform1f(this.uniforms.exposure, exposure);@@ -1971,6 +1977,7 @@ export class Renderer67 {dispose() {this.releaseFrameTargets();+ this.shadowCascades?.dispose(this.context);if (this.localShadowTexture) this.context.deleteTexture(this.localShadowTexture);if (this.localShadowFramebuffer) this.context.deleteFramebuffer(this.localShadowFramebuffer);this.batches.forEach((batch) => {diff --git a/src/shaders.js b/src/shaders.jsindex d9be5fa0..12d13083 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -798,7 +798,7 @@ void main() {vec3 specularNormal = normal;vec3 baseReflectance = mix(materialDielectric, color, metallic);${featureCode("mainSetup")} float visibility = shadowVisibility(normal);- vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility, color, metallic, roughness);+ vec3 radiance = illuminate(normal, viewDirection, normalize(lightDirection), keyColor * visibility${featureCode("linkSun")}, color, metallic, roughness);radiance += illuminate(normal, viewDirection, normalize(vec3(4.0, 2.0, -3.0)), mix(vec3(0.8, 2.0, 1.8), vec3(0.12, 0.17, 0.20) * daylight, worldMode) * fillIntensity, color, metallic, roughness);radiance += illuminate(normal, viewDirection, normalize(vec3(1.0, 2.0, 5.0)), vec3(0.6, 0.7, 0.8) * mix(1.0, 0.25 * daylight, worldMode) * fillIntensity, color, metallic, roughness);for (int index = 0; index < 8; index++) {@@ -808,7 +808,7 @@ ${featureCode("mainSetup")} float visibility = shadowVisibility(normal);if (distanceSquared < 1e-12 || pointLightColors[index].w == 0.0) continue;float attenuation = localAttenuation(distanceSquared, pointLightPositions[index].w, pointLightRadii[index]);if (attenuation == 0.0) continue;- vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;+${featureCode("linkPoint")} vec3 lightRadiance = pointLightColors[index].rgb * pointLightColors[index].w * attenuation;if (USES_LOCAL_SHADOWS && pointLightShadowTiles[index] >= 0.0) {float tile = pointLightShadowTiles[index] + pointShadowFace(-offset);lightRadiance *= localShadowVisibility(tile, worldPosition, normal, sqrt(distanceSquared));@@ -827,7 +827,7 @@ ${featureCode("mainSetup")} float visibility = shadowVisibility(normal);float cone = smoothstep(spotLightDirections[index].w, spotLightParameters[index].y, coneCosine);float attenuation = localAttenuation(distanceSquared, spotLightPositions[index].w, spotLightParameters[index].x) * cone;if (attenuation == 0.0) continue;- vec3 lightRadiance = spotLightColors[index].rgb * spotLightColors[index].w * attenuation;+${featureCode("linkSpot")} vec3 lightRadiance = spotLightColors[index].rgb * spotLightColors[index].w * attenuation;if (USES_LOCAL_SHADOWS && spotLightParameters[index].z >= 0.0) {lightRadiance *= localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));}@@ -837,7 +837,7 @@ ${featureCode("mainSetup")} float visibility = shadowVisibility(normal);if (USES_AREA_LIGHTS) {for (int index = 0; index < 4; index++) {if (index >= areaLightCount) break;- vec3 lightNormal = areaLightNormals[index].xyz;+${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;vec3 widthAxis = areaLightTangents[index].xyz;vec3 heightAxis = cross(lightNormal, widthAxis);vec2 halfSize = vec2(areaLightNormals[index].w, areaLightTangents[index].w) * 0.5;@@ -955,7 +955,9 @@ const SHADER_FEATURE_CONDITIONS = {// A feature that is not in the list above has its GLSL in another module, so a scene that never uses it does not carry// it. That module calls registerShaderFeatureCode on import, with blocks of GLSL that createFragmentShader splices in:-// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline.+// declarations, illuminateReflectance, illuminateSpecular, coatReset and mainSetup, each ending in a newline, and the+// one-line linkSun (a factor on the sun) with linkPoint, linkSpot and linkArea (statements that skip a light for a part).+// A feature that replaces the sun shadow defines shadowVisibility as a macro in its declarations.const registeredFeatureCode = new Map();/** Register the GLSL of an optional feature. Called by the module that holds it, on import. */diff --git a/tests/cascaded-shadows.test.js b/tests/cascaded-shadows.test.jsnew file mode 100644index 00000000..986e100b--- /dev/null+++ b/tests/cascaded-shadows.test.js@@ -0,0 +1,77 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { mat4, vec3 } from 'gl-matrix';+import { createFragmentShader } from '../src/shaders.js';+import { CascadedShadows, cascadeSplitDistances, createCascadedShadows, writeCascadeMatrix } from '../src/cascaded-shadows.js';++const TOWARD_LIGHT = vec3.normalize(vec3.create(), [-0.7, 0.8, 0.35]);+const RESOLUTION = 2048;+const CASTER_REACH = 200;++function projectedPoint(matrix, point) {+ return vec3.transformMat4(vec3.create(), point, matrix);+}++test('split distances grow, end at the far plane and sit between a uniform and a logarithmic split', () => {+ const splits = cascadeSplitDistances(4, 0.1, 100, 0.7);+ assert.equal(splits.length, 4);+ assert.equal(splits[3], 100);+ for (let index = 1; index < splits.length; index++) assert.ok(splits[index] > splits[index - 1]);+ const uniformFirst = 0.1 + (100 - 0.1) / 4;+ assert.ok(splits[0] < uniformFirst, 'the first slice is shorter than a uniform one');+ assert.ok(splits[0] > 0.1);+});++test('one cascade covers the whole range', () => {+ assert.deepEqual(cascadeSplitDistances(1, 0.5, 80), [80]);+});++test('a cascade matrix maps its own sphere inside the depth map', () => {+ const sphere = { center: [3, 1, -20], radius: 12 };+ const matrix = mat4.create();+ const { texel, range } = writeCascadeMatrix(matrix, sphere, TOWARD_LIGHT, RESOLUTION, CASTER_REACH);+ assert.ok(Math.abs(texel - 24 / RESOLUTION) < 1e-12);+ assert.ok(range > CASTER_REACH);+ const centre = projectedPoint(matrix, sphere.center);+ assert.ok(Math.abs(centre[0]) < 2 / RESOLUTION * 1.01 && Math.abs(centre[1]) < 2 / RESOLUTION * 1.01, 'the centre stays within a texel of the middle');+ const towardCamera = projectedPoint(matrix, vec3.scaleAndAdd(vec3.create(), sphere.center, TOWARD_LIGHT, 150));+ assert.ok(towardCamera[2] > -1 && towardCamera[2] < 1, 'a caster far toward the light is inside the depth range');+});++test('moving the slice by less than a texel leaves the matrix unchanged, so edges do not crawl', () => {+ const first = mat4.create();+ const second = mat4.create();+ const sphere = { center: [3, 1, -20], radius: 12 };+ writeCascadeMatrix(first, sphere, TOWARD_LIGHT, RESOLUTION, CASTER_REACH);+ const texel = 24 / RESOLUTION;+ const nudged = { center: [3 + texel * 0.01, 1, -20], radius: 12 };+ writeCascadeMatrix(second, nudged, TOWARD_LIGHT, RESOLUTION, CASTER_REACH);+ assert.deepEqual([...second], [...first]);+ const far = { center: [3 + texel * 5, 1, -20], radius: 12 };+ writeCascadeMatrix(second, far, TOWARD_LIGHT, RESOLUTION, CASTER_REACH);+ assert.notDeepEqual([...second], [...first]);+});++test('a vertical light still gets a valid view', () => {+ const matrix = mat4.create();+ writeCascadeMatrix(matrix, { center: [0, 0, 0], radius: 5 }, [0, 1, 0], RESOLUTION, CASTER_REACH);+ assert.ok([...matrix].every(Number.isFinite));+});++test('options are checked', () => {+ assert.throws(() => createCascadedShadows({ count: 0 }), /cascade count/);+ assert.throws(() => createCascadedShadows({ count: 5 }), /cascade count/);+ assert.throws(() => createCascadedShadows({ count: 2.5 }), /cascade count/);+ assert.throws(() => createCascadedShadows({ resolution: 100 }), /cascade resolution/);+ assert.throws(() => createCascadedShadows({ maximumDistance: -1 }), /maximumDistance/);+ assert.throws(() => createCascadedShadows({ splitLambda: 2 }), /splitLambda/);+ assert.ok(createCascadedShadows({ count: 4 }) instanceof CascadedShadows);+});++test('the cascade shader replaces the classic sun map and a plain shader has no trace of it', () => {+ const cascaded = createFragmentShader(['cascadedShadows']);+ assert.match(cascaded, /#define shadowVisibility\(normal\) cascadeVisibility\(normal\)/);+ const plain = createFragmentShader([]);+ assert.doesNotMatch(plain, /cascadeVisibility|cascadeShadowMap/);+ assert.doesNotMatch(plain, /#define shadowVisibility/);+});diff --git a/tests/light-linking.test.js b/tests/light-linking.test.jsnew file mode 100644index 00000000..8aa8648a--- /dev/null+++ b/tests/light-linking.test.js@@ -0,0 +1,63 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { createFragmentShader } from '../src/shaders.js';+import { ALL_LIGHTS_MASK, materialLayerState } from '../src/material-layers.js';+import { applyLightLinks, lightMaskFor, AREA_FIRST_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, SUN_BIT } from '../src/light-linking.js';++function part(name) {+ return { name, geometry: {}, matrix: new Float32Array(16), material: { tag: 'surface', color: [1, 1, 1], metallic: 0, roughness: 0.5 } };+}++const PARTS = ['left', 'right', 'floor'].map(part);++test('a scene whose lights all reach every part keeps its parts', () => {+ const environment = { pointLights: [{ position: [0, 1, 0] }], spotLights: [], areaLights: [] };+ assert.equal(applyLightLinks(PARTS, environment), PARTS);+});++test('an affects list limits a light to the named parts and leaves the others at full mask', () => {+ const environment = {+ pointLights: [{ affects: ['left'] }, { affects: ['right', 'floor'] }],+ spotLights: [{ affects: ['floor'] }],+ areaLights: [{}],+ };+ const [left, right, floor] = applyLightLinks(PARTS, environment);+ const point = index => 1 << (POINT_FIRST_BIT + index);+ const spot = 1 << SPOT_FIRST_BIT;+ const area = 1 << AREA_FIRST_BIT;+ const sun = 1 << SUN_BIT;+ assert.equal(left.material.lightMask, sun | point(0) | area);+ assert.equal(right.material.lightMask, sun | point(1) | area);+ assert.equal(floor.material.lightMask, sun | point(1) | spot | area);+ assert.equal(PARTS[0].material.lightMask, undefined, 'the input parts are not changed');+});++test('keyAffects limits the sun', () => {+ const [left, right] = applyLightLinks(PARTS, { pointLights: [], keyAffects: ['left'] });+ assert.equal(left.material.lightMask & 1, 1);+ assert.equal(right.material.lightMask & 1, 0);+});++test('a bad affects value is named in the error', () => {+ assert.throws(() => applyLightLinks(PARTS, { pointLights: [{ affects: 'left' }] }), /pointLights\[0\] affects/);+ assert.throws(() => applyLightLinks(PARTS, { pointLights: [{ affects: [3] }] }), /affects/);+});++test('lightMaskFor treats a null list as every part', () => {+ assert.equal(lightMaskFor('anything', [[0, null], [3, new Set(['other'])]]), 1);+});++test('the layer state carries the mask and defaults to every light', () => {+ assert.equal(materialLayerState({}).at(-1), ALL_LIGHTS_MASK);+ assert.equal(materialLayerState({ lightMask: 5 }).at(-1), 5);+ assert.equal(ALL_LIGHTS_MASK, (1 << (AREA_FIRST_BIT + 4)) - 1);+});++test('the mask test compiles in only with the feature', () => {+ const linked = createFragmentShader(['lightLinking']);+ for (const statement of ['lightLinked(1 + index)', 'lightLinked(9 + index)', 'lightLinked(17 + index)', 'float(lightLinked(0))']) {+ assert.ok(linked.includes(statement), statement);+ }+ const plain = createFragmentShader([]);+ assert.doesNotMatch(plain, /lightLink/);+});diff --git a/tests/material-layers.test.js b/tests/material-layers.test.jsindex 36f99bc6..9714d938 100644--- a/tests/material-layers.test.js+++ b/tests/material-layers.test.js@@ -98,9 +98,9 @@ test('a plain export declares no layer extension and an invalid layer is rejectetest('anisotropy and iridescence reach the renderer state and default to off', () => {const plain = materialLayerState({});assert.equal(plain.length, MATERIAL_LAYER_STATE_LENGTH);- assert.deepEqual(plain.slice(16), [0, 0, 0, 1.3, 400], 'anisotropy, rotation, iridescence, film IOR and thickness');+ assert.deepEqual(plain.slice(16, 21), [0, 0, 0, 1.3, 400], 'anisotropy, rotation, iridescence, film IOR and thickness');const brushed = materialLayerState({ anisotropy: 0.7, anisotropyRotation: 1, iridescence: 0.9, iridescenceIor: 1.8, iridescenceThickness: 250 });- assert.deepEqual(brushed.slice(16), [0.7, 1, 0.9, 1.8, 250]);+ assert.deepEqual(brushed.slice(16, 21), [0.7, 1, 0.9, 1.8, 250]);});test('recipes accept anisotropy and iridescence and export them', () => {diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.jsindex f4787f4c..ca81f496 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-graph', 'brick-room', 'brushed-film', 'car-paint', 'character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri', 'spot-area'];+const EXPECTED_SCENES = ['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_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/vite.lib.config.js b/vite.lib.config.jsindex 8ca43649..db95f9b2 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -44,6 +44,8 @@ export default defineConfig({'camera-effects': 'src/camera-effects.js','render-passes': 'src/render-passes.js','material-layer-shaders': 'src/material-layer-shaders.js',+ 'light-linking': 'src/light-linking.js',+ 'cascaded-shadows': 'src/cascaded-shadows.js',// Page of the MCP preview. It imports the engine chunks above instead of bundling its own copy.'mcp/preview': 'scripts/agent-preview-browser.js',},