3D engine that AI agents drive
Make the default look good without tuning
Nguyen Xuan An5aea701843d0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d195b037..2f4cc741 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,7 @@## Unreleased+- Make the default look good without tuning. Recipes get an image-based environment: `environment.setup` (`daylight` by default, `overcast`, `sunset`, `studio`) selects a small procedural sky map generated in code, plus its key light, with `environmentIntensity` and `environmentRotation`; no URLs or files from tool input. `effects.ambientOcclusion` (default `0.8`, `0` turns it off) and `ambientOcclusionRadius` add screen-space ambient occlusion from the depth texture; it compiles and allocates on first use and costs about 16 ms on a 190 ms SwiftShader frame (8 percent). `scene_capabilities` lists `lightingSetups`, `defaultLightingSetup` and `ambientOcclusion`. **This changes the look of every existing recipe that sets no lighting**: it now has an environment map, a key color of `[3, 2.8, 2.5]` instead of `[5.2, 4.7, 4.1]`, a fill intensity of `0` instead of `1`, and occlusion. The engine default is unchanged (occlusion off, no map) so code scenes keep their pixels. Reference scores against Cycles move by +0.0013 to -0.0019 in 8 of 9 scenes and by +0.0047 in `lit-interior`. Screen-space reflections are not part of this. Size budgets rise: `entry:core` +3,000, `entry:gltf` +500, `entry:agent-scene` +1,400, `entry:agent-asset` +1,300, `scene:lit-box` +3,500, `scene:gltf-box` +3,100, `scene:agent-scene` +3,100 (bytes gzip, about half of it spot and area light code from the lights branch)- Add ten cutting and repair edits: `fill_holes`, `dissolve_faces`, `dissolve_edges`, `dissolve_verts`, `dissolve_limited`, `bisect_plane` (with `fill`, `clearInner`, `clearOuter`), `bridge_edge_loops` (with `segments`), `subdivide_edges`, `grid_fill` and `knife_project`. Each tags what it makes, and the edge rule `{ "open": true }` picks boundary edges. The lint message for an open boundary now suggests `fill_holes`. 18 new cases match Blender in counts, face sizes, area, volume and positions; the knife is compared only with a straight plane cut and differs where a face runs along the projection direction- Export textures, skeletons and clips to GLB: `exportGlb(parts, { nodes, clips, maxTextureSize })` now writes `map`, `normalMap`, `metallicRoughnessMap`, `occlusionMap` and `emissiveMap` as embedded PNG (limit 2048 px by default, with an error that names the option), skins with joint nodes and inverse bind matrices, and animation clips (translation, rotation and scale tracks; SMOOTH becomes cubic with zero tangents). Pattern materials export their baked textures with box projected UVs, so the picture matches without `uv_unwrap`. It previously threw on skins and on every texture channel. The `entry:core` size budget goes from 67,100 to 70,500 bytes gzip (+3,400)- 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 34a029ca..f33ae801 100644--- a/bench/reference/README.md+++ b/bench/reference/README.md@@ -46,7 +46,8 @@ EEVEE against Cycles is a yardstick: it shows what a good rasterizer scores. In## Limits- Scores come from one camera for each scene and one machine. They do not measure motion or speed.-- 67.js reaches an HDRI only from code. A recipe can not set one yet, so these scores are better than what an agent gets today (issue #53).+- This suite sets an HDRI from code and turns occlusion on at the recipe default. A recipe reaches only the named procedural setups, so these scores still describe a better environment than an agent gets (issue #53).+- `character` has no new EEVEE render: Blender 5.2.2 crashed on that scene in `mesh_set_custom_normals` in every retry (a pre-existing crash that this change does not touch), so its EEVEE columns keep the earlier numbers.- The Blender leaf material has no translucency, and the 67.js foliage shader adds it by a trick. `foliage` is therefore partly a difference in materials.- `render-blender.py` does not read normal maps. No scene uses one yet, so a new scene with a normal map must add that first.- `glass` compares the 67.js `liquid` material with a Blender glass material. 67.js has no glass material (issue #51).diff --git a/bench/reference/baseline.json b/bench/reference/baseline.jsonindex 3a10752f..30982c0b 100644--- a/bench/reference/baseline.json+++ b/bench/reference/baseline.json@@ -1,120 +1,120 @@{- "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- }- },- "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- },- "spot-area": {- "gpu-vs-cycles": 0.1242,- "gpu-vs-eevee": 0.1707,- "cpu-vs-cycles": 0.1242,- "cpu-vs-eevee": 0.1709,- "eevee-vs-cycles": 0.1935,- "gpu-vs-cpu": 0.0032- }+ "metric": "FLIP (LDR), mean error, lower is better",+ "blenderVersion": "5.2.2 LTS",+ "seconds": {+ "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+ }+ },+ "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.1006,+ "gpu-vs-eevee": 0.0833,+ "cpu-vs-cycles": 0.1,+ "cpu-vs-eevee": 0.0826,+ "eevee-vs-cycles": 0.074,+ "gpu-vs-cpu": 0.0088+ },+ "fog": {+ "gpu-vs-cycles": 0.2623,+ "gpu-vs-eevee": 0.0557,+ "cpu-vs-cycles": 0.2619,+ "cpu-vs-eevee": 0.0557,+ "eevee-vs-cycles": 0.2662,+ "gpu-vs-cpu": 0.0088+ },+ "foliage": {+ "gpu-vs-cycles": 0.1575,+ "gpu-vs-eevee": 0.1362,+ "cpu-vs-cycles": 0.1572,+ "cpu-vs-eevee": 0.136,+ "eevee-vs-cycles": 0.0783,+ "gpu-vs-cpu": 0.0112+ },+ "glass": {+ "gpu-vs-cycles": 0.1446,+ "gpu-vs-eevee": 0.1467,+ "cpu-vs-cycles": 0.1442,+ "cpu-vs-eevee": 0.1468,+ "eevee-vs-cycles": 0.115,+ "gpu-vs-cpu": 0.0083+ },+ "lit-interior": {+ "gpu-vs-cycles": 0.5102,+ "gpu-vs-eevee": 0.0862,+ "cpu-vs-cycles": 0.5103,+ "cpu-vs-eevee": 0.0864,+ "eevee-vs-cycles": 0.5159,+ "gpu-vs-cpu": 0.0091+ },+ "material-spheres": {+ "gpu-vs-cycles": 0.1601,+ "gpu-vs-eevee": 0.1199,+ "cpu-vs-cycles": 0.1596,+ "cpu-vs-eevee": 0.1197,+ "eevee-vs-cycles": 0.1006,+ "gpu-vs-cpu": 0.0095+ },+ "metal": {+ "gpu-vs-cycles": 0.1877,+ "gpu-vs-eevee": 0.1574,+ "cpu-vs-cycles": 0.1879,+ "cpu-vs-eevee": 0.1577,+ "eevee-vs-cycles": 0.0934,+ "gpu-vs-cpu": 0.0084+ },+ "outdoor-hdri": {+ "gpu-vs-cycles": 0.0678,+ "gpu-vs-eevee": 0.0521,+ "cpu-vs-cycles": 0.0674,+ "cpu-vs-eevee": 0.0517,+ "eevee-vs-cycles": 0.0383,+ "gpu-vs-cpu": 0.0062+ },+ "spot-area": {+ "gpu-vs-cycles": 0.1255,+ "gpu-vs-eevee": 0.1697,+ "cpu-vs-cycles": 0.1254,+ "cpu-vs-eevee": 0.1698,+ "eevee-vs-cycles": 0.1935,+ "gpu-vs-cpu": 0.0047}+ }}diff --git a/bench/reference/harness.js b/bench/reference/harness.jsindex 7c3c1dde..4b3aa08c 100644--- a/bench/reference/harness.js+++ b/bench/reference/harness.js@@ -1,6 +1,7 @@// Runs in the page: draws one reference scene, and describes it as plain data for Blender.import { Renderer67 } from '/src/renderer.js';import { REFERENCE_SCENES } from './scenes.js';+import { DEFAULT_AMBIENT_OCCLUSION } from '/src/agent-scene-capabilities.js';function encodeBytes(typedArray) {const bytes = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);@@ -78,7 +79,7 @@ async function renderReferenceScene(id, { describe }) {environment: scene.environment, shadowBounds: scene.shadow,});renderer.resize();- const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: {} };+ const frame = { ...scene.camera, environment: scene.environment, time: 0, exposure: 1, effects: { ambientOcclusion: DEFAULT_AMBIENT_OCCLUSION } };renderer.render(frame);renderer.render(frame);const debug = renderer.context.getExtension('WEBGL_debug_renderer_info');diff --git a/bench/reference/images/fog.jpg b/bench/reference/images/fog.jpgindex fc059c2f..cda6b0ae 100644Binary files a/bench/reference/images/fog.jpg and b/bench/reference/images/fog.jpg differdiff --git a/bench/reference/images/foliage.jpg b/bench/reference/images/foliage.jpgindex f7211c79..26ec5c22 100644Binary files a/bench/reference/images/foliage.jpg and b/bench/reference/images/foliage.jpg differdiff --git a/bench/reference/images/glass.jpg b/bench/reference/images/glass.jpgindex b280c58b..b0c49c9f 100644Binary files a/bench/reference/images/glass.jpg and b/bench/reference/images/glass.jpg differdiff --git a/bench/reference/images/lit-interior.jpg b/bench/reference/images/lit-interior.jpgindex 8c9b91ed..ee489212 100644Binary files a/bench/reference/images/lit-interior.jpg and b/bench/reference/images/lit-interior.jpg differdiff --git a/bench/reference/images/material-spheres.jpg b/bench/reference/images/material-spheres.jpgindex 8e64566a..c228071c 100644Binary files a/bench/reference/images/material-spheres.jpg and b/bench/reference/images/material-spheres.jpg differdiff --git a/bench/reference/images/metal.jpg b/bench/reference/images/metal.jpgindex 48b06772..72ee46a3 100644Binary files a/bench/reference/images/metal.jpg and b/bench/reference/images/metal.jpg differdiff --git a/bench/reference/images/outdoor-hdri.jpg b/bench/reference/images/outdoor-hdri.jpgindex f0bc3297..b75d2aed 100644Binary files a/bench/reference/images/outdoor-hdri.jpg and b/bench/reference/images/outdoor-hdri.jpg differdiff --git a/bench/reference/images/spot-area.jpg b/bench/reference/images/spot-area.jpgindex ca687a0f..cbfd13e2 100644Binary files a/bench/reference/images/spot-area.jpg and b/bench/reference/images/spot-area.jpg differdiff --git a/bench/size/budgets.json b/bench/size/budgets.jsonindex 4a003581..1d4ac78f 100644--- a/bench/size/budgets.json+++ b/bench/size/budgets.json@@ -5,12 +5,12 @@"agent-scene": 100000},"budgets": {- "entry:core": 72900,+ "entry:core": 75900,"entry:model": 14400,"entry:nature": 13200,"entry:motion": 13600,"entry:canvas2d": 9400,- "entry:gltf": 44500,+ "entry:gltf": 45000,"entry:modeling": 6600,"entry:sculpt": 2500,"entry:surface": 10100,@@ -28,11 +28,11 @@"entry:grass": 4400,"entry:clutter": 5300,"entry:texture-set": 900,- "entry:agent-scene": 106700,- "entry:agent-asset": 114200,+ "entry:agent-scene": 108100,+ "entry:agent-asset": 115500,"entry:hdri": 3300,- "scene:lit-box": 50800,- "scene:gltf-box": 69900,- "scene:agent-scene": 132000+ "scene:lit-box": 54300,+ "scene:gltf-box": 73000,+ "scene:agent-scene": 135100}-}+}\ No newline at end of filediff --git a/docs/agent-look.md b/docs/agent-look.mdindex 63942de0..9a34eed9 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -105,12 +105,15 @@ Sky colors use display RGB, matching the renderer's existing environment contrac| Field | Default | Range or meaning || --- | --- | --- |-| `world` | `false` | Boolean world presentation flag |-| `lightDirection` | `[-3, 6, 4]` | Components within ±1000000, length at least `0.000001` |-| `keyColor` | `[5.2, 4.7, 4.1]` | Components from `0` to `1000` |+| `world` | `false` | Boolean world presentation flag. With `true` the setup environment is also the background |+| `setup` | `daylight` | `daylight`, `overcast`, `sunset` or `studio`. See Lighting setups |+| `environmentIntensity` | `1` | `0` to `100`. Scales the setup's environment light and reflections |+| `environmentRotation` | `0` | `-100` to `100` radians around the vertical axis |+| `lightDirection` | the setup's | Components within ±1000000, length at least `0.000001` |+| `keyColor` | the setup's | Components from `0` to `1000` || `keyIntensity` | `1` | `0` to `100` |-| `fillIntensity` | `1` | `0` to `100` |-| `ambientIntensity` | `1` | `0` to `100` |+| `fillIntensity` | `0` | `0` to `100` |+| `ambientIntensity` | `1` | `0` to `100`. Scales the environment light || `daylight` | `1` | `0` to `100` || `pointLights` | `[]` | At most eight point light records || `skyTop` | `[0.2, 0.38, 0.52]` | Components from `0` to `1` |@@ -125,6 +128,15 @@ Direction magnitude remains in the canonical recipe.The shadow projector uses its normalized direction, so changing only magnitude does not change shadow placement.High radiance can clip at the renderer's half-float HDR target limit of `65504` before bloom and tone mapping.+## Lighting setups++A recipe with no lighting settings uses `daylight`: a small procedural sky map (128 by 64, generated in code, no files or URLs) lights every surface and shows in metal and glossy reflections, with a warm key light for shadows.+The four setups are `daylight`, `overcast` (even grey light, weak key), `sunset` (low warm sun, dark blue zenith) and `studio` (neutral room with three soft boxes).+Setting `setup` through `set-environment` resets `lightDirection`, `keyColor`, `keyIntensity`, `fillIntensity`, `ambientIntensity`, `skyTop` and `skyBottom` to that setup; fields in the same call still win, and fields set earlier are replaced.+Remote URLs and HDRI files are not accepted from tool input.+This changes the look of every recipe that sets no lighting: before, the default had no environment map, a key color of `[5.2, 4.7, 4.1]` and a fill intensity of `1`.+To get the earlier flat look, set `keyColor`, `fillIntensity` and `environmentIntensity: 0` yourself.+## Point lightsEach point light requires a world-space `position`.@@ -175,6 +187,7 @@ See [volume fog](volumetric.md) for renderer requirements and frame-time limits.The controls reuse `resolveEffects` with a preview bloom strength of `0.12`.Exposure remains independent and maps to `frame.exposure`.Bloom strength zero disables bloom.+Ambient occlusion reads the depth texture, so it needs the HDR depth target that previews use. The program compiles and its half-resolution target allocates on first use. On SwiftShader at 960 by 540 it adds about 16 ms to a 190 ms frame (measured, 8 percent). The engine itself leaves it off unless a frame asks; only recipes default to `0.8`. Pixels that direct light already brightens keep less of it, because occlusion belongs to indirect light.| Field | Default | Range || --- | --- | --- |@@ -184,6 +197,8 @@ Bloom strength zero disables bloom.| `temperature` | `0` | `-1` to `1` || `vignette` | `0` | `0` to `1` || `grain` | `0` | `0` to `0.1` |+| `ambientOcclusion` | `0.8` | `0` to `1`. Screen-space contact darkening; `0` skips the pass and its program |+| `ambientOcclusionRadius` | `0.5` | `0.01` to `100` world units || `bloom.strength` | `0.12` | `0` to `2` || `bloom.threshold` | `1` | `0` to `10` || `bloom.radius` | `1` | `0.1` to `4` |diff --git a/docs/parity.md b/docs/parity.mdindex e764f57b..e5f1c083 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 > 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, 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 > Lights > World Environment | partial | Recipes pick a named setup (`daylight`, `overcast`, `sunset`, `studio`) that carries a procedural environment map, and get screen-space ambient occlusion. Code can load any HDRI; recipes reach only the named maps, with no URLs or files. No reflections between objects yet. | [environment](../tests/environment.test.js), [default look](../tests/default-look.test.js) | #53 || Rendering > Materials > Components | partial | Surfaces with PBR factors and five maps. There are no volume materials or displacement. | [texture-set](../tests/texture-set.test.js) | #50, #51 || Rendering > Materials > Assignment | done | A node names one material. | [agent-scene](../tests/agent-scene.test.js) | || Rendering > Materials > Preview | out of scope | Interface for a person. Agents use `scene_look`. | | |diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex 1ab73ca0..cf032eec 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -2,7 +2,7 @@ import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoadimport { Renderer67 } from '../src/renderer.js';import { applyProjection } from '../src/camera.js';import { mat4 } from 'gl-matrix';-import { resolveAgentShadow } from '../src/agent-look.js';+import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';import { createAgentAssetScene } from '../src/agent-asset.js';import { parseGltf } from '../src/gltf.js';@@ -104,7 +104,7 @@ function draw(record, time = 0, camera = record.scene.camera) {record.shadowKey = shadowKey;}record.renderer.world = environment.world;- record.renderer.render({ ...camera, environment, effects, exposure: effects.exposure, time });+ record.renderer.render({ ...camera, environment: { ...environment, map: agentEnvironmentMap(environment) }, effects, exposure: effects.exposure, time });const error = record.renderer.context.getError();if (error !== 0) {throw new Error(`WebGL render failed with error ${error}.`);@@ -153,7 +153,7 @@ function initializeRenderer(scene, { memoryBudgetMiB, backend }) {hdr: true,depth: true,world: scene.environment.world,- environment: scene.environment,+ environment: { ...scene.environment, map: agentEnvironmentMap(scene.environment) },shadowBounds: resolveAgentShadow(scene.shadow, scene.environment.lightDirection),pixelRatio: 1,samples: backend === 'cpu' ? 1 : 4,diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 5631385e..f1129ba4 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -5,7 +5,7 @@ import { setPriority, constants } from 'node:os';import { resolve } from 'node:path';import { pathToFileURL } from 'node:url';import packageMetadata from '../package.json' with { type: 'json' };-import { MATERIAL_PATTERN_TYPES } from '../src/agent-scene-capabilities.js';+import { MATERIAL_PATTERN_TYPES, LIGHTING_SETUP_NAMES } from '../src/agent-scene-capabilities.js';const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);const positive = finite.positive();@@ -82,6 +82,9 @@ const volumeFog = z.strictObject({});const environment = z.strictObject({world: z.boolean().optional().describe('Draw the sky and apply surface fog.'),+ setup: z.enum(LIGHTING_SETUP_NAMES).optional().describe('Named lighting: an image-based environment plus key light. Default daylight. Setting it resets the key light, fill and ambient fields to that setup; fields in the same call still win.'),+ environmentIntensity: bounded(0, 100).optional().describe('Scales the setup environment light and its reflections.'),+ environmentRotation: bounded(-100, 100).optional().describe('Turns the setup environment around the vertical axis, in radians.'),lightDirection: boundedVector(-1e6, 1e6).optional().describe('Nonzero direction toward the key light; shadows follow it.'),keyColor: boundedVector(0, 1000).optional(),keyIntensity: bounded(0, 100).optional(),@@ -130,6 +133,8 @@ const effects = z.strictObject({temperature: bounded(-1, 1).optional(),vignette: unit.optional(),grain: bounded(0, 0.1).optional(),+ ambientOcclusion: unit.optional().describe('Screen-space contact darkening, 0 off to 1 full. Default 0.7 when unset; 0 skips the pass.'),+ ambientOcclusionRadius: bounded(0.01, 100).optional().describe('World-space reach of the occlusion; default 0.5.'),bloom: z.strictObject({strength: bounded(0, 2).optional(),threshold: bounded(0, 10).optional(),diff --git a/skills/build-67js-scene/SKILL.md b/skills/build-67js-scene/SKILL.mdindex 1c7fe3b9..5c97eba0 100644--- a/skills/build-67js-scene/SKILL.md+++ b/skills/build-67js-scene/SKILL.md@@ -60,6 +60,7 @@ Read [scene-contract.md](references/scene-contract.md) before creating parts or7. Validate geometry, bounds and scene budgets with the existing Node tests.8. Capture actual rendered wide and narrow views. Inspect edges, highlights, overlap and the focal point.9. Exercise orbit, zoom, camera selection and the requested interaction through project dev tooling.+10. In a recipe, start from the default look: `environment.setup` is `daylight` and `effects.ambientOcclusion` is `0.8`. Pick `studio` for products, `overcast` for soft even light, `sunset` for warm low light; set `ambientOcclusion: 0` only to turn contact darkening off. Do not hand-tune key, fill and ambient first.Do not treat an `antialias: true` context as proof that the final image looks smooth.Report measured geometry, draw counts and render size separately from visual judgments.diff --git a/src/agent-asset.js b/src/agent-asset.jsindex f8f671fa..9a962f3e 100644--- a/src/agent-asset.js+++ b/src/agent-asset.js@@ -1,5 +1,6 @@import { mat4, mat3 } from 'gl-matrix';import { createAgentScene } from './agent-scene.js';+import { environmentPatchWithSetup } from './agent-look.js';import { fitPerspectiveDistance } from './camera.js';import { validateSkinGeometry, validateSkinPose } from './skinning.js';import { validateMorphGeometry, validateMorphTransform } from './morph.js';@@ -635,7 +636,7 @@ export function createAgentAssetScene(asset, inputRecipe) {const patch = operation[lookField];knownKeys(patch, Object.keys(candidate[lookField]), lookField);const nested = lookField === 'environment' ? 'volumeFog' : lookField === 'effects' ? 'bloom' : null;- const merged = { ...candidate[lookField], ...patch };+ const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };if (nested && Object.hasOwn(patch, nested)) {knownKeys(patch[nested], Object.keys(candidate[lookField][nested]), nested);merged[nested] = { ...candidate[lookField][nested], ...patch[nested] };diff --git a/src/agent-look.js b/src/agent-look.jsindex f8326875..2434981d 100644--- a/src/agent-look.js+++ b/src/agent-look.js@@ -3,13 +3,15 @@ import { createLightingState, updateLightingState, MAX_POINT_LIGHTS, MAX_SPOT_LIimport { resolveEffects } from './effects.js';import { resolveVolumeFog } from './volumetric.js';import { resolveLiquidOptics } from './renderer.js';+import { createLightingSetupMap, lightingSetupFields } from './lighting-setups.js';+import { DEFAULT_LIGHTING_SETUP, LIGHTING_SETUP_NAMES, DEFAULT_AMBIENT_OCCLUSION } from './agent-scene-capabilities.js';const ENVIRONMENT_FIELDS = [- 'world', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity',+ 'world', 'setup', 'environmentIntensity', 'environmentRotation', 'lightDirection', 'keyColor', 'keyIntensity', 'fillIntensity', 'ambientIntensity','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 EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom'];const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow'];const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow'];@@ -198,17 +200,25 @@ function environmentFrom(input = {}) {if (typeof world !== 'boolean') {throw new TypeError('environment.world must be boolean.');}+ const setup = fallback(input.setup, DEFAULT_LIGHTING_SETUP);+ if (!LIGHTING_SETUP_NAMES.includes(setup)) {+ throw new RangeError(`environment.setup must be one of ${LIGHTING_SETUP_NAMES.join(', ')}.`);+ }+ const defaults = lightingSetupFields(setup);const environment = {world,- lightDirection: directionFrom(fallback(input.lightDirection, [-3, 6, 4])).direction,- keyColor: vectorInRange(fallback(input.keyColor, [5.2, 4.7, 4.1]), 0, 1000, 'keyColor'),- keyIntensity: numberInRange(fallback(input.keyIntensity, 1), 0, 100, 'keyIntensity'),- fillIntensity: numberInRange(fallback(input.fillIntensity, 1), 0, 100, 'fillIntensity'),- ambientIntensity: numberInRange(fallback(input.ambientIntensity, 1), 0, 100, 'ambientIntensity'),+ setup,+ environmentIntensity: numberInRange(fallback(input.environmentIntensity, 1), 0, 100, 'environmentIntensity'),+ environmentRotation: numberInRange(fallback(input.environmentRotation, 0), -100, 100, 'environmentRotation'),+ lightDirection: directionFrom(fallback(input.lightDirection, defaults.lightDirection)).direction,+ keyColor: vectorInRange(fallback(input.keyColor, defaults.keyColor), 0, 1000, 'keyColor'),+ keyIntensity: numberInRange(fallback(input.keyIntensity, defaults.keyIntensity), 0, 100, 'keyIntensity'),+ fillIntensity: numberInRange(fallback(input.fillIntensity, defaults.fillIntensity), 0, 100, 'fillIntensity'),+ ambientIntensity: numberInRange(fallback(input.ambientIntensity, defaults.ambientIntensity), 0, 100, 'ambientIntensity'),daylight: numberInRange(fallback(input.daylight, 1), 0, 100, 'daylight'),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'),+ skyTop: vectorInRange(fallback(input.skyTop, defaults.skyTop), 0, 1, 'skyTop'),+ skyBottom: vectorInRange(fallback(input.skyBottom, defaults.skyBottom), 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),@@ -228,6 +238,26 @@ function environmentFrom(input = {}) {return environment;}+/**+ * Setup-derived fields come with the setup name, so switching setups never keeps the old key light.+ * Fields in the patch itself still win.+ */+export function environmentPatchWithSetup(patch) {+ if (patch.setup === undefined) {+ return patch;+ }+ return { ...lightingSetupFields(patch.setup), ...patch };+}++/** The procedural environment map that lights a normalized environment; the same object returns while inputs hold. */+export function agentEnvironmentMap(environment) {+ return createLightingSetupMap(environment.setup, {+ intensity: environment.environmentIntensity,+ rotation: environment.environmentRotation,+ showBackground: environment.world,+ });+}+function effectsFrom(input = {}) {knownKeys(input, EFFECT_FIELDS, 'effects');for (const field of EFFECT_FIELDS) {@@ -242,7 +272,8 @@ function effectsFrom(input = {}) {numberInRange(bloom[field], -Number.MAX_VALUE, Number.MAX_VALUE, `bloom.${field}`);}}- const resolved = resolveEffects({ ...input, bloom: { strength: 0.12, threshold: 1, radius: 1, ...bloom } });+ const ambientOcclusion = fallback(input.ambientOcclusion, DEFAULT_AMBIENT_OCCLUSION);+ const resolved = resolveEffects({ ...input, ambientOcclusion, bloom: { strength: 0.12, threshold: 1, radius: 1, ...bloom } });return { ...resolved, exposure: numberInRange(fallback(input.exposure, 1), 0.01, 16, 'exposure') };}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 09462f2c..c6a0f310 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -15,6 +15,11 @@ export const MAX_MATERIAL_PATTERNS = 16;// Recipe textures are opaque patterns, so cutout masking has nothing to cut.export const RECIPE_ALPHA_MODES = Object.freeze(['opaque', 'blend']);+// Named lighting setups (see lighting-setups.js) and the occlusion strength that recipes get when they set none.+export const LIGHTING_SETUP_NAMES = Object.freeze(['daylight', 'overcast', 'sunset', 'studio']);+export const DEFAULT_LIGHTING_SETUP = 'daylight';+export const DEFAULT_AMBIENT_OCCLUSION = 0.8;+export const AGENT_SCENE_CAPABILITIES = Object.freeze({format: '67js.scene', schemaVersion: 1,geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),@@ -30,6 +35,8 @@ 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,+ lightingSetups: LIGHTING_SETUP_NAMES, defaultLightingSetup: DEFAULT_LIGHTING_SETUP,+ ambientOcclusion: Object.freeze({ default: DEFAULT_AMBIENT_OCCLUSION, defaultRadius: 0.5, off: 0 }),// Local lights: spot and rectangular area lights. Shadows share one 2048 x 3072 depth atlas of 24 tiles; a shadowed// point light uses 6 tiles and a shadowed spot light 1. Area lights cast no shadow. Light linking is not supported.maxSpotLights: 8, maxAreaLights: 4,diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 5280641f..df114fba 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -3,7 +3,7 @@ import { box, cylinder, sphere, torus } from './geometry.js';import { lathe, extrude, tube } from './modeling.js';import { createSceneGraph } from './scene-graph.js';import { applyProjection } from './camera.js';-import { normalizeAgentLook } from './agent-look.js';+import { normalizeAgentLook, environmentPatchWithSetup } from './agent-look.js';import { normalizeAgentMotion, compileAgentMotion } from './agent-motion.js';import { meshReport, generateMeshGeometry, MESH_SMOOTH_ANGLE_DEFAULT } from './agent-mesh.js';import { normalizeMeshEdits, normalizeMeshStack } from './mesh-recipe.js';@@ -872,7 +872,7 @@ export function createAgentScene(input, inputLimits = {}) {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 };+ const merged = { ...candidate[lookField], ...(lookField === 'environment' ? environmentPatchWithSetup(patch) : patch) };if (nestedField && Object.hasOwn(patch, nestedField)) {knownKeys(patch[nestedField], Object.keys(candidate[lookField][nestedField]), nestedField);merged[nestedField] = { ...candidate[lookField][nestedField], ...patch[nestedField] };diff --git a/src/ambient-occlusion.js b/src/ambient-occlusion.jsnew file mode 100644index 00000000..9d0679e8--- /dev/null+++ b/src/ambient-occlusion.js@@ -0,0 +1,56 @@+export const AMBIENT_OCCLUSION_SAMPLES = 12;++/**+ * Screen-space ambient occlusion from the resolved depth texture alone.+ * The surface normal comes from screen derivatives of the position, so the pass needs no normal buffer.+ * It writes one visibility factor per pixel; the post pass blurs and applies it.+ */+export const ambientOcclusionFragment = `#version 300 es+precision highp float;+in vec2 textureCoordinate;+uniform sampler2D sceneDepth;+uniform mat4 inverseViewProjection;+uniform vec3 eye;+uniform float radius;+uniform float projectionScale;+uniform float aspect;+uniform float orthographic;+out vec4 occlusion;++vec3 worldPosition(vec2 uv, float depth) {+ vec4 point = inverseViewProjection * vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);+ return point.xyz / point.w;+}++float interleavedNoise(vec2 pixel) {+ return fract(52.9829189 * fract(dot(pixel, vec2(0.06711056, 0.00583715))));+}++void main() {+ float depth = texture(sceneDepth, textureCoordinate).r;+ if (depth >= 1.0) {+ occlusion = vec4(1.0);+ return;+ }+ vec3 position = worldPosition(textureCoordinate, depth);+ vec3 normal = normalize(cross(dFdx(position), dFdy(position)));+ if (orthographic < 0.5 && dot(normal, eye - position) < 0.0) normal = -normal;+ float distanceToEye = orthographic > 0.5 ? 1.0 : length(eye - position);+ float screenRadius = min(radius * projectionScale / distanceToEye, 0.25);+ float rotation = interleavedNoise(gl_FragCoord.xy) * 6.2831853;+ float total = 0.0;+ for (int index = 0; index < ${AMBIENT_OCCLUSION_SAMPLES}; index++) {+ float fraction = (float(index) + 0.5) / float(${AMBIENT_OCCLUSION_SAMPLES});+ float angle = rotation + float(index) * 2.3999632;+ vec2 offset = vec2(cos(angle), sin(angle)) * sqrt(fraction) * screenRadius;+ vec2 sampleUv = textureCoordinate + vec2(offset.x / aspect, offset.y);+ float sampleDepth = texture(sceneDepth, sampleUv).r;+ if (sampleDepth >= 1.0) continue;+ vec3 toSample = worldPosition(sampleUv, sampleDepth) - position;+ float sampleDistance = length(toSample);+ float falloff = 1.0 - clamp(sampleDistance / (radius * 1.5), 0.0, 1.0);+ total += max(dot(normal, toSample) / max(sampleDistance, 0.0001) - 0.15, 0.0) * falloff;+ }+ float visibility = clamp(1.0 - 2.5 * total / float(${AMBIENT_OCCLUSION_SAMPLES}), 0.0, 1.0);+ occlusion = vec4(vec3(visibility), 1.0);+}`;diff --git a/src/effects.js b/src/effects.jsindex 7d26a653..0429bcbb 100644--- a/src/effects.js+++ b/src/effects.js@@ -1,7 +1,7 @@export const EFFECT_PRESETS = Object.freeze({- neutral: Object.freeze({ saturation: 1, contrast: 1, temperature: 0, vignette: 0, grain: 0, bloom: Object.freeze({ strength: 0, threshold: 1, radius: 1 }) }),- cinematic: Object.freeze({ saturation: 0.88, contrast: 1.08, temperature: 0.08, vignette: 0.16, grain: 0.012, bloom: Object.freeze({ strength: 0.25, threshold: 1, radius: 1.5 }) }),- vivid: Object.freeze({ saturation: 1.15, contrast: 1.03, temperature: 0, vignette: 0.06, grain: 0, bloom: Object.freeze({ strength: 0.3, threshold: 0.9, radius: 1.2 }) }),+ neutral: Object.freeze({ saturation: 1, contrast: 1, temperature: 0, vignette: 0, grain: 0, ambientOcclusion: 0, ambientOcclusionRadius: 0.5, bloom: Object.freeze({ strength: 0, threshold: 1, radius: 1 }) }),+ cinematic: Object.freeze({ saturation: 0.88, contrast: 1.08, temperature: 0.08, vignette: 0.16, grain: 0.012, ambientOcclusion: 0, ambientOcclusionRadius: 0.5, bloom: Object.freeze({ strength: 0.25, threshold: 1, radius: 1.5 }) }),+ vivid: Object.freeze({ saturation: 1.15, contrast: 1.03, temperature: 0, vignette: 0.06, grain: 0, ambientOcclusion: 0, ambientOcclusionRadius: 0.5, bloom: Object.freeze({ strength: 0.3, threshold: 0.9, radius: 1.2 }) }),});function numberInRange(value, fallback, minimum, maximum, name) {@@ -20,6 +20,8 @@ export function resolveEffects(effects = {}) {temperature: numberInRange(effects.temperature, 0, -1, 1, 'Temperature'),vignette: numberInRange(effects.vignette, 0, 0, 1, 'Vignette'),grain: numberInRange(effects.grain, 0, 0, 0.1, 'Grain'),+ ambientOcclusion: numberInRange(effects.ambientOcclusion, 0, 0, 1, 'Ambient occlusion'),+ ambientOcclusionRadius: numberInRange(effects.ambientOcclusionRadius, 0.5, 0.01, 100, 'Ambient occlusion radius'),bloom: {strength: numberInRange(bloom.strength, 0, 0, 2, 'Bloom strength'),threshold: numberInRange(bloom.threshold, 1, 0, 10, 'Bloom threshold'),diff --git a/src/lighting-setups.js b/src/lighting-setups.jsnew file mode 100644index 00000000..f9958ed5--- /dev/null+++ b/src/lighting-setups.js@@ -0,0 +1,115 @@+import { createEnvironmentMap } from './environment.js';+import { LIGHTING_SETUP_NAMES } from './agent-scene-capabilities.js';++const MAP_WIDTH = 128;+const MAP_HEIGHT = 64;++// Radiance values are linear. A panel is a soft disc of light: direction, angular radius in radians, color.+const SETUPS = Object.freeze({+ daylight: Object.freeze({+ sky: { zenith: [0.28, 0.46, 0.95], horizon: [0.95, 1.0, 1.05], ground: [0.32, 0.29, 0.25] },+ panels: [],+ fields: { lightDirection: [-3, 6, 4], keyColor: [3, 2.8, 2.5], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 1, skyTop: [0.2, 0.38, 0.52], skyBottom: [0.62, 0.7, 0.67] },+ }),+ overcast: Object.freeze({+ sky: { zenith: [0.85, 0.88, 0.92], horizon: [0.6, 0.62, 0.65], ground: [0.28, 0.28, 0.28] },+ panels: [],+ fields: { lightDirection: [-1, 6, 2], keyColor: [0.9, 0.9, 0.92], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 1, skyTop: [0.6, 0.62, 0.66], skyBottom: [0.55, 0.57, 0.6] },+ }),+ sunset: Object.freeze({+ sky: { zenith: [0.12, 0.18, 0.42], horizon: [1.7, 0.75, 0.32], ground: [0.22, 0.13, 0.1] },+ panels: [{ direction: [-6, 1.5, 3], radius: 0.35, color: [6, 2.6, 0.9] }],+ fields: { lightDirection: [-6, 1.5, 3], keyColor: [3.4, 1.8, 0.85], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 1, skyTop: [0.1, 0.16, 0.38], skyBottom: [0.9, 0.45, 0.25] },+ }),+ studio: Object.freeze({+ sky: { zenith: [0.5, 0.5, 0.5], horizon: [0.3, 0.3, 0.31], ground: [0.22, 0.22, 0.22] },+ panels: [+ { direction: [-3, 6, 4], radius: 0.7, color: [5, 4.9, 4.7] },+ { direction: [0, 1, 0], radius: 0.8, color: [3, 3, 3.1] },+ { direction: [4, 1.5, -3], radius: 0.5, color: [1.8, 2, 2.4] },+ ],+ fields: { lightDirection: [-3, 6, 4], keyColor: [2.4, 2.3, 2.2], keyIntensity: 1, fillIntensity: 0, ambientIntensity: 1, skyTop: [0.45, 0.45, 0.46], skyBottom: [0.3, 0.3, 0.32] },+ }),+});++const mapDataByName = new Map();+const mapsByKey = new Map();+const MAXIMUM_CACHED_MAPS = 16;++function requireSetup(name) {+ if (!LIGHTING_SETUP_NAMES.includes(name)) {+ throw new RangeError(`Unknown lighting setup: ${String(name)}. Use ${LIGHTING_SETUP_NAMES.join(', ')}.`);+ }+ return SETUPS[name];+}++/** The environment fields a setup supplies, as fresh arrays. */+export function lightingSetupFields(name) {+ return structuredClone(requireSetup(name).fields);+}++function normalized(vector) {+ const length = Math.hypot(...vector);+ return vector.map(component => component / length);+}++function mixColors(from, to, amount) {+ return from.map((component, index) => component + (to[index] - component) * amount);+}++function skyRadiance(sky, upward) {+ if (upward >= 0) {+ return mixColors(sky.horizon, sky.zenith, Math.sqrt(upward));+ }+ return mixColors(sky.horizon, sky.ground, Math.min(1, Math.pow(-upward, 0.4) * 1.4));+}++function panelContribution(panel, direction) {+ const axis = normalized(panel.direction);+ const alignment = axis[0] * direction[0] + axis[1] * direction[1] + axis[2] * direction[2];+ const inner = Math.cos(panel.radius);+ const outer = Math.cos(panel.radius * 1.6);+ const amount = Math.min(1, Math.max(0, (alignment - outer) / (inner - outer)));+ return amount * amount * (3 - 2 * amount);+}++function buildMapData(setup) {+ const data = new Float32Array(MAP_WIDTH * MAP_HEIGHT * 3);+ for (let row = 0; row < MAP_HEIGHT; row++) {+ const polar = ((row + 0.5) / MAP_HEIGHT) * Math.PI;+ for (let column = 0; column < MAP_WIDTH; column++) {+ const azimuth = ((column + 0.5) / MAP_WIDTH - 0.5) * 2 * Math.PI;+ const direction = [Math.sin(polar) * Math.sin(azimuth), Math.cos(polar), -Math.sin(polar) * Math.cos(azimuth)];+ const radiance = skyRadiance(setup.sky, direction[1]);+ for (const panel of setup.panels) {+ const weight = panelContribution(panel, direction);+ for (let channel = 0; channel < 3; channel++) {+ radiance[channel] += panel.color[channel] * weight;+ }+ }+ data.set(radiance, (row * MAP_WIDTH + column) * 3);+ }+ }+ return data;+}++/**+ * The procedural environment map of a setup. Pixel data is built once per setup, so the renderer+ * keeps its prefiltered textures while only intensity, rotation or background change.+ */+export function createLightingSetupMap(name, { intensity = 1, rotation = 0, showBackground = false } = {}) {+ const setup = requireSetup(name);+ const key = [name, intensity, rotation, showBackground].join('|');+ if (mapsByKey.has(key)) {+ return mapsByKey.get(key);+ }+ if (!mapDataByName.has(name)) {+ mapDataByName.set(name, buildMapData(setup));+ }+ if (mapsByKey.size >= MAXIMUM_CACHED_MAPS) {+ mapsByKey.clear();+ }+ const map = createEnvironmentMap({ width: MAP_WIDTH, height: MAP_HEIGHT, data: mapDataByName.get(name), intensity, rotation, showBackground });+ mapsByKey.set(key, map);+ return map;+}diff --git a/src/post.js b/src/post.jsindex cbddcb54..f2d34826 100644--- a/src/post.js+++ b/src/post.js@@ -44,6 +44,9 @@ uniform float volumeNoiseAmount;uniform float volumeNoiseScale;uniform float volumeMaxDistance;uniform float orthographic;+uniform sampler2D occlusionTexture;+uniform float occlusionStrength;+uniform vec2 occlusionTexel;out vec4 outputColor;float luminance(vec3 color) { return dot(color, vec3(0.299, 0.587, 0.114)); }float hash(vec3 position) { return fract(sin(dot(position, vec3(127.1, 311.7, 74.7))) * 43758.5453); }@@ -169,6 +172,17 @@ void main() {if (maximumLuma - minimumLuma < max(0.03, maximumLuma * 0.125)) color = center;float coverage = texture(frameTexture, textureCoordinate).a;if (transparent > 0.5) color = center / max(coverage, 0.00001);+ if (occlusionStrength > 0.0) {+ float visibility = 0.0;+ for (int row = -1; row <= 1; row++) {+ for (int column = -1; column <= 1; column++) {+ visibility += texture(occlusionTexture, textureCoordinate + vec2(float(column), float(row)) * occlusionTexel).r;+ }+ }+ // Occlusion belongs to indirect light, so pixels already bright from direct light keep less of it.+ float directShare = 1.0 / (1.0 + 0.4 * luminance(color));+ color *= mix(1.0, visibility / 9.0, occlusionStrength * directShare);+ }if (bloomStrength > 0.0) color += texture(bloomTexture, textureCoordinate).rgb * bloomStrength;if (volumeDensity > 0.0) color = volumeFog(color);if (hdrEnabled > 0.5) {diff --git a/src/renderer.js b/src/renderer.jsindex c7a4a4db..590ee3d3 100644--- a/src/renderer.js+++ b/src/renderer.js@@ -1,6 +1,7 @@import { mat4, mat3 } from 'gl-matrix';import { vertexShader, createFragmentShader, liquidFragmentShader, depthVertexShader, depthFragmentShader, benchmarkVertexShader, benchmarkFragmentShader } from './shaders.js';import { fullscreenVertex, postFragment, skyFragment, bloomFragment } from './post.js';+import { ambientOcclusionFragment } from './ambient-occlusion.js';import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';import { applyProjection } from './camera.js';import { resolveEffects } from './effects.js';@@ -459,7 +460,7 @@ export class Renderer67 {if (!benchmark) {this.postProgram = finishProgram(this.context, pending.post);this.skyProgram = finishProgram(this.context, pending.sky);- this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));+ this.postUniforms = Object.fromEntries(['transparent', 'frameTexture', 'bloomTexture', 'bloomStrength', 'hdrEnabled', 'grade', 'vignette', 'grainAmount', 'resolution', 'monochrome', 'fade', 'cinematic', 'time', 'volumeExplosion', 'explosionProgress', 'inverseViewProjection', 'eye', 'sceneDepth', 'volumeShadowMap', 'volumeLightProjection', 'volumeLightDirection', 'volumeLightColor', 'volumeDensity', 'volumeMinimum', 'volumeMaximum', 'volumeColor', 'volumeAmbient', 'volumeDrift', 'volumeSteps', 'volumeAnisotropy', 'volumeNoiseAmount', 'volumeNoiseScale', 'volumeMaxDistance', 'orthographic', 'occlusionTexture', 'occlusionStrength', 'occlusionTexel'].map((name) => [name, this.context.getUniformLocation(this.postProgram, name)]));this.bloomProgram = finishProgram(this.context, pending.bloom);this.bloomUniforms = Object.fromEntries(['sourceTexture', 'texelDirection', 'threshold', 'extract'].map(name => [name, this.context.getUniformLocation(this.bloomProgram, name)]));this.skyUniforms = Object.fromEntries(['skyTop', 'skyBottom', 'sunDirection', 'inverseViewProjection', 'eye', 'time', 'daylight', 'hdrEnabled'].map((name) => [name, this.context.getUniformLocation(this.skyProgram, name)]));@@ -1134,6 +1135,7 @@ export class Renderer67 {context.deleteFramebuffer(target.framebuffer);}this.bloomTargets = [];+ this.releaseOcclusionTarget();this.multisampleFramebuffer = null;this.resolveFramebuffer = null;this.multisampleColor = null;@@ -1142,6 +1144,59 @@ export class Renderer67 {this.depthTexture = null;}+ releaseOcclusionTarget() {+ if (!this.occlusionTarget) return;+ this.context.deleteTexture(this.occlusionTarget.texture);+ this.context.deleteFramebuffer(this.occlusionTarget.framebuffer);+ this.occlusionTarget = null;+ }++ // Compiled and allocated on first use, so scenes without occlusion pay nothing.+ ensureOcclusionTarget() {+ const context = this.context;+ if (!this.occlusionProgram) {+ this.occlusionProgram = compileProgram(context, fullscreenVertex, ambientOcclusionFragment);+ const names = ['sceneDepth', 'inverseViewProjection', 'eye', 'radius', 'projectionScale', 'aspect', 'orthographic'];+ this.occlusionUniforms = Object.fromEntries(names.map(name => [name, context.getUniformLocation(this.occlusionProgram, name)]));+ }+ if (this.occlusionTarget) return;+ const width = Math.max(1, Math.ceil(this.canvas.width / 2));+ const height = Math.max(1, Math.ceil(this.canvas.height / 2));+ const texture = context.createTexture();+ context.bindTexture(context.TEXTURE_2D, texture);+ context.texImage2D(context.TEXTURE_2D, 0, context.R8, width, height, 0, context.RED, context.UNSIGNED_BYTE, null);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.LINEAR);+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.LINEAR);+ 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);+ const framebuffer = context.createFramebuffer();+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);+ this.occlusionTarget = { texture, framebuffer, width, height };+ }++ drawAmbientOcclusion(frame, effects) {+ const context = this.context;+ this.ensureOcclusionTarget();+ const uniforms = this.occlusionUniforms;+ context.bindFramebuffer(context.FRAMEBUFFER, this.occlusionTarget.framebuffer);+ context.viewport(0, 0, this.occlusionTarget.width, this.occlusionTarget.height);+ context.disable(context.DEPTH_TEST);+ context.disable(context.CULL_FACE);+ context.bindVertexArray(null);+ context.useProgram(this.occlusionProgram);+ context.activeTexture(context.TEXTURE1);+ context.bindTexture(context.TEXTURE_2D, this.depthTexture);+ context.uniform1i(uniforms.sceneDepth, 1);+ context.uniformMatrix4fv(uniforms.inverseViewProjection, false, this.inverseViewProjection);+ context.uniform3fv(uniforms.eye, frame.eye);+ context.uniform1f(uniforms.radius, effects.ambientOcclusionRadius);+ context.uniform1f(uniforms.projectionScale, 0.5 * this.projection[5]);+ context.uniform1f(uniforms.aspect, this.canvas.width / this.canvas.height);+ context.uniform1f(uniforms.orthographic, frame.projection === 'orthographic' ? 1 : 0);+ context.drawArrays(context.TRIANGLES, 0, 3);+ }+allocateFrameTargets(width, height) {const context = this.context;this.releaseFrameTargets();@@ -1317,6 +1372,8 @@ export class Renderer67 {context.bindFramebuffer(context.DRAW_FRAMEBUFFER, this.resolveFramebuffer);context.blitFramebuffer(0, 0, this.canvas.width, this.canvas.height, 0, 0, this.canvas.width, this.canvas.height, context.COLOR_BUFFER_BIT | (this.depth ? context.DEPTH_BUFFER_BIT : 0), context.NEAREST);if (effects.bloom.strength > 0) this.drawBloom(effects.bloom);+ const occluded = effects.ambientOcclusion > 0 && Boolean(this.depthTexture);+ if (occluded) this.drawAmbientOcclusion(frame, effects);context.bindFramebuffer(context.FRAMEBUFFER, null);context.viewport(0, 0, this.canvas.width, this.canvas.height);context.disable(context.DEPTH_TEST);@@ -1351,6 +1408,11 @@ export class Renderer67 {context.bindTexture(context.TEXTURE_2D, effects.bloom.strength > 0 ? this.bloomTargets[1].texture : this.whiteTexture);context.uniform1i(this.postUniforms.bloomTexture, 2);context.uniform1f(this.postUniforms.bloomStrength, effects.bloom.strength);+ context.activeTexture(context.TEXTURE4);+ context.bindTexture(context.TEXTURE_2D, occluded ? this.occlusionTarget.texture : this.whiteTexture);+ context.uniform1i(this.postUniforms.occlusionTexture, 4);+ context.uniform1f(this.postUniforms.occlusionStrength, occluded ? effects.ambientOcclusion : 0);+ context.uniform2f(this.postUniforms.occlusionTexel, 1 / Math.ceil(this.canvas.width / 2), 1 / Math.ceil(this.canvas.height / 2));context.uniform1f(this.postUniforms.transparent, this.transparent ? 1 : 0);context.uniform1f(this.postUniforms.hdrEnabled, this.hdr ? 1 : 0);context.uniform3f(this.postUniforms.grade, effects.saturation, effects.contrast, effects.temperature);@@ -1714,6 +1776,7 @@ export class Renderer67 {if (this.postProgram) this.context.deleteProgram(this.postProgram);if (this.skyProgram) this.context.deleteProgram(this.skyProgram);if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);+ if (this.occlusionProgram) this.context.deleteProgram(this.occlusionProgram);if (this.environmentBackgroundProgram) this.context.deleteProgram(this.environmentBackgroundProgram);this.environmentResources?.dispose();for (const texture of this.textures.values()) this.context.deleteTexture(texture);diff --git a/tests/agent-look.test.js b/tests/agent-look.test.jsindex c7e04673..de582bdc 100644--- a/tests/agent-look.test.js+++ b/tests/agent-look.test.js@@ -9,10 +9,13 @@ test('default look is complete, detached JSON and idempotent', () => {const look = normalizeAgentLook();assert.deepEqual(look.environment, {world: false,+ setup: 'daylight',+ environmentIntensity: 1,+ environmentRotation: 0,lightDirection: [-3, 6, 4],- keyColor: [5.2, 4.7, 4.1],+ keyColor: [3, 2.8, 2.5],keyIntensity: 1,- fillIntensity: 1,+ fillIntensity: 0,ambientIntensity: 1,daylight: 1,pointLights: [],@@ -24,6 +27,7 @@ test('default look is complete, detached JSON and idempotent', () => {});assert.deepEqual(look.effects, {saturation: 1, contrast: 1, temperature: 0, vignette: 0, grain: 0,+ ambientOcclusion: 0.8, ambientOcclusionRadius: 0.5,bloom: { strength: 0.12, threshold: 1, radius: 1 }, exposure: 1,});assert.deepEqual(look.shadow, { target: [0, 1, 0], extent: 3.5, distance: 8, near: 0.1, far: 15 });diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.jsindex 7f023f0c..90e04617 100644--- a/tests/agent-preview.test.js+++ b/tests/agent-preview.test.js@@ -5,7 +5,7 @@ import { Script, createContext } from 'node:vm';import { mat4 } from 'gl-matrix';import { createAgentScene, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded } from '../src/agent-scene.js';import { applyProjection } from '../src/camera.js';-import { resolveAgentShadow } from '../src/agent-look.js';+import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';import { createAgentAssetScene } from '../src/agent-asset.js';import { parseGltf } from '../src/gltf.js';import { skinnedStripAsset } from './fixtures/skinned-strip.js';@@ -68,7 +68,7 @@ function previewHarness() {// The harness loads Manifold from node_modules directly, so the preview's served-file loader is ignored.setManifoldModuleLoader: () => {},parseGltf, Uint8Array, atob,- applyProjection, mat4, resolveAgentShadow,+ applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap,Renderer67: FaultInjectedRenderer,});// Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.diff --git a/tests/default-look.test.js b/tests/default-look.test.jsnew file mode 100644index 00000000..52f7ba76--- /dev/null+++ b/tests/default-look.test.js@@ -0,0 +1,68 @@+import assert from 'node:assert/strict';+import test from 'node:test';+import { AGENT_SCENE_CAPABILITIES, DEFAULT_AMBIENT_OCCLUSION, DEFAULT_LIGHTING_SETUP, LIGHTING_SETUP_NAMES } from '../src/agent-scene-capabilities.js';+import { agentEnvironmentMap, environmentPatchWithSetup, normalizeAgentLook } from '../src/agent-look.js';+import { createLightingSetupMap, lightingSetupFields } from '../src/lighting-setups.js';+import { resolveEffects } from '../src/effects.js';++test('every named setup has fields and a finite environment map', () => {+ for (const name of LIGHTING_SETUP_NAMES) {+ const fields = lightingSetupFields(name);+ assert.equal(fields.lightDirection.length, 3);+ const map = createLightingSetupMap(name);+ assert.equal(map.kind, 'environment-map');+ assert.ok(map.data.every(Number.isFinite));+ assert.ok(map.data.some(value => value > 0));+ }+});++test('setups differ from each other', () => {+ const averages = LIGHTING_SETUP_NAMES.map(name => createLightingSetupMap(name).data.reduce((sum, value) => sum + value, 0));+ assert.equal(new Set(averages.map(value => value.toFixed(3))).size, LIGHTING_SETUP_NAMES.length);+});++test('a recipe with no lighting settings gets the default setup and occlusion', () => {+ const look = normalizeAgentLook({});+ assert.equal(look.environment.setup, DEFAULT_LIGHTING_SETUP);+ assert.equal(look.effects.ambientOcclusion, DEFAULT_AMBIENT_OCCLUSION);+ assert.deepEqual(look.environment.lightDirection, lightingSetupFields(DEFAULT_LIGHTING_SETUP).lightDirection);+});++test('a named setup supplies its fields and explicit fields win', () => {+ const sunset = normalizeAgentLook({ environment: { setup: 'sunset' } }).environment;+ assert.deepEqual(sunset.keyColor, lightingSetupFields('sunset').keyColor);+ const overridden = normalizeAgentLook({ environment: { setup: 'sunset', keyIntensity: 2 } }).environment;+ assert.equal(overridden.keyIntensity, 2);+});++test('an unknown setup is rejected with the valid names', () => {+ assert.throws(() => normalizeAgentLook({ environment: { setup: 'moonlit' } }), /daylight/);+});++test('switching setup resets setup fields, and fields in the patch still win', () => {+ const patch = environmentPatchWithSetup({ setup: 'studio', fillIntensity: 0.5 });+ assert.deepEqual(patch.keyColor, lightingSetupFields('studio').keyColor);+ assert.equal(patch.fillIntensity, 0.5);+ assert.deepEqual(environmentPatchWithSetup({ keyIntensity: 3 }), { keyIntensity: 3 });+});++test('occlusion zero turns the pass off and the radius is bounded', () => {+ assert.equal(normalizeAgentLook({ effects: { ambientOcclusion: 0 } }).effects.ambientOcclusion, 0);+ assert.throws(() => normalizeAgentLook({ effects: { ambientOcclusion: 2 } }), /Ambient occlusion/);+ assert.throws(() => normalizeAgentLook({ effects: { ambientOcclusionRadius: 0 } }), /radius/);+});++test('the engine itself keeps occlusion off unless asked', () => {+ assert.equal(resolveEffects({}).ambientOcclusion, 0);+});++test('the same inputs return the same environment map object', () => {+ const environment = normalizeAgentLook({}).environment;+ assert.equal(agentEnvironmentMap(environment), agentEnvironmentMap(environment));+ assert.equal(agentEnvironmentMap(environment).data, agentEnvironmentMap({ ...environment, environmentIntensity: 2 }).data);+});++test('capabilities list the setups and the occlusion default', () => {+ assert.deepEqual([...AGENT_SCENE_CAPABILITIES.lightingSetups], [...LIGHTING_SETUP_NAMES]);+ assert.equal(AGENT_SCENE_CAPABILITIES.ambientOcclusion.default, DEFAULT_AMBIENT_OCCLUSION);+});