Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

Add render passes, depth of field and camera motion blur

Nguyen Xuan Ande06044856ff
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7a5eda19..4209ac4d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,8 @@
## Unreleased
+- Add render passes, depth of field and camera motion blur (issue #54, first slice). Render jobs of kind `image` or `stills` take `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) and write each as a raw, unantialiased PNG beside the lit image (`render-depth.png`, `frame-3-objectId.png`); depth is 16 bits over 100 m in red and green, object IDs are 24 bits with the part names in the job metrics. In code, `renderer.render({ pass })` draws a pass into its own non-multisampled target. `effects.depthOfField` (`blur`, `focusDistance`) and `effects.motionBlur` (`shutter`) are new recipe effects: fixed sample patterns and a per-pixel rotation from the pixel position, so a seek to a frame repeats the same pixels. They live in the new `67js/addons/camera-effects` entry; the preview installs it, and the core renderer only gains a stage hook and the pass branch (a compiled-out shader feature). Motion blur follows camera tracks only, sampled from time at `motion.start + elapsed - shutter`. Measured on SwiftShader through MCP (`npm run smoke:render-passes`): 8 stills with 5 passes each, then four seeks, all byte-identical to the same frame in the sequence. Temporal anti-aliasing, accumulation and the compositing graph of #54 are not part of this slice.
+
- Add `decimate`, `remesh` and generated levels of detail (issue #40). `decimate` (a `ratio` of triangles) is a quadric edge collapse of our own that keeps open boundaries, the borders between tags and the tags themselves; it measured 0.25 to 0.85 of the Hausdorff error of meshoptimizer 1.3.0 on the same meshes and adds no dependency, but takes about 2.5 s on 100k triangles where meshoptimizer takes 0.09 s. `remesh` (`voxelSize` or `resolution`, at most 192 per side and 4,194,304 cells, checked before allocation) builds a closed quad surface from a BVH signed distance with surface nets. Both are edits and stack nodes, in the MCP schemas, and load on demand with the mesh code. `generateMeshLods`, `generateGeometryLods` and `generateAssetLods` (also in `67js/addons/mesh`) return levels with a measured error for runtime selection (issue #37). Four decimate and two remesh cases join the Blender comparison, compared by volume, area and Hausdorff distance because face counts differ.
- 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` (0 to 1) and `ambientOcclusionRadius` add screen-space ambient occlusion from the depth texture. It is off by default: measured with `npm run reference -- --ambient-occlusion`, it improved no score by more than 0.002 (strength 0.8: -0.0019 in foliage, +0.0047 in lit-interior; strength 0.4, radius 0.3: within +0.0013 everywhere). When used 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]`, and a fill intensity of `0` instead of `1`. The engine default is unchanged (occlusion off, no map) so code scenes keep their pixels. Screen-space reflections are not part of this. The `scene:lit-box` size budget rises by 100 bytes gzip for the environment and occlusion code. The reference suite gets `--ambient-occlusion`, and its Blender renderer drops triangles that repeat a vertex, which crashed Blender on the skinned character
diff --git a/bench/size/baseline.json b/bench/size/baseline.json
index 3bc3c06f..412b5e1c 100644
--- a/bench/size/baseline.json
+++ b/bench/size/baseline.json
@@ -14,9 +14,9 @@
},
"bundles": {
"entry:core": {
- "min": 274298,
- "gzip": 77983,
- "brotli": 66640
+ "min": 277563,
+ "gzip": 79010,
+ "brotli": 67555
},
"entry:model": {
"min": 40093,
@@ -39,9 +39,9 @@
"brotli": 7331
},
"entry:gltf": {
- "min": 152103,
- "gzip": 46693,
- "brotli": 39999
+ "min": 153718,
+ "gzip": 47184,
+ "brotli": 40362
},
"entry:modeling": {
"min": 15517,
@@ -129,49 +129,59 @@
"brotli": 762
},
"entry:agent-scene": {
- "min": 189992,
- "gzip": 57090,
- "brotli": 49452
+ "min": 192267,
+ "gzip": 57778,
+ "brotli": 49957
},
"entry:agent-scene+lazy": {
- "min": 489100,
- "gzip": 160873,
- "brotli": 140211
+ "min": 491375,
+ "gzip": 161557,
+ "brotli": 140698
},
"entry:agent-asset": {
- "min": 269753,
- "gzip": 81908,
- "brotli": 71452
+ "min": 272031,
+ "gzip": 82581,
+ "brotli": 71917
},
"entry:agent-asset+lazy": {
- "min": 516201,
- "gzip": 168134,
- "brotli": 146309
+ "min": 518479,
+ "gzip": 168806,
+ "brotli": 146806
},
"entry:hdri": {
"min": 8075,
"gzip": 3138,
"brotli": 2801
},
+ "entry:camera-effects": {
+ "min": 23985,
+ "gzip": 8396,
+ "brotli": 6688
+ },
+ "entry:render-passes": {
+ "min": 3412,
+ "gzip": 1608,
+ "brotli": 1425
+ },
"scene:lit-box": {
- "min": 206306,
- "gzip": 56013,
- "brotli": 47870
+ "min": 209404,
+ "gzip": 57025,
+ "brotli": 48681
},
"scene:gltf-box": {
- "min": 264183,
- "gzip": 74981,
- "brotli": 64331
+ "min": 267284,
+ "gzip": 75956,
+ "brotli": 65218
},
"scene:agent-scene": {
- "min": 293377,
- "gzip": 84106,
- "brotli": 72209
+ "min": 296711,
+ "gzip": 85191,
+ "brotli": 73189
},
"scene:agent-scene+lazy": {
- "min": 592485,
- "gzip": 187890,
- "brotli": 162954
+ "min": 595819,
+ "gzip": 188973,
+ "brotli": 163948
}
}
}
diff --git a/bench/size/budgets.json b/bench/size/budgets.json
index 1d2d99fa..c22f91ee 100644
--- a/bench/size/budgets.json
+++ b/bench/size/budgets.json
@@ -33,6 +33,8 @@
"entry:agent-asset": 83600,
"entry:agent-asset+lazy": 171500,
"entry:hdri": 3300,
+ "entry:camera-effects": 8600,
+ "entry:render-passes": 1700,
"scene:lit-box": 57200,
"scene:gltf-box": 76500,
"scene:agent-scene": 85800,
diff --git a/bench/tool-cost-budgets.json b/bench/tool-cost-budgets.json
index 644c2e22..adf01772 100644
--- a/bench/tool-cost-budgets.json
+++ b/bench/tool-cost-budgets.json
@@ -1,11 +1,11 @@
{
"measured": "2026-10-31, from scripts/measure-tool-cost.mjs; was 373388 schema bytes before shared IDs and recipe references",
- "schemaTotalBytes": 183800,
+ "schemaTotalBytes": 185700,
"schemaToolBytes": {
- "scene_create": 59400,
- "scene_apply": 44300,
+ "scene_create": 59900,
+ "scene_apply": 44800,
"mesh_edit": 34000,
- "scene_create_asset": 18300,
+ "scene_create_asset": 18700,
"mesh_stack": 11500
},
"schemaOtherToolBytes": 4000,
diff --git a/docs/agent-look.md b/docs/agent-look.md
index 1c5d5a55..e4a70c2d 100644
--- a/docs/agent-look.md
+++ b/docs/agent-look.md
@@ -202,6 +202,15 @@ Ambient occlusion reads the depth texture, so it needs the HDR depth target that
| `bloom.strength` | `0.12` | `0` to `2` |
| `bloom.threshold` | `1` | `0` to `10` |
| `bloom.radius` | `1` | `0.1` to `4` |
+| `depthOfField.blur` | `0` | `0` to `1`. Lens blur from depth, off by default; the widest circle is 5 percent of the image height |
+| `depthOfField.focusDistance` | `5` | `0.01` to `100000` metres from the camera that stay sharp |
+| `motionBlur.shutter` | `0` | `0` to `0.5` seconds of camera motion to smear |
+
+Depth of field and motion blur are deterministic: they read the frame, its depth and the camera, with fixed sample patterns, so a seek to a time gives the same pixels as playing to it.
+Depth of field applies to every render, including `scene_look`.
+Motion blur needs camera `motion` tracks and a render job with `settings.motion`: the job samples the camera at `motion.start + elapsed - shutter` as well, and smears each pixel along the screen movement between the two.
+It follows camera motion only; moving objects are not blurred.
+Both effects compile their shader and allocate their targets the first time a frame uses them, and a scene that leaves them at zero pays nothing.
## Directional shadows
diff --git a/docs/agent-render-jobs.md b/docs/agent-render-jobs.md
index bce9c2ee..a1a9fb5e 100644
--- a/docs/agent-render-jobs.md
+++ b/docs/agent-render-jobs.md
@@ -49,6 +49,28 @@ Creation and edits author tracks through scene recipes and `set-motion`, before
Static recipes remain static unless a shader uses renderer time.
Imported clips retain separate absolute sampling through `settings.animation`.
+## Render passes
+
+`image` and `stills` jobs accept `settings.passes`, a list of `albedo`, `normal`, `emission`, `depth` and `objectId`.
+Each frame writes its lit image and then one PNG per pass: `render.png` and `render-<pass>.png` for an image, `frame-N.png` and `frame-N-<pass>.png` for stills.
+Passes are raw data at the lit image's size: no tone mapping, grading, bloom, depth of field or antialiasing, so values stay exact at silhouettes.
+Only opaque and cutout geometry appears. Liquid, foam and blended parts, the sky and the environment background do not.
+
+| Pass | Pixel value |
+| --- | --- |
+| `albedo` | Base colour after maps and vertex colour, as stored |
+| `normal` | World-space normal after normal maps, `normal * 0.5 + 0.5` |
+| `emission` | Emissive colour times strength, clamped to 1 |
+| `depth` | Metres from the camera over 100 m as a 16-bit value, high byte in red and low byte in green. Background is `255, 255, 0` |
+| `objectId` | 24-bit ID, low byte in red, then green, then blue. Zero is background |
+
+`scene_render_result` metrics carry `objectNames`, the part name for ID 1, 2 and so on (the first 1000, with `objectNamesTruncated`), and `depthRangeMetres`.
+IDs follow draw order, which groups parts by shared geometry, so read the names list and not node order.
+Videos hold the lit image only.
+
+A seek to any frame gives the same pixels: a job samples each frame from its time and keeps no state between frames.
+`npm run smoke:render-passes` proves it through MCP: it renders eight stills with every pass, then renders frame 3 again as an image in a different order of seeks and compares the bytes of the lit image and all five passes.
+
## Controller API
This module provides persistent job records around a trusted render callback.
diff --git a/docs/guide.md b/docs/guide.md
index 35a1977e..048e6d9e 100644
--- a/docs/guide.md
+++ b/docs/guide.md
@@ -311,6 +311,17 @@ renderer.render({
Bloom cannot recover missing geometry or lighting detail.
+### Depth of field, motion blur and render passes
+
+Depth of field and camera motion blur live in `67js/addons/camera-effects`, so the core carries none of their shader text.
+Call `installCameraEffects(renderer)` on a renderer made with `depth: true`, then set `effects.depthOfField: { blur: 0.6, focusDistance: 4 }` or `effects.motionBlur: { shutter: 0.1 }`.
+Motion blur also needs `frame.previousCamera` (`eye`, `target`, `up` and the lens fields) for the camera at `time - shutter`; derive it from the frame time and the result repeats on every seek.
+Each effect compiles and allocates its targets on the first frame that turns it on. These targets are not in the memory estimate.
+
+`renderer.render({ ...camera, pass: 'depth' })` draws a raw pass instead of the lit image: `albedo`, `normal`, `emission`, `depth` (with `passDepthRange` metres, default 100) or `objectId`.
+Passes draw without multisampling into their own target, and `renderer.passObjectNames()` lists the part behind each object ID.
+The pass branch of the main shader compiles on the first pass request. MCP render jobs write passes to files; see [agent render jobs](agent-render-jobs.md#render-passes).
+
Outdoor `environment` accepts `skyTop`, `skyBottom` (display RGB), `fogColor` (linear RGB), `fogDensity`, `lightDirection` and `daylight`. Set `world: true` and `ground: false`. Frames can override environment and supply `time`, `wind`, `waterRipple` and `rippleTime`.
## Local lights and volume fog
diff --git a/docs/parity.md b/docs/parity.md
index 9215afbe..7bdb0559 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -187,7 +187,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Render Engines > EEVEE | partial | A WebGL2 rasterizer with PBR, one directional shadow, 8 point lights, fog and bloom. There are no light probes. | [renderer](../tests/renderer.test.js), [scores against EEVEE](../bench/reference/baseline.json) | #52, #53, #55, #56 |
| Rendering > Render Engines > 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 > Cameras | partial | Perspective, orthographic views, focal length, animated paths, depth of field from depth and camera motion blur, both repeatable per frame. Object motion blur and bokeh shapes are missing. | [camera-path](../tests/camera-path.test.js), [camera](../tests/camera.test.js), [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Lights > Light Objects | partial | One directional light with a shadow, 8 point lights, 8 spot lights and 4 rectangular area lights. Point and spot lights can cast shadows from one 24-tile atlas (a point light takes 6 tiles, a spot light 1). Area lights use a representative point and cast no shadow. The directional shadow is a single map, not cascaded. | [lighting](../tests/lighting.test.js), `npm run reference` scene `spot-area` | #52 |
| Rendering > Lights > Light Linking | missing | No light linking. | | #52 |
| Rendering > Lights > World Environment | partial | Recipes pick a named setup (`daylight`, `overcast`, `sunset`, `studio`) that carries a procedural environment map, with opt-in screen-space ambient occlusion. Code can load any HDRI; recipes reach only the named maps, with no URLs or files. No reflections between objects yet. | [environment](../tests/environment.test.js), [default look](../tests/default-look.test.js) | #53 |
@@ -207,7 +207,7 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Rendering > Shader Nodes > Group | missing | No node graph. | | #50 |
| Rendering > Color Management | partial | ACES tone mapping and grading. There is no choice of color space or display. | [effects](../tests/effects.test.js) | |
| Rendering > Freestyle | missing | No line rendering. | | |
-| Rendering > View Layers & Passes | missing | No layers or passes. | | #54 |
+| Rendering > View Layers & Passes | partial | Render jobs write albedo, normal, emission, depth and object ID passes as PNG files. There are no view layers, no cryptomatte and no lighting passes (diffuse, glossy, shadow). | [render-passes](../tests/render-passes.test.js) | #54 |
| Rendering > Render Output > Output Properties | partial | PNG and MP4, frame rate, duration and size. There is no stereo or metadata. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | #60 |
| Rendering > Render Output > Audio Rendering | missing | Render jobs have no audio. | | #60 |
| Rendering > Render Output > Rendering Animations | done | Snapshot render jobs with progress, cancel and verified output. | [agent-render-jobs](../tests/agent-render-jobs.test.js) | |
diff --git a/package.json b/package.json
index 320d26b4..0831f701 100644
--- a/package.json
+++ b/package.json
@@ -74,6 +74,8 @@
"./addons/agent-scene": "./build/agent-scene.js",
"./addons/agent-asset": "./build/agent-asset.js",
"./addons/hdri": "./build/hdri.js",
+ "./addons/camera-effects": "./build/camera-effects.js",
+ "./addons/render-passes": "./build/render-passes.js",
"./package.json": "./package.json"
},
"scripts": {
@@ -99,6 +101,7 @@
"smoke:agent-look": "node scripts/smoke-agent-look.mjs",
"smoke:agent-assets": "node scripts/smoke-agent-assets.mjs",
"smoke:agent-render-jobs": "node scripts/smoke-agent-render-jobs.mjs",
+ "smoke:render-passes": "node scripts/smoke-render-passes.mjs",
"smoke:agent-motion": "node scripts/smoke-agent-motion.mjs",
"smoke:agent-physics": "node scripts/smoke-agent-physics.mjs",
"smoke:frame-encoder": "node scripts/smoke-frame-encoder.mjs",
diff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.js
index b6c4d037..375ddf16 100644
--- a/scripts/agent-preview-browser.js
+++ b/scripts/agent-preview-browser.js
@@ -1,5 +1,7 @@
import { createAgentScene, loadAllAgentSceneModules, allAgentSceneModulesLoaded, needsMeshBooleans, loadMeshBooleans, meshBooleansLoaded, setManifoldModuleLoader, needsPhysics, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from '../src/agent-scene.js';
import { Renderer67 } from '../src/renderer.js';
+import { installCameraEffects } from '../src/camera-effects.js';
+import { installRenderPasses } from '../src/render-passes.js';
import { applyProjection } from '../src/camera.js';
import { mat4 } from 'gl-matrix';
import { resolveAgentShadow, agentEnvironmentMap } from '../src/agent-look.js';
@@ -78,7 +80,7 @@ function rebuildRenderer(record) {
record.shadowKey = null;
}
-function draw(record, time = 0, camera = record.scene.camera) {
+function draw(record, time = 0, camera = record.scene.camera, frameOptions = {}) {
if (!record.renderer) throw new Error('The scene renderer is leased to a render job.');
if (record.renderer.context.isContextLost()) {
throw new Error('The render context was lost. Export the recipe and dispose this session.');
@@ -108,7 +110,7 @@ function draw(record, time = 0, camera = record.scene.camera) {
record.shadowKey = shadowKey;
}
record.renderer.world = environment.world;
- record.renderer.render({ ...camera, environment: { ...environment, map: agentEnvironmentMap(environment) }, effects, exposure: effects.exposure, time });
+ record.renderer.render({ ...camera, environment: { ...environment, map: agentEnvironmentMap(environment) }, effects, exposure: effects.exposure, time, ...frameOptions });
const error = record.renderer.context.getError();
if (error !== 0) {
throw new Error(`WebGL render failed with error ${error}.`);
@@ -152,7 +154,7 @@ function resetCanvas() {
}
function initializeRenderer(scene, { memoryBudgetMiB, backend }) {
- return new Renderer67(canvas, scene.parts, {
+ return installRenderPasses(installCameraEffects(new Renderer67(canvas, scene.parts, {
ground: false,
hdr: true,
depth: true,
@@ -162,7 +164,17 @@ function initializeRenderer(scene, { memoryBudgetMiB, backend }) {
pixelRatio: 1,
samples: backend === 'cpu' ? 1 : 4,
memoryBudgetMiB,
- });
+ })));
+}
+
+// The camera at the start of the shutter interval, sampled from time so the same seek always gives the same blur.
+function previousCameraFor(record, motionTime) {
+ const shutter = record.scene.effects.motionBlur.shutter;
+ if (shutter <= 0 || motionTime === undefined || record.asset) return undefined;
+ record.scene.sampleMotion(Math.max(0, motionTime - shutter));
+ const previousCamera = record.scene.camera;
+ record.scene.sampleMotion(motionTime);
+ return previousCamera;
}
function createPreview(scene, { sessionId, memoryBudgetMiB, backend }, asset) {
@@ -336,7 +348,8 @@ window.__agentPreview = {
throw error;
}
},
- frame({ sessionId, animation, motionTime, rendererTime = 0 }) {
+ // `pass` draws one render pass instead of the lit image. Object ID frames also list the part behind each ID.
+ frame({ sessionId, animation, motionTime, rendererTime = 0, pass, passDepthRange }) {
const record = requireSession(sessionId);
if (!Number.isFinite(rendererTime) || rendererTime < 0 || rendererTime > 3600) throw new RangeError('Invalid render time.');
if (record.asset && (animation !== undefined || motionTime !== undefined)) {
@@ -345,8 +358,10 @@ window.__agentPreview = {
} else if (motionTime !== undefined) {
record.scene.sampleMotion(motionTime);
}
- draw(record, rendererTime);
- return renderInfo(record.renderer);
+ const previousCamera = pass ? undefined : previousCameraFor(record, motionTime);
+ draw(record, rendererTime, undefined, { pass, passDepthRange, previousCamera });
+ const info = renderInfo(record.renderer);
+ return pass === 'objectId' ? { ...info, objectNames: record.renderer.passSupport.objectNames() } : info;
},
create(input) {
if (active) throw new Error('Dispose the current scene before creating another.');
diff --git a/scripts/agent-render-jobs.mjs b/scripts/agent-render-jobs.mjs
index 0ea92826..6a0b89c4 100644
--- a/scripts/agent-render-jobs.mjs
+++ b/scripts/agent-render-jobs.mjs
@@ -2,7 +2,9 @@ import { mkdir, open, readFile, writeFile, rename, unlink, rmdir, readdir, lstat
import { randomUUID, createHash } from 'node:crypto';
import { isAbsolute, join, resolve } from 'node:path';
-const UUID = /^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
+import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+
+const UUID =/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/;
const STATES = ['queued', 'running', 'finalizing', 'completed', 'cancelling', 'cancelled', 'failed', 'interrupted'];
const TERMINAL = new Set(['completed', 'cancelled', 'failed', 'interrupted']);
const DEFAULT_LIMITS = Object.freeze({ maxRecords: 32, maxStoreBytes: 512 * 1024 ** 2, maxOutputBytes: 128 * 1024 ** 2, maxFrameBytes: 1024 ** 2, deadlineMs: 300000, cleanupMs: 5000 });
@@ -55,7 +57,7 @@ function jsonCopy(value, maximum = MAXIMUM_JSON_BYTES) {
}
function settingsFrom(input, clips, recipe) {
- objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime'], 'settings');
+ objectKeys(input, ['kind', 'width', 'height', 'fps', 'duration', 'animation', 'motion', 'rendererTime', 'passes'], 'settings');
if (!['image', 'stills', 'video'].includes(input.kind)) throw new TypeError('kind must be image, stills or video.');
const width = boundedNumber(input.width, 64, 1024, 'width', true);
const height = boundedNumber(input.height, 64, 1024, 'height', true);
@@ -65,6 +67,7 @@ function settingsFrom(input, clips, recipe) {
const frameCount = input.kind === 'image' ? 1 : input.kind === 'stills' ? 8 : Math.ceil(fps * duration);
if (frameCount > 900) throw new RangeError('Job exceeds 900 frames.');
const result = { kind: input.kind, width, height, fps, duration, frameCount };
+ if (input.passes !== undefined) result.passes = passesFrom(input.passes, input.kind);
const lastSampleTime = input.kind === 'image' ? 0 : input.kind === 'stills' ? duration : (frameCount - 1) / fps;
if (input.motion !== undefined) {
objectKeys(input.motion, ['start'], 'motion');
@@ -99,12 +102,27 @@ function settingsFrom(input, clips, recipe) {
return result;
}
-function artifactNames(kind) {
- return kind === 'video' ? ['render.mp4'] : kind === 'image' ? ['render.png'] : Array.from({ length: 8 }, (_, index) => `frame-${index}.png`);
+function passesFrom(passes, kind) {
+ if (kind === 'video') throw new RangeError('Render passes need kind image or stills; a video holds the lit image only.');
+ if (!Array.isArray(passes) || passes.length < 1 || passes.length > RENDER_PASS_NAMES.length) throw new TypeError(`passes must list 1 to ${RENDER_PASS_NAMES.length} pass names.`);
+ for (const name of passes) {
+ if (!RENDER_PASS_NAMES.includes(name)) throw new RangeError(`Unknown render pass: ${name}. Use ${RENDER_PASS_NAMES.join(', ')}.`);
+ }
+ if (new Set(passes).size !== passes.length) throw new RangeError('passes must not repeat a name.');
+ return [...passes];
+}
+
+/** Every artifact filename of a job, lit image first and then each requested pass, frame by frame. */
+export function artifactNames(kind, passes = []) {
+ if (kind === 'video') return ['render.mp4'];
+ const stems = kind === 'image' ? ['render'] : Array.from({ length: 8 }, (_, index) => `frame-${index}`);
+ return stems.flatMap(stem => [`${stem}.png`, ...passes.map(pass => `${stem}-${pass}.png`)]);
}
function allowedFile(name) {
- return INTERNAL_FILES.has(name) || /^(?:render\.(?:png|mp4)|frame-[0-7]\.png)(?:\.partial)?$/.test(name);
+ const passNames = RENDER_PASS_NAMES.join('|');
+ const artifact = new RegExp(`^(?:render\\.(?:png|mp4)|(?:render|frame-[0-7])(?:-(?:${passNames}))?\\.png)(?:\\.partial)?$`);
+ return INTERNAL_FILES.has(name) || artifact.test(name);
}
async function regularFile(path) {
@@ -301,7 +319,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {
boundedNumber(record.progress.maximumPendingFrames, 0, 1, 'persisted pending frames', true);
if (record.metrics !== undefined) record.metrics = jsonCopy(record.metrics, 65536);
if (record.reason !== undefined && (typeof record.reason !== 'string' || record.reason.length > 2048)) throw new Error('Invalid persisted job reason.');
- const namesAllowed = artifactNames(settings.kind);
+ const namesAllowed = artifactNames(settings.kind, settings.passes);
if (!Array.isArray(record.artifacts) || record.artifacts.length > namesAllowed.length) throw new Error('Invalid persisted artifacts.');
const seen = new Set();
for (const artifact of record.artifacts) {
@@ -365,7 +383,7 @@ export async function createAgentRenderJobs({ root, run, limits: inputLimits = {
record.state = 'finalizing';
await persist(job);
objectKeys(completed, ['artifacts', 'metrics'], 'runner result');
- const expected = artifactNames(record.settings.kind);
+ const expected = artifactNames(record.settings.kind, record.settings.passes);
if (!Array.isArray(completed.artifacts) || completed.artifacts.length !== expected.length) throw new Error('Runner did not return the required fixed artifacts.');
const directory = await directoryFor(record.jobId);
const metrics = jsonCopy(completed.metrics ?? {}, 65536);
diff --git a/scripts/agent-runtime.mjs b/scripts/agent-runtime.mjs
index 9129ac93..195976b1 100644
--- a/scripts/agent-runtime.mjs
+++ b/scripts/agent-runtime.mjs
@@ -5,7 +5,7 @@ import { lstat, mkdir, readFile, unlink, writeFile } from 'node:fs/promises';
import { dirname, isAbsolute, join } from 'node:path';
import { createRequire } from 'node:module';
import packageMetadata from '../package.json' with { type: 'json' };
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';
+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';
import { createAgentAssetCatalog } from './agent-asset-catalog.mjs';
import { createAgentRenderJobs, EXPORT_DIRECTORY_NAME } from './agent-render-jobs.mjs';
import { createFrameEncoder } from './frame-encoder.mjs';
@@ -15,6 +15,8 @@ import { sessionProblem } from '../src/agent-errors.js';
const SCENE_LIMITS = AGENT_SCENE_DEFAULT_LIMITS;
const MAXIMUM_IMAGE_BYTES = 1024 * 1024;
+// The object ID pass lists the part behind each ID in the job metrics; longer lists are cut and flagged.
+const MAXIMUM_OBJECT_NAMES = 1000;
const MAXIMUM_QUEUED_CALLS = 16;
const MAXIMUM_GLB_BYTES = 32 * 1024 * 1024;
const MAXIMUM_KEPT_GLBS = 8;
@@ -311,19 +313,37 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
metrics.width = width;
metrics.height = height;
metrics.estimatedBytes = rendered.estimatedBytes;
- const captureStarted = performance.now();
- const captured = await session.send('Page.captureScreenshot', { fromSurface: true,
- format: settings.kind === 'video' ? 'jpeg' : 'png',
- ...(settings.kind === 'video' ? { quality: 95 } : { optimizeForSpeed: true }) });
- const bytes = Buffer.from(captured.data, 'base64');
- metrics.captureSeconds += (performance.now() - captureStarted) / 1000;
- if (bytes.length > MAXIMUM_IMAGE_BYTES) throw new Error('Captured job frame exceeded 1 MiB.');
- signal.throwIfAborted();
+ async function captureFrameBytes() {
+ const captureStarted = performance.now();
+ const captured = await session.send('Page.captureScreenshot', { fromSurface: true,
+ format: settings.kind === 'video' ? 'jpeg' : 'png',
+ ...(settings.kind === 'video' ? { quality: 95 } : { optimizeForSpeed: true }) });
+ const captureBytes = Buffer.from(captured.data, 'base64');
+ metrics.captureSeconds += (performance.now() - captureStarted) / 1000;
+ if (captureBytes.length > MAXIMUM_IMAGE_BYTES) throw new Error('Captured job frame exceeded 1 MiB.');
+ signal.throwIfAborted();
+ return captureBytes;
+ }
+ async function writeArtifact(filename, artifactBytes) {
+ await writeFile(join(directory, `${filename}.partial`), artifactBytes, { flag: 'wx' });
+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: 'image/png' });
+ }
+ const bytes = await captureFrameBytes();
if (encoder) await encoder.writeFrame(bytes);
else {
- const filename = settings.kind === 'image' ? 'render.png' : `frame-${frame}.png`;
- await writeFile(join(directory, `${filename}.partial`), bytes, { flag: 'wx' });
- artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: 'image/png' });
+ const stem = settings.kind === 'image' ? 'render' : `frame-${frame}`;
+ await writeArtifact(`${stem}.png`, bytes);
+ // Passes follow the lit image of the same instant, so each seek yields every file for that frame.
+ for (const pass of settings.passes ?? []) {
+ const passInfo = await jobPage.evaluate(input => window.__agentPreview.frame(input),
+ { ...frameInput, pass, passDepthRange: RENDER_PASS_DEPTH_RANGE });
+ await writeArtifact(`${stem}-${pass}.png`, await captureFrameBytes());
+ if (pass === 'depth') metrics.depthRangeMetres = RENDER_PASS_DEPTH_RANGE;
+ if (pass === 'objectId') {
+ metrics.objectNames = passInfo.objectNames.slice(0, MAXIMUM_OBJECT_NAMES);
+ metrics.objectNamesTruncated = passInfo.objectNames.length > MAXIMUM_OBJECT_NAMES;
+ }
+ }
}
metrics.peakNodeBytes = Math.max(metrics.peakNodeBytes, process.memoryUsage().rss);
const heap = await session.send('Runtime.getHeapUsage');
@@ -381,7 +401,7 @@ export function createAgentRuntime({ backend = 'gpu', browser: browserPath, memo
maximumVertices: 250000, maximumParts: 4096, maximumTexturePixels: 4194304, maximumJoints: 1024, maximumClips: 256,
commands: ['set-root', 'set-asset-node', 'set-motion', 'set-animation', 'set-material', 'set-camera', 'set-environment', 'set-effects', 'set-shadow'],
},
- jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], maximumActiveJobs: 1,
+ jobs: { configured: Boolean(jobRoot), kinds: ['image', 'stills', 'video'], passes: RENDER_PASS_NAMES, maximumActiveJobs: 1,
maximumDuration: 30, maximumFps: 30, maximumFrames: 900, maximumStills: 8,
encoder: 'CPU H.264', audio: false, previewSuspendedDuringJob: true,
glbExport: { maximumBytes: MAXIMUM_GLB_BYTES, maximumKept: MAXIMUM_KEPT_GLBS, maximumTextureSize: 4096 },
diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjs
index 7401b2b2..80b583ef 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, LIGHTING_SETUP_NAMES } from '../src/agent-scene-capabilities.js';
+import { MATERIAL_PATTERN_TYPES, LIGHTING_SETUP_NAMES, RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
import { MATERIAL_LAYER_SCALAR_RANGES, MATERIAL_LAYER_COLOR_RANGES } from '../src/material-layers.js';
const finite = z.number().min(-3.4028234663852886e38).max(3.4028234663852886e38);
@@ -188,6 +188,8 @@ const effects = z.strictObject({
threshold: bounded(0, 10).optional(),
radius: bounded(0.1, 4).optional(),
}).optional(),
+ depthOfField: z.strictObject({ blur: unit.optional(), focusDistance: bounded(0.01, 100000).optional() }).optional().describe('Lens blur: blur 0 off to 1, focusDistance metres (5).'),
+ motionBlur: z.strictObject({ shutter: bounded(0, 0.5).optional() }).optional().describe('Camera motion smear in seconds; render jobs with settings.motion.'),
});
const shadow = z.strictObject({
target: boundedVector(-1e6, 1e6).optional(),
@@ -524,6 +526,7 @@ const renderSettings = z.strictObject({
animation: z.strictObject({ clip: z.number().int().min(0), start: z.number().min(0).max(3600).optional() }).optional(),
motion: z.strictObject({ start: z.number().min(0).max(3600).optional() }).optional(),
rendererTime: z.strictObject({ start: z.number().min(0).max(3600).optional(), rate: z.number().min(-16).max(16).optional() }).optional(),
+ passes: z.array(z.enum(RENDER_PASS_NAMES)).min(1).max(RENDER_PASS_NAMES.length).optional().describe('image and stills only: also write these raw, unantialiased PNGs per frame as render-<pass>.png or frame-N-<pass>.png. Opaque and cutout geometry only. depth packs 16 bits in red and green over 100 m, objectId packs 24 bits in RGB and its result lists the part names.'),
}).describe('Immutable snapshot render: one PNG, eight evenly spaced PNGs, or CPU H.264 MP4. Video dimensions must be even. Defaults: 24 fps, one second. Use motion.start for authored recipe tracks, animation for an imported clip, or both to layer them. Omitted motion holds time zero. Nonlooping samples must fit the authored duration.');
const readOnly = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
const edit = { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false };
diff --git a/scripts/smoke-render-passes.mjs b/scripts/smoke-render-passes.mjs
new file mode 100644
index 00000000..796991e3
--- /dev/null
+++ b/scripts/smoke-render-passes.mjs
@@ -0,0 +1,123 @@
+// Proves the two done conditions of render passes through the real MCP runtime: render jobs write every pass to a
+// file, and a seek to any frame gives the same pixels, with depth of field and motion blur on.
+import assert from 'node:assert/strict';
+import { createHash } from 'node:crypto';
+import { mkdtemp, readFile, writeFile } from 'node:fs/promises';
+import { tmpdir, constants, setPriority } from 'node:os';
+import { join, resolve } from 'node:path';
+import { setTimeout as delay } from 'node:timers/promises';
+import { Client } from '@modelcontextprotocol/client';
+import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
+
+setPriority(0, constants.priority.PRIORITY_BELOW_NORMAL);
+const directory = await mkdtemp(join(tmpdir(), '67js-mcp-passes-'));
+const jobs = join(directory, 'jobs');
+const cli = resolve(process.argv[2] ?? 'bin/67js-mcp.mjs');
+const backend = process.argv[3] ?? 'cpu';
+const transport = new StdioClientTransport({ command: process.execPath,
+ args: [cli, '--backend', backend, '--memory', '128', '--jobs', jobs], cwd: directory, stderr: 'pipe' });
+let diagnostics = '';
+transport.stderr.on('data', bytes => { diagnostics = (diagnostics + bytes).slice(-8192); });
+const client = new Client({ name: '67js-passes-proof', version: '1' });
+const ALL_PASSES = ['albedo', 'normal', 'emission', 'depth', 'objectId'];
+const SIZE = 160;
+
+async function call(name, argumentsValue = {}, timeout = 60000) {
+ const result = await client.callTool({ name, arguments: argumentsValue }, { timeout });
+ assert.equal(result.isError, undefined, result.content?.find(item => item.type === 'text')?.text);
+ return result;
+}
+
+async function finished(jobId) {
+ const deadline = Date.now() + 120000;
+ while (Date.now() < deadline) {
+ const record = (await call('scene_render_status', { jobId })).structuredContent;
+ if (['completed', 'cancelled', 'failed'].includes(record.state)) return record;
+ await delay(100);
+ }
+ throw new Error('Job did not finish within 120 seconds.');
+}
+
+async function runJob(sessionId, settings, expectedRevision = 0) {
+ const submitted = (await call('scene_render_submit', { sessionId, expectedRevision, settings })).structuredContent;
+ const record = await finished(submitted.jobId);
+ assert.equal(record.state, 'completed', record.reason);
+ const result = (await call('scene_render_result', { jobId: submitted.jobId })).structuredContent;
+ const files = new Map();
+ for (const artifact of result.artifacts) {
+ const bytes = await readFile(artifact.path);
+ assert.equal(createHash('sha256').update(bytes).digest('hex'), artifact.sha256);
+ files.set(artifact.path.split(/[\\/]/).pop(), bytes);
+ }
+ await call('scene_render_release', { jobId: submitted.jobId });
+ return { files, metrics: result.metrics ?? record.metrics };
+}
+
+function recipe() {
+ return {
+ format: '67js.scene', schemaVersion: 1,
+ geometries: [{ id: 'box', type: 'box' }, { id: 'sphere', type: 'sphere', segments: 24, rings: 16 }],
+ materials: [
+ { id: 'red', color: [0.8, 0.1, 0.1], roughness: 0.6 },
+ { id: 'glow', color: [0.1, 0.3, 0.9], emission: 2 },
+ ],
+ nodes: [
+ { id: 'floor', geometry: 'box', material: 'red', translation: [0, -0.1, 0], scale: [12, 0.2, 12] },
+ { id: 'near-ball', geometry: 'sphere', material: 'glow', translation: [-0.6, 0.5, 1.5], scale: [1, 1, 1] },
+ { id: 'far-block', geometry: 'box', material: 'red', translation: [1.4, 0.5, -3], scale: [1, 1, 1] },
+ ],
+ camera: { eye: [0, 1.6, 6], target: [0, 0.5, 0], fov: 40 },
+ effects: { depthOfField: { blur: 0.8, focusDistance: 4.5 }, motionBlur: { shutter: 0.25 } },
+ motion: { duration: 2, tracks: [{ kind: 'camera', property: 'eye', keyframes: [
+ { time: 0, value: [-2, 1.6, 6] }, { time: 2, value: [2, 1.6, 6] },
+ ] }] },
+ };
+}
+
+function pixelDigest(png) {
+ return createHash('sha256').update(png).digest('hex').slice(0, 12);
+}
+
+try {
+ await client.connect(transport);
+ const created = (await call('scene_create', { recipe: recipe() }, 180000)).structuredContent;
+ const sessionId = created.sessionId;
+ const base = { width: SIZE, height: SIZE, motion: { start: 0 } };
+
+ // Done condition 2: every pass becomes a file.
+ const stills = await runJob(sessionId, { ...base, kind: 'stills', duration: 2, passes: ALL_PASSES });
+ assert.equal(stills.files.size, 8 * (1 + ALL_PASSES.length));
+ for (const pass of ALL_PASSES) assert.ok(stills.files.has(`frame-3-${pass}.png`), `frame-3-${pass}.png is missing.`);
+ assert.deepEqual([...stills.metrics.objectNames].sort(), ['far-block', 'floor', 'near-ball']);
+ for (const [name, bytes] of process.env.RENDER_PASSES_COPY_DIRECTORY ? stills.files : []) await writeFile(join(process.env.RENDER_PASSES_COPY_DIRECTORY, name), bytes);
+ const digests = new Set(ALL_PASSES.map(pass => pixelDigest(stills.files.get(`frame-3-${pass}.png`))));
+ assert.equal(digests.size, ALL_PASSES.length, 'Each pass must differ from the others.');
+ assert.notEqual(pixelDigest(stills.files.get('frame-0.png')), pixelDigest(stills.files.get('frame-7.png')), 'The camera move must change the lit image.');
+
+ // Done condition 1: a seek to frame 3 gives the same pixels as that frame inside the sequence, in any order.
+ const frameTime = 2 * 3 / 7;
+ const seekOrder = [frameTime, 1.9, 0, frameTime];
+ for (const time of seekOrder) {
+ const seek = await runJob(sessionId, { ...base, kind: 'image', motion: { start: time }, passes: ALL_PASSES });
+ if (time === frameTime) {
+ assert.deepEqual(seek.files.get('render.png'), stills.files.get('frame-3.png'), 'Lit frame differs after a seek.');
+ for (const pass of ALL_PASSES) {
+ assert.deepEqual(seek.files.get(`render-${pass}.png`), stills.files.get(`frame-3-${pass}.png`), `${pass} differs after a seek.`);
+ }
+ }
+ }
+
+ // The effects visibly act: the same frame without them is different.
+ const plain = (await call('scene_apply', { sessionId, expectedRevision: 0, operations: [
+ { type: 'set-effects', effects: { depthOfField: { blur: 0 }, motionBlur: { shutter: 0 } } },
+ ] })).structuredContent;
+ assert.equal(plain.committed, true);
+ const unblurred = await runJob(sessionId, { ...base, kind: 'image', motion: { start: frameTime } }, plain.revision);
+ assert.notEqual(unblurred.files.get('render.png').equals(stills.files.get('frame-3.png')), true, 'Depth of field and motion blur changed nothing.');
+ console.log(`render passes smoke passed on ${backend}: ${stills.files.size} files, ${seekOrder.length} seeks identical (${stills.metrics.graphics})`);
+} catch (error) {
+ console.error(diagnostics);
+ throw error;
+} finally {
+ await client.close();
+}
diff --git a/skills/build-67js-scene/references/scene-contract.md b/skills/build-67js-scene/references/scene-contract.md
index 05d23935..7579fdaf 100644
--- a/skills/build-67js-scene/references/scene-contract.md
+++ b/skills/build-67js-scene/references/scene-contract.md
@@ -199,6 +199,8 @@ Read `docs/agent-look.md` for authored lighting, fog, effects and shadow coverag
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`, `spotLights` and `areaLights` fields each replace the full list. Point and spot lights cast shadows only with `castShadow: true`; area lights never do.
+`effects.depthOfField` (`blur` 0 to 1, `focusDistance` in metres) and `effects.motionBlur` (`shutter` seconds, camera tracks only, render jobs with `settings.motion`) are off by default and repeat per frame. A render job of kind `image` or `stills` with `settings.passes` (`albedo`, `normal`, `emission`, `depth`, `objectId`) also writes each pass as a raw PNG; `docs/agent-render-jobs.md` gives the encodings.
+
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.
Checkpoint before relighting, inspect the actual image and restore or export the complete recipe. Look changes retain topology and geometry.
diff --git a/src/agent-look.js b/src/agent-look.js
index 2434981d..851655a8 100644
--- a/src/agent-look.js
+++ b/src/agent-look.js
@@ -11,7 +11,7 @@ const ENVIRONMENT_FIELDS = [
'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', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom'];
+const EFFECT_FIELDS = ['exposure', 'saturation', 'contrast', 'temperature', 'vignette', 'grain', 'ambientOcclusion', 'ambientOcclusionRadius', 'bloom', 'depthOfField', 'motionBlur'];
const SHADOW_FIELDS = ['target', 'extent', 'distance', 'near', 'far'];
const POINT_LIGHT_FIELDS = ['position', 'color', 'intensity', 'radius', 'range', 'castShadow'];
const SPOT_LIGHT_FIELDS = ['position', 'direction', 'angle', 'penumbra', 'color', 'intensity', 'radius', 'range', 'castShadow'];
@@ -19,6 +19,8 @@ const AREA_LIGHT_FIELDS = ['position', 'direction', 'up', 'width', 'height', 'co
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'];
+const DEPTH_OF_FIELD_FIELDS = ['blur', 'focusDistance'];
+const MOTION_BLUR_FIELDS = ['shutter'];
function plainObject(value, label) {
if (!value || typeof value !== 'object' || Array.isArray(value) ||
@@ -260,20 +262,24 @@ export function agentEnvironmentMap(environment) {
function effectsFrom(input = {}) {
knownKeys(input, EFFECT_FIELDS, 'effects');
+ const groupFields = { bloom: BLOOM_FIELDS, depthOfField: DEPTH_OF_FIELD_FIELDS, motionBlur: MOTION_BLUR_FIELDS };
for (const field of EFFECT_FIELDS) {
- if (field !== 'bloom' && Object.hasOwn(input, field)) {
+ if (!(field in groupFields) && Object.hasOwn(input, field)) {
numberInRange(input[field], -Number.MAX_VALUE, Number.MAX_VALUE, `effects.${field}`);
}
}
- const bloom = fallback(input.bloom, {});
- knownKeys(bloom, BLOOM_FIELDS, 'bloom');
- for (const field of BLOOM_FIELDS) {
- if (Object.hasOwn(bloom, field)) {
- numberInRange(bloom[field], -Number.MAX_VALUE, Number.MAX_VALUE, `bloom.${field}`);
+ const groups = {};
+ for (const [group, fields] of Object.entries(groupFields)) {
+ groups[group] = fallback(input[group], {});
+ knownKeys(groups[group], fields, group);
+ for (const field of fields) {
+ if (Object.hasOwn(groups[group], field)) {
+ numberInRange(groups[group][field], -Number.MAX_VALUE, Number.MAX_VALUE, `${group}.${field}`);
+ }
}
}
const ambientOcclusion = fallback(input.ambientOcclusion, DEFAULT_AMBIENT_OCCLUSION);
- const resolved = resolveEffects({ ...input, ambientOcclusion, bloom: { strength: 0.12, threshold: 1, radius: 1, ...bloom } });
+ const resolved = resolveEffects({ ...input, ambientOcclusion, ...groups, bloom: { strength: 0.12, threshold: 1, radius: 1, ...groups.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.js
index 87ad67e2..3ebe9af0 100644
--- a/src/agent-scene-capabilities.js
+++ b/src/agent-scene-capabilities.js
@@ -23,6 +23,11 @@ export const LIGHTING_SETUP_NAMES = Object.freeze(['daylight', 'overcast', 'suns
export const DEFAULT_LIGHTING_SETUP = 'daylight';
export const DEFAULT_AMBIENT_OCCLUSION = 0;
+// Render passes a render job can write next to the lit image (see RENDER_PASS_MODES in renderer.js, which must list the same names).
+export const RENDER_PASS_NAMES = Object.freeze(['albedo', 'normal', 'emission', 'depth', 'objectId']);
+// Metres that depth pass values 0 to 65535 span, measured from the camera.
+export const RENDER_PASS_DEPTH_RANGE = 100;
+
export const AGENT_SCENE_CAPABILITIES = Object.freeze({
format: '67js.scene', schemaVersion: 1,
geometryTypes: Object.freeze(['box', 'cylinder', 'sphere', 'torus', 'lathe', 'extrude', 'tube', 'mesh']),
diff --git a/src/camera-effects.js b/src/camera-effects.js
new file mode 100644
index 00000000..0af48511
--- /dev/null
+++ b/src/camera-effects.js
@@ -0,0 +1,212 @@
+import { mat4 } from 'gl-matrix';
+import { applyProjection } from './camera.js';
+import { compileProgram, fullscreenVertex } from './gl-program.js';
+
+// Depth of field and camera motion blur as optional full-frame stages. The core renderer carries no shader text for
+// them: installCameraEffects adds the stages, and each one compiles and allocates only when a frame turns it on.
+//
+// Both are deterministic. They read only the resolved frame, its depth and the camera of this frame (plus the camera
+// of an earlier instant that the caller samples from time, never from render history). Sample patterns are fixed and
+// the per-pixel rotation comes from the pixel position, so a seek to a frame repeats the same pixels.
+
+const DEPTH_OF_FIELD_SAMPLES = 32;
+const MOTION_BLUR_SAMPLES = 16;
+// Largest blur circle as a fraction of image height at full blur; the blur setting scales it from zero.
+const MAXIMUM_BLUR_HEIGHT_FRACTION = 0.05;
+// Longest motion streak as a fraction of the frame, so a camera cut cannot smear the whole image.
+const MAXIMUM_STREAK = 0.1;
+
+const sharedFragmentHeader = `#version 300 es
+precision highp float;
+in vec2 textureCoordinate;
+uniform sampler2D sourceTexture;
+uniform sampler2D sceneDepth;
+uniform mat4 inverseViewProjection;
+uniform vec2 resolution;
+out vec4 outputColor;
+float pixelRotation() {
+ return 6.2831853 * fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
+}
+vec3 worldPointAt(vec2 coordinate) {
+ float depth = texture(sceneDepth, coordinate).r;
+ vec4 point = inverseViewProjection * vec4(coordinate * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
+ return point.xyz / point.w;
+}
+`;
+
+export const depthOfFieldFragment = `${sharedFragmentHeader}
+uniform vec3 eye;
+uniform vec3 forward;
+uniform float focusDistance;
+uniform float blurPixels;
+float blurRadius(vec2 coordinate) {
+ float distanceAlongView = max(dot(worldPointAt(coordinate) - eye, forward), 0.001);
+ // Thin-lens shape: zero at the focus plane, rising toward one for very near and very far surfaces.
+ return blurPixels * clamp(abs(distanceAlongView - focusDistance) / distanceAlongView, 0.0, 1.0);
+}
+void main() {
+ float centerRadius = blurRadius(textureCoordinate);
+ vec4 center = texture(sourceTexture, textureCoordinate);
+ if (centerRadius < 0.5) {
+ outputColor = center;
+ return;
+ }
+ float rotation = pixelRotation();
+ vec4 sum = center;
+ float weightSum = 1.0;
+ for (int index = 0; index < ${DEPTH_OF_FIELD_SAMPLES}; index++) {
+ float ring = sqrt((float(index) + 0.5) / ${DEPTH_OF_FIELD_SAMPLES}.0);
+ float angle = float(index) * 2.3999632 + rotation;
+ vec2 offsetPixels = vec2(cos(angle), sin(angle)) * ring * centerRadius;
+ vec2 coordinate = textureCoordinate + offsetPixels / resolution;
+ // A sample only spreads onto this pixel when its own circle reaches it, so sharp foreground does not bleed.
+ float reach = clamp(blurRadius(coordinate) - length(offsetPixels) + 1.0, 0.0, 1.0);
+ sum += texture(sourceTexture, coordinate) * reach;
+ weightSum += reach;
+ }
+ outputColor = sum / weightSum;
+}`;
+
+export const motionBlurFragment = `${sharedFragmentHeader}
+uniform mat4 previousViewProjection;
+void main() {
+ vec3 world = worldPointAt(textureCoordinate);
+ vec4 previousClip = previousViewProjection * vec4(world, 1.0);
+ vec2 velocity = vec2(0.0);
+ if (previousClip.w > 0.0) velocity = (previousClip.xy / previousClip.w * 0.5 + 0.5) - textureCoordinate;
+ float streak = length(velocity);
+ if (streak > ${MAXIMUM_STREAK}) velocity *= ${MAXIMUM_STREAK} / streak;
+ if (length(velocity * resolution) < 0.5) {
+ outputColor = texture(sourceTexture, textureCoordinate);
+ return;
+ }
+ float jitter = pixelRotation() / 6.2831853;
+ vec4 sum = vec4(0.0);
+ for (int index = 0; index < ${MOTION_BLUR_SAMPLES}; index++) {
+ float along = (float(index) + jitter) / ${MOTION_BLUR_SAMPLES}.0;
+ sum += texture(sourceTexture, textureCoordinate + velocity * along);
+ }
+ outputColor = sum / ${MOTION_BLUR_SAMPLES}.0;
+}`;
+
+function createTarget(renderer) {
+ const context = renderer.context;
+ const { width, height } = renderer.canvas;
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D, texture);
+ context.texImage2D(context.TEXTURE_2D, 0, renderer.hdr ? context.RGBA16F : context.RGBA8, width, height, 0, context.RGBA,
+ renderer.hdr ? context.HALF_FLOAT : 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);
+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) {
+ throw new Error('Camera effect framebuffer allocation failed. Choose a lower quality preset.');
+ }
+ return { texture, framebuffer };
+}
+
+/**
+ * One full-frame stage. `isActive` decides from the resolved effects whether it runs, and `setUniforms` fills the
+ * values that are specific to the effect.
+ */
+function createStage({ name, fragment, uniformNames, isActive, setUniforms }) {
+ let program = null;
+ let uniforms = null;
+ let target = null;
+
+ function releaseTargets(context) {
+ if (!target) return;
+ context.deleteTexture(target.texture);
+ context.deleteFramebuffer(target.framebuffer);
+ target = null;
+ }
+
+ function apply(renderer, frame, effects, sourceTexture) {
+ if (!isActive(effects, frame)) return null;
+ if (!renderer.depthTexture) throw new Error(`${name} requires depth:true on the renderer.`);
+ const context = renderer.context;
+ if (!program) {
+ program = compileProgram(context, fullscreenVertex, fragment);
+ const names = ['sourceTexture', 'sceneDepth', 'inverseViewProjection', 'resolution', ...uniformNames];
+ uniforms = Object.fromEntries(names.map(uniformName => [uniformName, context.getUniformLocation(program, uniformName)]));
+ }
+ target ??= createTarget(renderer);
+ context.bindFramebuffer(context.FRAMEBUFFER, target.framebuffer);
+ context.viewport(0, 0, renderer.canvas.width, renderer.canvas.height);
+ context.disable(context.DEPTH_TEST);
+ context.disable(context.CULL_FACE);
+ context.bindVertexArray(null);
+ context.useProgram(program);
+ context.activeTexture(context.TEXTURE0);
+ context.bindTexture(context.TEXTURE_2D, sourceTexture);
+ context.uniform1i(uniforms.sourceTexture, 0);
+ context.activeTexture(context.TEXTURE1);
+ context.bindTexture(context.TEXTURE_2D, renderer.depthTexture);
+ context.uniform1i(uniforms.sceneDepth, 1);
+ context.uniformMatrix4fv(uniforms.inverseViewProjection, false, renderer.inverseViewProjection);
+ context.uniform2f(uniforms.resolution, renderer.canvas.width, renderer.canvas.height);
+ setUniforms(context, uniforms, renderer, frame, effects);
+ context.drawArrays(context.TRIANGLES, 0, 3);
+ return target.texture;
+ }
+
+ function dispose(context) {
+ releaseTargets(context);
+ if (program) context.deleteProgram(program);
+ program = null;
+ }
+
+ return { name, apply, releaseTargets, dispose };
+}
+
+function createDepthOfFieldStage() {
+ return createStage({
+ name: 'Depth of field',
+ fragment: depthOfFieldFragment,
+ uniformNames: ['eye', 'forward', 'focusDistance', 'blurPixels'],
+ isActive: effects => effects.depthOfField.blur > 0,
+ setUniforms(context, uniforms, renderer, frame, effects) {
+ context.uniform3fv(uniforms.eye, frame.eye);
+ context.uniform3fv(uniforms.forward, renderer.viewForward);
+ context.uniform1f(uniforms.focusDistance, effects.depthOfField.focusDistance);
+ context.uniform1f(uniforms.blurPixels, effects.depthOfField.blur * MAXIMUM_BLUR_HEIGHT_FRACTION * renderer.canvas.height);
+ },
+ });
+}
+
+function createMotionBlurStage() {
+ return createStage({
+ name: 'Motion blur',
+ fragment: motionBlurFragment,
+ uniformNames: ['previousViewProjection'],
+ // Without a previous camera there is no known motion, so the frame passes through untouched.
+ isActive: (effects, frame) => effects.motionBlur.shutter > 0 && Boolean(frame.previousCamera),
+ setUniforms(context, uniforms, renderer, frame) {
+ context.uniformMatrix4fv(uniforms.previousViewProjection, false, previousViewProjectionOf(renderer, frame));
+ },
+ });
+}
+
+// The previous camera only replaces what it names (eye, target, up, lens), so a partial camera works.
+function previousViewProjectionOf(renderer, frame) {
+ const previous = { ...frame, ...frame.previousCamera };
+ const aspect = renderer.canvas.width / renderer.canvas.height;
+ const projection = applyProjection(mat4.create(), previous, aspect, { world: renderer.world });
+ const view = mat4.lookAt(mat4.create(), previous.eye, previous.target ?? [0, 1.2, 0], previous.up ?? [0, 1, 0]);
+ return mat4.multiply(mat4.create(), projection, view);
+}
+
+/**
+ * Adds depth of field and camera motion blur to a renderer. Both need `depth: true`. Motion blur reads
+ * `frame.previousCamera`, the camera at the start of the shutter interval; derive it from the frame time.
+ */
+export function installCameraEffects(renderer) {
+ if (!renderer.postStages.some(stage => stage.name === 'Depth of field')) {
+ renderer.postStages.push(createDepthOfFieldStage(), createMotionBlurStage());
+ }
+ return renderer;
+}
diff --git a/src/effects.js b/src/effects.js
index 0429bcbb..1cb65407 100644
--- a/src/effects.js
+++ b/src/effects.js
@@ -1,7 +1,10 @@
+// Camera effects stay off in every preset; a recipe turns them on with a blur above zero or a shutter above zero.
+const CAMERA_OFF = Object.freeze({ depthOfField: Object.freeze({ blur: 0, focusDistance: 5 }), motionBlur: Object.freeze({ shutter: 0 }) });
+
export const EFFECT_PRESETS = Object.freeze({
- 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 }) }),
+ neutral: Object.freeze({ depthOfField: CAMERA_OFF.depthOfField, motionBlur: CAMERA_OFF.motionBlur, 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({ depthOfField: CAMERA_OFF.depthOfField, motionBlur: CAMERA_OFF.motionBlur, 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({ depthOfField: CAMERA_OFF.depthOfField, motionBlur: CAMERA_OFF.motionBlur, 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) {
@@ -14,7 +17,16 @@ export function resolveEffects(effects = {}) {
if (!effects || typeof effects !== 'object' || Array.isArray(effects)) throw new Error('Effects must be an object.');
const bloom = effects.bloom ?? {};
if (!bloom || typeof bloom !== 'object' || Array.isArray(bloom)) throw new Error('Bloom must be an object.');
+ const depthOfField = effects.depthOfField ?? {};
+ const motionBlur = effects.motionBlur ?? {};
+ if (typeof depthOfField !== 'object' || Array.isArray(depthOfField)) throw new Error('Depth of field must be an object.');
+ if (typeof motionBlur !== 'object' || Array.isArray(motionBlur)) throw new Error('Motion blur must be an object.');
return {
+ depthOfField: {
+ blur: numberInRange(depthOfField.blur, 0, 0, 1, 'Depth of field blur'),
+ focusDistance: numberInRange(depthOfField.focusDistance, 5, 0.01, 100000, 'Depth of field focus distance'),
+ },
+ motionBlur: { shutter: numberInRange(motionBlur.shutter, 0, 0, 0.5, 'Motion blur shutter') },
saturation: numberInRange(effects.saturation, 1, 0, 2, 'Saturation'),
contrast: numberInRange(effects.contrast, 1, 0.1, 2, 'Contrast'),
temperature: numberInRange(effects.temperature, 0, -1, 1, 'Temperature'),
diff --git a/src/gl-program.js b/src/gl-program.js
new file mode 100644
index 00000000..bf925111
--- /dev/null
+++ b/src/gl-program.js
@@ -0,0 +1,42 @@
+// Shader program helpers shared by the renderer and its optional addons, kept apart so an addon does not pull in the renderer.
+
+export const fullscreenVertex = `#version 300 es
+precision highp float;
+out vec2 textureCoordinate;
+void main() {
+ vec2 position = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
+ textureCoordinate = position;
+ gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0);
+}`;
+
+// Starting a program without asking for its result lets the driver build several programs at once.
+export function startProgram(context, vertexSource, fragmentSource) {
+ const program = context.createProgram();
+ context.getExtension('KHR_parallel_shader_compile');
+ const shaders = [];
+ for (const [kind, source] of [[context.VERTEX_SHADER, vertexSource], [context.FRAGMENT_SHADER, fragmentSource]]) {
+ const shader = context.createShader(kind);
+ context.shaderSource(shader, source);
+ context.compileShader(shader);
+ context.attachShader(program, shader);
+ shaders.push(shader);
+ }
+ context.linkProgram(program);
+ return { program, shaders };
+}
+
+export function finishProgram(context, { program, shaders }) {
+ const linked = context.getProgramParameter(program, context.LINK_STATUS);
+ const failedShader = shaders.find(shader => !context.getShaderParameter(shader, context.COMPILE_STATUS));
+ const message = failedShader ? context.getShaderInfoLog(failedShader) : context.getProgramInfoLog(program);
+ shaders.forEach((shader) => context.deleteShader(shader));
+ if (!linked) {
+ context.deleteProgram(program);
+ throw new Error(failedShader ? `Shader compilation failed: ${message}` : `Shader linking failed: ${message}`);
+ }
+ return program;
+}
+
+export function compileProgram(context, vertexSource, fragmentSource) {
+ return finishProgram(context, startProgram(context, vertexSource, fragmentSource));
+}
diff --git a/src/post.js b/src/post.js
index f2d34826..27ba77de 100644
--- a/src/post.js
+++ b/src/post.js
@@ -1,11 +1,4 @@
-export const fullscreenVertex = `#version 300 es
-precision highp float;
-out vec2 textureCoordinate;
-void main() {
- vec2 position = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
- textureCoordinate = position;
- gl_Position = vec4(position * 2.0 - 1.0, 0.0, 1.0);
-}`;
+export { fullscreenVertex } from './gl-program.js';
export const postFragment = `#version 300 es
precision highp float;
diff --git a/src/render-passes.js b/src/render-passes.js
new file mode 100644
index 00000000..83fa1d1b
--- /dev/null
+++ b/src/render-passes.js
@@ -0,0 +1,109 @@
+import { compileProgram, fullscreenVertex } from './gl-program.js';
+
+// Render passes draw raw material data (albedo, normal, emission, depth, object ID) instead of the lit image.
+// The shader branch lives in the main fragment shader behind the `renderPass` feature, which compiles on the first
+// pass request; this addon owns the rest: the target, the copy to the canvas and the object ID table.
+
+/** The shader's `renderPassMode` for each pass name. agent-scene-capabilities.js lists the same names. */
+export const RENDER_PASS_MODES = Object.freeze({ albedo: 1, normal: 2, emission: 3, depth: 4, objectId: 5 });
+// Background pixels: depth reads as the far limit; every other pass reads zero, and object ID zero means no object.
+const PASS_BACKGROUNDS = Object.freeze({ depth: [1, 1, 0, 1] });
+const DEFAULT_BACKGROUND = Object.freeze([0, 0, 0, 1]);
+
+// Copies a pass texture to the canvas byte for byte: one texel per pixel, no filtering, no grading.
+const passCopyFragment = `#version 300 es
+precision highp float;
+uniform sampler2D sourceTexture;
+out vec4 outputColor;
+void main() { outputColor = vec4(texelFetch(sourceTexture, ivec2(gl_FragCoord.xy), 0).rgb, 1.0); }`;
+
+function createPassTarget(context, width, height) {
+ const texture = context.createTexture();
+ context.bindTexture(context.TEXTURE_2D, texture);
+ context.texImage2D(context.TEXTURE_2D, 0, context.RGBA8, width, height, 0, context.RGBA, context.UNSIGNED_BYTE, null);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MIN_FILTER, context.NEAREST);
+ context.texParameteri(context.TEXTURE_2D, context.TEXTURE_MAG_FILTER, context.NEAREST);
+ const depth = context.createRenderbuffer();
+ context.bindRenderbuffer(context.RENDERBUFFER, depth);
+ context.renderbufferStorage(context.RENDERBUFFER, context.DEPTH_COMPONENT24, width, height);
+ const framebuffer = context.createFramebuffer();
+ context.bindFramebuffer(context.FRAMEBUFFER, framebuffer);
+ context.framebufferTexture2D(context.FRAMEBUFFER, context.COLOR_ATTACHMENT0, context.TEXTURE_2D, texture, 0);
+ context.framebufferRenderbuffer(context.FRAMEBUFFER, context.DEPTH_ATTACHMENT, context.RENDERBUFFER, depth);
+ if (context.checkFramebufferStatus(context.FRAMEBUFFER) !== context.FRAMEBUFFER_COMPLETE) {
+ throw new Error('Render pass framebuffer allocation failed. Choose a lower quality preset.');
+ }
+ return { texture, depth, framebuffer };
+}
+
+/**
+ * Lets `renderer.render({ ...camera, pass })` draw one pass. Passes draw without multisampling into their own target,
+ * so object IDs and normals stay exact at silhouettes. Only opaque and cutout parts appear. `passDepthRange` is the
+ * number of metres that depth values 0 to 65535 span (default 100).
+ */
+export function installRenderPasses(renderer) {
+ if (renderer.passSupport) return renderer;
+ let target = null;
+ let copyProgram = null;
+ let copyTextureUniform = null;
+
+ function releaseTargets(context) {
+ if (!target) return;
+ context.deleteTexture(target.texture);
+ context.deleteRenderbuffer(target.depth);
+ context.deleteFramebuffer(target.framebuffer);
+ target = null;
+ }
+
+ function dispose(context) {
+ releaseTargets(context);
+ if (copyProgram) context.deleteProgram(copyProgram);
+ copyProgram = null;
+ }
+
+ function prepare(frame) {
+ const mode = RENDER_PASS_MODES[frame.pass];
+ if (!mode) throw new RangeError(`Unknown render pass: ${frame.pass}. Use ${Object.keys(RENDER_PASS_MODES).join(', ')}.`);
+ if (renderer.benchmark) throw new Error('Render passes are unavailable in benchmark mode.');
+ const depthRange = frame.passDepthRange ?? 1;
+ if (!Number.isFinite(depthRange) || depthRange <= 0) throw new RangeError('Pass depth range must be positive and finite.');
+ const context = renderer.context;
+ renderer.requireFeatureNames(['renderPass']);
+ if (!copyProgram) {
+ copyProgram = compileProgram(context, fullscreenVertex, passCopyFragment);
+ copyTextureUniform = context.getUniformLocation(copyProgram, 'sourceTexture');
+ }
+ target ??= createPassTarget(context, renderer.canvas.width, renderer.canvas.height);
+ return mode;
+ }
+
+ function copyToCanvas() {
+ const context = renderer.context;
+ context.bindFramebuffer(context.FRAMEBUFFER, null);
+ context.viewport(0, 0, renderer.canvas.width, renderer.canvas.height);
+ context.disable(context.DEPTH_TEST);
+ context.disable(context.CULL_FACE);
+ context.bindVertexArray(null);
+ context.useProgram(copyProgram);
+ context.activeTexture(context.TEXTURE0);
+ context.bindTexture(context.TEXTURE_2D, target.texture);
+ context.uniform1i(copyTextureUniform, 0);
+ context.drawArrays(context.TRIANGLES, 0, 3);
+ }
+
+ // Part names by object ID minus one, in the order the object ID pass numbers them (draw order, grouped by geometry).
+ function objectNames() {
+ return renderer.batches.filter(batch => renderer.drawsInOpaqueLoop(batch)).flatMap(batch => batch.parts.map(part => part.name));
+ }
+
+ renderer.passSupport = {
+ prepare,
+ get framebuffer() { return target.framebuffer; },
+ background: pass => PASS_BACKGROUNDS[pass] ?? DEFAULT_BACKGROUND,
+ copyToCanvas,
+ objectNames,
+ releaseTargets,
+ dispose,
+ };
+ return renderer;
+}
diff --git a/src/renderer.js b/src/renderer.js
index 55f13634..2322ec8a 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 { postFragment, skyFragment, bloomFragment } from './post.js';
+import { fullscreenVertex, startProgram, finishProgram, compileProgram } from './gl-program.js';
import { ambientOcclusionFragment } from './ambient-occlusion.js';
import { planRenderSize, estimateTextureBytes, estimateFrameBytes } from './budget.js';
import { applyProjection } from './camera.js';
@@ -203,38 +204,6 @@ function packInstance(data, index, part, normalMatrix) {
data.set(part.material.emissiveColor ?? part.material.color, offset + 38);
}
-// Starting a program without asking for its result lets the driver build several programs at once.
-function startProgram(context, vertexSource, fragmentSource) {
- const program = context.createProgram();
- context.getExtension('KHR_parallel_shader_compile');
- const shaders = [];
- for (const [kind, source] of [[context.VERTEX_SHADER, vertexSource], [context.FRAGMENT_SHADER, fragmentSource]]) {
- const shader = context.createShader(kind);
- context.shaderSource(shader, source);
- context.compileShader(shader);
- context.attachShader(program, shader);
- shaders.push(shader);
- }
- context.linkProgram(program);
- return { program, shaders };
-}
-
-function finishProgram(context, { program, shaders }) {
- const linked = context.getProgramParameter(program, context.LINK_STATUS);
- const failedShader = shaders.find(shader => !context.getShaderParameter(shader, context.COMPILE_STATUS));
- const message = failedShader ? context.getShaderInfoLog(failedShader) : context.getProgramInfoLog(program);
- shaders.forEach((shader) => context.deleteShader(shader));
- if (!linked) {
- context.deleteProgram(program);
- throw new Error(failedShader ? `Shader compilation failed: ${message}` : `Shader linking failed: ${message}`);
- }
- return program;
-}
-
-function compileProgram(context, vertexSource, fragmentSource) {
- return finishProgram(context, startProgram(context, vertexSource, fragmentSource));
-}
-
function groundPart() {
return {
name: 'Studio floor',
@@ -368,6 +337,10 @@ export class Renderer67 {
this.batches = [];
this.partLocations = new Map();
this.updateBatches = new Set();
+ // Addons plug in here: full-frame effects (camera-effects.js) run between the resolve and the post pass, and
+ // render-passes.js sets passSupport. None by default.
+ this.postStages = [];
+ this.passSupport = null;
this.updateSkins = new Set();
this.updateMorphs = new Set();
this.skinTextures = new Map();
@@ -514,7 +487,7 @@ export class Renderer67 {
finishMainProgram(pendingProgram) {
this.program = finishProgram(this.context, pendingProgram);
- this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', '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)]));
+ this.uniforms = Object.fromEntries(['materialDielectric', 'materialCoat', 'materialSheen', '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', 'renderPassMode', 'renderPassDepthRange', 'renderPassObjectBase', ...ALPHA_UNIFORMS].map((name) => [name, this.context.getUniformLocation(this.program, name)]));
for (const name of LIGHT_UNIFORMS) {
this.uniforms[name] = this.context.getUniformLocation(this.program, name);
}
@@ -1142,6 +1115,8 @@ export class Renderer67 {
}
this.bloomTargets = [];
this.releaseOcclusionTarget();
+ this.passSupport?.releaseTargets(context);
+ for (const stage of this.postStages ?? []) stage.releaseTargets(context);
this.multisampleFramebuffer = null;
this.resolveFramebuffer = null;
this.multisampleColor = null;
@@ -1157,6 +1132,11 @@ export class Renderer67 {
this.occlusionTarget = null;
}
+ /** Whether a batch is drawn by the opaque loop, and so by render passes. Its parts take object IDs in this order. */
+ drawsInOpaqueLoop(batch) {
+ return batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend';
+ }
+
// Compiled and allocated on first use, so scenes without occlusion pay nothing.
ensureOcclusionTarget() {
const context = this.context;
@@ -1377,7 +1357,9 @@ export class Renderer67 {
context.bindFramebuffer(context.READ_FRAMEBUFFER, this.multisampleFramebuffer);
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);
+ let sourceTexture = this.frameTexture;
+ for (const stage of this.postStages) sourceTexture = stage.apply(this, frame, effects, sourceTexture) ?? sourceTexture;
+ if (effects.bloom.strength > 0) this.drawBloom(effects.bloom, sourceTexture);
const occluded = effects.ambientOcclusion > 0 && Boolean(this.depthTexture);
if (occluded) this.drawAmbientOcclusion(frame, effects);
context.bindFramebuffer(context.FRAMEBUFFER, null);
@@ -1387,7 +1369,7 @@ export class Renderer67 {
context.bindVertexArray(null);
context.useProgram(this.postProgram);
context.activeTexture(context.TEXTURE0);
- context.bindTexture(context.TEXTURE_2D, this.frameTexture);
+ context.bindTexture(context.TEXTURE_2D, sourceTexture);
context.uniform1i(this.postUniforms.frameTexture, 0);
context.activeTexture(context.TEXTURE1);
context.bindTexture(context.TEXTURE_2D, this.depthTexture ?? this.whiteTexture);
@@ -1501,7 +1483,7 @@ export class Renderer67 {
context.bindVertexArray(null);
}
- drawBloom(bloom) {
+ drawBloom(bloom, sourceTexture = this.frameTexture) {
const context = this.context;
context.disable(context.DEPTH_TEST);
context.disable(context.CULL_FACE);
@@ -1513,7 +1495,7 @@ export class Renderer67 {
for (let pass = 0; pass < 2; pass++) {
context.bindFramebuffer(context.FRAMEBUFFER, this.bloomTargets[pass].framebuffer);
context.activeTexture(context.TEXTURE0);
- context.bindTexture(context.TEXTURE_2D, pass === 0 ? this.frameTexture : this.bloomTargets[0].texture);
+ context.bindTexture(context.TEXTURE_2D, pass === 0 ? sourceTexture : this.bloomTargets[0].texture);
context.uniform1f(this.bloomUniforms.extract, pass === 0 ? 1 : 0);
context.uniform2f(this.bloomUniforms.texelDirection, pass === 0 ? bloom.radius / this.bloomWidth : 0, pass === 1 ? bloom.radius / this.bloomHeight : 0);
context.drawArrays(context.TRIANGLES, 0, 3);
@@ -1541,7 +1523,7 @@ export class Renderer67 {
}
return;
}
- const useCoverage = masked && this.samples > 1 && !this.benchmark;
+ const useCoverage = masked && this.samples > 1 && !this.benchmark && !this.renderingPass;
if (useCoverage) {
context.enable(context.SAMPLE_ALPHA_TO_COVERAGE);
} else {
@@ -1660,6 +1642,13 @@ export class Renderer67 {
this.context.drawElementsInstanced(this.context.TRIANGLES, batch.indexCount, this.context.UNSIGNED_INT, 0, batch.instanceCount);
}
+ // A render pass draws raw material data instead of the lit image; the addon validates frame.pass and returns the shader mode.
+ preparePass(frame) {
+ if (frame.pass === undefined) return 0;
+ if (!this.passSupport) throw new Error('Render passes need installRenderPasses(renderer) from 67js/addons/render-passes.');
+ return this.passSupport.prepare(frame);
+ }
+
render(frame) {
const { eye, target = [0, 1.2, 0], armorColor = [0.53, 0.39, 0.24], armorSurface = [0.88, 0.32], exposure = 1, inspection = false } = frame;
const effects = resolveEffects(frame.effects);
@@ -1680,6 +1669,8 @@ export class Renderer67 {
const windChanged = this.updateWindState(frame);
const casterChanged = this.assemblyAmount !== assemblyAmount || this.shadowsDirty || windChanged;
this.requireFeatureNames(shaderFeaturesOfLighting(this.lighting));
+ const passMode = this.preparePass(frame);
+ this.renderingPass = passMode > 0;
if (casterChanged) {
this.assemblyAmount = assemblyAmount;
this.createShadowMap();
@@ -1690,16 +1681,19 @@ export class Renderer67 {
mat4.lookAt(this.view, eye, target, frame.up ?? [0, 1, 0]);
mat4.multiply(this.viewProjection, this.projection, this.view);
mat4.invert(this.inverseViewProjection, this.viewProjection);
- context.bindFramebuffer(context.FRAMEBUFFER, this.benchmark ? null : this.multisampleFramebuffer);
+ this.viewForward = [-this.view[2], -this.view[6], -this.view[10]];
+ context.bindFramebuffer(context.FRAMEBUFFER, passMode ? this.passSupport.framebuffer : this.benchmark ? null : this.multisampleFramebuffer);
context.viewport(0, 0, this.canvas.width, this.canvas.height);
- if (this.transparent) {
+ if (passMode) {
+ context.clearColor(...this.passSupport.background(frame.pass));
+ } else if (this.transparent) {
context.clearColor(0, 0, 0, 0);
} else {
context.clearColor(0.145, 0.162, 0.177, 1);
}
context.clear(context.COLOR_BUFFER_BIT | context.DEPTH_BUFFER_BIT);
- const environmentBackgroundDrawn = this.drawEnvironmentBackground(environmentMap, frame, exposure);
- if (this.world && !this.benchmark && !environmentBackgroundDrawn) this.drawSky(frame);
+ const environmentBackgroundDrawn = !passMode && this.drawEnvironmentBackground(environmentMap, frame, exposure);
+ if (this.world && !this.benchmark && !passMode && !environmentBackgroundDrawn) this.drawSky(frame);
context.enable(context.DEPTH_TEST);
context.enable(context.CULL_FACE);
context.useProgram(this.program);
@@ -1735,19 +1729,29 @@ export class Renderer67 {
context.bindTexture(context.TEXTURE_2D, this.shadowTexture);
context.uniform1i(this.uniforms.shadowMap, 0);
this.applyEnvironmentUniforms(environmentMap);
+ context.uniform1f(this.uniforms.renderPassMode, passMode);
+ context.uniform1f(this.uniforms.renderPassDepthRange, frame.passDepthRange ?? 100);
+ let objectBase = 0;
for (const batch of this.batches) {
if (this.benchmark) {
this.drawBatch(batch, true);
- } else if (batchPass(batch) === 'opaque' && batch.alphaMode !== 'blend') {
+ } else if (this.drawsInOpaqueLoop(batch)) {
+ context.uniform1f(this.uniforms.renderPassObjectBase, objectBase);
+ objectBase += batch.instanceCount;
this.drawAlphaBatch(batch, true);
}
}
context.disable(context.SAMPLE_ALPHA_TO_COVERAGE);
context.enable(context.CULL_FACE);
context.bindVertexArray(null);
- if (!this.benchmark) this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);
- if (!this.benchmark) this.drawBlendBatches(frame);
- if (!this.benchmark) this.resolveFrame(frame, effects, environment, volume);
+ if (passMode) {
+ this.passSupport.copyToCanvas();
+ } else if (!this.benchmark) {
+ this.drawTranslucent(frame, environment, assemblyAmount, environmentMap);
+ this.drawBlendBatches(frame);
+ this.resolveFrame(frame, effects, environment, volume);
+ }
+ this.renderingPass = false;
this.cpuMilliseconds = performance.now() - start;
}
@@ -1790,6 +1794,8 @@ export class Renderer67 {
if (this.skyProgram) this.context.deleteProgram(this.skyProgram);
if (this.bloomProgram) this.context.deleteProgram(this.bloomProgram);
if (this.occlusionProgram) this.context.deleteProgram(this.occlusionProgram);
+ this.passSupport?.dispose(this.context);
+ for (const stage of this.postStages ?? []) stage.dispose(this.context);
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/src/shaders.js b/src/shaders.js
index 8f708643..41bc2816 100644
--- a/src/shaders.js
+++ b/src/shaders.js
@@ -117,6 +117,7 @@ out vec4 shadowPosition;
out vec2 textureUV;
out vec3 vertexTint;
flat out vec3 emissionColor;
+flat out float instanceOrdinal;
out vec3 boxPosition;
out vec3 boxNormal;
flat out mat3 boxNormalMatrix;
@@ -146,6 +147,7 @@ void main() {
textureUV = uv;
vertexTint = vertexColor;
emissionColor = instanceEmissive;
+ instanceOrdinal = float(gl_InstanceID);
surface = instanceSurface;
shadowPosition = lightProjection * world;
gl_Position = viewProjection * world;
@@ -355,7 +357,11 @@ in vec4 shadowPosition;
in vec2 textureUV;
in vec3 vertexTint;
flat in vec3 emissionColor;
+flat in float instanceOrdinal;
uniform vec3 eye;
+uniform float renderPassMode;
+uniform float renderPassDepthRange;
+uniform float renderPassObjectBase;
uniform vec3 armorColor;
uniform vec2 armorSurface;
uniform float exposure;
@@ -675,6 +681,23 @@ vec3 sheenLayer(vec3 baseRadiance, vec3 normal, vec3 viewDirection, float visibi
return baseRadiance * shadowedBase + keyTerm + rimTerm;
}
+// Raw data for a render pass: modes are 1 albedo, 2 normal, 3 emission, 4 depth, 5 object ID. Depth packs 16 bits
+// into red and green, object IDs pack 24 bits into red, green and blue. Nothing here is tone mapped or graded.
+vec3 renderPassValue(vec3 color, vec3 normal, vec3 emission) {
+ if (renderPassMode < 1.5) return clamp(color, 0.0, 1.0);
+ if (renderPassMode < 2.5) return normal * 0.5 + 0.5;
+ if (renderPassMode < 3.5) return clamp(emission, 0.0, 1.0);
+ if (renderPassMode < 4.5) {
+ float steps = floor(clamp(length(worldPosition - eye) / renderPassDepthRange, 0.0, 1.0) * 65535.0 + 0.5);
+ float high = floor(steps / 256.0);
+ return vec3(high, steps - high * 256.0, 0.0) / 255.0;
+ }
+ float identifier = renderPassObjectBase + instanceOrdinal + 1.0;
+ float high = floor(identifier / 65536.0);
+ float middle = floor((identifier - high * 65536.0) / 256.0);
+ return vec3(identifier - high * 65536.0 - middle * 256.0, middle, high) / 255.0;
+}
+
void main() {
vec3 normal = normalize(worldNormal);
// Foliage and grass cards are single-sided geometry whose shading normal already leans toward the
@@ -694,6 +717,10 @@ void main() {
float alpha = surfaceAlpha(textureAlpha);
vec3 emission = emissionColor * surface.z;
if (USES_EMISSIVE_MAP) emission *= texture(emissiveMap, textureUV).rgb;
+ if (USES_RENDER_PASS) {
+ outputColor = vec4(renderPassValue(color, normal, emission), 1.0);
+ return;
+ }
if (TAG_UNLIT) {
vec3 radiance = color * exposure + emission;
outputColor = vec4(hdrEnabled > 0.5 ? radiance : pow(max(radiance, vec3(0)), vec3(1.0 / 2.2)), alpha);
@@ -910,6 +937,7 @@ const SHADER_FEATURE_CONDITIONS = {
spotLights: ['USES_SPOT_LIGHTS', 'spotLightCount > 0'],
areaLights: ['USES_AREA_LIGHTS', 'areaLightCount > 0'],
localShadows: ['USES_LOCAL_SHADOWS', 'true'],
+ renderPass: ['USES_RENDER_PASS', 'renderPassMode > 0.5'],
};
export const SHADER_FEATURES = Object.freeze(Object.keys(SHADER_FEATURE_CONDITIONS));
diff --git a/tests/agent-look.test.js b/tests/agent-look.test.js
index bf0d5a60..7d6b7514 100644
--- a/tests/agent-look.test.js
+++ b/tests/agent-look.test.js
@@ -26,6 +26,7 @@ test('default look is complete, detached JSON and idempotent', () => {
volumeFog: resolveVolumeFog(),
});
assert.deepEqual(look.effects, {
+ depthOfField: { blur: 0, focusDistance: 5 }, motionBlur: { shutter: 0 },
saturation: 1, contrast: 1, temperature: 0, vignette: 0, grain: 0,
ambientOcclusion: 0, ambientOcclusionRadius: 0.5,
bloom: { strength: 0.12, threshold: 1, radius: 1 }, exposure: 1,
diff --git a/tests/agent-preview.test.js b/tests/agent-preview.test.js
index dfc1bab7..d7fc34ef 100644
--- a/tests/agent-preview.test.js
+++ b/tests/agent-preview.test.js
@@ -71,6 +71,8 @@ function previewHarness() {
parseGltf, Uint8Array, atob,
applyProjection, mat4, resolveAgentShadow, agentEnvironmentMap,
Renderer67: FaultInjectedRenderer,
+ // The optional addons only plug stages into a real renderer; the fault-injected one needs none.
+ installCameraEffects: renderer => renderer, installRenderPasses: renderer => renderer,
});
// Evaluate only trusted repository adapter code; inject the driver boundary for failure cases.
new Script(source).runInContext(context);
diff --git a/tests/agent-runtime.test.js b/tests/agent-runtime.test.js
index 6e9f2910..4bf7384c 100644
--- a/tests/agent-runtime.test.js
+++ b/tests/agent-runtime.test.js
@@ -6,7 +6,7 @@ import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import { randomUUID } from 'node:crypto';
import { createContext, Script } from 'node:vm';
-import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS } from '../src/agent-scene-capabilities.js';
+import { AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE } from '../src/agent-scene-capabilities.js';
import { normalizeReview, REVIEW_LIMITS } from '../scripts/agent-review.mjs';
test('runtime reports real scene capabilities without launching a browser and closes idempotently', async () => {
@@ -96,7 +96,7 @@ async function reviewRuntimeHarness({ failShot, blockShot = false, oversize = fa
const context = createContext({ createServer, randomUUID, existsSync: () => true,
readFile: async () => '', packageMetadata: { version: 'test' },
createRequire: () => ({ resolve: () => { throw new Error('no peer in tests'); } }),
- AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, normalizeReview, REVIEW_LIMITS, isPreviewHost,
+ AGENT_SCENE_CAPABILITIES, AGENT_SCENE_DEFAULT_LIMITS, RENDER_PASS_NAMES, RENDER_PASS_DEPTH_RANGE, normalizeReview, REVIEW_LIMITS, isPreviewHost,
chromium: { launch: async () => browser }, URL, Buffer, process, performance, setTimeout, clearTimeout,
});
new Script(`${source}\nglobalThis.runtime = createAgentRuntime({ backend: 'cpu' });`).runInContext(context);
diff --git a/tests/render-passes.test.js b/tests/render-passes.test.js
new file mode 100644
index 00000000..6d9e6bd9
--- /dev/null
+++ b/tests/render-passes.test.js
@@ -0,0 +1,97 @@
+import { mkdtemp, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { resolveEffects } from '../src/effects.js';
+import { normalizeAgentLook } from '../src/agent-look.js';
+import { RENDER_PASS_MODES, installRenderPasses } from '../src/render-passes.js';
+import { createFragmentShader } from '../src/shaders.js';
+import { RENDER_PASS_NAMES } from '../src/agent-scene-capabilities.js';
+import { installCameraEffects, depthOfFieldFragment, motionBlurFragment } from '../src/camera-effects.js';
+import { createAgentRenderJobs, artifactNames } from '../scripts/agent-render-jobs.mjs';
+
+const limits = { maxOutputBytes: 1024, maxFrameBytes: 128, maxStoreBytes: 1024 ** 2, cleanupMs: 100 };
+
+test('capabilities and the renderer list the same passes in the same order', () => {
+ assert.deepEqual(Object.keys(RENDER_PASS_MODES), [...RENDER_PASS_NAMES]);
+ assert.deepEqual(Object.values(RENDER_PASS_MODES), [1, 2, 3, 4, 5]);
+});
+
+test('the pass branch of the main shader is compiled out unless a pass is requested', () => {
+ assert.match(createFragmentShader([]), /#define USES_RENDER_PASS false/);
+ assert.match(createFragmentShader(['renderPass']), /#define USES_RENDER_PASS \(renderPassMode > 0\.5\)/);
+});
+
+test('camera effects default off, validate ranges and survive look normalization', () => {
+ const neutral = resolveEffects();
+ assert.equal(neutral.depthOfField.blur, 0);
+ assert.equal(neutral.motionBlur.shutter, 0);
+ const look = normalizeAgentLook({ effects: { depthOfField: { blur: 0.5 }, motionBlur: { shutter: 0.1 } } });
+ assert.deepEqual(look.effects.depthOfField, { blur: 0.5, focusDistance: 5 });
+ assert.equal(look.effects.motionBlur.shutter, 0.1);
+ assert.deepEqual(normalizeAgentLook(look), look);
+ for (const effects of [{ depthOfField: { blur: 2 } }, { depthOfField: { focusDistance: 0 } }, { depthOfField: { mystery: 1 } },
+ { motionBlur: { shutter: 0.6 } }, { motionBlur: { shutter: 'long' } }, { motionBlur: 1 }]) {
+ assert.throws(() => normalizeAgentLook({ effects }), undefined, JSON.stringify(effects));
+ }
+});
+
+test('installing camera effects adds two stages once and costs nothing until a frame uses them', () => {
+ const unusedContext = new Proxy({}, { get() { throw new Error('The GL context was touched.'); } });
+ const renderer = { postStages: [], context: unusedContext };
+ installCameraEffects(installCameraEffects(renderer));
+ assert.deepEqual(renderer.postStages.map(stage => stage.name), ['Depth of field', 'Motion blur']);
+ const effects = resolveEffects();
+ for (const stage of renderer.postStages) assert.equal(stage.apply(renderer, {}, effects, null), null);
+ const withoutPreviousCamera = resolveEffects({ motionBlur: { shutter: 0.2 } });
+ assert.equal(renderer.postStages[1].apply({ ...renderer, previousViewProjection: null }, {}, withoutPreviousCamera, null), null);
+ const blurred = resolveEffects({ depthOfField: { blur: 1 } });
+ assert.throws(() => renderer.postStages[0].apply(renderer, {}, blurred, null), /requires depth:true/);
+ for (const source of [depthOfFieldFragment, motionBlurFragment]) assert.doesNotMatch(source, /rand\(|Math\.random|time/);
+});
+
+test('render passes need the addon, reject unknown names and touch no GL until asked', () => {
+ const unusedContext = new Proxy({}, { get() { throw new Error('The GL context was touched.'); } });
+ const renderer = { passSupport: null, context: unusedContext, canvas: { width: 8, height: 8 }, benchmark: false };
+ installRenderPasses(installRenderPasses(renderer));
+ assert.ok(renderer.passSupport);
+ assert.throws(() => renderer.passSupport.prepare({ pass: 'beauty' }), /Unknown render pass/);
+ assert.throws(() => renderer.passSupport.prepare({ pass: 'depth', passDepthRange: 0 }), /depth range/);
+ assert.deepEqual(renderer.passSupport.background('depth'), [1, 1, 0, 1]);
+ assert.deepEqual(renderer.passSupport.background('objectId'), [0, 0, 0, 1]);
+});
+
+test('artifact names list the lit image and each pass per frame', () => {
+ assert.deepEqual(artifactNames('image'), ['render.png']);
+ assert.deepEqual(artifactNames('image', ['depth', 'objectId']), ['render.png', 'render-depth.png', 'render-objectId.png']);
+ assert.equal(artifactNames('stills', ['normal']).length, 16);
+ assert.ok(artifactNames('stills', ['normal']).includes('frame-7-normal.png'));
+ assert.deepEqual(artifactNames('video'), ['render.mp4']);
+});
+
+test('a job with passes publishes every pass file and rejects bad pass requests', async context => {
+ const root = await mkdtemp(join(tmpdir(), '67js-render-passes-'));
+ context.after(() => rm(root, { recursive: true, force: true }));
+ const run = async ({ directory, settings }) => {
+ const artifacts = [];
+ for (const filename of artifactNames(settings.kind, settings.passes)) {
+ await writeFile(join(directory, `${filename}.partial`), Buffer.from(filename));
+ artifacts.push({ temporary: `${filename}.partial`, filename, mimeType: 'image/png' });
+ }
+ return { artifacts, metrics: {} };
+ };
+ const controller = await createAgentRenderJobs({ root, limits, run });
+ const snapshot = { recipe: { format: 'fixture' } };
+ const submitted = await controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'image', width: 64, height: 64, passes: ['depth', 'albedo'] } });
+ while (controller.status(submitted.jobId).state !== 'completed') await new Promise(resolve => setTimeout(resolve, 2));
+ const record = controller.status(submitted.jobId);
+ assert.deepEqual(record.artifacts.map(artifact => artifact.filename), ['render.png', 'render-depth.png', 'render-albedo.png']);
+ assert.deepEqual(record.settings.passes, ['depth', 'albedo']);
+ await controller.release(submitted.jobId);
+ for (const passes of [['mystery'], ['depth', 'depth'], [], 'depth']) {
+ await assert.rejects(controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'image', width: 64, height: 64, passes } }), /pass/i);
+ }
+ await assert.rejects(controller.submit({ sourceRevision: 0, snapshot, settings: { kind: 'video', width: 64, height: 64, passes: ['depth'] } }), /image or stills/);
+ await controller.close();
+});
diff --git a/vite.lib.config.js b/vite.lib.config.js
index 07f2ed2c..afba8f1b 100644
--- a/vite.lib.config.js
+++ b/vite.lib.config.js
@@ -38,6 +38,8 @@ export default defineConfig({
'agent-scene': 'src/agent-scene.js',
'agent-asset': 'src/agent-asset.js',
hdri: 'src/hdri.js',
+ 'camera-effects': 'src/camera-effects.js',
+ 'render-passes': 'src/render-passes.js',
},
formats: ['es'],
fileName: (_, entry) => entry === 'core' ? '67.module.js' : `${entry}.js`,