3D engine that AI agents drive
Add spot and area lights and shadows for point and spot lights
Nguyen Xuan And5426351faad
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2ac1179e..4d738c63 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,8 @@## Unreleased+- Add spot lights (`environment.spotLights`, 8), rectangular area lights (`environment.areaLights`, 4) and shadows for point and spot lights (`castShadow: true`). Intensity of a spot light is candela, as for a point light, with Blender's cone mask. Area lights use a representative point, within 1.2 percent of Cycles on the axis. Shadows share one 2048 x 3072 depth atlas of 24 tiles (24 MiB, allocated on first use): a point light takes 6 and a spot light 1, and a request for more is an error. The shader code and the atlas exist only in a scene that uses them. Recipes get all of it through `set-environment`, the MCP schema and `scene_capabilities` (`maxSpotLights`, `maxAreaLights`, `localShadows`). Cascaded directional shadows and light linking are not part of this+- Remove `67js/addons/film` from the npm package. It held the 187-second trailer demo with its baked physics recording, 75 KB gzip of the archive. Nothing else in the package used it. To keep using it, copy `src/film.js`, `src/film-rig.js`, `src/film-character.js`, `src/film-physics-definition.js` and `src/film-physics-clip.json` from the repository, or read the trailer on the site at `/film.html`. The archive goes from 901,314 to 829,085 bytes- Remove three.js from modeling and the agent scene: `lathe`, `extrude` and `tube` no longer import it, and `scene:agent-scene` drops from 185,681 to 117,290 bytes gzip. `lathe` and `tube` output is identical to before, vertex for vertex. `extrude` walls, bevels, UVs, normals and bounds are identical, and volume matches within 1e-4. Extrusion caps use a new ear-clipping triangulation, so a cap can split along other diagonals, and a cap with collinear points can add or drop a seam vertex. A clockwise hole under a clockwise contour is now flipped to face outward, where it used to keep inward walls- Make the first frame and the SwiftShader frame cost less, with the same pixels. The main fragment shader now compiles only the features that a scene uses (maps, splat layers, moss, alpha and the special material tags), and a part that needs another feature later recompiles it. All programs, with the environment prefilter, now start together and use `KHR_parallel_shader_compile`. On an RTX 3060 the first frame went from 3.7 to 4.4 seconds down to 0.5 to 1.0 seconds, and a SwiftShader frame costs 0.4 to 0.5 times what it did. `bench/runtime/PROFILE.md` has the profilediff --git a/bench/reference/README.md b/bench/reference/README.mdindex e121a53a..34a029ca 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -1,6 +1,6 @@# Reference renders-This suite scores how close a 67.js render is to Blender on 8 fixed scenes. Later work uses these scores as its starting point.+This suite scores how close a 67.js render is to Blender on 9 fixed scenes. Later work uses these scores as its starting point.## Run it@@ -24,6 +24,9 @@ Measured on 2026-10-30 with an RTX 3060, SwiftShader and Blender 5.2.2. The metr| `metal` | 0.1868 | 0.0934 | 0.1565 | No reflection between objects || `fog` | 0.2612 | 0.2662 | 0.0542 | No multiple scattering || `lit-interior` | 0.4997 | 0.5159 | 0.1204 | No indirect light, and point lights cast no shadows |+| `spot-area` | 0.1242 | 0.1935 | 0.1707 | The sphere is lit more weakly at its shaded edge, and the wall has no bounce light |++Rows are the baseline taken before shadows for point lights. The `lit-interior` scene now sets `castShadow` on its three point lights. With shadows, 67.js scores 0.5055 against Cycles (0.4997 before, so 0.0058 worse) and 0.0923 against EEVEE (0.1204 before, better): the shadow shape now matches, but Cycles fills its shadows with indirect light and 67.js leaves them dark. The committed `lit-interior` row stays at the earlier numbers. `spot-area` is new with shadows, a spot light and an area light.The mean against Cycles is 0.198 for 67.js and 0.160 for EEVEE. The mean difference between the RTX 3060 and SwiftShader is 0.007.diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 1321a7d9..3a10752f 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -1,108 +1,120 @@{- "metric": "FLIP (LDR), mean error, lower is better",- "blenderVersion": "5.2.2 LTS",- "seconds": {- "character": {- "cycles": 4.5,- "eevee": 1.1+ "metric": "FLIP (LDR), mean error, lower is better",+ "blenderVersion": "5.2.2 LTS",+ "seconds": {+ "character": {+ "cycles": 4.5,+ "eevee": 1.1+ },+ "fog": {+ "cycles": 16.6,+ "eevee": 1.1+ },+ "foliage": {+ "cycles": 5.8,+ "eevee": 1+ },+ "glass": {+ "cycles": 5.8,+ "eevee": 0.4+ },+ "lit-interior": {+ "cycles": 10,+ "eevee": 0.6+ },+ "material-spheres": {+ "cycles": 6.7,+ "eevee": 0.4+ },+ "metal": {+ "cycles": 5,+ "eevee": 0.3+ },+ "outdoor-hdri": {+ "cycles": 4.1,+ "eevee": 0.4+ },+ "spot-area": {+ "cycles": 20.3,+ "eevee": 13.2+ }},- "fog": {- "cycles": 16.6,- "eevee": 1.1+ "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)"},- "foliage": {- "cycles": 5.8,- "eevee": 1.0- },- "glass": {- "cycles": 5.8,- "eevee": 0.4- },- "lit-interior": {- "cycles": 10.0,- "eevee": 0.6- },- "material-spheres": {- "cycles": 6.7,- "eevee": 0.4- },- "metal": {- "cycles": 5.0,- "eevee": 0.3- },- "outdoor-hdri": {- "cycles": 4.1,- "eevee": 0.4- }- },- "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": {- "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.145,- "gpu-vs-eevee": 0.1469,- "cpu-vs-cycles": 0.1447,- "cpu-vs-eevee": 0.1471,- "eevee-vs-cycles": 0.115,- "gpu-vs-cpu": 0.0074- },- "lit-interior": {- "gpu-vs-cycles": 0.4997,- "gpu-vs-eevee": 0.1204,- "cpu-vs-cycles": 0.4993,- "cpu-vs-eevee": 0.1209,- "eevee-vs-cycles": 0.5159,- "gpu-vs-cpu": 0.006- },- "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+ "scores": {+ "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.145,+ "gpu-vs-eevee": 0.1469,+ "cpu-vs-cycles": 0.1447,+ "cpu-vs-eevee": 0.1471,+ "eevee-vs-cycles": 0.115,+ "gpu-vs-cpu": 0.0074+ },+ "lit-interior": {+ "gpu-vs-cycles": 0.4997,+ "gpu-vs-eevee": 0.1204,+ "cpu-vs-cycles": 0.4993,+ "cpu-vs-eevee": 0.1209,+ "eevee-vs-cycles": 0.5159,+ "gpu-vs-cpu": 0.006+ },+ "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/images/spot-area.jpg b/bench/reference/images/spot-area.jpgnew file mode 100644index 00000000..ca687a0fBinary files /dev/null and b/bench/reference/images/spot-area.jpg differdiff --git a/bench/reference/render-blender.py b/bench/reference/render-blender.pyindex 3bd64839..855f5717 100644--- a/bench/reference/render-blender.py+++ b/bench/reference/render-blender.py@@ -1,7 +1,7 @@# Renders each described scene in Cycles and EEVEE, and saves linear pixels as .npy for the scorer.# blender -b --factory-startup --python bench/reference/render-blender.py -- <work directory>-# Light units were measured on a white plane: sun strength equals irradiance, and a point light has 4 pi watts for each-# unit of 67.js intensity.+# Light units were measured on a white plane: sun strength equals irradiance, a point or spot light has 4 pi watts for each+# unit of 67.js intensity, and an area light has pi watts for each unit.import base64import jsonimport math@@ -18,6 +18,7 @@ HEIGHT = 540CYCLES_SAMPLES = 256EEVEE_SAMPLES = 64WATTS_PER_INTENSITY = 4 * math.pi+WATTS_PER_AREA_INTENSITY = math.piSUN_ANGLE = math.radians(1)# 67.js is Y up, and Blender is Z up.Y_UP_TO_Z_UP = Matrix(((1, 0, 0, 0), (0, 0, -1, 0), (0, 1, 0, 0), (0, 0, 0, 1)))@@ -205,6 +206,52 @@ 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)+ for index, spot in enumerate(environment.get("spotLights", [])):+ build_spot_light(scene, index, spot)+ for index, area in enumerate(environment.get("areaLights", [])):+ build_area_light(scene, index, area)+++def build_spot_light(scene, index, spot):+ # A Blender spot light has the watts of a point light of the same strength, and its cone only masks that light.+ # Both use one cone mask: a smoothstep from the outer cosine to a penumbra fraction of the way to cosine 1.+ light = bpy.data.lights.new(f"Spot-{index}", "SPOT")+ light.energy = spot["intensity"] * WATTS_PER_INTENSITY+ light.color = spot["color"]+ light.shadow_soft_size = spot["radius"]+ light.spot_size = 2 * spot["angle"]+ light.spot_blend = spot["penumbra"]+ spot_object = bpy.data.objects.new(f"Spot-{index}", light)+ spot_object.location = to_blender(spot["position"])+ spot_object.rotation_mode = "QUATERNION"+ direction = Vector(to_blender(spot["direction"])).normalized()+ spot_object.rotation_quaternion = direction.to_track_quat("-Z", "Y")+ scene.collection.objects.link(spot_object)+++def build_area_light(scene, index, area):+ # Measured on a white plane: a Blender area light of W watts matches a 67.js area light of W / pi candela, and the+ # 67.js formula stays within about 1.2 percent on the axis from 0.2 m to 2 m for 1 m and 2 m squares.+ light = bpy.data.lights.new(f"Area-{index}", "AREA")+ light.energy = area["intensity"] * WATTS_PER_AREA_INTENSITY+ light.color = area["color"]+ light.shape = "RECTANGLE"+ light.size = area["width"]+ light.size_y = area["height"]+ area_object = bpy.data.objects.new(f"Area-{index}", light)+ area_object.location = to_blender(area["position"])+ normal = Vector(to_blender(area["direction"])).normalized()+ up = Vector(to_blender(area.get("up", [0, 1, 0]))).normalized()+ width_axis = up.cross(normal)+ if width_axis.length < 1e-3:+ width_axis = Vector((1, 0, 0))+ width_axis.normalize()+ height_axis = width_axis.cross(normal)+ # The light shines toward its local -Z, and the 67.js rectangle faces along its direction.+ rotation = Matrix((width_axis, height_axis, -normal)).transposed()+ area_object.rotation_mode = "QUATERNION"+ area_object.rotation_quaternion = rotation.to_quaternion()+ scene.collection.objects.link(area_object)def build_fog(scene, fog):diff --git a/bench/reference/scenes.js b/bench/reference/scenes.jsindex 905617e0..bc1e3445 100644--- a/bench/reference/scenes.js+++ b/bench/reference/scenes.js@@ -39,9 +39,9 @@ function constantLighting(value) {return { map, blenderWorld: { type: 'constant', value } };}-function environment(lighting, { lightDirection = [-3, 6, 4], keyColor = [0, 0, 0], pointLights = [], volumeFog } = {}) {+function environment(lighting, { lightDirection = [-3, 6, 4], keyColor = [0, 0, 0], pointLights = [], spotLights = [], areaLights = [], volumeFog } = {}) {return {- world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0, lightDirection, keyColor, pointLights,+ world: true, fillIntensity: 0, ambientIntensity: 1, fogDensity: 0, lightDirection, keyColor, pointLights, spotLights, areaLights,map: lighting.map, ...(volumeFog ? { volumeFog } : {}),};}@@ -82,9 +82,9 @@ export const REFERENCE_SCENES = {part('block', cube, [0.6, 1, -1], [0.4, 0.5, 0.4], { color: [0.75, 0.7, 0.2], roughness: 0.5 }),];const pointLights = [- { position: [0, 2.6, -0.5], color: [1, 0.9, 0.75], intensity: 8, radius: 0.05 },- { position: [-2.5, 1.5, 1.5], color: [1, 0.6, 0.4], intensity: 2, radius: 0.05 },- { position: [2.5, 1.5, 1.5], color: [0.5, 0.7, 1], intensity: 2, radius: 0.05 },+ { position: [0, 2.6, -0.5], color: [1, 0.9, 0.75], intensity: 8, radius: 0.05, castShadow: true },+ { position: [-2.5, 1.5, 1.5], color: [1, 0.6, 0.4], intensity: 2, radius: 0.05, castShadow: true },+ { position: [2.5, 1.5, 1.5], color: [0.5, 0.7, 1], intensity: 2, radius: 0.05, castShadow: true },];return {parts, blenderWorld: lighting.blenderWorld,@@ -93,6 +93,31 @@ export const REFERENCE_SCENES = {};},+ // A shadowing spot light with a soft cone edge and a rectangular panel, over objects that block the spot.+ async 'spot-area'() {+ const lighting = constantLighting(0.01);+ const cube = box(0, 1);+ const wall = { color: [0.7, 0.68, 0.62], roughness: 0.9 };+ const parts = [+ part('stage-floor', cube, [0, -0.05, 0], [10, 0.1, 10], { color: [0.55, 0.5, 0.45], roughness: 0.7 }),+ part('stage-back', cube, [0, 1.5, -4.05], [10, 3.2, 0.1], wall),+ part('column', cube, [-0.9, 0.75, -1.5], [0.4, 1.5, 0.4], { color: [0.6, 0.6, 0.65], roughness: 0.5 }),+ part('ball', sphere(48, 32), [0.6, 0.5, -1], [0.5, 0.5, 0.5], { color: [0.8, 0.25, 0.2], roughness: 0.3 }),+ part('block', cube, [1.8, 0.3, -2], [0.6, 0.6, 0.6], { color: [0.2, 0.45, 0.75], roughness: 0.6 }),+ ];+ const spotLights = [+ { position: [-2.4, 3.2, 0.5], direction: [2.4, -3.2, -1.7], angle: 0.5, penumbra: 0.3, color: [1, 0.92, 0.8], intensity: 40, radius: 0.05, castShadow: true },+ ];+ const areaLights = [+ { position: [2.2, 2.6, 0], direction: [0, -1, 0], up: [0, 0, 1], width: 1.5, height: 0.8, color: [0.7, 0.8, 1], intensity: 4 },+ ];+ return {+ parts, blenderWorld: lighting.blenderWorld,+ environment: environment(lighting, { spotLights, areaLights }),+ camera: { eye: [0, 1.8, 4.5], target: [0, 0.7, -1.5], 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/budgets.json b/bench/size/budgets.jsonindex 6c3a53dd..74051c91 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -5,12 +5,12 @@"agent-scene": 100000},"budgets": {- "entry:core": 67100,+ "entry:core": 70130,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,"entry:canvas2d": 9400,- "entry:gltf": 44100,+ "entry:gltf": 45050,"entry:modeling": 6600,"entry:sculpt": 2500,"entry:surface": 74500,@@ -28,11 +28,11 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 95100,- "entry:agent-asset": 102600,+ "entry:agent-scene": 96320,+ "entry:agent-asset": 103700,"entry:hdri": 3300,- "scene:lit-box": 49800,- "scene:gltf-box": 68900,- "scene:agent-scene": 119700+ "scene:lit-box": 53165,+ "scene:gltf-box": 71874,+ "scene:agent-scene": 122195}}diff --git a/docs/lighting.md b/docs/lighting.mdindex a12c5ae8..a7b922f6 100644--- a/docs/lighting.md+++ b/docs/lighting.md@@ -73,7 +73,27 @@ Inputs must be finite numbers. Positions are within ±1,000,000 scene units. ColKey/fill/ambient intensity is between zero and 100. Key color components are between zero and 1,000. Large coordinates still inherit Float32 rendering precision limits.-Lights currently cast no local shadows and can illuminate through opaque walls. The original directional shadow map remains in use. Source-only [volume fog](volumetric.md) receives directional scattering and shadows. Point-light shadows and scattering, spotlights, area lights and indirect bounces remain unfinished.+A point light casts a shadow only with `castShadow: true` (see [Local shadows](#local-shadows)); without it the light can illuminate through opaque walls. The original directional shadow map remains in use. Source-only [volume fog](volumetric.md) receives directional scattering and shadows. Point-light scattering and indirect bounces remain unfinished.++## Spot lights++`environment.spotLights` holds at most eight lights. Each has `position` and `direction` (any nonzero length). Optional fields: `angle` (outer half angle in radians, 0.01 to just under pi/2, default pi/4), `penumbra` (0 to 1, default 0.15), `color`, `intensity`, `radius`, `range` and `castShadow`, with the point light defaults and limits.++`intensity` is candela, so a spot light and a point light of the same intensity give the same light inside the cone. The cone mask is a smoothstep from the outer cosine to `outer + (1 - outer) * penumbra`, which is Blender's spot blend, so a `bench/reference` Blender spot with `spot_size = 2 * angle` and `spot_blend = penumbra` matches. Falloff, `radius` and `range` work as for point lights.++## Area lights++`environment.areaLights` holds at most four 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.++## Local shadows++`castShadow: true` on a point or spot light draws that light's depth into one shared atlas of 2048 x 3072 texels: 24 tiles of 512 x 512, a 24 MiB depth texture allocated on first use. A spot light takes one tile with a perspective view of `2 * angle + 4` degrees (170 at most). A point light takes six tiles, one per cube face, each 92 degrees wide. Lights are given tiles in order: point lights, then spot lights. A request for more than 24 tiles, for example five shadowed point lights, throws `RangeError` and changes nothing. So the most is four shadowed point lights, or for example two point lights and eight spot lights.++Shadows 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.## Animation and resourcesdiff --git a/docs/parity.md b/docs/parity.mdindex bc84068b..b17f18d9 100644--- a/docs/parity.md+++ b/docs/parity.md@@ -188,7 +188,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.| Rendering > Render Engines > Cycles | missing | No path tracer and no render baking. | | #55, #57 || Rendering > Render Engines > Workbench | out of scope | A viewport engine for working by hand. | | || Rendering > Cameras | partial | Perspective, orthographic views, focal length and animated paths. There is no depth of field. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js) | #54 |-| Rendering > Lights > Light Objects | partial | One directional light with a shadow, and 8 point lights without shadows. There are no spot or area lights. | [lighting](../tests/lighting.test.js) | #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, 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 > World Environment | partial | Recipes have sky colors, daylight and fog. Code can load an HDRI, and recipes can not reach it. | [environment](../tests/environment.test.js) | #53 || Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps. There are no volume materials or displacement. | [texture-set](../tests/texture-set.test.js) | #50, #51 |diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex c6fa258f..6021230f 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -94,7 +94,28 @@ const environment = z.strictObject({intensity: bounded(0, 1e5).optional(),radius: bounded(0.001, 1e6).optional(),range: z.union([z.literal(0), bounded(0.001, 1e6)]).optional(),- })).max(8).optional().describe('Replace the entire list; [] removes all point lights. No local shadows.'),+ castShadow: z.boolean().optional().describe('Casts a cube shadow; uses 6 of the 24 shadow atlas tiles.'),+ })).max(8).optional().describe('Replace the entire list; [] removes all point lights. Intensity is candela: inverse-square falloff.'),+ spotLights: z.array(z.strictObject({+ position: boundedVector(-1e6, 1e6),+ direction: boundedVector(-1e6, 1e6).describe('Nonzero direction the cone points along.'),+ angle: bounded(0.01, Math.PI / 2 - 0.01).optional().describe('Outer half angle of the cone in radians; default pi/4.'),+ penumbra: unit.optional().describe('Fraction of the cone cosine range that fades out; 0 is a hard edge, default 0.15.'),+ color: color.optional(),+ intensity: bounded(0, 1e5).optional().describe('Candela, the same units as a point light.'),+ 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; uses 1 of the 24 shadow atlas tiles.'),+ })).max(8).optional().describe('Replace the entire list; [] removes all spot lights.'),+ areaLights: z.array(z.strictObject({+ position: boundedVector(-1e6, 1e6).describe('Center of the rectangle.'),+ direction: boundedVector(-1e6, 1e6).describe('Nonzero direction the rectangle faces; it emits to that side only.'),+ up: boundedVector(-1e6, 1e6).optional().describe('Sets which way the height axis runs; default world up.'),+ width: bounded(0.001, 1e4),+ height: bounded(0.001, 1e4),+ color: color.optional(),+ intensity: bounded(0, 1e5).optional().describe('Candela of the whole rectangle seen head on.'),+ })).max(4).optional().describe('Replace the entire list; [] removes all area lights. Area lights cast no shadow.'),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 827bf919..05d23935 100644--- a/skills/build-67js-scene/references/scene-contract.md+++ b/skills/build-67js-scene/references/scene-contract.md@@ -66,7 +66,10 @@ The environment provides `fogColor`, `fogDensity`, `skyTop`, `skyBottom`, `lightThe sky colors are display RGB. Fog colors are linear RGB.Local `environment.pointLights` support eight world-space sources with inverse-square falloff.-Each light provides `position` and optional `color`, `intensity`, `radius` and `range`.+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.+`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.`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.@@ -194,7 +197,7 @@ Bounds describe authored base geometry, not the deformed skin/morph silhouette.Read `docs/agent-look.md` for authored lighting, fog, effects and shadow coverage, included in npm `0.5.0`.Use atomic `set-environment`, `set-effects` and `set-shadow` partial records instead of editing renderer internals through MCP.-Nested `volumeFog` and `bloom` fields merge. The `pointLights` field replaces the full list. Point lights do not cast local shadows.+Nested `volumeFog` and `bloom` fields merge. The `pointLights`, `spotLights` and `areaLights` fields each replace the full list. Point and spot lights cast shadows only with `castShadow: true`; area lights never do.Volume fog requires opaque HDR/depth rendering. The preview adapter allocates depth support at creation and rejects unsupported fog before commit.Keep key-light direction aligned with the derived shadow projector. The optional addon exports `resolveAgentShadow` for custom adapters.diff --git a/src/agent-look.js b/src/agent-look.jsindex 62452847..f8326875 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -1,17 +1,19 @@import { mat4 } from 'gl-matrix';-import { createLightingState, updateLightingState, MAX_POINT_LIGHTS } from './lighting.js';+import { createLightingState, updateLightingState, MAX_POINT_LIGHTS, MAX_SPOT_LIGHTS, MAX_AREA_LIGHTS } from './lighting.js';import { resolveEffects } from './effects.js';import { resolveVolumeFog } from './volumetric.js';import { resolveLiquidOptics } from './renderer.js';const ENVIRONMENT_FIELDS = ['world', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',- 'daylight', 'pointLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid',+ 'daylight', 'pointLights', 'spotLights', 'areaLights', 'skyTop', 'skyBottom', 'fogColor', 'fogDensity', 'volumeFog', 'liquid',];const LIQUID_FIELDS = ['thickness', 'ior', 'refraction', 'scattering', 'foamOpacity', 'foamSoftness'];const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'bloom'];const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];-const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range'];+const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow'];+const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow'];+const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'color', 'intensity'];const VOLUME_VECTOR_FIELDS = ['minimum', 'maximum', 'color', 'ambient', 'drift'];const VOLUME_NUMBER_FIELDS = ['density', 'steps', 'anisotropy', 'noiseAmount', 'noiseScale', 'maxDistance'];const BLOOM_FIELDS = ['strength', 'threshold', 'radius'];@@ -100,15 +102,81 @@ function fallback(value, defaultValue) {return value === undefined ? defaultValue : value;}-function directionFrom(value) {- const direction = vectorInRange(value, -1e6, 1e6, 'lightDirection');+function directionFrom(value, label = 'lightDirection') {+ const direction = vectorInRange(value, -1e6, 1e6, label);const length = Math.hypot(...direction);if (length < 1e-6) {- throw new RangeError('lightDirection length must be at least 0.000001.');+ throw new RangeError(`${label} length must be at least 0.000001.`);}return { direction, unitDirection: direction.map(component => component / length) };}+function lightListFrom(value, maximum, name) {+ const lights = fallback(value, []);+ if (!Array.isArray(lights) || lights.length > maximum) {+ throw new RangeError(`${name} must contain at most ${maximum} lights.`);+ }+ return lights;+}++function rangeFrom(light, label) {+ const range = numberInRange(fallback(light.range, 0), 0, 1e6, `${label} range`);+ if (range !== 0 && range < 0.001) {+ throw new RangeError(`${label} range must be zero or at least 0.001.`);+ }+ return range;+}++// Only a light that casts shadows carries the field, so recipes without shadows keep their exported shape.+function shadowFieldFrom(light, label) {+ const castShadow = fallback(light.castShadow, false);+ if (typeof castShadow !== 'boolean') {+ throw new TypeError(`${label} castShadow must be boolean.`);+ }+ return castShadow ? { castShadow } : {};+}++function pointLightFrom(light) {+ knownKeys(light, POINT_LIGHT_FIELDS, 'point light');+ return {+ position: vectorInRange(light.position, -1e6, 1e6, 'point light position'),+ color: vectorInRange(fallback(light.color, [1, 1, 1]), 0, 1, 'point light color'),+ intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'point light intensity'),+ radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'point light radius'),+ range: rangeFrom(light, 'point light'),+ ...shadowFieldFrom(light, 'point light'),+ };+}++function spotLightFrom(light) {+ knownKeys(light, SPOT_LIGHT_FIELDS, 'spot light');+ return {+ position: vectorInRange(light.position, -1e6, 1e6, 'spot light position'),+ direction: directionFrom(light.direction, 'spot light direction').direction,+ angle: numberInRange(fallback(light.angle, Math.PI / 4), 0.01, Math.PI / 2 - 0.01, 'spot light angle'),+ penumbra: numberInRange(fallback(light.penumbra, 0.15), 0, 1, 'spot light penumbra'),+ color: vectorInRange(fallback(light.color, [1, 1, 1]), 0, 1, 'spot light color'),+ intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'spot light intensity'),+ radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'spot light radius'),+ range: rangeFrom(light, 'spot light'),+ ...shadowFieldFrom(light, 'spot light'),+ };+}++function areaLightFrom(light) {+ knownKeys(light, AREA_LIGHT_FIELDS, 'area light');+ const resolved = {+ position: vectorInRange(light.position, -1e6, 1e6, 'area light position'),+ direction: directionFrom(light.direction, 'area light direction').direction,+ width: numberInRange(light.width, 0.001, 1e4, 'area light width'),+ height: numberInRange(light.height, 0.001, 1e4, 'area light height'),+ color: vectorInRange(fallback(light.color, [1, 1, 1]), 0, 1, 'area light color'),+ 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;+}+function volumeFogFrom(input = {}) {knownKeys(input, [...VOLUME_VECTOR_FIELDS, ...VOLUME_NUMBER_FIELDS], 'volumeFog');for (const field of VOLUME_VECTOR_FIELDS) {@@ -130,10 +198,6 @@ function environmentFrom(input = {}) {if (typeof world !== 'boolean') {throw new TypeError('environment.world must be boolean.');}- const pointLights = fallback(input.pointLights, []);- if (!Array.isArray(pointLights) || pointLights.length > MAX_POINT_LIGHTS) {- throw new RangeError(`pointLights must contain at most ${MAX_POINT_LIGHTS} lights.`);- }const environment = {world,lightDirection: directionFrom(fallback(input.lightDirection, [-3, 6, 4])).direction,@@ -142,27 +206,20 @@ function environmentFrom(input = {}) {fillIntensity: numberInRange(fallback(input.fillIntensity, 1), 0, 100, 'fillIntensity'),ambientIntensity: numberInRange(fallback(input.ambientIntensity, 1), 0, 100, 'ambientIntensity'),daylight: numberInRange(fallback(input.daylight, 1), 0, 100, 'daylight'),- pointLights: pointLights.map(light => {- knownKeys(light, POINT_LIGHT_FIELDS, 'point light');- const range = numberInRange(fallback(light.range, 0), 0, 1e6, 'point light range');- if (range !== 0 && range < 0.001) {- throw new RangeError('Point light range must be zero or at least 0.001.');- }- return {- position: vectorInRange(light.position, -1e6, 1e6, 'point light position'),- color: vectorInRange(fallback(light.color, [1, 1, 1]), 0, 1, 'point light color'),- intensity: numberInRange(fallback(light.intensity, 1), 0, 1e5, 'point light intensity'),- radius: numberInRange(fallback(light.radius, 0.05), 0.001, 1e6, 'point light radius'),- range,- };- }),+ pointLights: lightListFrom(input.pointLights, MAX_POINT_LIGHTS, 'pointLights').map(pointLightFrom),skyTop: vectorInRange(fallback(input.skyTop, [0.2, 0.38, 0.52]), 0, 1, 'skyTop'),skyBottom: vectorInRange(fallback(input.skyBottom, [0.62, 0.7, 0.67]), 0, 1, 'skyBottom'),fogColor: vectorInRange(fallback(input.fogColor, [0.35, 0.43, 0.43]), 0, 1, 'fogColor'),fogDensity: numberInRange(fallback(input.fogDensity, 0.006), 0, 10, 'fogDensity'),volumeFog: volumeFogFrom(input.volumeFog),};- // Optional so recipes without liquids keep their exported shape.+ // Optional so recipes without these lights or liquids keep their exported shape.+ if (input.spotLights !== undefined) {+ environment.spotLights = lightListFrom(input.spotLights, MAX_SPOT_LIGHTS, 'spotLights').map(spotLightFrom);+ }+ if (input.areaLights !== undefined) {+ environment.areaLights = lightListFrom(input.areaLights, MAX_AREA_LIGHTS, 'areaLights').map(areaLightFrom);+ }if (input.liquid !== undefined) {knownKeys(input.liquid, LIQUID_FIELDS, 'liquid');environment.liquid = copiedJson(resolveLiquidOptics(copiedJson(input.liquid)));diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 792fd683..09462f2c 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -30,6 +30,11 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({materialPatterns: MATERIAL_PATTERN_TYPES, maxMaterialPatterns: MAX_MATERIAL_PATTERNS,fixedResources: false, dynamicTopology: true, checkpoints: true, positiveScaleOnly: true,authoredLook: true, maxPointLights: 8,+ // 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.+ maxSpotLights: 8, maxAreaLights: 4,+ localShadows: Object.freeze({ lights: Object.freeze(['pointLights', 'spotLights']), atlasTiles: 24, pointLightTiles: 6, spotLightTiles: 1, tileSize: 512 }),+ lightLinking: false,proceduralMotion: true,motionIk: Object.freeze(['two-bone', 'aim']),motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),diff --git a/src/agent-scene.js b/src/agent-scene.jsindex d767db71..5280641f 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -868,7 +868,9 @@ export function createAgentScene(input, inputLimits = {}) {if (lookField) {knownKeys(operation, ['type', lookField], 'operation');const patch = operation[lookField];- knownKeys(patch, Object.keys(candidate[lookField]), lookField);+ // Spot and area lights are absent from a recipe until it sets them.+ const optionalFields = lookField === 'environment' ? ['spotLights', 'areaLights'] : [];+ knownKeys(patch, [...Object.keys(candidate[lookField]), ...optionalFields], lookField);const nestedField = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;const merged = { ...candidate[lookField], ...patch };if (nestedField && Object.hasOwn(patch, nestedField)) {@@ -1033,6 +1035,8 @@ export function createAgentScene(input, inputLimits = {}) {look: {world: state.recipe.environment.world,pointLights: state.recipe.environment.pointLights.length,+ spotLights: state.recipe.environment.spotLights?.length ?? 0,+ areaLights: state.recipe.environment.areaLights?.length ?? 0,volumeFogDensity: state.recipe.environment.volumeFog.density,exposure: state.recipe.effects.exposure,},diff --git a/src/lighting.js b/src/lighting.jsindex 6e2814bb..2acb6a32 100644--- a/src/lighting.js+++ b/src/lighting.js@@ -1,4 +1,14 @@export const MAX_POINT_LIGHTS = 8;+export const MAX_SPOT_LIGHTS = 8;+export const MAX_AREA_LIGHTS = 4;+// One 2048 x 3072 depth atlas holds 24 tiles of 512 x 512 (24 MiB). A shadowed spot light uses one tile and a shadowed point+// light uses six, one for each cube face.+export const SHADOW_ATLAS_TILES = 24;+export const POINT_SHADOW_TILES = 6;+export const NO_SHADOW_TILE = -1;+export const SPOT_FACE = -1;+const SPOT_MAXIMUM_ANGLE = Math.PI / 2 - 0.01;+const SPOT_COSINE_GAP = 1e-4;function numberInRange(value, minimum, maximum, name) {if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {@@ -13,43 +23,113 @@ function vectorInRange(value, minimum, maximum, name) {return value;}+function lightList(environment, field, maximum) {+ const lights = environment[field] ?? [];+ if (!Array.isArray(lights) || lights.length > maximum) {+ throw new RangeError(`${field} must be an array of at most ${maximum} lights`);+ }+ return lights;+}++function lightObject(light, name) {+ if (!light || typeof light !== 'object' || Array.isArray(light)) throw new TypeError(`${name} must be an object`);+ return light;+}++function validateRange(light, name) {+ const range = light.range ?? 0;+ numberInRange(range, 0, 1e6, `${name} range`);+ if (range !== 0 && range < 0.001) throw new RangeError(`${name} range must be zero or at least 0.001`);+}++function validateCastShadow(light, name) {+ if (light.castShadow !== undefined && typeof light.castShadow !== 'boolean') throw new TypeError(`${name} castShadow must be true or false`);+}++function normalizedDirection(direction, name) {+ vectorInRange(direction, -1e6, 1e6, name);+ const length = Math.hypot(direction[0], direction[1], direction[2]);+ if (length < 1e-6) throw new RangeError(`${name} must not be zero length`);+ return [direction[0] / length, direction[1] / length, direction[2] / length];+}++function validatePointLight(light) {+ lightObject(light, 'Point light');+ vectorInRange(light.position, -1e6, 1e6, 'Point light position');+ vectorInRange(light.color ?? [1, 1, 1], 0, 1, 'Point light color');+ numberInRange(light.intensity ?? 1, 0, 1e5, 'Point light intensity');+ numberInRange(light.radius ?? 0.05, 0.001, 1e6, 'Point light radius');+ validateRange(light, 'Point light');+ validateCastShadow(light, 'Point light');+}++function validateSpotLight(light) {+ lightObject(light, 'Spot light');+ vectorInRange(light.position, -1e6, 1e6, 'Spot light position');+ normalizedDirection(light.direction, 'Spot light direction');+ vectorInRange(light.color ?? [1, 1, 1], 0, 1, 'Spot light color');+ numberInRange(light.intensity ?? 1, 0, 1e5, 'Spot light intensity');+ numberInRange(light.radius ?? 0.05, 0.001, 1e6, 'Spot light radius');+ numberInRange(light.angle ?? Math.PI / 4, 0.01, SPOT_MAXIMUM_ANGLE, 'Spot light angle');+ numberInRange(light.penumbra ?? 0.15, 0, 1, 'Spot light penumbra');+ validateRange(light, 'Spot light');+ validateCastShadow(light, 'Spot light');+}++function validateAreaLight(light) {+ lightObject(light, 'Area light');+ vectorInRange(light.position, -1e6, 1e6, 'Area light position');+ const direction = normalizedDirection(light.direction, 'Area light direction');+ const up = normalizedDirection(light.up ?? [0, 1, 0], 'Area light up');+ const alignment = Math.abs(direction[0] * up[0] + direction[1] * up[1] + direction[2] * up[2]);+ if (alignment > 0.999 && light.up !== undefined) throw new RangeError('Area light up must not be parallel to its direction');+ vectorInRange(light.color ?? [1, 1, 1], 0, 1, 'Area light color');+ 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');+}++// 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) {+ 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;+ 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)`);+ }+ return tiles;+}+export function createLightingState() {return {positions: new Float32Array(MAX_POINT_LIGHTS * 4),colors: new Float32Array(MAX_POINT_LIGHTS * 4),radii: new Float32Array(MAX_POINT_LIGHTS),+ pointShadows: new Float32Array(MAX_POINT_LIGHTS),+ spotPositions: new Float32Array(MAX_SPOT_LIGHTS * 4),+ spotColors: new Float32Array(MAX_SPOT_LIGHTS * 4),+ spotDirections: new Float32Array(MAX_SPOT_LIGHTS * 4),+ spotParameters: new Float32Array(MAX_SPOT_LIGHTS * 4),+ areaPositions: new Float32Array(MAX_AREA_LIGHTS * 4),+ areaColors: new Float32Array(MAX_AREA_LIGHTS * 4),+ areaNormals: new Float32Array(MAX_AREA_LIGHTS * 4),+ areaTangents: new Float32Array(MAX_AREA_LIGHTS * 4),+ // The lights that own atlas tiles, so the renderer can build each tile's view.+ shadowCasters: [],keyColor: new Float32Array(3),pointCount: 0,+ spotCount: 0,+ areaCount: 0,fillIntensity: 1,ambientIntensity: 1,};}-// Preflight before publishing so malformed later lights cannot corrupt retained uniforms.-export function updateLightingState(state, environment, { world = false } = {}) {- const pointLights = environment.pointLights ?? [];- if (!Array.isArray(pointLights) || pointLights.length > MAX_POINT_LIGHTS) {- throw new RangeError(`pointLights must be an array of at most ${MAX_POINT_LIGHTS} lights`);- }- const keyIntensity = numberInRange(environment.keyIntensity ?? 1, 0, 100, 'Key intensity');- const fillIntensity = numberInRange(environment.fillIntensity ?? 1, 0, 100, 'Fill intensity');- const ambientIntensity = numberInRange(environment.ambientIntensity ?? 1, 0, 100, 'Ambient intensity');- const daylight = numberInRange(environment.daylight ?? 1, 0, 100, 'Daylight');- const keyColor = environment.keyColor ?? (world ? [3.7 * daylight, 3.4 * daylight, 2.9 * daylight] : [5.2, 4.7, 4.1]);- vectorInRange(keyColor, 0, 1000, 'Key color');- for (const light of pointLights) {- if (!light || typeof light !== 'object' || Array.isArray(light)) throw new TypeError('Point light must be an object');- vectorInRange(light.position, -1e6, 1e6, 'Point light position');- vectorInRange(light.color ?? [1, 1, 1], 0, 1, 'Point light color');- numberInRange(light.intensity ?? 1, 0, 1e5, 'Point light intensity');- numberInRange(light.radius ?? 0.05, 0.001, 1e6, 'Point light radius');- const range = light.range ?? 0;- numberInRange(range, 0, 1e6, 'Point light range');- if (range !== 0 && range < 0.001) throw new RangeError('Point light range must be zero or at least 0.001');- }+function writePointLights(state, pointLights) {state.positions.fill(0);state.colors.fill(0);state.radii.fill(0);+ state.pointShadows.fill(NO_SHADOW_TILE);for (let index = 0; index < pointLights.length; index++) {const light = pointLights[index];state.positions.set(light.position, index * 4);@@ -57,9 +137,86 @@ export function updateLightingState(state, environment, { world = false } = {})state.colors.set(light.color ?? [1, 1, 1], index * 4);state.colors[index * 4 + 3] = light.intensity ?? 1;state.radii[index] = light.radius ?? 0.05;+ if (!light.castShadow) continue;+ state.pointShadows[index] = state.shadowCasters.length;+ for (let face = 0; face < POINT_SHADOW_TILES; face++) state.shadowCasters.push({ light, face });+ }+}++function writeSpotLights(state, spotLights) {+ state.spotPositions.fill(0);+ state.spotColors.fill(0);+ state.spotDirections.fill(0);+ state.spotParameters.fill(0);+ for (let index = 0; index < spotLights.length; index++) {+ const light = spotLights[index];+ const angle = light.angle ?? Math.PI / 4;+ const cosineOuter = Math.cos(angle);+ const cosineInner = cosineOuter + Math.max((1 - cosineOuter) * (light.penumbra ?? 0.15), SPOT_COSINE_GAP);+ state.spotPositions.set(light.position, index * 4);+ state.spotPositions[index * 4 + 3] = light.range ?? 0;+ state.spotColors.set(light.color ?? [1, 1, 1], index * 4);+ state.spotColors[index * 4 + 3] = light.intensity ?? 1;+ state.spotDirections.set(normalizedDirection(light.direction, 'Spot light direction'), index * 4);+ state.spotDirections[index * 4 + 3] = cosineOuter;+ state.spotParameters[index * 4] = light.radius ?? 0.05;+ state.spotParameters[index * 4 + 1] = cosineInner;+ state.spotParameters[index * 4 + 2] = NO_SHADOW_TILE;+ if (!light.castShadow) continue;+ state.spotParameters[index * 4 + 2] = state.shadowCasters.length;+ state.shadowCasters.push({ light, face: SPOT_FACE });}+}++function writeAreaLights(state, areaLights) {+ state.areaPositions.fill(0);+ state.areaColors.fill(0);+ state.areaNormals.fill(0);+ state.areaTangents.fill(0);+ for (let index = 0; index < areaLights.length; index++) {+ const light = areaLights[index];+ const normal = normalizedDirection(light.direction, 'Area light direction');+ const up = normalizedDirection(light.up ?? [0, 1, 0], 'Area light up');+ // The rectangle's width axis is up x normal, which keeps width horizontal for an upright light.+ let tangent = [up[1] * normal[2] - up[2] * normal[1], up[2] * normal[0] - up[0] * normal[2], up[0] * normal[1] - up[1] * normal[0]];+ let tangentLength = Math.hypot(...tangent);+ if (tangentLength < 1e-3) {+ tangent = [1, 0, 0];+ tangentLength = 1;+ }+ state.areaPositions.set(light.position, index * 4);+ state.areaColors.set(light.color ?? [1, 1, 1], index * 4);+ state.areaColors[index * 4 + 3] = light.intensity ?? 1;+ state.areaNormals.set(normal, index * 4);+ state.areaNormals[index * 4 + 3] = light.width;+ state.areaTangents.set(tangent.map(component => component / tangentLength), index * 4);+ state.areaTangents[index * 4 + 3] = light.height;+ }+}++// Preflight before publishing so malformed later lights cannot corrupt retained uniforms.+export function updateLightingState(state, environment, { world = false } = {}) {+ const pointLights = lightList(environment, 'pointLights', MAX_POINT_LIGHTS);+ const spotLights = lightList(environment, 'spotLights', MAX_SPOT_LIGHTS);+ const areaLights = lightList(environment, 'areaLights', MAX_AREA_LIGHTS);+ const keyIntensity = numberInRange(environment.keyIntensity ?? 1, 0, 100, 'Key intensity');+ const fillIntensity = numberInRange(environment.fillIntensity ?? 1, 0, 100, 'Fill intensity');+ const ambientIntensity = numberInRange(environment.ambientIntensity ?? 1, 0, 100, 'Ambient intensity');+ const daylight = numberInRange(environment.daylight ?? 1, 0, 100, 'Daylight');+ const keyColor = environment.keyColor ?? (world ? [3.7 * daylight, 3.4 * daylight, 2.9 * daylight] : [5.2, 4.7, 4.1]);+ vectorInRange(keyColor, 0, 1000, 'Key color');+ pointLights.forEach(validatePointLight);+ spotLights.forEach(validateSpotLight);+ areaLights.forEach(validateAreaLight);+ countShadowTiles(pointLights, spotLights);+ state.shadowCasters = [];+ writePointLights(state, pointLights);+ writeSpotLights(state, spotLights);+ writeAreaLights(state, areaLights);for (let axis = 0; axis < 3; axis++) state.keyColor[axis] = keyColor[axis] * keyIntensity;state.pointCount = pointLights.length;+ state.spotCount = spotLights.length;+ state.areaCount = areaLights.length;state.fillIntensity = fillIntensity;state.ambientIntensity = ambientIntensity;return state;diff --git a/src/local-shadows.js b/src/local-shadows.jsnew file mode 100644index 00000000..05834a0d--- /dev/null+++ b/src/local-shadows.js@@ -0,0 +1,43 @@+import { mat4 } from 'gl-matrix';+import { SPOT_FACE } from './lighting.js';++export const SHADOW_ATLAS_WIDTH = 2048;+export const SHADOW_ATLAS_HEIGHT = 3072;+export const SHADOW_TILE_SIZE = 512;+export const SHADOW_TILES_PER_ROW = SHADOW_ATLAS_WIDTH / SHADOW_TILE_SIZE;+const NEAR_PLANE = 0.05;+// Without a range, a light shadows what is within this distance. Farther surfaces are lit as if nothing blocked them.+const DEFAULT_SHADOW_DISTANCE = 30;+// A cube face is a little wider than 90 degrees, so filtering at the edge of a tile never reads another face.+const FACE_FIELD_OF_VIEW = (92 * Math.PI) / 180;+const SPOT_FIELD_OF_VIEW_MARGIN = (4 * Math.PI) / 180;+const MAXIMUM_SPOT_FIELD_OF_VIEW = (170 * Math.PI) / 180;+// Order matches the face index the fragment shader picks: +X, -X, +Y, -Y, +Z, -Z.+const FACE_DIRECTIONS = [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]];+const FACE_UPS = [[0, 1, 0], [0, 1, 0], [0, 0, 1], [0, 0, -1], [0, 1, 0], [0, 1, 0]];++function spotUp(direction) {+ return Math.abs(direction[1]) > 0.99 ? [1, 0, 0] : [0, 1, 0];+}++// Writes the view-projection of one atlas tile and returns the angle one shadow texel covers, in radians.+export function writeShadowTile({ light, face }, target) {+ const far = light.range > 0 ? light.range : DEFAULT_SHADOW_DISTANCE;+ const isSpot = face === SPOT_FACE;+ const fieldOfView = isSpot+ ? Math.min(2 * (light.angle ?? Math.PI / 4) + SPOT_FIELD_OF_VIEW_MARGIN, MAXIMUM_SPOT_FIELD_OF_VIEW)+ : FACE_FIELD_OF_VIEW;+ const direction = isSpot ? light.direction : FACE_DIRECTIONS[face];+ const up = isSpot ? spotUp(direction) : FACE_UPS[face];+ const lookTarget = [light.position[0] + direction[0], light.position[1] + direction[1], light.position[2] + direction[2]];+ const view = mat4.lookAt(mat4.create(), light.position, lookTarget, up);+ const projection = mat4.perspective(mat4.create(), fieldOfView, 1, NEAR_PLANE, far);+ mat4.multiply(target, projection, view);+ return 2 * Math.tan(fieldOfView / 2) / SHADOW_TILE_SIZE;+}++export function tileViewport(tileIndex) {+ const column = tileIndex % SHADOW_TILES_PER_ROW;+ const row = Math.floor(tileIndex / SHADOW_TILES_PER_ROW);+ return [column * SHADOW_TILE_SIZE, row * SHADOW_TILE_SIZE, SHADOW_TILE_SIZE, SHADOW_TILE_SIZE];+}diff --git a/src/renderer.js b/src/renderer.jsindex 9d296b82..c7a4a4db 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -5,6 +5,7 @@ import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budgimport { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';import { createLightingState, updateLightingState } from './lighting.js';+import { SHADOW_ATLAS_WIDTH, SHADOW_ATLAS_HEIGHT, tileViewport, writeShadowTile } from './local-shadows.js';import { resolveVolumeFog } from './volumetric.js';import { assertEnvironmentMap, createEnvironmentResources, environmentBackgroundFragment, environmentBrdfFragment, environmentPrefilterFragment, estimateEnvironmentBytes } from './environment.js';import { validateSkinGeometry, validateSkinPose, skinTextureLayout, packSkinInfluences } from './skinning.js';@@ -31,6 +32,14 @@ const MAP_SHADER_FEATURES = ['baseMap', 'normalMap', 'metallicRoughnessMap', 'oc// Tags whose look the main fragment shader draws with code that other tags never reach.const TAG_SHADER_FEATURES = new Set(['floor', 'water', 'foliage', 'terrain', 'grass', 'fire', 'smoke', 'unlit']);+function shaderFeaturesOfLighting(lighting) {+ const features = [];+ if (lighting.spotCount > 0) features.push('spotLights');+ if (lighting.areaCount > 0) features.push('areaLights');+ if (lighting.shadowCasters.length > 0) features.push('localShadows');+ return features;+}+function shaderFeaturesOfParts(parts) {const features = new Set();for (const { material } of parts) {@@ -77,6 +86,11 @@ const SPLAT_COLOR_UNIT = 11;const SPLAT_NORMAL_UNIT = 12;const SPLAT_PACKED_UNIT = 13;const SPLAT_MASK_UNIT = 14;+const LOCAL_SHADOW_UNIT = 15;+const LIGHT_UNIFORMS = ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'pointLightShadowTiles[0]',+ 'spotLightCount', 'spotLightPositions[0]', 'spotLightColors[0]', 'spotLightDirections[0]', 'spotLightParameters[0]',+ 'areaLightCount', 'areaLightPositions[0]', 'areaLightColors[0]', 'areaLightNormals[0]', 'areaLightTangents[0]',+ 'localShadowAtlas', 'localShadowMatrices[0]', 'localShadowTexelAngles[0]', 'keyColor', 'fillIntensity', 'ambientIntensity'];const SPLAT_UNIFORMS = ['splatEnabled', 'splatColor', 'splatNormal', 'splatPacked', 'splatMask', 'splatLayer[0]', 'splatTint[0]', 'splatSlope[0]', 'splatHeightRange[0]', 'splatMaskChannel[0]', 'splatMaskInvert[0]', 'splatBlend', 'splatOptions', 'splatMaskBounds', 'splatVariation'];function validateMaterialMaps(material) {@@ -426,6 +440,7 @@ export class Renderer67 {this.lightProjection = mat4.create();this.inverseViewProjection = mat4.create();this.shaderFeatures = shaderFeaturesOfParts(groups.flat());+ shaderFeaturesOfLighting(this.lighting).forEach(feature => this.shaderFeatures.add(feature));const pending = {main: this.startMainProgram(),depth: startProgram(this.context, depthVertexShader, depthFragmentShader),@@ -495,7 +510,7 @@ export class Renderer67 {finishMainProgram(pendingProgram) {this.program = finishProgram(this.context, pendingProgram);this.uniforms = Object.fromEntries(['boxMapScale', 'boxMapAxis', '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', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));- for (const name of ['pointLightCount', 'pointLightPositions[0]', 'pointLightColors[0]', 'pointLightRadii[0]', 'keyColor', 'fillIntensity', 'ambientIntensity']) {+ for (const name of LIGHT_UNIFORMS) {this.uniforms[name] = this.context.getUniformLocation(this.program, name);}for (const name of ENVIRONMENT_UNIFORMS) this.uniforms[name] = this.context.getUniformLocation(this.program, name);@@ -641,8 +656,12 @@ export class Renderer67 {// Parts can arrive after construction (replaceParts) or change their tag (updateParts). When one needs a shader feature// that the program left out, the program is compiled again with that feature added.requireShaderFeatures(parts) {+ this.requireFeatureNames([...shaderFeaturesOfParts(parts)]);+ }++ requireFeatureNames(features) {if (this.benchmark || !this.shaderFeatures) return;- const missing = [...shaderFeaturesOfParts(parts)].filter(feature => !this.shaderFeatures.has(feature));+ const missing = features.filter(feature => !this.shaderFeatures.has(feature));if (missing.length === 0) return;missing.forEach(feature => this.shaderFeatures.add(feature));this.rebuildMainProgram();@@ -1010,8 +1029,16 @@ export class Renderer67 {context.enable(context.DEPTH_TEST);context.enable(context.CULL_FACE);context.clear(context.DEPTH_BUFFER_BIT);+ this.drawShadowCasters();+ context.bindFramebuffer(context.FRAMEBUFFER, null);+ this.shadowsDirty = false;+ }++ // Draws every shadow-casting batch into the bound depth target with this.lightProjection.+ drawShadowCasters(lightMatrix = this.lightProjection) {+ const context = this.context;context.useProgram(this.depthProgram);- context.uniformMatrix4fv(this.depthUniform, false, this.lightProjection);+ context.uniformMatrix4fv(this.depthUniform, false, lightMatrix);context.uniform1f(this.depthAssemblyUniform, this.assemblyAmount ?? 0);context.uniform1f(this.depthWindUniforms.time, this.windState.time);context.uniform1f(this.depthWindUniforms.wind, this.windState.strength);@@ -1022,8 +1049,54 @@ export class Renderer67 {for (const batch of this.batches) if (!batch.floor && batch.castShadow) this.drawAlphaBatch(batch, false);context.disable(context.POLYGON_OFFSET_FILL);context.enable(context.CULL_FACE);+ }++ allocateLocalShadowAtlas() {+ const context = this.context;+ this.localShadowTexture = context.createTexture();+ context.activeTexture(context.TEXTURE0 + LOCAL_SHADOW_UNIT);+ context.bindTexture(context.TEXTURE_2D, this.localShadowTexture);+ context.texImage2D(context.TEXTURE_2D, 0, context.DEPTH_COMPONENT24, SHADOW_ATLAS_WIDTH, SHADOW_ATLAS_HEIGHT, 0, context.DEPTH_COMPONENT, context.UNSIGNED_INT, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_S, context.CLAMP_TO_EDGE);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_WRAP_T, context.CLAMP_TO_EDGE);+ this.localShadowFramebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, this.localShadowFramebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.TEXTURE_2D, this.localShadowTexture, 0);+ context.drawBuffers([context.NONE]);+ context.readBuffer(context.NONE);+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) throw new Error('Local shadow framebuffer is incomplete.');+ context.activeTexture(context.TEXTURE0);+ }++ // Builds the view of each atlas tile, and draws the atlas again only when a light moved or the casters changed.+ updateLocalShadows(casterChanged) {+ const casters = this.lighting.shadowCasters;+ if (casters.length === 0 || this.benchmark) return;+ const matrices = this.localShadowMatrices ??= new Float32Array(24 * 16);+ const texelAngles = this.localShadowTexelAngles ??= new Float32Array(24);+ const previous = this.localShadowPreviousMatrices ??= new Float32Array(24 * 16);+ const tileMatrix = new Float32Array(16);+ casters.forEach((caster, tile) => {+ texelAngles[tile] = writeShadowTile(caster, tileMatrix);+ matrices.set(tileMatrix, tile * 16);+ });+ const moved = casters.length !== this.localShadowTileCount || matrices.some((value, index) => value !== previous[index]);+ if (!moved && !casterChanged && this.localShadowTexture) return;+ previous.set(matrices);+ this.localShadowTileCount = casters.length;+ const context = this.context;+ if (!this.localShadowTexture) this.allocateLocalShadowAtlas();+ context.bindFramebuffer(context.FRAMEBUFFER, this.localShadowFramebuffer);+ context.viewport(0, 0, SHADOW_ATLAS_WIDTH, SHADOW_ATLAS_HEIGHT);+ context.enable(context.DEPTH_TEST);+ context.clear(context.DEPTH_BUFFER_BIT);+ for (let tile = 0; tile < casters.length; tile++) {+ context.viewport(...tileViewport(tile));+ this.drawShadowCasters(matrices.subarray(tile * 16, tile * 16 + 16));+ }context.bindFramebuffer(context.FRAMEBUFFER, null);- this.shadowsDirty = false;}/** Stores the wind time and strength the shadow pass must use; true when swaying batches need a new shadow map. */@@ -1530,10 +1603,13 @@ export class Renderer67 {const assemblyAmount = Math.max(0, Math.min(1, frame.assemblyAmount ?? 0));// Swaying foliage moves every frame, so its shadow map is redrawn whenever time or wind changes.const windChanged = this.updateWindState(frame);- if (this.assemblyAmount !== assemblyAmount || this.shadowsDirty || windChanged) {+ const casterChanged = this.assemblyAmount !== assemblyAmount || this.shadowsDirty || windChanged;+ this.requireFeatureNames(shaderFeaturesOfLighting(this.lighting));+ if (casterChanged) {this.assemblyAmount = assemblyAmount;this.createShadowMap();}+ this.updateLocalShadows(casterChanged);const environmentMap = this.activateEnvironment(environment.map);applyProjection(this.projection, frame, this.canvas.width / this.canvas.height, { world: this.world });mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);@@ -1564,6 +1640,7 @@ export class Renderer67 {context.uniform4fv(this.uniforms['pointLightPositions[0]'], this.lighting.positions);context.uniform4fv(this.uniforms['pointLightColors[0]'], this.lighting.colors);context.uniform1fv(this.uniforms['pointLightRadii[0]'], this.lighting.radii);+ this.applyLocalLightUniforms();context.uniform3fv(this.uniforms.keyColor, this.lighting.keyColor);context.uniform1f(this.uniforms.fillIntensity, this.lighting.fillIntensity);context.uniform1f(this.uniforms.ambientIntensity, this.lighting.ambientIntensity);@@ -1599,8 +1676,34 @@ export class Renderer67 {this.cpuMilliseconds = performance.now() - start;}+ applyLocalLightUniforms() {+ const context = this.context;+ const lighting = this.lighting;+ const uniforms = this.uniforms;+ context.uniform1fv(uniforms['pointLightShadowTiles[0]'], lighting.pointShadows);+ context.uniform1i(uniforms.spotLightCount, lighting.spotCount);+ context.uniform4fv(uniforms['spotLightPositions[0]'], lighting.spotPositions);+ context.uniform4fv(uniforms['spotLightColors[0]'], lighting.spotColors);+ context.uniform4fv(uniforms['spotLightDirections[0]'], lighting.spotDirections);+ context.uniform4fv(uniforms['spotLightParameters[0]'], lighting.spotParameters);+ context.uniform1i(uniforms.areaLightCount, lighting.areaCount);+ context.uniform4fv(uniforms['areaLightPositions[0]'], lighting.areaPositions);+ context.uniform4fv(uniforms['areaLightColors[0]'], lighting.areaColors);+ context.uniform4fv(uniforms['areaLightNormals[0]'], lighting.areaNormals);+ context.uniform4fv(uniforms['areaLightTangents[0]'], lighting.areaTangents);+ if (lighting.shadowCasters.length === 0 || !this.localShadowTexture) return;+ context.uniformMatrix4fv(uniforms['localShadowMatrices[0]'], false, this.localShadowMatrices);+ context.uniform1fv(uniforms['localShadowTexelAngles[0]'], this.localShadowTexelAngles);+ context.activeTexture(context.TEXTURE0 + LOCAL_SHADOW_UNIT);+ context.bindTexture(context.TEXTURE_2D, this.localShadowTexture);+ context.uniform1i(uniforms.localShadowAtlas, LOCAL_SHADOW_UNIT);+ context.activeTexture(context.TEXTURE0);+ }+dispose() {this.releaseFrameTargets();+ if (this.localShadowTexture) this.context.deleteTexture(this.localShadowTexture);+ if (this.localShadowFramebuffer) this.context.deleteFramebuffer(this.localShadowFramebuffer);this.batches.forEach((batch) => this.context.deleteVertexArray(batch.vertexArray));this.buffers.forEach((buffer) => this.context.deleteBuffer(buffer));this.geometryBuffers?.clear();diff --git a/src/shaders.js b/src/shaders.jsindex a2b9c687..5c8609c4 100644--- a/src/shaders.js+++ b/src/shaders.js@@ -357,6 +357,20 @@ uniform int pointLightCount;uniform vec4 pointLightPositions[8];uniform vec4 pointLightColors[8];uniform float pointLightRadii[8];+uniform float pointLightShadowTiles[8];+uniform int spotLightCount;+uniform vec4 spotLightPositions[8];+uniform vec4 spotLightColors[8];+uniform vec4 spotLightDirections[8];+uniform vec4 spotLightParameters[8];+uniform int areaLightCount;+uniform vec4 areaLightPositions[4];+uniform vec4 areaLightColors[4];+uniform vec4 areaLightNormals[4];+uniform vec4 areaLightTangents[4];+uniform sampler2D localShadowAtlas;+uniform mat4 localShadowMatrices[24];+uniform float localShadowTexelAngles[24];uniform vec3 keyColor;uniform float fillIntensity;uniform float ambientIntensity;@@ -448,6 +462,46 @@ float shadowVisibility(vec3 normal) {return visibility / 9.0;}+// Atlas tiles are 512 texels square on a 4 x 4 grid. The receiver is pushed off its surface by about two shadow texels,+// which removes acne without a depth bias that grows with distance.+float localShadowVisibility(float tile, vec3 position, vec3 normal, float lightDistance) {+ int tileIndex = int(tile);+ vec3 shifted = position + normal * (lightDistance * localShadowTexelAngles[tileIndex] * 2.0);+ vec4 clip = localShadowMatrices[tileIndex] * vec4(shifted, 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 - 0.5;+ ivec2 corner = ivec2(floor(pixel));+ vec2 blend = fract(pixel);+ float receiverDepth = projected.z - 0.00002;+ float lit[4];+ for (int tap = 0; tap < 4; tap++) {+ ivec2 texel = clamp(corner + ivec2(tap & 1, tap >> 1), ivec2(0), ivec2(511));+ lit[tap] = step(receiverDepth, texelFetch(localShadowAtlas, tileOrigin + texel, 0).r);+ }+ return mix(mix(lit[0], lit[1], blend.x), mix(lit[2], lit[3], blend.x), blend.y);+}++// Cube face of a point light's shadow, in the order +X, -X, +Y, -Y, +Z, -Z.+float pointShadowFace(vec3 fromLight) {+ vec3 magnitude = abs(fromLight);+ if (magnitude.x >= magnitude.y && magnitude.x >= magnitude.z) return fromLight.x < 0.0 ? 1.0 : 0.0;+ if (magnitude.y >= magnitude.z) return fromLight.y < 0.0 ? 3.0 : 2.0;+ return fromLight.z < 0.0 ? 5.0 : 4.0;+}++float localAttenuation(float distanceSquared, float range, float radius) {+ float cutoff = 1.0;+ if (range > 0.0) {+ float squaredRatio = distanceSquared / (range * range);+ float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);+ cutoff = fade * fade;+ }+ return cutoff / max(distanceSquared, radius * radius);+}+vec3 studio(vec3 direction, float roughness) {vec3 color = mix(vec3(0.025, 0.035, 0.045), vec3(0.22, 0.25, 0.27), smoothstep(-0.3, 0.8, direction.y));float blur = roughness * 0.35;@@ -666,19 +720,57 @@ void main() {vec3 offset = pointLightPositions[index].xyz - worldPosition;float distanceSquared = dot(offset, offset);if (distanceSquared < 1e-12 || pointLightColors[index].w == 0.0) continue;- float range = pointLightPositions[index].w;- float cutoff = 1.0;- if (range > 0.0) {- float squaredRatio = distanceSquared / (range * range);- float fade = max(1.0 - squaredRatio * squaredRatio, 0.0);- cutoff = fade * fade;- }- if (cutoff == 0.0) continue;- float radius = pointLightRadii[index];- float attenuation = cutoff / max(distanceSquared, radius * radius);+ float attenuation = localAttenuation(distanceSquared, pointLightPositions[index].w, pointLightRadii[index]);+ if (attenuation == 0.0) continue;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));+ }radiance += illuminate(normal, viewDirection, offset * inversesqrt(distanceSquared), lightRadiance, color, metallic, roughness);}+ if (USES_SPOT_LIGHTS) {+ for (int index = 0; index < 8; index++) {+ if (index >= spotLightCount) break;+ vec3 offset = spotLightPositions[index].xyz - worldPosition;+ float distanceSquared = dot(offset, offset);+ if (distanceSquared < 1e-12 || spotLightColors[index].w == 0.0) continue;+ vec3 toLight = offset * inversesqrt(distanceSquared);+ float coneCosine = dot(-toLight, spotLightDirections[index].xyz);+ // The same cone mask as Blender: smoothstep between the outer and inner cosines.+ 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;+ if (USES_LOCAL_SHADOWS && spotLightParameters[index].z >= 0.0) {+ lightRadiance *= localShadowVisibility(spotLightParameters[index].z, worldPosition, normal, sqrt(distanceSquared));+ }+ radiance += illuminate(normal, viewDirection, toLight, lightRadiance, color, metallic, roughness);+ }+ }+ if (USES_AREA_LIGHTS) {+ for (int index = 0; index < 4; index++) {+ if (index >= areaLightCount) break;+ 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;+ vec3 fromCenter = worldPosition - areaLightPositions[index].xyz;+ // Representative point: the closest point of the rectangle stands in for the whole source.+ vec3 closest = areaLightPositions[index].xyz+ + widthAxis * clamp(dot(fromCenter, widthAxis), -halfSize.x, halfSize.x)+ + heightAxis * clamp(dot(fromCenter, heightAxis), -halfSize.y, halfSize.y);+ vec3 offset = closest - worldPosition;+ float distanceSquared = dot(offset, offset);+ vec3 toLight = offset * inversesqrt(max(distanceSquared, 1e-12));+ float emission = max(dot(-toLight, lightNormal), 0.0);+ float area = 4.0 * halfSize.x * halfSize.y;+ // 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);+ }+ }vec3 reflectance = fresnel(max(dot(normal, viewDirection), 0.0), mix(vec3(0.04), color, metallic));float occlusion = 1.0;if (USES_OCCLUSION_MAP) occlusion = mix(1.0, texture(occlusionMap, textureUV).r, occlusionStrength);@@ -764,6 +856,9 @@ const SHADER_FEATURE_CONDITIONS = {fire: ['TAG_FIRE', 'surface.w == 8.0'],smoke: ['TAG_SMOKE', 'surface.w == 9.0'],unlit: ['TAG_UNLIT', 'surface.w == 10.0'],+ spotLights: ['USES_SPOT_LIGHTS', 'spotLightCount > 0'],+ areaLights: ['USES_AREA_LIGHTS', 'areaLightCount > 0'],+ localShadows: ['USES_LOCAL_SHADOWS', 'true'],};export const SHADER_FEATURES = Object.freeze(Object.keys(SHADER_FEATURE_CONDITIONS));diff --git a/tests/agent-look-lights.test.js b/tests/agent-look-lights.test.jsnew file mode 100644index 00000000..5327db54--- /dev/null+++ b/tests/agent-look-lights.test.js@@ -0,0 +1,29 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { normalizeAgentLook } from '../src/agent-look.js';++test('a default look omits spot and area lights so exported recipes keep their shape', () => {+ const { environment } = normalizeAgentLook();+ assert.equal(Object.hasOwn(environment, 'spotLights'), false);+ assert.equal(Object.hasOwn(environment, 'areaLights'), false);+ assert.equal(Object.hasOwn(environment.pointLights, 'castShadow'), false);+});++test('spot and area lights normalize with defaults and keep castShadow only when true', () => {+ const { environment } = normalizeAgentLook({ environment: {+ pointLights: [{ position: [0, 2, 0], castShadow: true }, { position: [1, 2, 0], castShadow: false }],+ spotLights: [{ position: [0, 3, 0], direction: [0, -1, 0], castShadow: true }],+ areaLights: [{ position: [0, 3, 0], direction: [0, -1, 0], width: 1, height: 2 }],+ } });+ assert.equal(environment.pointLights[0].castShadow, true);+ assert.equal(Object.hasOwn(environment.pointLights[1], 'castShadow'), false);+ assert.equal(environment.spotLights[0].angle, Math.PI / 4);+ assert.equal(environment.spotLights[0].penumbra, 0.15);+ assert.equal(environment.areaLights[0].width, 1);+});++test('look rejects an unknown spot light field and too many shadow casters', () => {+ assert.throws(() => normalizeAgentLook({ environment: { spotLights: [{ position: [0, 3, 0], direction: [0, -1, 0], cone: 1 }] } }), /Unknown spot light field/);+ const fivePointLights = [0, 1, 2, 3, 4].map(index => ({ position: [index, 1, 0], castShadow: true }));+ assert.throws(() => normalizeAgentLook({ environment: { pointLights: fivePointLights } }), /atlas/);+});diff --git a/tests/lighting.test.js b/tests/lighting.test.jsindex deb1d8a4..05f9c54a 100644--- a/tests/lighting.test.js+++ b/tests/lighting.test.js@@ -56,3 +56,61 @@ test('malformed later lights reject atomically before replacing any retained ligassert.throws(() => updateLightingState(state, { ambientIntensity: Infinity }));assert.deepEqual(state, snapshot);});++test('spot lights store a normalized direction and the Blender cone cosines', () => {+ const state = createLightingState();+ updateLightingState(state, { spotLights: [{ position: [0, 3, 0], direction: [0, -2, 0], angle: Math.PI / 3, penumbra: 0.5, intensity: 9 }] });+ assert.equal(state.spotCount, 1);+ assert.deepEqual(Array.from(state.spotDirections.slice(0, 3)), [0, -1, 0]);+ const cosineOuter = Math.cos(Math.PI / 3);+ assert.ok(Math.abs(state.spotDirections[3] - cosineOuter) < 1e-6);+ assert.ok(Math.abs(state.spotParameters[1] - (cosineOuter + (1 - cosineOuter) * 0.5)) < 1e-6);+ assert.equal(state.spotParameters[2], -1);+ assert.equal(state.spotColors[3], 9);+});++test('a hard-edged spot light keeps its inner cosine above the outer one', () => {+ const state = createLightingState();+ updateLightingState(state, { spotLights: [{ position: [0, 3, 0], direction: [0, -1, 0], penumbra: 0 }] });+ assert.ok(state.spotParameters[1] > state.spotDirections[3]);+});++test('shadow tiles go to point lights first, six for a point light and one for a spot light', () => {+ const state = createLightingState();+ updateLightingState(state, {+ spotLights: [{ position: [0, 3, 0], direction: [0, -1, 0], castShadow: true }],+ pointLights: [{ position: [1, 1, 1] }, { position: [2, 2, 2], castShadow: true }],+ });+ assert.equal(state.pointShadows[0], -1);+ assert.equal(state.pointShadows[1], 0);+ assert.equal(state.spotParameters[2], 6);+ assert.equal(state.shadowCasters.length, 7);+});++test('shadow casters beyond the 24 tile atlas are rejected before any state changes', () => {+ const state = createLightingState();+ updateLightingState(state, { pointLights: [{ position: [1, 1, 1] }] });+ const fivePointLights = [0, 1, 2, 3, 4].map(index => ({ position: [index, 1, 1], castShadow: true }));+ assert.throws(() => updateLightingState(state, { pointLights: fivePointLights }), /atlas/);+ assert.equal(state.pointCount, 1);+});++test('area lights store a unit normal and a width axis perpendicular to it', () => {+ const state = createLightingState();+ updateLightingState(state, { areaLights: [{ position: [0, 3, 0], direction: [0, -1, 0], up: [0, 0, 1], width: 2, height: 1, intensity: 5 }] });+ assert.equal(state.areaCount, 1);+ const normal = Array.from(state.areaNormals.slice(0, 3));+ const tangent = Array.from(state.areaTangents.slice(0, 3));+ assert.equal(normal[0] * tangent[0] + normal[1] * tangent[1] + normal[2] * tangent[2], 0);+ assert.equal(state.areaNormals[3], 2);+ assert.equal(state.areaTangents[3], 1);+ assert.equal(state.areaColors[3], 5);+});++test('malformed spot and area lights are rejected', () => {+ const state = createLightingState();+ assert.throws(() => updateLightingState(state, { spotLights: [{ position: [0, 0, 0], direction: [0, 0, 0] }] }), /zero length/);+ assert.throws(() => updateLightingState(state, { spotLights: [{ position: [0, 0, 0], direction: [0, -1, 0], angle: 2 }] }), /angle/);+ assert.throws(() => updateLightingState(state, { areaLights: [{ position: [0, 0, 0], direction: [0, -1, 0], width: 0, height: 1 }] }), /width/);+ assert.throws(() => updateLightingState(state, { areaLights: new Array(5).fill({ position: [0, 0, 0], direction: [0, -1, 0], width: 1, height: 1 }) }), /at most 4/);+});diff --git a/tests/reference-baseline.test.js b/tests/reference-baseline.test.jsindex bc076d05..bc9bc5ea 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 = ['character', 'fog', 'foliage', 'glass', 'lit-interior', 'material-spheres', 'metal', 'outdoor-hdri'];+const EXPECTED_SCENES = ['character', 'fog', 'foliage', 'glass', 'lit-interior', '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', () => {