3D engine that AI agents drive
Add soft area light shadows, a soft sun angle and IES profiles (issue #612)
Nguyen Xuan An6c3620efcebe
diff --git a/bench/lighting/soft-lights.html b/bench/lighting/soft-lights.htmlnew file mode 100644index 00000000..f3ccfb29--- /dev/null+++ b/bench/lighting/soft-lights.html@@ -0,0 +1,10 @@+<!doctype html>+<html>+<head>+<style>html,body{margin:0;height:100%;background:#000}canvas{width:100vw;height:100vh;display:block}</style>+</head>+<body>+<canvas></canvas>+<script type="module" src="./soft-lights.js"></script>+</body>+</html>diff --git a/bench/lighting/soft-lights.js b/bench/lighting/soft-lights.jsnew file mode 100644index 00000000..c255bf23--- /dev/null+++ b/bench/lighting/soft-lights.js@@ -0,0 +1,68 @@+// Runs in the page: a pillar and a floating cube over a floor, drawn with each soft-light feature off and on.+import { Renderer67 } from '/src/renderer.js';+import { box } from '/src/geometry.js';++// The light-shapes and cascade modules are optional: this harness loads them only when the source tree has them,+// so the same page also draws the default picture of an older tree.+const lightShapesPath = '/src/light-shapes.js';+const lightShapes = await import(/* @vite-ignore */ lightShapesPath).catch(() => null);+const cascades = await import('/src/cascaded-shadows.js');++function placed(center, size) {+ return new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);+}++function sceneParts() {+ const material = { color: [0.75, 0.75, 0.78], metallic: 0, roughness: 0.7 };+ return [+ { geometry: box(), matrix: placed([0, -0.05, 0], [8, 0.1, 8]), material },+ { geometry: box(), matrix: placed([0, 0.6, 0], [0.4, 1.2, 0.4]), material },+ { geometry: box(), matrix: placed([-1.1, 0.9, 0.2], [0.35, 0.35, 0.35]), material },+ { geometry: box(), matrix: placed([1.1, 0.12, 0.4], [0.5, 0.24, 0.5]), material },+ ];+}++const baseEnvironment = { keyIntensity: 0, fillIntensity: 0, ambientIntensity: 0.15 };+const CASES = {+ 'sun-hard': { environment: { lightDirection: [-3, 6, 4], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 0.15 }, cascadeCount: 0 },+ 'sun-soft': { environment: { lightDirection: [-3, 6, 4], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 0.15, sunAngularRadius: 0.05 }, cascadeCount: 1 },+ 'area-lit': { environment: { ...baseEnvironment, areaLights: [{ position: [-0.6, 2.6, 0.4], direction: [0.15, -1, -0.05], width: 0.7, height: 0.7, intensity: 30 }] } },+ 'area-shadow': { environment: { ...baseEnvironment, areaLights: [{ position: [-0.6, 2.6, 0.4], direction: [0.15, -1, -0.05], width: 0.7, height: 0.7, intensity: 30, castShadow: true }] }, needsShapes: true },+ 'spot-plain': { environment: { ...baseEnvironment, spotLights: [{ position: [0, 3, 2.5], direction: [0, -1, -0.6], angle: 1.2, penumbra: 0.1, intensity: 60 }] } },+ 'spot-ies': { environment: { ...baseEnvironment, spotLights: [{ position: [0, 3, 2.5], direction: [0, -1, -0.6], angle: 1.2, penumbra: 0.1, intensity: 60, ies: 'narrow-spot' }] }, needsShapes: true },+};++const camera = { eye: [3.4, 2.6, 4.2], target: [0, 0.4, 0], fov: 45 };++async function drawCase(name, { warmupFrames = 10, measuredFrames = 60 } = {}) {+ const definition = CASES[name];+ const canvas = document.querySelector('canvas');+ const options = { ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, environment: definition.environment };+ if (definition.cascadeCount > 0) options.shadowCascades = cascades.createCascadedShadows({ count: definition.cascadeCount });+ const renderer = new Renderer67(canvas, sceneParts(), options);+ renderer.resize();+ const frame = { ...camera, environment: definition.environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0 } };+ 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);+ finishDrawing();+ }+ const frameMilliseconds = [];+ for (let index = 0; index < measuredFrames; index++) {+ const started = performance.now();+ renderer.render(frame);+ finishDrawing();+ frameMilliseconds.push(performance.now() - started);+ }+ renderer.render(frame);+ const glError = renderer.context.getError();+ const image = canvas.toDataURL('image/png').split(',')[1];+ renderer.dispose();+ frameMilliseconds.sort((first, second) => first - second);+ return { name, glError, image, medianMilliseconds: frameMilliseconds[Math.floor(measuredFrames / 2)] };+}++window.hasLightShapes = Boolean(lightShapes);+window.caseNames = Object.keys(CASES);+window.drawCase = drawCase;diff --git a/bench/lighting/soft-lights.mjs b/bench/lighting/soft-lights.mjsnew file mode 100644index 00000000..ef30121b--- /dev/null+++ b/bench/lighting/soft-lights.mjs@@ -0,0 +1,53 @@+// Draws the soft sun, soft area light shadow and IES cases and writes a still and a frame time for each.+// node bench/lighting/soft-lights.mjs [--root=<source tree>] [--out=<folder>] [--rounds=N] [--size=WIDTHxHEIGHT]+// --root draws another checkout's src (for example `git archive origin/main` unpacked in a temporary folder),+// which is how the default pictures are compared byte for byte with main; its cases that need the new code are skipped.+import { constants, setPriority } from 'node:os';+import { createHash } from 'node:crypto';+import { mkdir, writeFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import { chromium } from 'playwright';+import { createServer } from 'vite';++const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const PAGE_LOAD_TIMEOUT = 60000;+const argumentValue = (name, fallback) => process.argv.find(argument => argument.startsWith(`--${name}=`))?.split('=')[1] ?? fallback;+const root = resolve(argumentValue('root', '.'));+const outputFolder = resolve(argumentValue('out', 'artifacts/soft-lights'));+const rounds = Number(argumentValue('rounds', 3));+const [width, height] = argumentValue('size', '480x270').split('x').map(Number);++setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);+const server = await createServer({ root, server: { host: '127.0.0.1', port: 0, fs: { strict: false } }, logLevel: 'silent' });+await server.listen();+const serverUrl = `http://127.0.0.1:${server.httpServer.address().port}`;+const browser = await chromium.launch({ executablePath: CHROME, headless: true, args: ['--enable-webgl', '--ignore-gpu-blocklist', '--use-angle=d3d11', '--enable-gpu', '--disable-renderer-backgrounding'] });+try {+ const page = await browser.newPage({ viewport: { width, height } });+ await page.goto(`${serverUrl}/bench/lighting/soft-lights.html`, { timeout: PAGE_LOAD_TIMEOUT });+ await page.waitForFunction(() => window.drawCase, null, { timeout: PAGE_LOAD_TIMEOUT });+ const hasLightShapes = await page.evaluate(() => window.hasLightShapes);+ const names = (await page.evaluate(() => window.caseNames)).filter(name => hasLightShapes || !/area-shadow|spot-ies|sun-soft/.test(name));+ await mkdir(outputFolder, { recursive: true });+ const medians = new Map(names.map(name => [name, []]));+ const hashes = {};+ for (let round = 0; round < rounds; round++) {+ for (const name of round % 2 === 0 ? names : [...names].reverse()) {+ const result = await page.evaluate(caseName => window.drawCase(caseName), name);+ if (result.glError !== 0) throw new Error(`${name}: GL error ${result.glError}`);+ medians.get(name).push(result.medianMilliseconds);+ const png = Buffer.from(result.image, 'base64');+ hashes[name] = createHash('sha256').update(png).digest('hex').slice(0, 16);+ await writeFile(resolve(outputFolder, `${name}.png`), png);+ }+ }+ const summary = {};+ for (const [name, values] of medians) {+ const sorted = [...values].sort((first, second) => first - second);+ summary[name] = { medianMilliseconds: Number(sorted[Math.floor(sorted.length / 2)].toFixed(3)), rangeMilliseconds: [sorted[0], sorted.at(-1)].map(value => Number(value.toFixed(3))), hash: hashes[name] };+ }+ console.log(JSON.stringify({ size: [width, height], rounds, summary }, null, 1));+} finally {+ await browser.close();+ await server.close();+}diff --git a/changes/612-lights.md b/changes/612-lights.mdnew file mode 100644index 00000000..cb5c6057--- /dev/null+++ b/changes/612-lights.md@@ -0,0 +1,3 @@+- Area lights can cast soft shadows: `castShadow: true` on an `areaLights` entry takes one tile of the local shadow atlas, and the penumbra widens with the rectangle and with the gap between blocker and receiver. Cost is 16 blocker taps and 32 filter taps per lit pixel, only for a shadowed area light.+- `environment.sunAngularRadius` (radians, 0.0005 to 0.2) softens the sun shadow in the raster through the cascades (at least one slice is used) and sets the sun disk of the path tracer, which was fixed at 0.0087. Without the field nothing changes.+- IES profiles: `ies` on spot and area lights takes a bundled name (`wide-flood`, `downlight`, `narrow-spot`, `batwing`) or `{ angles, candela }`; `parseIesPhotometry` reads an LM-63 file into that shape. The raster and the CPU path tracer read the same 16 samples. The GPU path tracer and the light bake ignore profiles.diff --git a/changes/612-lights.size.md b/changes/612-lights.size.mdnew file mode 100644index 00000000..cca3e985--- /dev/null+++ b/changes/612-lights.size.md@@ -0,0 +1,13 @@+- entry:core: area light shadow tiles, the profile counter and two shader slots; the shader code, the profile math and the file reader are in the lazy light-shapes module.+- entry:core+lazy: same core change.+- entry:path-tracer: the sun disk radius and the 16-sample IES profile math (light-profile.js) so the tracer matches the raster.+- entry:cascaded-shadows: the soft sun (blocker search plus a 16 tap filter) lives in the lazy cascade module and runs only when sunAngularRadius is set.+- scene:lit-box: the same core change, 191 bytes for the area shadow tile and profile hooks.+- scene:lit-box+lazy: same.+- scene:gltf-box: same core change.+- scene:gltf-box+lazy: same.+- scene:agent-scene: recipe validation for sunAngularRadius, area castShadow and ies, the lazy module marker and a capabilities line (359 bytes gzip); the rest is lazy.+- scene:agent-scene+lazy: the new lazy modules light-shapes and light-profile (about 3 KB) plus the cascade and tracer additions, loaded only for a recipe that names them.+- goal:lit-box: area shadow tiles and profile hooks in the core renderer (191 bytes); the code that uses them is lazy.+- goal:gltf-box: same core change (196 bytes).+- goal:agent-scene: recipe fields and a marker (359 bytes); the code is lazy.diff --git a/docs/lighting.md b/docs/lighting.mdindex 70cb2c14..8104710c 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -89,7 +89,7 @@ A point light casts a shadow only with `castShadow: true` (see [Local shadows](#`environment.areaLights` holds at most seven rectangles. Each has `position` (the center), `direction` (the side it emits to), `width` and `height` in scene units, and optional `up`, `color` and `intensity`. The width axis is `up x direction`, so a downward panel with `up: [0, 0, 1]` has its width along X. `intensity` is the candela of the whole rectangle seen head on, and the light has Lambert emission, so it fades with the cosine to the side.-Method: representative point, not a light-transform lookup table. The closest point of the rectangle to the shaded point stands in for the source, and the light is `intensity * cos(emission) / (d^2 + area / pi)`. The `area / pi` term keeps it finite at the surface and equals a disc source on its axis. Measured against Cycles on a white plane, a Blender area light of W watts matches `W / pi` candela, and this formula is within 1.2 percent on the axis for 1 m and 2 m squares from 0.2 m to 2 m away (measured). Off-axis error and the shape of a specular highlight are not measured: the highlight is a point highlight from the representative point, so a large panel does not give a stretched reflection. Area lights cast no shadow and a rectangle seen from behind gives no light.+Method: representative point, not a light-transform lookup table. The closest point of the rectangle to the shaded point stands in for the source, and the light is `intensity * cos(emission) / (d^2 + area / pi)`. The `area / pi` term keeps it finite at the surface and equals a disc source on its axis. Measured against Cycles on a white plane, a Blender area light of W watts matches `W / pi` candela, and this formula is within 1.2 percent on the axis for 1 m and 2 m squares from 0.2 m to 2 m away (measured). Off-axis error and the shape of a specular highlight are not measured: the highlight is a point highlight from the representative point, so a large panel does not give a stretched reflection. A rectangle seen from behind gives no light. An area light casts a shadow only with `castShadow: true` (see [Soft area shadows, soft sun and IES profiles](#soft-area-shadows-soft-sun-and-ies-profiles)).## Light counts and frame cost@@ -182,6 +182,16 @@ The other 19 reference scenes drew the same pixels (mean, p20 and FLIP identicalShadows 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.+## Soft area shadows, soft sun and IES profiles++Three opt-in looks share one lazy module (`67js/addons/light-shapes`, loaded by `loadAgentSceneModules` for a recipe that names them). A scene that uses none of them draws the same pixels as before (checked by hashing the default stills against main).++- **Area light shadows.** `castShadow: true` on an `areaLights` entry takes one tile of the local shadow atlas, drawn from the centre of the rectangle with a 170 degree view along its emitting side, after the point and spot tiles. The shader searches 16 taps for blockers, derives the penumbra as `half size * (receiver - blocker) / blocker` (the usual percentage closer soft shadow estimate, from the larger half side of the rectangle) and filters with 32 taps over that radius, clamped to 1 to 24 texels. Per-pixel rotation of the taps makes a little grain in a wide penumbra. The shadow comes from the centre, so a wide panel close to a wall can still leak a hard edge at the rectangle's border.+- **Soft sun.** `environment.sunAngularRadius` is the radius of the sun disk in radians (0.0005 to 0.2; half a degree is 0.0087, which is what the path tracer always used and still uses when the field is absent). The path tracer and the GPU tracer sample that disk. The raster softens the sun shadow through the cascades: naming the field gives at least one slice (`shadowCascades: 0` keeps the single hard map), and the cascade shader searches 12 taps for blockers, sets the penumbra to `tan(radius) * gap` and filters with 16 taps. The shadow stays sharp at contact and widens with the distance between blocker and receiver.+- **IES profiles.** `ies` on a spot or area light is a bundled name (`wide-flood`, `downlight`, `narrow-spot`, `batwing`, made for 67js as cosine powers) or `{ angles, candela }` (degrees from the axis, 2 to 32 rising points). It is stored as 16 values from 0 to 90 degrees divided by the axis value, so `intensity` stays the candela head on; a spot light multiplies its cone by it and an area light multiplies its Lambert emission by it. `parseIesPhotometry(text)` (`67js/addons/light-shapes`) turns an LM-63 file with `TILT=NONE` into that shape, averaging the horizontal planes. The raster and the CPU path tracer read the same samples; the GPU path tracer and the light bake ignore profiles. Point lights and bundled catalog file IDs for `.ies` files are not supported yet.++Frame time on an RTX 3060 at 480x270 with 4 samples (`node bench/lighting/soft-lights.mjs`, median of 3 runs of 60 frames, shared machine, read the spread as load): hard sun 0.94 ms (range 0.73 to 0.99), soft sun 0.92 (0.79 to 0.99); unshadowed area light 0.88 (0.71 to 0.93), shadowed 0.97 (0.82 to 1.08); spot 0.79 (0.63 to 1.17), spot with an IES profile 0.71 (0.60 to 0.96). The scene is tiny and the machine was loaded, so the differences are inside the spread: the soft paths cost under a tenth of a millisecond here, and cost more as more of the frame is penumbra. Render tests: \`tests/light-shapes.test.js\` (state, shaders inputs, tracer agreement) and the stills the bench writes.+## Cascaded sun shadowsThe 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.diff --git a/docs/parity.md b/docs/parity.mdindex 9f677156..681be092 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -190,7 +190,7 @@ 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); since issue #284 it traces emissive maps and homogeneous volume fog, and at 64 samples `fog` scores 0.0312 against the rasterizer's 0.2021 and the new `emissive-sign` scene 0.0800 against 0.2372; 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 translucent leaves without a `subsurface` block, occlusion maps, anisotropy, iridescence or sheen (the job result names them in `metrics.pathTracer.ignored`), and it is not Cycles parity. The darker floor was the diffuse layer losing light at grazing angles, fixed in issue #215, which also added light linking: at 64 samples against Cycles `outdoor-hdri` is 0.0226, `character` 0.0287 and `light-linking` 0.0213, and the current scores of every scene are in `bench/reference/path-tracer.json`. `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 and standard presets, with fine the same as standard, shrunk deterministically to a path step budget of 5 million, then by bounces, so a preset bakes even a large hall; 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, 16 point lights, 8 spot lights and 7 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 and `environment.shadowCascades` in recipes, three by themselves when `shadow.extent` is above 40): 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 Objects | partial | One directional light with a shadow, 16 point lights, 8 spot lights and 7 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 a soft shadow with `castShadow: true`. The directional shadow is a single map, or up to four cascades through `addons/cascaded-shadows` (`shadowCascades` on the renderer and `environment.shadowCascades` in recipes, three by themselves when `shadow.extent` is above 40): 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 (issue #215) and the light bake honour it, and recipes reach it through `affects` and `environment.keyAffects` (`lightLinking` in `scene_capabilities`). 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. The MCP preview adds an automatic floor with a contact shadow (`environment.ground: false` removes it). Cold-run reference-free score for sitting on a surface, summed over six tasks and 0 to 3 each: 0 before, 6 with the floor and 7 after a lone flat object (a gear) stopped being read as a floor; the front and side cameras see it edge-on, so only the three-quarter view shows it. A blind pairwise Sonnet judge (`default-judge.mjs`, six cold recipes, two cameras, 18 calls) prefers the floor to none 18 of 18 (p 0.0000076) and the darker floor now used (0.22) to the first one (0.6) 18 of 18; its control, one image against itself, picks the first 17 of 18. | [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. Subsurface scattering (the `subsurface` block: weight, radius, scale, color; sun light only in the rasterizer, compiled in only when a part uses it) approximates skin, wax and leaves; the CPU path tracer traces it as a bounded Random Walk (at most 32 scattering events, thin cards as translucency), and so does the GPU tracer. In the `subsurface` reference scene, scored against the Cycles render with subsurface on, the path tracer gets 0.0795 with weight 1 and 0.0875 with weight 0 (64 samples, 28.8 s against 20.7 s; the GPU tracer 0.0795 and 0.0876), the rasterizer 0.1180 and 0.1229. There is no volume material or displacement. | [texture-set](../tests/texture-set.test.js), [material-layers](../tests/material-layers.test.js) | #50, #51 |diff --git a/package.json b/package.jsonindex 40808847..5fbba929 100644--- a/package.json+++ b/package.json@@ -110,6 +110,7 @@"./addons/fog-shader": "./build/fog-shader.js","./addons/light-linking": "./build/light-linking.js","./addons/cascaded-shadows": "./build/cascaded-shadows.js",+ "./addons/light-shapes": "./build/light-shapes.js","./addons/compact-color": "./build/compact-color.js","./addons/gaussian-splats": "./build/gaussian-splats.js","./addons/replace-textured-parts": "./build/replace-textured-parts.js",diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex bbf5aedc..33d7df61 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -13,6 +13,7 @@ import { MATERIAL_PATTERN_TYPES, MATERIAL_MAPPINGS, LIGHTING_SETUP_NAMES, RENDERimport { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';import { SUBSURFACE_RANGES } from '../src/subsurface-limits.js';import { MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from '../src/light-limits.js';+import { IES_PROFILE_NAMES } from '../src/light-profile.js';const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);const positive = finite.positive();@@ -194,6 +195,10 @@ const volumeFog = z.strictObject({keyScattering: bounded(0, 10).optional(),});const affects = z.array(z.string()).optional();+const iesProfile = z.union([+ z.enum(IES_PROFILE_NAMES),+ z.strictObject({ angles: z.array(z.number().min(0).max(180)).min(2).max(32), candela: z.array(z.number().min(0).max(1e7)).min(2).max(32) }),+]).optional().describe('Intensity against the angle from the axis: a bundled name or { angles (degrees, rising), candela }; 1 on the axis, so intensity stays the head-on candela.');const lines = z.record(z.string(), z.unknown()).describe('Outlines, toon light and polylines as plain JSON; fields and limits in scene_capabilities lineArt. null clears.');const environment = z.strictObject({world: z.boolean().optional().describe('Draw the sky and apply surface fog.'),@@ -210,6 +215,7 @@ const environment = z.strictObject({daylight: bounded(0, 100).optional(),keyAffects: affects.describe('Node IDs lit; default all.'),shadowCascades: z.number().int().min(0).max(4).optional().describe('Sun shadow slices; 0 one map.'),+ sunAngularRadius: bounded(0.0005, 0.2).optional().describe('Sun disk radius, radians; softens the sun shadow (0.0087 is half a degree, the path tracer default).'),pointLights: z.array(z.strictObject({position: boundedVector(-1e6, 1e6),color: color.optional(),@@ -229,6 +235,7 @@ const environment = z.strictObject({radius: bounded(0.001, 1e6).optional(),range: z.union([z.literal(0), bounded(0.001, 1e6)]).optional(),castShadow: z.boolean().optional().describe('Casts a shadow; 1 atlas tile.'),+ ies: iesProfile,affects,})).max(MAX_SPOT_LIGHTS).optional().describe('Replaces the list; [] clears.'),areaLights: z.array(z.strictObject({@@ -239,8 +246,10 @@ const environment = z.strictObject({height: bounded(0.001, 1e4),color: color.optional(),intensity: bounded(0, 1e5).optional().describe('Candela head on.'),+ castShadow: z.boolean().optional().describe('Casts a soft shadow, wider with the rectangle; 1 atlas tile.'),+ ies: iesProfile,affects,- })).max(MAX_AREA_LIGHTS).optional().describe('Replaces the list; [] clears. No shadow.'),+ })).max(MAX_AREA_LIGHTS).optional().describe('Replaces the list; [] clears.'),skyTop: color.optional(),skyBottom: color.optional(),fogColor: color.optional(),diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.mdindex 6e8cc38b..0ab7dc5b 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -68,7 +68,7 @@ The sky colors are display RGB. Fog colors are linear RGB.Local `environment.pointLights` support 16 world-space sources with inverse-square falloff.Each 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.+`environment.areaLights` (four) are rectangles with `position`, `direction` (the side that emits), `width`, `height`, optional `up`, `color` and `intensity` (candela seen head on). With `castShadow: true` (1 of the 24 tiles) they cast a soft shadow. `environment.sunAngularRadius` (radians) softens the sun shadow; `ies` on a spot or area light takes `downlight`, `wide-flood`, `narrow-spot`, `batwing` or `{ angles, candela }`.`environment.viewTransform` (`aces` default, `agx` for lit scenes and Blender comparisons, `neutral` for product and brand colour) and `environment.look` (`warm`, `cool`, `contrast`, `faded`) set the display curve and a grade; `scene_capabilities.viewTransform` says when to pick each, and a recipe using them needs `loadAgentSceneModules`.`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. `affects: ['node-id', ...]` on a point, spot or area light, and `environment.keyAffects` for the sun, limit a light to those nodes (a light without it lights every node; an unknown ID is rejected; the bake honours it, the path tracer ignores it and says so). `environment.shadowCascades` (1 to 4, 0 for one map) sharpens a long sun shadow near the camera; it turns on by itself at 3 when `shadow.extent` is above 40, so set it only to choose another count or 0. Details: docs/lighting.md.diff --git a/src/agent-look.js b/src/agent-look.jsindex 85d0b01e..e416ceaf 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -14,13 +14,13 @@ const MAX_LOOK_ARRAY_ENTRIES = Math.max(MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_Aconst ENVIRONMENT_FIELDS = ['world', 'ground', 'setup', 'hdri', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',- 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'wind',+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'wind',];const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow', 'affects'];-const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow', 'affects'];-const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity', 'affects'];+const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow', 'ies', 'affects'];+const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity', 'castShadow', 'ies', 'affects'];const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance', 'shadowAmbient', 'heightFalloff', 'detailOctaves', 'detailAmount', 'warp', 'contrast', 'profileSoftness', 'keyScattering', 'scatterOctaves', 'multiScatter', 'multiExtinction', 'multiAnisotropy', 'keyTransmittance', 'surfaceTransmittance'];const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];@@ -173,6 +173,11 @@ function shadowFieldFrom(light, label) {return castShadow ? { castShadow } : {};}+// An IES profile (a bundled name or { angles, candela }) is checked by the light shapes module, which loads on demand.+function profileFieldFrom(light, label) {+ return light.ies === undefined ? {} : { ies: copiedJson(agentSceneModule('lightShapes').resolveIesProfile(light.ies, `${label} ies`)) };+}+function pointLightFrom(light) {knownKeys(light, POINT_LIGHT_FIELDS, 'point light');return {@@ -198,6 +203,7 @@ function spotLightFrom(light) {radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'spot light radius'),range: rangeFrom(light, 'spot light'),...shadowFieldFrom(light, 'spot light'),+ ...profileFieldFrom(light, 'spot light'),...affectsFrom(light, 'spot light'),};}@@ -213,7 +219,7 @@ function areaLightFrom(light) {intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'area light intensity'),};if (light.up !== undefined) resolved.up = directionFrom(light.up, 'area light up').direction;- return { ...resolved, ...affectsFrom(light, 'area light') };+ return { ...resolved, ...shadowFieldFrom(light, 'area light'), ...profileFieldFrom(light, 'area light'), ...affectsFrom(light, 'area light') };}function volumeFogFrom(input = {}) {@@ -291,6 +297,10 @@ function environmentFrom(input = {}) {if (input.specularAntiAliasing !== undefined) {environment.specularAntiAliasing = numberInRange(input.specularAntiAliasing, 0, MAXIMUM_SPECULAR_ANTI_ALIASING, 'specularAntiAliasing');}+ // Angular radius of the sun disk in radians (0.0087 is half a degree, the path tracer's default). Raster shadows soften with it through the cascades; the path tracer samples the same disk.+ if (input.sunAngularRadius !== undefined) {+ environment.sunAngularRadius = numberInRange(input.sunAngularRadius, 0.0005, 0.2, 'sunAngularRadius');+ }// Outlines and line geometry; null clears them. The module checks the fields and loads on demand.if (input.lines !== undefined && input.lines !== null) {environment.lines = copiedJson(agentSceneModule('lineArt').resolveLineArt(input.lines));diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 448faede..3a5d3677 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -220,9 +220,10 @@ 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. Recipes reach light linking and cascaded sun shadows through lightLinking and shadowCascades below.+ // point light uses 6 tiles and a shadowed spot light 1. A shadowed area light uses 1 and its shadow softens with the rectangle. Recipes reach light linking and cascaded sun shadows through lightLinking and shadowCascades below.maxSpotLights: MAX_SPOT_LIGHTS, maxAreaLights: MAX_AREA_LIGHTS,- localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),+ localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights', 'areaLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, areaLightTiles: 1, tileSize: 512 }),+ lightShapes: Object.freeze({ ies: Object.freeze(['wide-flood', 'downlight', 'narrow-spot', 'batwing']), sunAngularRadius: 'radians 0.0005 to 0.2, soft sun shadow' }),lightLinking: Object.freeze({ fields: Object.freeze(['environment.keyAffects', 'pointLights[].affects', 'spotLights[].affects', 'areaLights[].affects']), unlisted: 'a light without affects lights every node', unknownNode: 'rejected', bake: 'honoured', pathTracer: 'ignored, named in report.ignored' }),shadowCascades: Object.freeze({ field: 'environment.shadowCascades', counts: Object.freeze([0, 1, 2, 3, 4]), zero: 'one shadow map', automatic: 'three cascades when shadow.extent is above 40 and the field is unset', maximumDistance: 150, note: 'volume fog and water read the single map' }),lineArt: Object.freeze({ field: 'environment.lines', fields: 'width px 0.25-16 (1.5), color, boundaries, creaseAngle deg (35), depthJump (0.08), toon steps 0-8, polylines [{points [x,y,z] 2-256, color, width, depthTest, closed}] max 64; {} turns on, null clears; material toon 0-8', note: 'docs/line-art.md' }),diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex d72495ee..ad8f2d9b 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -26,6 +26,7 @@ const MODULE_LOADERS = {navigation: () => import('./agent-navigation.js'),lightLinking: () => import('./light-linking.js'),cascades: () => import('./cascaded-shadows.js'),+ lightShapes: () => import('./light-shapes.js'),assets: () => import('./agent-scene-assets.js'),vegetation: () => import('./agent-vegetation.js'),crowd: () => import('./agent-crowd.js'),@@ -68,7 +69,9 @@ const MODULE_MARKERS = {// No recipe text asks for it, only the path option of scene_inspect does, so a host loads it with loadAllAgentSceneModules.navigation: [],lightLinking: ['"affects"', '"keyAffects"'],- cascades: ['"shadowCascades"'],+ cascades: ['"shadowCascades"', '"sunAngularRadius"'],+ // Soft area light shadows and IES profiles; the module checks the fields. An area light loads it because the text does not say whether it casts a shadow.+ lightShapes: ['"areaLights":[{', '"ies"'],assets: ['"asset":{', '"sequence":{'],vegetation: ['"vegetation":{', '"wind":{'],crowd: ['"crowd":{'],diff --git a/src/agent-scene.js b/src/agent-scene.jsindex d5445d5b..d2fd399f 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1559,7 +1559,7 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {knownKeys(operation, ['type', lookField], 'operation');const patch = operation[lookField];// Spot and area lights, cascades and sun links are absent from a recipe until it sets them.- const optionalFields = lookField === 'environment' ? ['ground', 'spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'hdri'] : [];+ const optionalFields = lookField === 'environment' ? ['ground', 'spotLights', 'areaLights', 'shadowCascades', 'keyAffects', 'objectReflections', 'floorSkyTrace', 'sunBounce', 'specularAntiAliasing', 'sunAngularRadius', 'lines', 'resolveCoplanar', 'viewTransform', 'look', 'hdri'] : [];knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };diff --git a/src/cascaded-shadows.js b/src/cascaded-shadows.jsindex 5c448c2d..c66cea06 100644--- a/src/cascaded-shadows.js+++ b/src/cascaded-shadows.js@@ -32,6 +32,11 @@ uniform vec4 cascadeSplits;uniform vec4 cascadeTexels;uniform vec4 cascadeRanges;uniform vec4 cascadeFrame;+uniform float sunSoftness;+vec2 cascadeVogel(int index, int count, float rotation) {+ float angle = float(index) * 2.399963 + rotation;+ return sqrt((float(index) + 0.5) / float(count)) * vec2(cos(angle), sin(angle));+}float cascadeTap(int layer, vec2 coordinates, float receiverDepth, ivec2 dimensions) {vec2 pixel = coordinates * vec2(dimensions) - 0.5;ivec2 origin = ivec2(floor(pixel));@@ -43,12 +48,35 @@ float cascadeTap(int layer, vec2 coordinates, float receiverDepth, ivec2 dimensifloat 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 cascadeSoftVisibility(int layer, vec3 projected, float receiverDepth, ivec2 dimensions) {+ float rotation = 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));+ float texelWorld = cascadeTexels[layer];+ float searchTexels = clamp(sunSoftness * 12.0 / texelWorld, 1.0, 24.0);+ float gapSum = 0.0;+ float blockers = 0.0;+ for (int tap = 0; tap < 12; tap++) {+ ivec2 texel = clamp(ivec2(floor(projected.xy * vec2(dimensions) + cascadeVogel(tap, 12, rotation) * searchTexels)), ivec2(0), dimensions - 1);+ float stored = texelFetch(cascadeShadowMap, ivec3(texel, layer), 0).r;+ if (stored < receiverDepth) {+ gapSum += receiverDepth - stored;+ blockers += 1.0;+ }+ }+ if (blockers == 0.0) return 1.0;+ float penumbraTexels = clamp(sunSoftness * (gapSum / blockers) * cascadeRanges[layer] / texelWorld, 1.0, 24.0);+ float lit = 0.0;+ for (int tap = 0; tap < 16; tap++) {+ lit += cascadeTap(layer, projected.xy + cascadeVogel(tap, 16, rotation) * penumbraTexels / vec2(dimensions), receiverDepth, dimensions);+ }+ return lit / 16.0;+}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;+ if (sunSoftness > 0.0) return cascadeSoftVisibility(layer, projected, projected.z - bias, dimensions);vec2 texel = 1.0 / vec2(dimensions);float visibility = 0.0;for (int row = -1; row <= 1; row++) {@@ -297,7 +325,7 @@ export class CascadedShadows {bindUniforms(renderer) {const context = renderer.context;if (this.locationProgram !== renderer.program) {- const names = ['cascadeShadowMap', 'cascadeMatrices[0]', 'cascadeSplits', 'cascadeTexels', 'cascadeRanges', 'cascadeFrame'];+ const names = ['cascadeShadowMap', 'cascadeMatrices[0]', 'cascadeSplits', 'cascadeTexels', 'cascadeRanges', 'cascadeFrame', 'sunSoftness'];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);@@ -310,6 +338,8 @@ export class CascadedShadows {context.uniform4fv(this.locations.cascadeTexels, this.texels);context.uniform4fv(this.locations.cascadeRanges, this.ranges);context.uniform4fv(this.locations.cascadeFrame, this.forward);+ const sunAngularRadius = renderer.environment?.sunAngularRadius;+ context.uniform1f(this.locations.sunSoftness, sunAngularRadius > 0 ? Math.tan(sunAngularRadius) : 0);}dispose(context, renderTargets = null) {@@ -337,5 +367,7 @@ export function effectiveShadowCascades(environment, shadow) {if (environment.shadowCascades !== undefined) {return environment.shadowCascades;}- return shadow.extent > AUTOMATIC_CASCADE_EXTENT ? AUTOMATIC_CASCADE_COUNT : 0;+ const automaticCount = shadow.extent > AUTOMATIC_CASCADE_EXTENT ? AUTOMATIC_CASCADE_COUNT : 0;+ // A soft sun reads depths from the cascade array, so a scene that names an angle gets at least one slice.+ return environment.sunAngularRadius > 0 ? Math.max(automaticCount, 1) : automaticCount;}diff --git a/src/light-profile.js b/src/light-profile.jsnew file mode 100644index 00000000..b7c0b767--- /dev/null+++ b/src/light-profile.js@@ -0,0 +1,89 @@+// The IES profile math, apart from the shader code so the path tracer can read it alone.++// An IES profile is the candela of a lamp against the angle from its axis, in degrees. It is stored as 16 relative+// values at equal steps of angle from 0 (the axis) to 90 degrees (the plane of the lamp), divided by the value on the+// axis, so `intensity` stays the candela head on. The raster shader and the path tracer read the same 16 values.+// A spot light multiplies its cone by the profile; an area light multiplies its Lambert emission by it.++export const PROFILE_SAMPLE_COUNT = 16;+const PROFILE_MAXIMUM_POINTS = 32;++// Bundled profiles, made for 67js as cosine powers (CC0): the exponent sets how tight the beam is.+// 'batwing' peaks at 45 degrees off the axis, as a wall washer does.+const BUNDLED_EXPONENTS = { 'wide-flood': 1.5, downlight: 6, 'narrow-spot': 30 };+export const IES_PROFILE_NAMES = Object.freeze([...Object.keys(BUNDLED_EXPONENTS), 'batwing']);++function bundledCandela(name, angleDegrees) {+ const radians = (angleDegrees * Math.PI) / 180;+ if (name === 'batwing') return 0.35 + 0.65 * Math.sin(2 * radians) ** 2;+ return Math.cos(radians) ** BUNDLED_EXPONENTS[name];+}++function bundledProfile(name) {+ const angles = [];+ for (let step = 0; step <= 9; step++) angles.push(step * 10);+ return { angles, candela: angles.map(angle => bundledCandela(name, angle)) };+}++/** Checks a recipe's `ies` value (a bundled name or { angles, candela }) and returns it in one canonical shape. */+export function resolveIesProfile(value, label = 'ies') {+ if (typeof value === 'string') {+ if (!IES_PROFILE_NAMES.includes(value)) throw new RangeError(`${label} must be one of ${IES_PROFILE_NAMES.join(', ')} or { angles, candela }.`);+ return value;+ }+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new TypeError(`${label} must be a profile name or { angles, candela }.`);+ const { angles, candela } = value;+ if (!Array.isArray(angles) || !Array.isArray(candela) || angles.length !== candela.length || angles.length < 2 || angles.length > PROFILE_MAXIMUM_POINTS) {+ throw new RangeError(`${label} angles and candela must be arrays of the same length, from 2 to ${PROFILE_MAXIMUM_POINTS}.`);+ }+ angles.forEach((angle, index) => {+ if (typeof angle !== 'number' || !Number.isFinite(angle) || angle < 0 || angle > 180 || (index > 0 && angle <= angles[index - 1])) {+ throw new RangeError(`${label} angles must be degrees from 0 to 180, strictly rising.`);+ }+ });+ candela.forEach(entry => {+ if (typeof entry !== 'number' || !Number.isFinite(entry) || entry < 0 || entry > 1e7) throw new RangeError(`${label} candela must be numbers from 0 to 10000000.`);+ });+ if (!candela.some(entry => entry > 0)) throw new RangeError(`${label} candela needs a value above zero.`);+ return { angles: [...angles], candela: [...candela] };+}++function candelaAt(profile, angleDegrees) {+ const { angles, candela } = profile;+ if (angleDegrees <= angles[0]) return candela[0];+ for (let index = 1; index < angles.length; index++) {+ if (angleDegrees <= angles[index]) {+ const fraction = (angleDegrees - angles[index - 1]) / (angles[index] - angles[index - 1]);+ return candela[index - 1] + (candela[index] - candela[index - 1]) * fraction;+ }+ }+ return 0;+}++const profileCache = new Map();++/** The 16 relative values of a profile, 1 on the axis. The array is shared: do not change it. */+export function profileSamples(value) {+ const key = typeof value === 'string' ? value : JSON.stringify(value);+ const cached = profileCache.get(key);+ if (cached) return cached;+ const profile = typeof value === 'string' ? bundledProfile(value) : value;+ const onAxis = candelaAt(profile, 0) > 0 ? candelaAt(profile, 0) : Math.max(...profile.candela);+ const samples = new Float32Array(PROFILE_SAMPLE_COUNT);+ for (let index = 0; index < PROFILE_SAMPLE_COUNT; index++) {+ samples[index] = candelaAt(profile, (index / (PROFILE_SAMPLE_COUNT - 1)) * 90) / onAxis;+ }+ if (profileCache.size > 64) profileCache.clear();+ profileCache.set(key, samples);+ return samples;+}++/** The gain of a profile at the cosine of the angle from the lamp's axis; 0 at or past 90 degrees. */+export function profileGain(samples, cosine) {+ if (cosine <= 0) return 0;+ const position = (Math.acos(Math.min(cosine, 1)) / (Math.PI / 2)) * (PROFILE_SAMPLE_COUNT - 1);+ const lower = Math.floor(position);+ const upper = Math.min(lower + 1, PROFILE_SAMPLE_COUNT - 1);+ return samples[lower] + (samples[upper] - samples[lower]) * (position - lower);+}+diff --git a/src/light-shapes.js b/src/light-shapes.jsnew file mode 100644index 00000000..f099403d--- /dev/null+++ b/src/light-shapes.js@@ -0,0 +1,128 @@+import { registerShaderFeatureCode, lightShapeSupport } from './shader-registry.js';+import { MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './light-limits.js';+import { PROFILE_SAMPLE_COUNT, resolveIesProfile, profileSamples } from './light-profile.js';++export { PROFILE_SAMPLE_COUNT, IES_PROFILE_NAMES, resolveIesProfile, profileSamples, profileGain } from './light-profile.js';++// Soft area light shadows and IES light profiles: the shader code, the file reader and the uniform upload. The profile math is in light-profile.js.+// The code loads on demand, so a scene with neither never carries it.+const PROFILE_LIGHT_COUNT = MAX_SPOT_LIGHTS + MAX_AREA_LIGHTS;+const ATLAS_NEAR = 0.05;+const ATLAS_FAR = 30;+/**+ * Reads the text of an IES file (LM-63) into { angles, candela }: the vertical angles, with the candela averaged over+ * the horizontal angles and times the file's multiplier. A file with TILT=INCLUDE is refused.+ */+export function parseIesPhotometry(text) {+ const tiltIndex = text.search(/^TILT=/im);+ if (tiltIndex < 0) throw new RangeError('The file has no TILT line, so it is not an IES file.');+ const afterTilt = text.slice(tiltIndex);+ const lineEnd = afterTilt.indexOf('\n');+ if (!/^TILT=NONE/i.test(afterTilt)) throw new RangeError('IES files with TILT=INCLUDE or TILT=filename are not supported.');+ const numbers = afterTilt.slice(lineEnd + 1).split(/[\s,]+/).filter(Boolean).map(Number);+ if (numbers.some(entry => !Number.isFinite(entry))) throw new RangeError('The IES file holds text where numbers belong.');+ const multiplier = numbers[2];+ const verticalCount = numbers[3];+ const horizontalCount = numbers[4];+ const header = 13;+ if (!(verticalCount >= 2) || !(horizontalCount >= 1) || numbers.length < header + verticalCount + horizontalCount + verticalCount * horizontalCount) {+ throw new RangeError('The IES file is shorter than its header says.');+ }+ const angles = numbers.slice(header, header + verticalCount);+ const candelaStart = header + verticalCount + horizontalCount;+ const candela = angles.map((angle, row) => {+ let sum = 0;+ for (let column = 0; column < horizontalCount; column++) sum += numbers[candelaStart + column * verticalCount + row];+ return (sum / horizontalCount) * multiplier;+ });+ return resolveIesProfile({ angles, candela }, 'IES file');+}++const SOFT_AREA_SHADOW = `+float areaShadowNoise() {+ return 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));+}+vec2 areaShadowDisk(int index, int count, float rotation) {+ float angle = float(index) * 2.399963 + rotation;+ return sqrt((float(index) + 0.5) / float(count)) * vec2(cos(angle), sin(angle));+}+float areaShadowLinearDepth(float stored) {+ return 2.0 * ${ATLAS_NEAR.toFixed(2)} * ${ATLAS_FAR.toFixed(1)} / (${ATLAS_FAR.toFixed(1)} + ${ATLAS_NEAR.toFixed(2)} - (stored * 2.0 - 1.0) * (${ATLAS_FAR.toFixed(1)} - ${ATLAS_NEAR.toFixed(2)}));+}+float softLocalShadow(float tile, vec3 position, vec3 normal, float lightDistance, float lightHalfSize) {+ int tileIndex = int(tile);+ float texelAngle = localShadowTexelAngles[tileIndex];+ vec4 clip = localShadowMatrices[tileIndex] * vec4(position + normal * (lightDistance * texelAngle * 2.0), 1.0);+ if (clip.w <= 0.0) return 1.0;+ vec3 projected = clip.xyz / clip.w * 0.5 + 0.5;+ if (projected.z > 1.0 || any(lessThan(projected.xy, vec2(0.0))) || any(greaterThan(projected.xy, vec2(1.0)))) return 1.0;+ ivec2 tileOrigin = ivec2(tileIndex % 4, tileIndex / 4) * 512;+ vec2 pixel = projected.xy * 512.0;+ float receiverDepth = projected.z - 0.00002;+ float rotation = areaShadowNoise();+ float texelSize = texelAngle * clip.w;+ float searchTexels = clamp(lightHalfSize * 2.0 / texelSize, 2.0, 20.0);+ float blockerSum = 0.0;+ float blockers = 0.0;+ for (int tap = 0; tap < 16; tap++) {+ ivec2 texel = clamp(ivec2(floor(pixel + areaShadowDisk(tap, 16, rotation) * searchTexels)), ivec2(0), ivec2(511));+ float stored = texelFetch(localShadowAtlas, tileOrigin + texel, 0).r;+ if (stored < receiverDepth) {+ blockerSum += areaShadowLinearDepth(stored);+ blockers += 1.0;+ }+ }+ if (blockers == 0.0) return 1.0;+ float blockerDepth = blockerSum / blockers;+ float penumbraTexels = clamp(lightHalfSize * (clip.w - blockerDepth) / (blockerDepth * texelSize), 1.0, 24.0);+ float lit = 0.0;+ for (int tap = 0; tap < 32; tap++) {+ ivec2 texel = clamp(ivec2(floor(pixel + areaShadowDisk(tap, 32, rotation) * penumbraTexels)), ivec2(0), ivec2(511));+ lit += step(receiverDepth, texelFetch(localShadowAtlas, tileOrigin + texel, 0).r);+ }+ return lit / 32.0;+}+`;++const PROFILE_DECLARATIONS = `+uniform float lightProfileTable[${PROFILE_LIGHT_COUNT * PROFILE_SAMPLE_COUNT}];+float lightProfileGain(int light, vec3 fromLight, vec3 axis) {+ float cosine = dot(fromLight, axis);+ if (cosine <= 0.0) return 0.0;+ float position = acos(min(cosine, 1.0)) * ${((PROFILE_SAMPLE_COUNT - 1) / (Math.PI / 2)).toFixed(7)};+ int lower = int(floor(position));+ int upper = min(lower + 1, ${PROFILE_SAMPLE_COUNT - 1});+ return mix(lightProfileTable[light * ${PROFILE_SAMPLE_COUNT} + lower], lightProfileTable[light * ${PROFILE_SAMPLE_COUNT} + upper], fract(position));+}+`;++registerShaderFeatureCode('areaShadows', {+ declarations: SOFT_AREA_SHADOW,+ areaRadiance: ' if (USES_LOCAL_SHADOWS && areaLightPositions[index].w >= 0.0) lightRadiance *= shadowBlind > 0.5 ? 1.0 : softLocalShadow(areaLightPositions[index].w, worldPosition, normal, length(fromCenter), max(halfSize.x, halfSize.y));\n',+});++registerShaderFeatureCode('lightProfiles', {+ declarations: PROFILE_DECLARATIONS,+ spotRadiance: ' lightRadiance *= lightProfileGain(index, -toLight, spotLightDirections[index].xyz);\n',+ areaRadiance: ` lightRadiance *= lightProfileGain(${MAX_SPOT_LIGHTS} + index, -toLight, lightNormal);\n`,+});++const profileTable = new Float32Array(PROFILE_LIGHT_COUNT * PROFILE_SAMPLE_COUNT);+const tableLocations = new WeakMap();++// Spot lights fill the first rows of the table and area lights the rows after them; a light with no profile has a row of ones.+function fillProfileTable(environment) {+ profileTable.fill(1);+ const rows = [...(environment.spotLights ?? []).map((light, index) => [index, light]), ...(environment.areaLights ?? []).map((light, index) => [MAX_SPOT_LIGHTS + index, light])];+ for (const [row, light] of rows) {+ if (light.ies !== undefined) profileTable.set(profileSamples(resolveIesProfile(light.ies, 'ies')), row * PROFILE_SAMPLE_COUNT);+ }+}++lightShapeSupport.bind = renderer => {+ if (!(renderer.lighting.profileCount > 0)) return;+ const context = renderer.context;+ if (!tableLocations.has(renderer.program)) tableLocations.set(renderer.program, context.getUniformLocation(renderer.program, 'lightProfileTable[0]'));+ fillProfileTable(renderer.environment);+ context.uniform1fv(tableLocations.get(renderer.program), profileTable);+};diff --git a/src/lighting.js b/src/lighting.jsindex 17fd32ce..8bcbb3c5 100644--- a/src/lighting.js+++ b/src/lighting.js@@ -90,13 +90,15 @@ function validateAreaLight(light) {numberInRange(light.intensity ?? 1, 0, 1e5, 'Area light intensity');numberInRange(light.width, 0.001, 1e4, 'Area light width');numberInRange(light.height, 0.001, 1e4, 'Area light height');+ validateCastShadow(light, 'Area light');}// Shadow tiles are handed out in order, point lights first. A request beyond the atlas is an error, not a silent drop.-function countShadowTiles(pointLights, spotLights) {+function countShadowTiles(pointLights, spotLights, areaLights) {let tiles = 0;for (const light of pointLights) if (light.castShadow) tiles += POINT_SHADOW_TILES;for (const light of spotLights) if (light.castShadow) tiles += 1;+ for (const light of areaLights) if (light.castShadow) tiles += 1;if (tiles > SHADOW_ATLAS_TILES) {throw new RangeError(`Shadow casting lights need ${tiles} atlas tiles, and the atlas holds ${SHADOW_ATLAS_TILES} (a point light uses ${POINT_SHADOW_TILES}, a spot light one)`);}@@ -123,6 +125,8 @@ export function createLightingState() {pointCount: 0,spotCount: 0,areaCount: 0,+ areaShadowCount: 0,+ profileCount: 0,fillIntensity: 1,ambientIntensity: 1,specularAntiAliasing: DEFAULT_SPECULAR_ANTI_ALIASING,@@ -195,6 +199,12 @@ function writeAreaLights(state, areaLights) {state.areaNormals[index * 4 + 3] = light.width;state.areaTangents.set(tangent.map(component => component / tangentLength), index * 4);state.areaTangents[index * 4 + 3] = light.height;+ // The w of the position is the atlas tile of the light's shadow. The tile looks along the emitting side with the widest view a tile allows.+ state.areaPositions[index * 4 + 3] = NO_SHADOW_TILE;+ if (!light.castShadow) continue;+ state.areaPositions[index * 4 + 3] = state.shadowCasters.length;+ state.shadowCasters.push({ light: { position: light.position, direction: normal, range: 0, angle: SPOT_MAXIMUM_ANGLE }, face: SPOT_FACE });+ state.areaShadowCount++;}}@@ -213,8 +223,9 @@ export function updateLightingState(state, environment, { world = false } = {})pointLights.forEach(validatePointLight);spotLights.forEach(validateSpotLight);areaLights.forEach(validateAreaLight);- countShadowTiles(pointLights, spotLights);+ countShadowTiles(pointLights, spotLights, areaLights);state.shadowCasters = [];+ state.areaShadowCount = 0;writePointLights(state, pointLights);writeSpotLights(state, spotLights);writeAreaLights(state, areaLights);@@ -222,6 +233,7 @@ export function updateLightingState(state, environment, { world = false } = {})state.pointCount = pointLights.length;state.spotCount = spotLights.length;state.areaCount = areaLights.length;+ state.profileCount = [...spotLights, ...areaLights].filter(light => light.ies !== undefined).length;state.fillIntensity = fillIntensity;state.ambientIntensity = ambientIntensity;state.specularAntiAliasing = specularAntiAliasing;diff --git a/src/path-tracer-gpu.js b/src/path-tracer-gpu.jsindex 5ca8b2a4..190af0ec 100644--- a/src/path-tracer-gpu.js+++ b/src/path-tracer-gpu.js@@ -125,7 +125,7 @@ export function setSceneUniforms(gl, program, scene, camera, options, lightCountgl.uniform1i(location('uHasSun'), sun ? 1 : 0);gl.uniform3fv(location('uSunDirection'), sun?.direction ?? [0, 1, 0]);gl.uniform3fv(location('uSunColor'), sun?.color ?? [0, 0, 0]);- gl.uniform1f(location('uSunCosineMax'), Math.cos(Math.PI / 360));+ gl.uniform1f(location('uSunCosineMax'), Math.cos(sun?.angularRadius ?? Math.PI / 360));gl.uniform1i(location('uHasEnvironment'), environment ? 1 : 0);gl.uniform4f(location('uEnvironmentShape'), environment?.width ?? 1, environment?.height ?? 1, environment?.intensity ?? 1, environment?.total ?? 1);gl.uniform2f(location('uEnvironmentRotation'), environment?.cosine ?? 1, environment?.sine ?? 0);diff --git a/src/path-tracer-scene.js b/src/path-tracer-scene.jsindex 4259f572..6de05960 100644--- a/src/path-tracer-scene.js+++ b/src/path-tracer-scene.js@@ -4,6 +4,7 @@ import { SUN_BIT, POINT_FIRST_BIT, SPOT_FIRST_BIT, AREA_FIRST_BIT } from './lighimport { boxProjectedGeometry, columnLengths } from './export-box-uv.js';import { resolveTraceVolume } from './path-tracer-volume.js';import { resolveTraceSubsurface } from './path-tracer-subsurface.js';+import { profileSamples, resolveIesProfile } from './light-profile.js';// The scene a path trace reads: every part flattened into one world-space triangle soup with per-vertex normals, UVs// and colours, one resolved material per part, the lights in plain arrays, and the environment map as a sampling table.@@ -230,17 +231,23 @@ function normalized(vector) {return [vector[0] / length, vector[1] / length, vector[2] / length];}+// The 16 relative values of the light's IES profile, or null for a light with none.+function traceProfile(light) {+ return light.ies === undefined ? null : Array.from(profileSamples(resolveIesProfile(light.ies, 'ies')));+}+function resolveLights(environment) {const sunPower = Math.max(...(environment.keyColor ?? [0, 0, 0]));const lightCount = (environment.pointLights?.length ?? 0) + (environment.spotLights?.length ?? 0) + (environment.areaLights?.length ?? 0);if (lightCount > MAX_TRACE_LIGHTS) throw new RangeError(`A path trace takes at most ${MAX_TRACE_LIGHTS} point, spot and area lights.`);return {- sun: sunPower > 0 ? { bit: SUN_BIT, direction: normalized(environment.lightDirection ?? [0, 1, 0]), color: environment.keyColor } : null,+ sun: sunPower > 0 ? { bit: SUN_BIT, direction: normalized(environment.lightDirection ?? [0, 1, 0]), color: environment.keyColor, angularRadius: environment.sunAngularRadius ?? SUN_ANGULAR_RADIUS } : null,points: (environment.pointLights ?? []).map((light, index) => ({ bit: POINT_FIRST_BIT + index, position: light.position, color: light.color, intensity: light.intensity, radius: light.radius ?? 0, range: light.range ?? 0 })),spots: (environment.spotLights ?? []).map((light, index) => ({bit: SPOT_FIRST_BIT + index, position: light.position, color: light.color, intensity: light.intensity, radius: light.radius ?? 0, range: light.range ?? 0,direction: normalized(light.direction),cosineHalfAngle: Math.cos(light.angle),+ profile: traceProfile(light),blend: (1 - Math.cos(light.angle)) * (light.penumbra ?? 0),})),areas: (environment.areaLights ?? []).map((light, index) => {@@ -248,7 +255,7 @@ function resolveLights(environment) {const guide = normalized(light.up ?? [0, 1, 0]);const across = normalized([guide[1] * normal[2] - guide[2] * normal[1], guide[2] * normal[0] - guide[0] * normal[2], guide[0] * normal[1] - guide[1] * normal[0]]);const along = [normal[1] * across[2] - normal[2] * across[1], normal[2] * across[0] - normal[0] * across[2], normal[0] * across[1] - normal[1] * across[0]];- return { bit: AREA_FIRST_BIT + index, position: light.position, color: light.color, intensity: light.intensity, width: light.width, height: light.height, normal, across, along };+ return { bit: AREA_FIRST_BIT + index, position: light.position, color: light.color, intensity: light.intensity, width: light.width, height: light.height, normal, across, along, profile: traceProfile(light) };}),};}diff --git a/src/path-tracer.js b/src/path-tracer.jsindex 70628f49..c1b562db 100644--- a/src/path-tracer.js+++ b/src/path-tracer.js@@ -1,5 +1,6 @@import { cameraFieldOfView } from './camera.js';import { pointLightFalloff } from './ray-query.js';+import { profileGain } from './light-profile.js';import { buildTraceScene, SUN_ANGULAR_RADIUS } from './path-tracer-scene.js';import { denoiseRadiance } from './path-tracer-denoise.js';import { acesChannel, displayColor } from './view-transform.js';@@ -453,7 +454,7 @@ function createPathTracer(scene, options) {let featuresRecorded = false;const { lights, environment } = scene;if (lights.sun) buildFrame(lights.sun.direction, sunFrame);- const sunCosineMax = Math.cos(SUN_ANGULAR_RADIUS);+ const sunCosineMax = Math.cos(lights.sun?.angularRadius ?? SUN_ANGULAR_RADIUS);function addRadiance(depth, red, green, blue) {let clampedRed = red;@@ -591,7 +592,7 @@ function createPathTracer(scene, options) {const inside = axisCosine - light.cosineHalfAngle;if (inside <= 0) return;const mask = light.blend > 0 && inside < light.blend ? smoothstep(inside / light.blend) : 1;- const strength = light.intensity * pointLightFalloff(distanceSquared, light) * mask;+ const strength = light.intensity * pointLightFalloff(distanceSquared, light) * mask * (light.profile ? profileGain(light.profile, axisCosine) : 1);for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = light.color[channel] * strength;addDirect(depth, normal, distance - scene.surfaceOffset, fullWeight);}@@ -607,7 +608,7 @@ function createPathTracer(scene, options) {if (distance < 1e-6) return;const emitCosine = -(light.normal[0] * lightDirection[0] + light.normal[1] * lightDirection[1] + light.normal[2] * lightDirection[2]);if (emitCosine <= 0) return;- const strength = light.intensity * emitCosine / distanceSquared;+ const strength = light.intensity * emitCosine / distanceSquared * (light.profile ? profileGain(light.profile, emitCosine) : 1);for (let channel = 0; channel < 3; channel++) lightRadiance[channel] = light.color[channel] * strength;addDirect(depth, normal, distance - scene.surfaceOffset, fullWeight);}diff --git a/src/renderer.js b/src/renderer.jsindex 9ce1514a..c87958c4 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -19,7 +19,7 @@ import { MaterialSnapshot } from './material-snapshot.js';import { fittedFogDensity } from './fog-fit.js';import { InstanceSelection, extractFrustumPlanes, geometryBoundingSphere, selectInstances } from './render-culling.js';import { resolveShadowLight, shadowBiasPerSlope } from './shadow-light.js';-import { requireFeatureCode, deformationSupport, requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';+import { requireFeatureCode, lightShapeSupport, deformationSupport, requireDeformationSupport, texturedReplaceSupport, textureUpdateSupport } from './shader-registry.js';const SHADOW_MAP_SIZE = 2048;// Liquid and foam see the resolved opaque scene, so they draw in their own pass after it.@@ -72,6 +72,8 @@ function shaderFeaturesOfLighting(lighting) {if (lighting.spotCount > 0) features.push('spotLights');if (lighting.areaCount > 0) features.push('areaLights');if (lighting.shadowCasters.length > 0) features.push('localShadows');+ if (lighting.areaShadowCount > 0) features.push('areaShadows');+ if (lighting.profileCount > 0) features.push('lightProfiles');if (lighting.fillIntensity > 0) features.push('fill');return features;}@@ -2264,6 +2266,7 @@ export class Renderer67 {context.uniform4fv(this.uniforms['pointLightColors[0]'], this.lighting.colors);context.uniform1fv(this.uniforms['pointLightRadii[0]'], this.lighting.radii);this.applyLocalLightUniforms(Boolean(frame.reflectionTarget));+ lightShapeSupport.bind?.(this);context.uniform3fv(this.uniforms.keyColor, this.lighting.keyColor);context.uniform1f(this.uniforms.fillIntensity, this.lighting.fillIntensity);context.uniform1f(this.uniforms.ambientIntensity, this.lighting.ambientIntensity);diff --git a/src/shader-registry.js b/src/shader-registry.jsindex 0863233e..f7b4afd9 100644--- a/src/shader-registry.js+++ b/src/shader-registry.js@@ -15,6 +15,9 @@ export const layerTextureSupport = {};// view-transform-shader.js sets apply(source, kind, viewTransform, hasLook), bindLook(renderer, program) and dispose(renderer).export const viewTransformShader = {};+// light-shapes.js sets bind(renderer): it uploads the light profile table that the lightProfiles shader code reads.+export const lightShapeSupport = {};+// texture-update.js sets update(renderer, descriptor, update): the body of renderer.updateTexture.export const textureUpdateSupport = {};@@ -45,7 +48,7 @@ export function registerShaderFeatureCode(feature, slots) {}// The addon that registers each feature's code; a feature not listed here is registered by material-layer-shaders.-const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader', volumeFog: 'fog-shader' };+const FEATURE_ADDONS = { splat: 'splat-shader', liquid: 'liquid-shader', worldMaterials: 'world-material-shader', subsurface: 'subsurface-shader', volumeFog: 'fog-shader', areaShadows: 'light-shapes', lightProfiles: 'light-shapes' };export function requireFeatureCode(feature) {const slots = registeredFeatureCode.get(feature);diff --git a/src/shaders.js b/src/shaders.jsindex 6acf8fb8..35932087 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -656,6 +656,7 @@ ${featureCode("linkSpot")} vec3 lightRadiance = spotLightColors[index].rgbif (USES_LOCAL_SHADOWS && spotLightParameters[index].z >= 0.0) {lightRadiance *= shadowBlind > 0.5 ? 1.0 : localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));}+${featureCode("spotRadiance")}radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);}}@@ -679,7 +680,7 @@ ${featureCode("linkArea")} vec3 lightNormal = areaLightNormals[index].xyz;// Adding area / pi keeps the term finite at the surface and matches a disc source on its axis.float attenuation = emission / (distanceSquared + area / PI);vec3 lightRadiance = areaLightColors[index].rgb * areaLightColors[index].w * attenuation;- radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);+${featureCode("areaRadiance")} radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);}}vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), baseReflectance);diff --git a/tests/light-shapes-render.test.js b/tests/light-shapes-render.test.jsnew file mode 100644index 00000000..4d1e87d3--- /dev/null+++ b/tests/light-shapes-render.test.js@@ -0,0 +1,25 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { existsSync } from 'node:fs';+import { execFileSync } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join } from 'node:path';++// Draws each soft-light feature off and on in Chrome and records the frame time, so it runs only when asked:+// RENDER_TESTS=1 bash ~/.agents/tools/gpu-lock.sh node --test tests/light-shapes-render.test.js+const chromePath = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';+const enabled = process.env.RENDER_TESTS === '1' && existsSync(chromePath);+const PAIRS = [['sun-hard', 'sun-soft'], ['area-lit', 'area-shadow'], ['spot-plain', 'spot-ies']];++test('each soft-light feature changes the picture, and the default stills keep their hashes', { skip: !enabled, timeout: 300000 }, () => {+ const output = execFileSync('node', ['bench/lighting/soft-lights.mjs', '--rounds=1', `--out=${join(tmpdir(), 'soft-lights-test')}`], { encoding: 'utf8' });+ const { summary } = JSON.parse(output);+ for (const [before, after] of PAIRS) {+ assert.notEqual(summary[before].hash, summary[after].hash, `${after} differs from ${before}`);+ assert.ok(summary[after].medianMilliseconds > 0, `${after} has a frame time`);+ }+ // Hashes of the default stills as main drew them before the soft-light code (bench/lighting/soft-lights.mjs on origin/main).+ assert.equal(summary['sun-hard'].hash, 'c2ed7c8f8ff1908a');+ assert.equal(summary['area-lit'].hash, '227c6a488f89da9b');+ assert.equal(summary['spot-plain'].hash, '4846417a8b3711b6');+});diff --git a/tests/light-shapes.test.js b/tests/light-shapes.test.jsnew file mode 100644index 00000000..5a8db43b--- /dev/null+++ b/tests/light-shapes.test.js@@ -0,0 +1,92 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { IES_PROFILE_NAMES, parseIesPhotometry, profileGain, profileSamples, resolveIesProfile } from '../src/light-shapes.js';+import { createLightingState, updateLightingState, NO_SHADOW_TILE } from '../src/lighting.js';+import { effectiveShadowCascades } from '../src/cascaded-shadows.js';+import { normalizeAgentLook } from '../src/agent-look.js';+import { loadAgentSceneModules } from '../src/agent-scene-modules.js';+import { buildTraceScene, SUN_ANGULAR_RADIUS } from '../src/path-tracer-scene.js';+import { box } from '../src/geometry.js';++const areaLight = { position: [0, 3, 0], direction: [0, -1, 0], width: 1, height: 1 };++test('a bundled profile is 1 on the axis and falls to the plane of the lamp', () => {+ for (const name of IES_PROFILE_NAMES) assert.equal(profileSamples(name)[0], 1, name);+ const narrow = profileSamples('narrow-spot');+ assert.ok(narrow[8] < 0.05, 'a narrow spot has almost nothing at 48 degrees');+ assert.equal(profileGain(narrow, 1), 1);+ assert.equal(profileGain(narrow, -0.2), 0);+ assert.ok(profileSamples('batwing')[5] > 0.95, 'a batwing peaks near 30 to 60 degrees');+});++test('an inline profile is checked and normalized to its axis value', () => {+ const samples = profileSamples(resolveIesProfile({ angles: [0, 90], candela: [200, 100] }));+ assert.equal(samples[0], 1);+ assert.ok(Math.abs(samples[15] - 0.5) < 1e-6);+ assert.throws(() => resolveIesProfile('floodlight'), /must be one of/);+ assert.throws(() => resolveIesProfile({ angles: [0, 0], candela: [1, 1] }), /strictly rising/);+ assert.throws(() => resolveIesProfile({ angles: [0, 45], candela: [0, 0] }), /above zero/);+});++test('an IES file averages its horizontal planes and applies the multiplier', () => {+ const text = ['IESNA:LM-63-2002', '[TEST] sample', 'TILT=NONE', '1 1000 2 3 2 1 2 0 0 0', '1 1 100', '0 45 90', '0 90', '100 80 0', '300 120 0'].join('\n');+ const profile = parseIesPhotometry(text);+ assert.deepEqual(profile.angles, [0, 45, 90]);+ assert.deepEqual(profile.candela, [400, 200, 0]);+ assert.throws(() => parseIesPhotometry('TILT=INCLUDE\n1'), /not supported/);+});++test('an area light that casts a shadow takes one tile after the spot lights, and the default takes none', () => {+ const plain = updateLightingState(createLightingState(), { areaLights: [areaLight] });+ assert.equal(plain.shadowCasters.length, 0);+ assert.equal(plain.areaShadowCount, 0);+ assert.equal(plain.areaPositions[3], NO_SHADOW_TILE);+ const shadowed = updateLightingState(createLightingState(), {+ spotLights: [{ position: [0, 2, 0], direction: [0, -1, 0], castShadow: true }],+ areaLights: [areaLight, { ...areaLight, castShadow: true }],+ });+ assert.equal(shadowed.shadowCasters.length, 2);+ assert.equal(shadowed.areaShadowCount, 1);+ assert.equal(shadowed.areaPositions[3], NO_SHADOW_TILE);+ assert.equal(shadowed.areaPositions[7], 1);+ assert.throws(() => updateLightingState(createLightingState(), { pointLights: Array.from({ length: 5 }, () => ({ position: [0, 1, 0], castShadow: true })) }), /atlas/);+});++test('a lamp with an ies profile is counted so the renderer compiles the profile code', () => {+ const state = updateLightingState(createLightingState(), { spotLights: [{ position: [0, 2, 0], direction: [0, -1, 0], ies: 'downlight' }], areaLights: [areaLight] });+ assert.equal(state.profileCount, 1);+ assert.equal(updateLightingState(createLightingState(), {}).profileCount, 0);+});++test('a named sun angle gives the sun at least one cascade, and an explicit count wins', () => {+ assert.equal(effectiveShadowCascades({}, { extent: 3.5 }), 0);+ assert.equal(effectiveShadowCascades({ sunAngularRadius: 0.02 }, { extent: 3.5 }), 1);+ assert.equal(effectiveShadowCascades({ sunAngularRadius: 0.02 }, { extent: 60 }), 3);+ assert.equal(effectiveShadowCascades({ sunAngularRadius: 0.02, shadowCascades: 0 }, { extent: 3.5 }), 0);+});++test('a recipe look carries the sun angle, area shadows and profiles, and refuses bad values', async () => {+ await loadAgentSceneModules({ environment: { sunAngularRadius: 0.01, areaLights: [{}], spotLights: [{ ies: 'x' }] } });+ const { environment } = normalizeAgentLook({ environment: {+ sunAngularRadius: 0.02,+ areaLights: [{ ...areaLight, castShadow: true, ies: 'batwing' }],+ spotLights: [{ position: [0, 2, 0], direction: [0, -1, 0], ies: { angles: [0, 60], candela: [10, 5] } }],+ } });+ assert.equal(environment.sunAngularRadius, 0.02);+ assert.equal(environment.areaLights[0].castShadow, true);+ assert.equal(environment.areaLights[0].ies, 'batwing');+ assert.deepEqual(environment.spotLights[0].ies, { angles: [0, 60], candela: [10, 5] });+ assert.throws(() => normalizeAgentLook({ environment: { sunAngularRadius: 1 } }), /sunAngularRadius/);+ assert.throws(() => normalizeAgentLook({ environment: { areaLights: [{ ...areaLight, ies: 'nope' }] } }), /ies/);+ assert.equal(Object.hasOwn(normalizeAgentLook().environment, 'sunAngularRadius'), false);+});++test('the path tracer reads the same sun disk and profile samples as the raster', () => {+ const parts = [{ geometry: box(0, 1), matrix: new Float32Array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1]), material: { color: [1, 1, 1] } }];+ const lit = buildTraceScene(parts, { keyColor: [1, 1, 1], spotLights: [{ position: [0, 2, 0], direction: [0, -1, 0], angle: 0.5, intensity: 1, ies: 'downlight' }] });+ assert.equal(lit.lights.sun.angularRadius, SUN_ANGULAR_RADIUS);+ assert.deepEqual(lit.lights.spots[0].profile, Array.from(profileSamples('downlight')));+ const soft = buildTraceScene(parts, { keyColor: [1, 1, 1], sunAngularRadius: 0.05, areaLights: [areaLight] });+ assert.equal(soft.lights.sun.angularRadius, 0.05);+ assert.equal(soft.lights.areas[0].profile, null);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex 2ec53f60..fff0d8bd 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -100,6 +100,7 @@ export default defineConfig({'fog-shader': 'src/fog-shader.js','light-linking': 'src/light-linking.js','cascaded-shadows': 'src/cascaded-shadows.js',+ 'light-shapes': 'src/light-shapes.js','compact-color': 'src/compact-color.js','gaussian-splats': 'src/gaussian-splats.js','texture-update': 'src/texture-update.js',