3D engine that AI agents drive
Add composite post step: chroma and luma key over a background (part of #707)
Nguyen Xuan Anf80303a860a2
diff --git a/bench/post/post-steps.js b/bench/post/post-steps.jsindex 89137c6e..1571dccc 100644--- a/bench/post/post-steps.js+++ b/bench/post/post-steps.js@@ -13,12 +13,16 @@ function placed(center, size) {return new Float32Array([size[0], 0, 0, 0, 0, size[1], 0, 0, 0, 0, size[2], 0, center[0], center[1], center[2], 1]);}-function sceneParts() {+// The hero is a green screen in the keying cases, so a chroma key has something to remove.+const GREEN_SCREEN = [0.05, 0.8, 0.1];++function sceneParts(greenHero) {const material = { color: [0.75, 0.75, 0.78], metallic: 0, roughness: 0.7 };+ const heroMaterial = greenHero ? { color: GREEN_SCREEN, metallic: 0, roughness: 0.7 } : material;const lamp = { color: [1, 0.9, 0.7], emissiveColor: [1, 0.9, 0.7], metallic: 0, roughness: 1, emission: 14 };const parts = [{ geometry: box(), matrix: placed([0, -0.05, 0], [10, 0.1, 10]), material },- { name: 'hero', geometry: box(), matrix: placed([0, 0.6, 0], [0.4, 1.2, 0.4]), material },+ { name: 'hero', geometry: box(), matrix: placed([0, 0.6, 0], [0.4, 1.2, 0.4]), material: heroMaterial },{ geometry: box(), matrix: placed([-1.2, 1.6, -0.6], [0.9, 0.06, 0.06]), material: lamp },];for (let index = 0; index < 5; index++) {@@ -45,7 +49,12 @@ const CASES = {posterize: { stylize: { posterize: 4 } },pixelate: { stylize: { pixelate: 8 } },'pixelate-hero': { stylize: { pixelate: 8, mask: { objects: ['hero'] } } },+ 'green-default': {},+ 'key-chroma': { composite: { background: { top: [0.9, 0.35, 0.1], bottom: [0.1, 0.2, 0.6] }, key: { chroma: { color: GREEN_SCREEN, tolerance: 0.25, softness: 0.1 } } } },+ 'key-chroma-masked': { composite: { background: { color: [0.9, 0.35, 0.1] }, key: { chroma: { color: GREEN_SCREEN, tolerance: 0.25 } }, mask: { depth: { near: 0, far: 3 } } } },+ 'key-luma': { composite: { background: { color: [0.1, 0.2, 0.6] }, key: { luma: { low: 0.05, high: 0.3 } } } },};+const GREEN_CASES = ['green-default', 'key-chroma', 'key-chroma-masked'];const camera = { eye: [3.4, 1.8, 4.6], target: [0, 0.8, -1], fov: 45 };// Mean color of a 6 by 6 pixel patch at a point of the frame (0 to 1, from the lower left), to check where a step changed the picture.@@ -60,7 +69,7 @@ function regionMean(context, x, y) {async function drawCase(name, { warmupFrames = 4, measuredFrames = 20 } = {}) {const canvas = document.querySelector('canvas');- const renderer = installRenderPasses(installCameraEffects(new Renderer67(canvas, sceneParts(), { ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, environment })));+ const renderer = installRenderPasses(installCameraEffects(new Renderer67(canvas, sceneParts(GREEN_CASES.includes(name)), { ground: false, hdr: true, depth: true, samples: 4, pixelRatio: 1, memoryBudgetMiB: 1024, environment })));if (postSteps) postSteps.installPostSteps(renderer);renderer.resize();const frame = { ...camera, environment, time: 0, exposure: 1, effects: { ambientOcclusion: 0, ...CASES[name] } };diff --git a/changes/707-compositing-keys.md b/changes/707-compositing-keys.mdnew file mode 100644index 00000000..4038b240--- /dev/null+++ b/changes/707-compositing-keys.md@@ -0,0 +1 @@+- `effects.composite` keys a green screen (chroma) or a luma range out of the frame and draws it over a colour or gradient background, with the same `mask` as the other post steps (part of #707)diff --git a/docs/agent-look.md b/docs/agent-look.mdindex acccb9c1..81fc1cd2 100644--- a/docs/agent-look.md+++ b/docs/agent-look.md@@ -274,10 +274,14 @@ Ambient occlusion reads the depth texture, so it needs the HDR depth target that| `stylize.posterize` | off | Whole number, `0` to `256`. Rounds each channel to this many steps || `stylize.pixelate` | off | Whole number, `0` to `64`. Block size in pixels || `colorBalance.mask`, `stylize.mask` | none | Limits the step to part of the frame, see below |+| `composite.background` | none | `{ color: [r, g, b] }` or `{ top, bottom }` (a vertical gradient), each channel `0` to `64`. Shows through keyed pixels and through any alpha the frame has |+| `composite.key.chroma` | none | `{ color, tolerance, softness }`: pixels whose chroma (hue and saturation, not brightness) is within `tolerance` (`0` to `1`, default `0.3`) of `color` turn transparent, fading over `softness` (`0` to `1`, default `0.1`) |+| `composite.key.luma` | none | `{ low, high, invert }`: pixels darker than `low` turn transparent and those brighter than `high` stay, `0` to `10` in linear light (`0.18` is middle grey), smooth between. `invert: true` keeps the dark ones instead |+| `composite.mask` | none | Limits the key to part of the frame, same fields as the other masks || `lensDistortion.distortion` | `0` | `-1` to `1`. Above `0` is barrel, below is pincushion || `lensDistortion.dispersion` | `0` | `0` to `1`. Red and blue split apart toward the edges, up to 3 percent of the distance from the center |-A step with a `mask` applies only where the mask is on; with no `mask` it applies to the whole frame, as before. `mask` takes `objects` (one to 16 part names, as `scene_look` with `pass: "objectId"` lists them), `depth` (`near`, `far` metres along the view direction, and `feather`, the metres over which each end fades; defaults `0`, `100000`, `0`), or both, which multiply, and `invert: true` to flip the result. A grade for the hero part only: `{ "colorBalance": { "gain": [1.3, 1, 0.8], "mask": { "objects": ["hero"] } } }`. A mask by parts reads the object ID pass, so the frame is drawn twice, and its edges are hard because an object ID cannot be antialiased; a mask by depth costs nothing extra. A name that is not a part of the frame fails with the names it knows. A mask cannot be combined with an active `lensDistortion` (distortion other than 0, or dispersion above 0): the mask is built in undistorted screen space, so it would not line up with the warped image, and the recipe fails with an error that says so. `stylize` runs after color balance: pixelate first (the other filters read the blocks), then kuwahara, sharpen, posterize. Every filter is off until named, and a filter set to `0` is off.+A step with a `mask` applies only where the mask is on; with no `mask` it applies to the whole frame, as before. `mask` takes `objects` (one to 16 part names, as `scene_look` with `pass: "objectId"` lists them), `depth` (`near`, `far` metres along the view direction, and `feather`, the metres over which each end fades; defaults `0`, `100000`, `0`), or both, which multiply, and `invert: true` to flip the result. A grade for the hero part only: `{ "colorBalance": { "gain": [1.3, 1, 0.8], "mask": { "objects": ["hero"] } } }`. A mask by parts reads the object ID pass, so the frame is drawn twice, and its edges are hard because an object ID cannot be antialiased; a mask by depth costs nothing extra. A name that is not a part of the frame fails with the names it knows. A mask cannot be combined with an active `lensDistortion` (distortion other than 0, or dispersion above 0): the mask is built in undistorted screen space, so it would not line up with the warped image, and the recipe fails with an error that says so. `composite` runs last, after `stylize`: it keys the finished frame, grade and filters included, and draws it over the background, so key a green screen with the colour it has after those steps. A key needs a background, and a mask needs a key. Only keys are in so far: alpha over an image, Z combine and cryptomatte are not. A mask on `composite` limits where the key applies, so pixels outside it stay as drawn. `stylize` runs after color balance: pixelate first (the other filters read the blocks), then kuwahara, sharpen, posterize. Every filter is off until named, and a filter set to `0` is off.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`.@@ -285,7 +289,7 @@ Motion blur needs camera `motion` tracks and a render job with `settings.motion`With `motionBlur.objects` above zero, a part that moves between `motion.start + elapsed - shutter` and `motion.start + elapsed` also smears along its own screen path while the still background stays sharp (`1` is the full shutter). It reads each pixel's part from an object ID pass, so it costs a second draw of the frame, and it replaces the camera smear on that frame, since it covers the camera's motion too. A part is moved as one rigid body by its node transform: a skinned or morphed part, an imported asset and a translucent part are not smeared per object.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.-The named post steps are `depthOfField` (defocus from depth), `colorBalance`, `glare`, `lensDistortion` and `stylize`. Each is its own group, off until a recipe names it, and a group at its neutral values draws nothing. They run on the resolved HDR frame, before bloom and tone mapping, in this order: depth of field, motion blur, glare, lens distortion, color balance, stylize. Like the two above they are deterministic, and `colorBalance`, `glare`, `lensDistortion` and `stylize` load their code and shaders only for a recipe that names one.+The named post steps are `depthOfField` (defocus from depth), `colorBalance`, `glare`, `lensDistortion`, `stylize` and `composite`. Each is its own group, off until a recipe names it, and a group at its neutral values draws nothing. They run on the resolved HDR frame, before bloom and tone mapping, in this order: depth of field, motion blur, glare, lens distortion, color balance, stylize, composite. Like the two above they are deterministic, and `colorBalance`, `glare`, `lensDistortion`, `stylize` and `composite` load their code and shaders only for a recipe that names one.## Directional shadowsdiff --git a/scripts/agent-preview-browser.js b/scripts/agent-preview-browser.jsindex f670d6f0..a7107d72 100644--- a/scripts/agent-preview-browser.js+++ b/scripts/agent-preview-browser.js@@ -287,7 +287,7 @@ function draw(record, time = 0, camera = record.scene.camera, frameOptions = {})const { objectMotion, ...renderOptions } = frameOptions;const frame = { ...camera, environment: litEnvironment(record.scene.parts, environment, Boolean(record.renderer.groundPart)), effects, exposure: effects.exposure, time, lines: environment.lines, ...windFrame(environment), ...renderOptions, effects: effectsWithFStop(renderOptions.effects ?? effects, camera) };let needsObjectIds = Boolean(objectMotion);- if (effects.colorBalance || effects.glare || effects.lensDistortion || effects.stylize) {+ if (effects.colorBalance || effects.glare || effects.lensDistortion || effects.stylize || effects.composite) {const postSteps = agentSceneModule('postSteps');postSteps.installPostSteps(record.renderer);needsObjectIds ||= postSteps.usesObjectMask(postSteps.resolvePostSteps(frame.effects));diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex d08a34dd..49ecf612 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -316,8 +316,9 @@ const effects = z.strictObject({glare: looseField,lensDistortion: looseField,stylize: looseField,+ composite: looseField,});-const effectsListed = listed('effects', effects, 'Post effects: exposure, saturation, contrast, temperature, vignette, grain, ambientOcclusion, ambientOcclusionRadius, bloom {strength, threshold, radius}, depthOfField {blur, focusDistance}, motionBlur {shutter}, colorBalance, glare, lensDistortion, stylize; see scene_capabilities effects.', coreOf(effects.shape, ['exposure']));+const effectsListed = listed('effects', effects, 'Post effects: exposure, saturation, contrast, temperature, vignette, grain, ambientOcclusion, ambientOcclusionRadius, bloom {strength, threshold, radius}, depthOfField {blur, focusDistance}, motionBlur {shutter}, colorBalance, glare, lensDistortion, stylize, composite; see scene_capabilities effects.', coreOf(effects.shape, ['exposure']));const shadow = z.strictObject({target: boundedVector(-1e6, 1e6).optional(),extent: bounded(0.01, 1e5).optional(),diff --git a/skills/build-67js-scene/references/look.md b/skills/build-67js-scene/references/look.mdindex eb99cfab..97cc4554 100644--- a/skills/build-67js-scene/references/look.md+++ b/skills/build-67js-scene/references/look.md@@ -91,8 +91,8 @@ Point lights do not scatter in volume fog; the sun does. A sunlit closed room wi`effects` holds `exposure`, `saturation`, `contrast`, `temperature`, `vignette`, `grain`, `ambientOcclusion` (0 = off),`bloom` and `depthOfField` (see `camera.md`). Nested `bloom` fields merge.Named post steps, each off until set: `colorBalance` (`lift`, `gamma`, `gain`, three numbers each), `glare` (`streaks`,-`count`, `angle`, `fogGlow`, `threshold`, `size`) `lensDistortion` (`distortion`, `dispersion`) and `stylize` (`sharpen`, `kuwahara`, `posterize`, `pixelate`); ranges in `docs/agent-look.md`.-`colorBalance` and `stylize` take a `mask` (`objects` part names, `depth` `{ near, far, feather }`, `invert`) to apply only to a hero part or a depth band.+`count`, `angle`, `fogGlow`, `threshold`, `size`) `lensDistortion` (`distortion`, `dispersion`), `stylize` (`sharpen`, `kuwahara`, `posterize`, `pixelate`) and `composite` (`background` `{ color }` or `{ top, bottom }`, `key` `{ chroma: { color, tolerance, softness } }` or `{ luma: { low, high, invert } }`, `mask`; a key needs a background); ranges in `docs/agent-look.md`.+`colorBalance`, `stylize` and `composite` take a `mask` (`objects` part names, `depth` `{ near, far, feather }`, `invert`) to apply only to a hero part or a depth band.Tool `scene_apply`:diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex 641bf3ea..a3e0e0f7 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -90,7 +90,7 @@ const MODULE_MARKERS = {materialSnippet: ['"snippet":{'],// Only a motionBlur object that sets a non-zero `objects` loads it; the common `"shutter":0` look does not.objectMotionBlur: [/"motionBlur":\{[^}]*"objects":(?!0[,}])/],- postSteps: [/"(?:colorBalance|glare|lensDistortion|stylize)"/],+ postSteps: [/"(?:colorBalance|glare|lensDistortion|stylize|composite)"/],};/** Whether a recipe, operation list or edit list contains a boolean edit, which needs loadMeshBooleans() first. */diff --git a/src/post-steps.js b/src/post-steps.jsindex 0dd96fbd..cd8e1465 100644--- a/src/post-steps.js+++ b/src/post-steps.js@@ -5,8 +5,8 @@ import { resolveMask, usesObjectMask, maskShader, bindMask, unbindMask, MASK_UNIexport { usesObjectMask };// Named post steps for a graded film: color balance (lift, gamma, gain), glare (streaks and fog glow), lens distortion with-// dispersion, and stylize filters (sharpen, kuwahara, posterize, pixelate). Color balance and stylize take a `mask` (post-mask.js)-// that limits them to named parts or a range of distance. They are optional full-frame stages. The core renderer carries none of their code: a recipe that names one+// dispersion, stylize filters (sharpen, kuwahara, posterize, pixelate) and composite (a chroma or luma key over a background).+// Color balance, stylize and composite take a `mask` (post-mask.js) that limits them to named parts or a range of distance. They are optional full-frame stages. The core renderer carries none of their code: a recipe that names one// loads this module (agent-scene-modules.js), and each stage compiles only on the first frame that turns it on. Defocus from// depth is the `depthOfField` group of camera-effects.js, which is the same step under its older name.//@@ -74,6 +74,66 @@ function resolveStylize(input) {return resolved;}+const MAXIMUM_LIGHT = 64;+const CHROMA_DISTANCE_SCALE = 0.7;++function backgroundColor(value, name) {+ if (!Array.isArray(value) || value.length !== 3) throw new TypeError(`${name} must be three numbers.`);+ return triple(value, [0, 0, 0], 0, MAXIMUM_LIGHT, name);+}++function resolveBackground(input) {+ const group = groupOf(input, 'composite.background');+ onlyKeys(group, ['color', 'top', 'bottom'], 'composite.background');+ if (group.color !== undefined) {+ if (group.top !== undefined || group.bottom !== undefined) throw new TypeError('composite.background takes color, or top and bottom, not both. Fix: pass one of them.');+ return { color: backgroundColor(group.color, 'composite.background.color') };+ }+ if (group.top === undefined || group.bottom === undefined) {+ throw new TypeError('composite.background needs color, or both top and bottom. Fix: { "color": [0.1, 0.3, 0.8] } or { "top": [..], "bottom": [..] }.');+ }+ return { top: backgroundColor(group.top, 'composite.background.top'), bottom: backgroundColor(group.bottom, 'composite.background.bottom') };+}++function resolveKey(input) {+ const group = groupOf(input, 'composite.key');+ onlyKeys(group, ['chroma', 'luma'], 'composite.key');+ if ((group.chroma === undefined) === (group.luma === undefined)) {+ throw new TypeError('composite.key needs exactly one of chroma ({ color, tolerance, softness }) or luma ({ low, high, invert }).');+ }+ if (group.chroma !== undefined) {+ const chroma = groupOf(group.chroma, 'composite.key.chroma');+ onlyKeys(chroma, ['color', 'tolerance', 'softness'], 'composite.key.chroma');+ return {+ chroma: {+ color: backgroundColor(chroma.color, 'composite.key.chroma.color'),+ tolerance: numberInRange(chroma.tolerance, 0.3, 0, 1, 'composite.key.chroma.tolerance'),+ softness: numberInRange(chroma.softness, 0.1, 0, 1, 'composite.key.chroma.softness'),+ },+ };+ }+ const luma = groupOf(group.luma, 'composite.key.luma');+ onlyKeys(luma, ['low', 'high', 'invert'], 'composite.key.luma');+ const low = numberInRange(luma.low, 0, 0, 10, 'composite.key.luma.low');+ const high = numberInRange(luma.high, 1, 0, 10, 'composite.key.luma.high');+ if (high <= low) throw new RangeError('composite.key.luma.high must be greater than low. Fix: luma is linear scene light, 0.18 is middle grey.');+ if (luma.invert !== undefined && typeof luma.invert !== 'boolean') throw new TypeError('composite.key.luma.invert must be true or false.');+ return { luma: { low, high, invert: luma.invert === true } };+}++// A key turns pixels transparent; the background is what shows through, so a key without one has nothing to show.+function resolveComposite(input) {+ const group = groupOf(input, 'composite');+ onlyKeys(group, ['background', 'key', 'mask'], 'composite');+ const resolved = {};+ if (group.background !== undefined) resolved.background = resolveBackground(group.background);+ if (group.key !== undefined) resolved.key = resolveKey(group.key);+ if (group.mask !== undefined) resolved.mask = resolveMask(group.mask, 'composite.mask');+ if (resolved.key && !resolved.background) throw new TypeError('composite.key needs composite.background to show through the keyed pixels. Fix: add background { color } or { top, bottom }.');+ if (resolved.mask && !resolved.key) throw new TypeError('composite.mask limits the key, so it needs composite.key. Fix: add a key, or remove the mask.');+ return resolved;+}+function resolveGlare(input) {const group = groupOf(input, 'glare');onlyKeys(group, ['streaks', 'count', 'angle', 'fogGlow', 'threshold', 'size'], 'glare');@@ -105,6 +165,7 @@ export function resolvePostSteps(effects) {if (effects.glare !== undefined) resolved.glare = resolveGlare(effects.glare);if (effects.lensDistortion !== undefined) resolved.lensDistortion = resolveLensDistortion(effects.lensDistortion);if (effects.stylize !== undefined) resolved.stylize = resolveStylize(effects.stylize);+ if (effects.composite !== undefined) resolved.composite = resolveComposite(effects.composite);refuseMaskWithLensDistortion(resolved);return resolved;}@@ -114,14 +175,14 @@ export function resolvePostSteps(effects) {function refuseMaskWithLensDistortion(resolved) {const lens = resolved.lensDistortion;const lensIsOn = Boolean(lens) && (lens.distortion !== 0 || lens.dispersion > 0);- const maskedStep = ['colorBalance', 'stylize'].find(name => resolved[name]?.mask);+ const maskedStep = ['colorBalance', 'stylize', 'composite'].find(name => resolved[name]?.mask);if (lensIsOn && maskedStep) {throw new TypeError(`${maskedStep}.mask cannot be combined with lensDistortion: the mask is in undistorted screen space and would not line up with the warped image. Fix: remove the mask, or set lensDistortion.distortion and dispersion to 0.`);}}// Registers what the look needs: the field names it accepts and how to resolve them (src/shader-registry.js).-postStepSupport.fields = ['colorBalance', 'glare', 'lensDistortion', 'stylize'];+postStepSupport.fields = ['colorBalance', 'glare', 'lensDistortion', 'stylize', 'composite'];postStepSupport.resolve = resolvePostSteps;export const colorBalanceFragment = `${sharedFragmentHeader}@@ -196,6 +257,36 @@ void main() {outputColor = vec4(mask < 1.0 ? mix(source.rgb, color, mask) : color, source.a);}`;+export const compositeFragment = `${sharedFragmentHeader}+${maskShader}+uniform float keyMode;+uniform vec3 keyColor;+uniform vec3 keyRange;+uniform float keyInvert;+uniform vec3 backgroundTop;+uniform vec3 backgroundBottom;+vec2 chromaOf(vec3 color) {+ vec3 normalized = color / max(max(color.r, max(color.g, color.b)), 0.0001);+ return vec2(dot(normalized, vec3(-0.169, -0.331, 0.5)), dot(normalized, vec3(0.5, -0.419, -0.081)));+}+// 1 keeps the pixel, 0 shows the background. Chroma: distance between the pixel's and the key's chroma, so brightness does not matter.+float keepAmount(vec3 color) {+ if (keyMode > 1.5) {+ float luma = dot(color, vec3(0.2126, 0.7152, 0.0722));+ float keep = smoothstep(keyRange.x, keyRange.y, luma);+ return mix(keep, 1.0 - keep, keyInvert);+ }+ float distanceToKey = distance(chromaOf(color), chromaOf(keyColor));+ return smoothstep(keyRange.x, keyRange.x + keyRange.y, distanceToKey);+}+void main() {+ vec4 source = texture(sourceTexture, textureCoordinate);+ float keep = 1.0;+ if (keyMode > 0.5) keep = mix(1.0, keepAmount(source.rgb), maskAt(textureCoordinate));+ vec3 background = mix(backgroundBottom, backgroundTop, textureCoordinate.y);+ outputColor = vec4(mix(background, source.rgb, keep * source.a), 1.0);+}`;+export const glareFragment = `${sharedFragmentHeader}uniform float streakAmount;uniform int streakCount;@@ -326,6 +417,31 @@ function createStylizeStage() {}));}+function createCompositeStage() {+ return withMaskUnbound(createStage({+ name: 'Composite',+ fragment: compositeFragment,+ uniformNames: ['keyMode', 'keyColor', 'keyRange', 'keyInvert', 'backgroundTop', 'backgroundBottom', ...MASK_UNIFORM_NAMES],+ isActive: (effects, frame) => Boolean(stepsOf(frame).composite?.background),+ setUniforms(context, uniforms, renderer, frame) {+ const { composite } = stepsOf(frame);+ const { background, key } = composite;+ context.uniform3fv(uniforms.backgroundTop, background.color ?? background.top);+ context.uniform3fv(uniforms.backgroundBottom, background.color ?? background.bottom);+ const chroma = key?.chroma;+ const luma = key?.luma;+ context.uniform1f(uniforms.keyMode, chroma ? 1 : luma ? 2 : 0);+ context.uniform3fv(uniforms.keyColor, chroma?.color ?? [0, 0, 0]);+ const range = chroma+ ? [chroma.tolerance * CHROMA_DISTANCE_SCALE, Math.max(chroma.softness * CHROMA_DISTANCE_SCALE, 0.0001), 0]+ : [luma?.low ?? 0, luma?.high ?? 1, 0];+ context.uniform3fv(uniforms.keyRange, range);+ context.uniform1f(uniforms.keyInvert, luma?.invert ? 1 : 0);+ bindMask(context, uniforms, renderer, frame, composite.mask);+ },+ }));+}+function createGlareStage() {const stage = createStage({name: 'Glare',@@ -389,13 +505,13 @@ function createLensDistortionStage() {}/**- * Adds glare, lens distortion, color balance and the stylize filters to a renderer, after any depth of field and motion blur it has, in that+ * Adds glare, lens distortion, color balance, the stylize filters and the composite key to a renderer, after any depth of field and motion blur it has, in that* order. Like them it needs `depth: true`. Each stage runs only for a frame whose effects set it. A step with a `mask` by* objects reads the object ID pass: install the render passes and draw that pass before the lit frame (`usesObjectMask` says when).*/export function installPostSteps(renderer) {if (!renderer.postStages.some(stage => stage.name === 'Glare')) {- renderer.postStages.push(createGlareStage(), createLensDistortionStage(), createColorBalanceStage(), createStylizeStage());+ renderer.postStages.push(createGlareStage(), createLensDistortionStage(), createColorBalanceStage(), createStylizeStage(), createCompositeStage());}return renderer;}diff --git a/tests/post-steps.test.js b/tests/post-steps.test.jsindex c0fb9910..d7aa7b89 100644--- a/tests/post-steps.test.js+++ b/tests/post-steps.test.js@@ -9,7 +9,7 @@ import { resolveEffects } from '../src/effects.js';import { normalizeAgentLook } from '../src/agent-look.js';import { agentSceneModulesNeeded, loadAgentSceneModules } from '../src/agent-scene-modules.js';import { installCameraEffects } from '../src/camera-effects.js';-import { installPostSteps, resolvePostSteps, glareFragment, lensDistortionFragment, colorBalanceFragment, stylizeFragment, usesObjectMask } from '../src/post-steps.js';+import { installPostSteps, resolvePostSteps, glareFragment, lensDistortionFragment, colorBalanceFragment, stylizeFragment, compositeFragment, usesObjectMask } from '../src/post-steps.js';import { createAgentScene } from '../src/agent-scene.js';function recordingContext(calls) {@@ -33,7 +33,7 @@ function fakeRenderer(context) {};}-const STAGE_NAMES = ['Glare', 'Lens distortion', 'Color balance', 'Stylize'];+const STAGE_NAMES = ['Glare', 'Lens distortion', 'Color balance', 'Stylize', 'Composite'];test('a look that names no step resolves exactly as before', async () => {await loadAgentSceneModules({});@@ -86,14 +86,15 @@ test('each stage draws only for a frame that sets its step, and frees its targetconst context = recordingContext(calls);const renderer = installPostSteps(installCameraEffects(fakeRenderer(context)));assert.deepEqual(renderer.postStages.slice(2).map(stage => stage.name), STAGE_NAMES);- assert.equal(installPostSteps(renderer).postStages.length, 6);+ assert.equal(installPostSteps(renderer).postStages.length, 7);const unset = { eye: [0, 1, 5], effects: {} };- const neutral = { eye: [0, 1, 5], effects: { colorBalance: {}, glare: {}, lensDistortion: {}, stylize: {} } };+ const neutral = { eye: [0, 1, 5], effects: { colorBalance: {}, glare: {}, lensDistortion: {}, stylize: {}, composite: {} } };const named = [['Glare', { glare: { streaks: 0.6 } }],['Lens distortion', { lensDistortion: { distortion: 0.5, dispersion: 0.5 } }],['Color balance', { colorBalance: { gain: [1.1, 1, 0.9] } }],['Stylize', { stylize: { posterize: 4 } }],+ ['Composite', { composite: { background: { color: [0.1, 0.2, 0.6] }, key: { luma: { low: 0.1, high: 0.4 } } } }],];const effects = resolveEffects({});for (const [name, input] of named) {@@ -104,8 +105,8 @@ test('each stage draws only for a frame that sets its step, and frees its targetstage.releaseTargets(context);stage.dispose(context);}- assert.ok(calls.filter(call => call[0] === 'drawArrays').length === 4);- assert.ok(calls.filter(call => call[0] === 'deleteTexture').length === 4);+ assert.ok(calls.filter(call => call[0] === 'drawArrays').length === 5);+ assert.ok(calls.filter(call => call[0] === 'deleteTexture').length === 5);});test('a stylize step resolves its filters and a mask, and refuses bad input', () => {@@ -163,8 +164,27 @@ test('a mask cannot be combined with an active lens distortion, which warps theassert.ok(resolvePostSteps({ lensDistortion: { distortion: 0.2 }, colorBalance: { gain: [1.2, 1, 1] } }).lensDistortion);});+test('a composite step resolves a background and a key, and says what to pass when it is wrong', () => {+ const resolved = resolvePostSteps({ composite: { background: { top: [1, 0, 0], bottom: [0, 0, 1] }, key: { chroma: { color: [0, 1, 0] } } } }).composite;+ assert.deepEqual(resolved, { background: { top: [1, 0, 0], bottom: [0, 0, 1] }, key: { chroma: { color: [0, 1, 0], tolerance: 0.3, softness: 0.1 } } });+ assert.deepEqual(resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, key: { luma: { low: 0.1, high: 0.5, invert: true } } } }).composite.key, { luma: { low: 0.1, high: 0.5, invert: true } });+ assert.deepEqual(resolvePostSteps({ composite: {} }).composite, {});+ assert.throws(() => resolvePostSteps({ composite: { key: { luma: {} } } }), /composite.key needs composite.background/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0], top: [0, 0, 0] } } }), /not both/);+ assert.throws(() => resolvePostSteps({ composite: { background: { top: [0, 0, 0] } } }), /both top and bottom/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, key: {} } }), /exactly one of chroma/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, key: { chroma: {} } } }), /key.chroma.color must be three numbers/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, key: { chroma: { color: [0, 1, 0], tolerance: 2 } } } }), /tolerance must be between/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, key: { luma: { low: 0.5, high: 0.5 } } } }), /high must be greater than low/);+ assert.throws(() => resolvePostSteps({ composite: { background: { color: [0, 0, 0] }, mask: { depth: { far: 5 } } } }), /mask limits the key/);+ assert.throws(() => resolvePostSteps({ composite: { image: 'plate.png' } }), /Unknown composite field/);+ const masked = { composite: { background: { color: [0, 0, 0] }, key: { luma: {} }, mask: { objects: ['hero'] } } };+ assert.equal(usesObjectMask(resolvePostSteps(masked)), true);+ assert.throws(() => resolvePostSteps({ ...masked, lensDistortion: { distortion: 0.2 } }), /composite.mask cannot be combined with lensDistortion/);+});+test('the shaders keep their fixed sample patterns and read no history', () => {- for (const fragment of [glareFragment, lensDistortionFragment, colorBalanceFragment, stylizeFragment]) {+ for (const fragment of [glareFragment, lensDistortionFragment, colorBalanceFragment, stylizeFragment, compositeFragment]) {assert.match(fragment, /^#version 300 es/);assert.doesNotMatch(fragment, /previousViewProjection|time/);}@@ -175,7 +195,7 @@ test('the shaders keep their fixed sample patterns and read no history', () => {const chromePath = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe';const rendersEnabled = process.env.RENDER_TESTS === '1' && existsSync(chromePath);const STEP_CASES = ['defocus', 'color-balance', 'glare-streaks', 'glare-streaks-6', 'glare-anamorphic', 'glare-fog', 'lens-distortion', 'lens-dispersion',- 'grade-hero', 'grade-depth', 'sharpen', 'kuwahara', 'posterize', 'pixelate', 'pixelate-hero'];+ 'grade-hero', 'grade-depth', 'sharpen', 'kuwahara', 'posterize', 'pixelate', 'pixelate-hero', 'key-chroma', 'key-luma'];test('each named step changes the picture and the default still keeps its hash', { skip: !rendersEnabled, timeout: 300000 }, () => {const output = execFileSync('node', ['bench/post/post-steps.mjs', '--rounds=1', `--out=${join(tmpdir(), 'post-steps-test')}`], { encoding: 'utf8' });@@ -185,6 +205,10 @@ test('each named step changes the picture and the default still keeps its hash',assert.ok(summary[name].medianMilliseconds > 0, `${name} has a frame time`);}// A grade masked to the hero part changes the hero and leaves the floor as the default drew it; the unmasked grade changes both.+ // A green-screen hero keyed out shows the background there; the floor is untouched. A key limited by a depth mask that leaves the hero out changes nothing.+ assert.notDeepEqual(summary['key-chroma'].regions.hero, summary['green-default'].regions.hero);+ assert.deepEqual(summary['key-chroma'].regions.floor, summary['green-default'].regions.floor);+ assert.deepEqual(summary['key-chroma-masked'].regions.hero, summary['green-default'].regions.hero);assert.notDeepEqual(summary['grade-hero'].regions.hero, summary.default.regions.hero);assert.deepEqual(summary['grade-hero'].regions.floor, summary.default.regions.floor);assert.notDeepEqual(summary['color-balance'].regions.floor, summary.default.regions.floor);