Skip to content

Official Codebase of 3DCodeVerse

Python

scene host: a post chain — GTAO, selective glow bloom, grade (default ON for scenes)

gaoypengf73c76e2f1c0
diff --git a/harness/codeverse/spatial/render_scene.py b/harness/codeverse/spatial/render_scene.py
index d1a40e80..a055253f 100644
--- a/harness/codeverse/spatial/render_scene.py
+++ b/harness/codeverse/spatial/render_scene.py
@@ -92,6 +92,15 @@ def probe_env_args() -> list[str]:
return args
+def post_chain_args() -> list[str]:
+ """``--no-post`` when ``CV3D_POST`` is off. The post chain (GTAO + selective
+ bloom + grade, ``runtime_js/lib/browser/post.js``) is ON by default for scene
+ PICTURES only: object renders never touch this driver, and the scene probe runs
+ raw because it is a 320x180 geometry instrument, not a judged frame. Kept out
+ of :func:`probe_env_args` for exactly that reason."""
+ return [] if env_flag("CV3D_POST", True) else ["--no-post"]
+
+
def _camera_json(cams: Sequence[CameraPlan]) -> str:
return json.dumps([
{"name": c.name, "position": list(c.position), "lookAt": list(c.look_at), "fov": c.fov} for c in cams
@@ -161,6 +170,7 @@ def render_scene(
tmo = timeout_s or settings.limits.render_timeout_s
args += ["--timeout-ms", str(int(tmo * 1000))]
args += probe_env_args()
+ args += post_chain_args()
driver_error = ""
try:
res = run_scene_script("render_scene.mjs", args, timeout_s=tmo + 30)
diff --git a/harness/runtime_js/lib/browser/post.js b/harness/runtime_js/lib/browser/post.js
new file mode 100644
index 00000000..27a409d6
--- /dev/null
+++ b/harness/runtime_js/lib/browser/post.js
@@ -0,0 +1,605 @@
+// THE post chain for scene renders (scene_host.mjs; object renders stay raw —
+// object judging was calibrated without it). One EffectComposer:
+//
+// RenderPass -> finite clamp -> GTAO (blend) -> glow bloom -> grade -> OutputPass
+//
+// Why each stage exists, all four measured on the effect-library showcase:
+//
+// clamp a specular spike past half-float range rides the blur mips and blanks
+// part of the frame's glow; only finite, non-negative colour continues.
+//
+// GTAO without contact darkening correct geometry reads as stickers. It
+// MULTIPLIES the final image, so a surface lit only by the hemisphere
+// fill goes to zero at full strength — `ao` is the dial, and the
+// Poisson denoise is turned up from three's defaults because at a blend
+// that actually reads, the raw AO dots flat walls.
+//
+// bloom SELECTIVE, from an emissive mask — NOT a luminance bright-pass.
+// Measured 2026-09-01 on our renderer: every daylight scene tops out at
+// 1.88 linear (the sky dome) with 38% of the frame above 0.9, while the
+// brightest authored emissive in the library is 1.23. A global bright
+// pass therefore cannot separate "a neon sign" from "the sky": at the
+// reference's threshold (0.85) a daylit frame lost a QUARTER of its
+// saturation (0.313 -> 0.070) and read as fog soup. So the bloom source
+// is a second, cheap render in which every material is replaced by its
+// EMISSION only — the sky, the sun-lit ground and diffuse albedo are
+// black there by construction, and brightness stops being the question.
+// A scene with nothing emissive pays nothing: the mask render is skipped.
+//
+// grade exposure trim, a real S-curve (anchored at 0 and 1, so it deepens the
+// mids without crushing blacks or blowing whites), saturation, white
+// balance, split-tone and a shadow lift. IDENTITY unless the scene
+// asks: a scene sets `scene.userData.grade = {exposure, contrast, ...}`.
+//
+// output the renderer's own ACES + sRGB, unchanged from the raw path.
+//
+// MSAA: the renderer's `antialias` flag is DEAD once a composer renders into its
+// own target, so the composer's target carries `samples` itself — otherwise every
+// judged frame is 1-sample raw and reads as severe aliasing.
+//
+// import { makePostChain, GRADE_DEFAULTS } from '/__runtime/lib/browser/post.js';
+
+import * as THREE from 'three';
+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
+import { ShaderPass } from 'three/addons/postprocessing/ShaderPass.js';
+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+import { FullScreenQuad } from 'three/addons/postprocessing/Pass.js';
+import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
+
+/** Chain shape. `ao: 0` drops the GTAO pass, `bloom: 0` drops the glow bloom. */
+export const POST_DEFAULTS = Object.freeze({
+ // 0.8 measured on the indoor showcase: corners, the wall/floor junction and the
+ // column base gain contact shading for -0.004 mean luminance — the shadows are
+ // shaped, not crushed. At 0.45 it does not read; three's raw AO at this blend
+ // dots a flat wall, which is what the denoise settings below are for.
+ ao: 0.8, // GTAOPass.blendIntensity
+ aoRadius: 1.6, // world units: architectural scale, not a turntable prop
+ aoDistanceExponent: 1.2,
+ aoThickness: 1.0,
+ aoSamples: 16,
+ aoDenoiseRings: 3, // raised from three's 2: kills the AO dots on flat walls
+ aoDenoiseSamples: 16, // ... and so does this (three's default is 8)
+ // 0.15 measured on the neon showcase: the sign haloes and the light trails read
+ // as light while the letters stay legible. At 0.30 both bleach out.
+ bloom: 0.15, // how much of the blurred emission is added back
+ bloomLevels: 5, // blur pyramid depth = how WIDE the veil spreads
+ bloomThreshold: 0.02, // emission below this is not a light source, it is noise
+ samples: 4, // MSAA samples on the composer target
+ clampMax: 64.0, // finite-colour ceiling entering the chain
+});
+
+/**
+ * Grade uniforms. Every default is the IDENTITY — an ungraded scene renders
+ * through the grade stage unchanged (`tests/scene_runtime/test_post.py` pins
+ * that), so the only shift the chain introduces is AO + bloom.
+ */
+export const GRADE_DEFAULTS = Object.freeze({
+ exposure: 1.0, // linear multiplier, applied before the curve
+ contrast: 1.0, // 1 = off; S-curve strength around the mid tones
+ saturation: 1.0, // 1 = off
+ warmth: 0.0, // -1 cool (blue) .. +1 warm (amber), luminance preserving
+ tint: 0.0, // -1 green .. +1 magenta, luminance preserving
+ shadowTint: [0, 0, 0], // split-tone: multiplicative shift on the low tones
+ highlightTint: [0, 0, 0], // ... and on the high tones
+ shadowLift: 0.0, // additive floor under the darkest tones (kills pure black)
+ vignette: 0.0, // 0 = off .. 1 = strong corner falloff
+});
+
+const QUAD_VERT = /* glsl */`
+ varying vec2 vUv;
+ void main() {
+ vUv = uv;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
+ }`;
+
+const GRADE_SHADER = {
+ uniforms: {
+ tDiffuse: { value: null },
+ exposure: { value: 1.0 },
+ contrast: { value: 1.0 },
+ saturation: { value: 1.0 },
+ warmth: { value: 0.0 },
+ tint: { value: 0.0 },
+ shadowTint: { value: new THREE.Vector3(0, 0, 0) },
+ highlightTint: { value: new THREE.Vector3(0, 0, 0) },
+ shadowLift: { value: 0.0 },
+ vignette: { value: 0.0 },
+ },
+ vertexShader: QUAD_VERT,
+ fragmentShader: /* glsl */`
+ varying vec2 vUv;
+ uniform sampler2D tDiffuse;
+ uniform float exposure, contrast, saturation, warmth, tint, shadowLift, vignette;
+ uniform vec3 shadowTint, highlightTint;
+
+ const vec3 LUMA = vec3(0.2126, 0.7152, 0.0722);
+
+ void main() {
+ vec4 texel = texture2D(tDiffuse, vUv);
+ vec3 c = max(texel.rgb, vec3(0.0));
+
+ // white balance — channel gains renormalised by luma, so a warm or cool
+ // push changes the hue and never the overall brightness
+ if (warmth != 0.0 || tint != 0.0) {
+ vec3 wb = vec3(1.0 + 0.20 * warmth + 0.05 * tint,
+ 1.0 - 0.10 * tint,
+ 1.0 - 0.20 * warmth + 0.05 * tint);
+ wb /= max(dot(wb, LUMA), 1e-4);
+ c *= wb;
+ }
+
+ c *= exposure;
+
+ // S-CURVE: into a bounded tonal domain, smoothstep there (anchored at 0 and
+ // 1 — blacks stay black, whites do not clip), back out.
+ if (contrast != 1.0) {
+ vec3 t = c / (c + vec3(1.0));
+ vec3 s = t * t * (vec3(3.0) - 2.0 * t);
+ t = clamp(mix(t, s, contrast - 1.0), vec3(0.0), vec3(0.999));
+ c = t / (vec3(1.0) - t);
+ }
+
+ if (saturation != 1.0) c = mix(vec3(dot(c, LUMA)), c, saturation);
+
+ // split-tone: shadows and highlights pull apart in hue. Multiplicative, so
+ // it tints what is there and never paints light into black.
+ float l = dot(c, LUMA);
+ float hi = smoothstep(0.15, 0.75, l / (l + 1.0));
+ c *= vec3(1.0) + mix(shadowTint, highlightTint, hi);
+
+ // lift: a dielectric ambient floor, strongest where the frame is darkest
+ if (shadowLift > 0.0) c += shadowLift * (1.0 - smoothstep(0.0, 0.35, l));
+
+ if (vignette > 0.0) {
+ float r = length(vUv - 0.5) * 1.4142;
+ c *= 1.0 - vignette * smoothstep(0.45, 1.0, r);
+ }
+
+ gl_FragColor = vec4(max(c, vec3(0.0)), texel.a);
+ }`,
+};
+
+// Only FINITE, non-negative colour may continue down the chain.
+const clampShader = (maxValue) => ({
+ uniforms: { tDiffuse: { value: null }, maxValue: { value: maxValue } },
+ vertexShader: QUAD_VERT,
+ fragmentShader: /* glsl */`
+ varying vec2 vUv;
+ uniform sampler2D tDiffuse;
+ uniform float maxValue;
+ void main() {
+ vec4 c = texture2D(tDiffuse, vUv);
+ vec3 v = clamp(c.rgb, vec3(0.0), vec3(maxValue));
+ // NaN never compares equal to itself
+ if (v.r != v.r) v.r = 0.0;
+ if (v.g != v.g) v.g = 0.0;
+ if (v.b != v.b) v.b = 0.0;
+ gl_FragColor = vec4(v, c.a);
+ }`,
+});
+
+// base + strength * blurred emission
+const BLOOM_COMPOSITE_SHADER = {
+ uniforms: { tDiffuse: { value: null }, tGlow: { value: null }, strength: { value: 0 } },
+ vertexShader: QUAD_VERT,
+ fragmentShader: /* glsl */`
+ varying vec2 vUv;
+ uniform sampler2D tDiffuse;
+ uniform sampler2D tGlow;
+ uniform float strength;
+ void main() {
+ vec4 base = texture2D(tDiffuse, vUv);
+ vec3 glow = max(texture2D(tGlow, vUv).rgb, vec3(0.0));
+ gl_FragColor = vec4(base.rgb + strength * glow, base.a);
+ }`,
+};
+
+// Dual-filter (Kawase) down/up blur: the cheap way to a WIDE, soft veil. A
+// straight Gaussian at this radius would cost an order of magnitude more taps.
+const DOWN_SHADER = {
+ uniforms: { tDiffuse: { value: null }, texel: { value: new THREE.Vector2() } },
+ vertexShader: QUAD_VERT,
+ fragmentShader: /* glsl */`
+ varying vec2 vUv;
+ uniform sampler2D tDiffuse;
+ uniform vec2 texel;
+ void main() {
+ vec4 s = texture2D(tDiffuse, vUv) * 4.0;
+ s += texture2D(tDiffuse, vUv - texel);
+ s += texture2D(tDiffuse, vUv + texel);
+ s += texture2D(tDiffuse, vUv + vec2(texel.x, -texel.y));
+ s += texture2D(tDiffuse, vUv - vec2(texel.x, -texel.y));
+ gl_FragColor = s / 8.0;
+ }`,
+};
+
+const UP_SHADER = {
+ uniforms: { tDiffuse: { value: null }, texel: { value: new THREE.Vector2() } },
+ vertexShader: QUAD_VERT,
+ fragmentShader: /* glsl */`
+ varying vec2 vUv;
+ uniform sampler2D tDiffuse;
+ uniform vec2 texel;
+ void main() {
+ vec4 s = texture2D(tDiffuse, vUv + vec2(-texel.x * 2.0, 0.0));
+ s += texture2D(tDiffuse, vUv + vec2(-texel.x, texel.y)) * 2.0;
+ s += texture2D(tDiffuse, vUv + vec2(0.0, texel.y * 2.0));
+ s += texture2D(tDiffuse, vUv + vec2(texel.x, texel.y)) * 2.0;
+ s += texture2D(tDiffuse, vUv + vec2(texel.x * 2.0, 0.0));
+ s += texture2D(tDiffuse, vUv + vec2(texel.x, -texel.y)) * 2.0;
+ s += texture2D(tDiffuse, vUv + vec2(0.0, -texel.y * 2.0));
+ s += texture2D(tDiffuse, vUv + vec2(-texel.x, -texel.y)) * 2.0;
+ gl_FragColor = s / 12.0;
+ }`,
+};
+
+/**
+ * What a material contributes to the bloom mask. Three answers:
+ *
+ * 'keep' the material ALREADY draws light and nothing else —
+ * an additive veil, shaft, halo or flare, or an unlit
+ * decal marked `toneMapped = false`. It renders into
+ * the mask AS ITSELF, so a custom shader's own falloff,
+ * alpha and animation survive. Replacing these with a
+ * flat proxy is what turns a thin neon tube into a white
+ * blob, so we do not.
+ * {color, map} a LIT material (anything with `.emissive`): only its
+ * emission belongs in the mask, so it is swapped for an
+ * unlit proxy carrying emissive * emissiveIntensity.
+ * null not a light source: black in the mask.
+ *
+ * `material.userData.bloom` overrides all of it — `false` to opt out, `true` to
+ * say "this material IS the light" (a custom shader has no other way to say so),
+ * or a colour to name the emission outright.
+ *
+ * @returns {'keep'|{color: THREE.Color, map: THREE.Texture|null}|null}
+ */
+export function glowRoleOf(material, threshold = 0) {
+ if (!material) return null;
+ const ud = material.userData || {};
+ if (ud.bloom === false) return null;
+ if (ud.bloom === true) return 'keep';
+ if (ud.bloom) {
+ const c = new THREE.Color();
+ try { c.set(ud.bloom); } catch (e) { c.set(0xffffff); }
+ return { color: c, map: material.emissiveMap || material.map || null };
+ }
+
+ if (material.emissive && material.emissive.isColor) {
+ const i = Number.isFinite(material.emissiveIntensity) ? material.emissiveIntensity : 1;
+ const c = material.emissive.clone().multiplyScalar(Math.max(0, i));
+ // three multiplies emissiveMap BY emissive, so a black emissive emits nothing
+ // however bright its map — a map alone must never invent a light source.
+ return Math.max(c.r, c.g, c.b) > threshold
+ ? { color: c, map: material.emissiveMap || null }
+ : null;
+ }
+
+ // Order matters: a LIT material answered above on its emissive alone, so an
+ // additive lit material with nothing emissive stays out of the mask — additive
+ // is only evidence of light for a material that carries no lighting of its own.
+ if (material.blending === THREE.AdditiveBlending) return 'keep';
+ const unlit = material.isMeshBasicMaterial || material.isSpriteMaterial || material.isPointsMaterial;
+ if (unlit && material.toneMapped === false) return 'keep';
+ return null;
+}
+
+/**
+ * The bloom source: the scene re-rendered with every material replaced by its
+ * EMISSION (see `emissionOf`), then blurred down/up into a wide soft veil.
+ *
+ * The proxy is a MeshBasicMaterial, so a custom vertex program (the library's
+ * wind bend, for instance) is NOT reproduced — an emissive that is also vertex
+ * displaced glows from its rest pose. Inside a blur that wide it is invisible,
+ * and the alternative (cloning materials with live uniform closures) is a much
+ * worse trade.
+ */
+function makeGlowLayer(renderer, scene, { width, height, levels, threshold }) {
+ const opts = { type: THREE.HalfFloatType, depthBuffer: true };
+ const targets = [];
+ let w = Math.max(2, width >> 1), h = Math.max(2, height >> 1);
+ for (let i = 0; i < Math.max(1, levels); i++) {
+ targets.push(new THREE.WebGLRenderTarget(w, h, i === 0 ? opts : { type: THREE.HalfFloatType }));
+ w = Math.max(2, w >> 1);
+ h = Math.max(2, h >> 1);
+ }
+ const quad = new FullScreenQuad();
+ const down = new THREE.ShaderMaterial({ ...DOWN_SHADER, uniforms: THREE.UniformsUtils.clone(DOWN_SHADER.uniforms) });
+ const up = new THREE.ShaderMaterial({
+ ...UP_SHADER,
+ uniforms: THREE.UniformsUtils.clone(UP_SHADER.uniforms),
+ blending: THREE.AdditiveBlending, // each level ADDS: a long, soft falloff
+ depthTest: false,
+ depthWrite: false,
+ });
+
+ const proxies = new Map(); // material.uuid -> MeshBasicMaterial | null (= black)
+ const black = new THREE.MeshBasicMaterial({ color: 0x000000, fog: false });
+ const swapped = [];
+ let sources = 0;
+
+ /** 'keep' | MeshBasicMaterial proxy | null (black), cached per material. */
+ function proxyFor(material) {
+ if (proxies.has(material.uuid)) return proxies.get(material.uuid);
+ const role = glowRoleOf(material, threshold);
+ let proxy = role === 'keep' ? 'keep' : null;
+ if (role && role !== 'keep') {
+ proxy = new THREE.MeshBasicMaterial({
+ color: role.color,
+ map: role.map || null,
+ fog: false,
+ toneMapped: false,
+ transparent: !!material.transparent,
+ opacity: Number.isFinite(material.opacity) ? material.opacity : 1,
+ alphaTest: material.alphaTest || 0,
+ alphaMap: material.alphaMap || null,
+ side: material.side,
+ depthTest: material.depthTest !== false,
+ depthWrite: material.depthWrite !== false,
+ blending: material.blending === THREE.AdditiveBlending ? THREE.AdditiveBlending : THREE.NormalBlending,
+ vertexColors: !!material.vertexColors,
+ });
+ }
+ proxies.set(material.uuid, proxy);
+ return proxy;
+ }
+
+ /** Swap in the emission proxies; returns how many real light sources were found. */
+ function swapIn() {
+ swapped.length = 0;
+ sources = 0;
+ scene.traverse((o) => {
+ if (!o.visible || !o.material) return;
+ if (!(o.isMesh || o.isPoints || o.isSprite || o.isLine || o.isInstancedMesh)) return;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ const next = mats.map((m, i) => {
+ const p = proxyFor(m);
+ if (p) sources += 1;
+ return p === 'keep' ? mats[i] : (p || black);
+ });
+ if (next.every((m, i) => m === mats[i])) return; // all 'keep': nothing to restore
+ swapped.push([o, o.material]);
+ o.material = Array.isArray(o.material) ? next : next[0];
+ });
+ return sources;
+ }
+
+ function swapOut() {
+ for (const [o, m] of swapped) o.material = m;
+ swapped.length = 0;
+ }
+
+ return {
+ get texture() { return targets[0].texture; },
+ get sources() { return sources; },
+
+ /** Render + blur the emission mask. Returns false when nothing glows. */
+ render(camera) {
+ const found = swapIn();
+ if (!found) { swapOut(); return false; }
+ const savedBg = scene.background;
+ const savedFog = scene.fog;
+ const savedClear = renderer.getClearColor(new THREE.Color());
+ const savedAlpha = renderer.getClearAlpha();
+ const savedTarget = renderer.getRenderTarget();
+ try {
+ scene.background = null;
+ scene.fog = null; // fog would grey the mask into a global glow
+ renderer.setClearColor(0x000000, 1);
+ renderer.setRenderTarget(targets[0]);
+ renderer.clear();
+ renderer.render(scene, camera);
+ } finally {
+ scene.background = savedBg;
+ scene.fog = savedFog;
+ renderer.setClearColor(savedClear, savedAlpha);
+ swapOut();
+ }
+
+ // down the pyramid ...
+ for (let i = 1; i < targets.length; i++) {
+ down.uniforms.tDiffuse.value = targets[i - 1].texture;
+ down.uniforms.texel.value.set(1 / targets[i - 1].width, 1 / targets[i - 1].height);
+ quad.material = down;
+ renderer.setRenderTarget(targets[i]);
+ renderer.clear();
+ quad.render(renderer);
+ }
+ // ... and back up, adding every level into the one above it
+ const autoClear = renderer.autoClear;
+ renderer.autoClear = false;
+ for (let i = targets.length - 1; i > 0; i--) {
+ up.uniforms.tDiffuse.value = targets[i].texture;
+ up.uniforms.texel.value.set(1 / targets[i].width, 1 / targets[i].height);
+ quad.material = up;
+ renderer.setRenderTarget(targets[i - 1]);
+ quad.render(renderer);
+ }
+ renderer.autoClear = autoClear;
+ renderer.setRenderTarget(savedTarget);
+ return true;
+ },
+
+ setSize(width2, height2) {
+ let w2 = Math.max(2, width2 >> 1), h2 = Math.max(2, height2 >> 1);
+ for (const t of targets) {
+ t.setSize(w2, h2);
+ w2 = Math.max(2, w2 >> 1);
+ h2 = Math.max(2, h2 >> 1);
+ }
+ },
+
+ dispose() {
+ for (const t of targets) t.dispose();
+ for (const p of proxies.values()) if (p) p.dispose();
+ proxies.clear();
+ black.dispose();
+ down.dispose();
+ up.dispose();
+ quad.dispose();
+ },
+ };
+}
+
+function num(v, fallback) {
+ return Number.isFinite(v) ? Number(v) : fallback;
+}
+
+function vec3From(v, target) {
+ if (Array.isArray(v) && v.length >= 3 && v.every((x) => Number.isFinite(x))) {
+ target.set(Number(v[0]), Number(v[1]), Number(v[2]));
+ } else if (v && Number.isFinite(v.r) && Number.isFinite(v.g) && Number.isFinite(v.b)) {
+ target.set(v.r, v.g, v.b); // a THREE.Color reads as a tint triple
+ }
+ return target;
+}
+
+/**
+ * Read `scene.userData.grade` into a grade pass's uniforms. Unknown keys are
+ * ignored and a malformed one keeps its identity default, so a scene can never
+ * break the chain by asking for nonsense.
+ * @returns {object} the applied values (for the census)
+ */
+export function applyGrade(pass, grade) {
+ const u = pass.uniforms;
+ const g = (grade && typeof grade === 'object') ? grade : {};
+ u.exposure.value = Math.min(8, Math.max(0.05, num(g.exposure, GRADE_DEFAULTS.exposure)));
+ u.contrast.value = Math.min(2, Math.max(0.2, num(g.contrast, GRADE_DEFAULTS.contrast)));
+ u.saturation.value = Math.min(2.5, Math.max(0, num(g.saturation, GRADE_DEFAULTS.saturation)));
+ u.warmth.value = Math.min(1, Math.max(-1, num(g.warmth, GRADE_DEFAULTS.warmth)));
+ u.tint.value = Math.min(1, Math.max(-1, num(g.tint, GRADE_DEFAULTS.tint)));
+ u.shadowLift.value = Math.min(0.25, Math.max(0, num(g.shadowLift, GRADE_DEFAULTS.shadowLift)));
+ u.vignette.value = Math.min(1, Math.max(0, num(g.vignette, GRADE_DEFAULTS.vignette)));
+ vec3From(g.shadowTint, u.shadowTint.value).clampScalar(-0.5, 0.5);
+ vec3From(g.highlightTint, u.highlightTint.value).clampScalar(-0.5, 0.5);
+ return {
+ exposure: u.exposure.value, contrast: u.contrast.value, saturation: u.saturation.value,
+ warmth: u.warmth.value, tint: u.tint.value, shadow_lift: u.shadowLift.value,
+ vignette: u.vignette.value,
+ shadow_tint: u.shadowTint.value.toArray().map((x) => +x.toFixed(3)),
+ highlight_tint: u.highlightTint.value.toArray().map((x) => +x.toFixed(3)),
+ };
+}
+
+/** Is this grade the identity (nothing to report, nothing shifted)? */
+export function isNeutralGrade(applied) {
+ return applied.exposure === 1 && applied.contrast === 1 && applied.saturation === 1
+ && applied.warmth === 0 && applied.tint === 0 && applied.shadow_lift === 0 && applied.vignette === 0
+ && applied.shadow_tint.every((x) => x === 0) && applied.highlight_tint.every((x) => x === 0);
+}
+
+/**
+ * Build the post chain for `scene` on `renderer`.
+ *
+ * @param {THREE.WebGLRenderer} renderer
+ * @param {THREE.Scene} scene
+ * @param {{width:number, height:number, options?:object}} spec
+ * @returns {{render(camera):void, setSize(w,h):void, dispose():void, info:object,
+ * refreshGrade():void, composer:EffectComposer}}
+ */
+export function makePostChain(renderer, scene, { width, height, options = {} } = {}) {
+ const opt = { ...POST_DEFAULTS, ...(options || {}) };
+ const warnings = [];
+ const target = new THREE.WebGLRenderTarget(width, height, {
+ type: THREE.HalfFloatType,
+ samples: Math.max(0, opt.samples | 0),
+ });
+ const composer = new EffectComposer(renderer, target);
+ composer.setSize(width, height);
+
+ const renderPass = new RenderPass(scene, null);
+ composer.addPass(renderPass);
+ composer.addPass(new ShaderPass(clampShader(opt.clampMax)));
+
+ let gtao = null;
+ if (opt.ao > 0) {
+ try {
+ // GTAOPass reads projection flags at construction; the real camera is
+ // swapped in before every render (its uniforms refresh per frame).
+ const aoCam = new THREE.PerspectiveCamera(50, width / height, 0.1, 1000);
+ gtao = new GTAOPass(scene, aoCam, width, height);
+ gtao.updateGtaoMaterial({
+ radius: opt.aoRadius,
+ distanceExponent: opt.aoDistanceExponent,
+ thickness: opt.aoThickness,
+ scale: 1.0,
+ samples: opt.aoSamples,
+ });
+ gtao.updatePdMaterial({ rings: opt.aoDenoiseRings, samples: opt.aoDenoiseSamples });
+ gtao.blendIntensity = opt.ao;
+ composer.addPass(gtao);
+ } catch (e) {
+ gtao = null;
+ warnings.push(`GTAO unavailable: ${String((e && e.message) || e).slice(0, 200)}`);
+ }
+ }
+
+ let glow = null;
+ let bloomPass = null;
+ if (opt.bloom > 0) {
+ glow = makeGlowLayer(renderer, scene, {
+ width, height, levels: opt.bloomLevels, threshold: opt.bloomThreshold,
+ });
+ bloomPass = new ShaderPass(BLOOM_COMPOSITE_SHADER);
+ composer.addPass(bloomPass);
+ }
+
+ const gradePass = new ShaderPass(GRADE_SHADER);
+ composer.addPass(gradePass);
+ composer.addPass(new OutputPass());
+
+ let applied = applyGrade(gradePass, scene.userData && scene.userData.grade);
+
+ const info = {
+ enabled: true,
+ ao: gtao ? opt.ao : 0,
+ ao_radius: opt.aoRadius,
+ bloom: glow ? opt.bloom : 0,
+ bloom_levels: opt.bloomLevels,
+ bloom_sources: 0,
+ samples: Math.max(0, opt.samples | 0),
+ passes: composer.passes.length,
+ grade: applied,
+ grade_neutral: isNeutralGrade(applied),
+ warnings,
+ };
+
+ return {
+ composer,
+ info,
+ /** Re-read scene.userData.grade (a scene may set it during createScene or update). */
+ refreshGrade() {
+ applied = applyGrade(gradePass, scene.userData && scene.userData.grade);
+ info.grade = applied;
+ info.grade_neutral = isNeutralGrade(applied);
+ },
+ render(camera) {
+ if (glow) {
+ const lit = glow.render(camera);
+ info.bloom_sources = glow.sources;
+ // keep the sampler bound either way (an unbound sampler2D is a warning);
+ // strength 0 is what makes a scene with nothing emissive pay nothing.
+ bloomPass.uniforms.tGlow.value = glow.texture;
+ // the up-chain ADDS every mip into the one above it, so the veil already
+ // carries ~one unit of energy per level: normalise, or `bloom` would mean
+ // something different at every pyramid depth.
+ bloomPass.uniforms.strength.value = lit ? opt.bloom / Math.max(1, opt.bloomLevels) : 0;
+ }
+ renderPass.camera = camera;
+ if (gtao) gtao.camera = camera;
+ composer.render();
+ },
+ setSize(w, h) {
+ composer.setSize(w, h);
+ if (gtao) gtao.setSize(w, h);
+ if (glow) glow.setSize(w, h);
+ },
+ dispose() {
+ for (const p of composer.passes) { if (typeof p.dispose === 'function') p.dispose(); }
+ if (glow) glow.dispose();
+ composer.renderTarget1.dispose();
+ composer.renderTarget2.dispose();
+ },
+ };
+}
diff --git a/harness/runtime_js/lib/cli.mjs b/harness/runtime_js/lib/cli.mjs
index 6b97a482..7d5660cd 100644
--- a/harness/runtime_js/lib/cli.mjs
+++ b/harness/runtime_js/lib/cli.mjs
@@ -12,6 +12,19 @@ export function parseCli(spec, argv = process.argv.slice(2)) {
return values;
}
+/**
+ * Boolean env switch with a default: '0'/'off'/'false'/'no' are OFF,
+ * '1'/'on'/'true'/'yes' are ON, anything else (including unset) keeps `fallback`.
+ * THE spelling for every driver env flag, so `CV3D_POST=0` reads the same way
+ * `CV3D_RENDER_GPU=off` does.
+ */
+export function envFlag(name, fallback) {
+ const raw = String(process.env[name] ?? '').trim().toLowerCase();
+ if (raw === '0' || raw === 'off' || raw === 'false' || raw === 'no') return false;
+ if (raw === '1' || raw === 'on' || raw === 'true' || raw === 'yes') return true;
+ return fallback;
+}
+
/** Print the final JSON summary as the LAST stdout line and exit. */
export function finish(summary, code = 0) {
process.stdout.write(JSON.stringify(summary) + '\n');
diff --git a/harness/runtime_js/lib/host_page.mjs b/harness/runtime_js/lib/host_page.mjs
index 02caa02a..97a4290b 100644
--- a/harness/runtime_js/lib/host_page.mjs
+++ b/harness/runtime_js/lib/host_page.mjs
@@ -55,7 +55,7 @@ export function requestFailureLine(url, base, hasResponse, errorText) {
* Open the host for workspace `wsRoot`.
* @returns {Promise<{page, browser, base, gpu, renderer, errors, boot, close}>}
*/
-export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false } = {}) {
+export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto', logDepth = false, sceneRel = 'src/scene.js', createSceneTimeoutMs = 0, settle = true, cameraRepair = false, autoExposure = false, post = true, postOptions = null } = {}) {
wsRoot = path.resolve(wsRoot);
if (!fs.existsSync(path.join(wsRoot, sceneRel))) {
throw new Error(`missing ${sceneRel} in workspace ${wsRoot}`);
@@ -101,7 +101,7 @@ export async function openHost(wsRoot, { width = 1024, height = 576, gpu = 'auto
await page.waitForFunction('window.__c3v_ready === true', { timeout: 60000 });
const boot = await page.evaluate(
(o) => window.__c3v.boot(o),
- { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure },
+ { sceneUrl: `/${sceneRel}`, width, height, logDepth, createSceneTimeoutMs, settle, cameraRepair, autoExposure, post, postOptions },
);
const close = async () => {
// page first, then release: a SHARED browser (connect-first reuse) must get
diff --git a/harness/runtime_js/lib/scene_host.mjs b/harness/runtime_js/lib/scene_host.mjs
index 1e94ca54..631c6b59 100644
--- a/harness/runtime_js/lib/scene_host.mjs
+++ b/harness/runtime_js/lib/scene_host.mjs
@@ -5,15 +5,18 @@
* sRGB, shadow maps), imports the agent's `src/scene.js` through the import
* map, calls `createScene({THREE, renderer, loaders})`, validates the returned
* shape and exposes `window.__c3v` with deterministic instruments:
+ * Scene renders go through the post chain (browser/post.js: GTAO + soft bloom +
+ * grade, `post: false` to disable); the coverage mask passes stay raw.
* boot(opts) · renderAt(cameraSpec, t) · census() · fps(seconds)
* cameraChecks(cameraSpec) (near geometry + luminance + content coverage)
- * compileAll(cameraSpec) · shaderErrors()
+ * compileAll(cameraSpec) · shaderErrors() · ablation(opts) (shader presence)
* Node drivers (render_scene / probe_scene / check_shaders) call these via
* page.evaluate. Agent code never imports this file.
*/
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { ablationReport, frameSampler } from './host_ablation.mjs';
import { sceneCensus } from './host_census.mjs';
import { placementTable, settleScene } from './host_placement.mjs';
import { frameStats, nearGeometry, repairCameraSpec } from './host_metrics.mjs';
@@ -52,6 +55,8 @@ const state = {
repairedSpecs: new Map(),
autoExposure: false,
autoExposureInfo: null,
+ post: null,
+ postInfo: null,
};
/**
@@ -236,6 +241,29 @@ async function boot(opts) {
state.simTime = 0;
state.scene.updateMatrixWorld(true);
+ // post chain (browser/post.js): ON for scene renders unless `post: false`.
+ // Built here — after the first update, so a scene that sets its grade hint
+ // while building has already set it — and before auto-exposure, which must
+ // measure the frame that will actually be judged. A chain that cannot be
+ // built is a host WARNING, never a boot failure: the raw path still renders.
+ if (opts.post !== false) {
+ info.stage = 'post';
+ try {
+ const { makePostChain } = await import('./browser/post.js');
+ state.post = makePostChain(state.renderer, state.scene, {
+ width: state.width, height: state.height, options: opts.postOptions || {},
+ });
+ state.postInfo = state.post.info;
+ for (const w of state.post.info.warnings) state.hostWarnings.push(`post: ${w}`);
+ } catch (e) {
+ state.post = null;
+ state.postInfo = { enabled: false, error: String((e && e.message) || e).slice(0, 300) };
+ state.hostWarnings.push(`post chain unavailable, plain render: ${state.postInfo.error}`);
+ }
+ } else {
+ state.postInfo = { enabled: false };
+ }
+
// settle (2026-08-30): deterministically seat floating / sunken assets before any
// census or render — the placement gate measured the errors for two batteries and
// the refine agent left 38 sunken + 22 floating standing in final rounds. Runs on
@@ -279,6 +307,14 @@ async function boot(opts) {
}
state.booted = true;
info.ok = cameras.length > 0;
+ // A camera-less scene used to fail with info.error EMPTY, so the caller
+ // reported `scene did not boot at stage 'ready': ` and named no reason —
+ // ~20 minutes of blind bisecting down to a two-line scene, twice.
+ // validateCameras already said WHY; carry it into the error.
+ if (!info.ok) {
+ info.error = 'createScene() returned no usable cameras'
+ + (problems.length ? ': ' + problems.join('; ') : '');
+ }
info.stage = 'ready';
} catch (e) {
info.error = formatError(e);
@@ -391,8 +427,14 @@ function advanceTo(t) {
}
}
+/** One frame to the canvas — through the post chain when it is armed. */
function renderOnce(cam) {
- state.renderer.render(state.scene, cam);
+ if (state.post) {
+ state.post.refreshGrade(); // a scene may set userData.grade from update()
+ state.post.render(cam);
+ } else {
+ state.renderer.render(state.scene, cam);
+ }
try { const gl = state.renderer.getContext(); if (gl && gl.finish) gl.finish(); } catch (e) { /* ignore */ }
}
@@ -466,15 +508,50 @@ function fps(seconds, spec) {
while (performance.now() < deadline) {
state.simTime += FIXED_DT;
runUpdate(state.simTime, FIXED_DT);
- state.renderer.render(state.scene, cam);
+ if (state.post) state.post.render(cam); else state.renderer.render(state.scene, cam);
frames += 1;
}
try { state.renderer.getContext().finish(); } catch (e) { /* ignore */ }
const elapsed = (performance.now() - t0) / 1000;
+ // draw calls / triangles must stay the SCENE's numbers: renderer.info resets on
+ // every render() call, so after a composer frame it holds the last full-screen
+ // quad. One plain render refills it with what the agent's budget is about.
+ if (state.post) state.renderer.render(state.scene, cam);
const r = state.renderer.info.render;
return { fps: frames / Math.max(elapsed, 1e-3), frames, seconds: elapsed, draw_calls: r.calls, triangles: r.triangles };
}
+/**
+ * Ablation instrument (host_ablation.mjs): render each camera as authored and
+ * again with every custom shader replaced by a neutral material, and report the
+ * fraction of the frame the shaders actually paint.
+ *
+ * Time is advanced ONCE, before any render, and never again: every frame in the
+ * report — authored, fully ablated, leave-one-out — is the same instant of the
+ * same scene, so the only thing that differs between two frames is the shader
+ * under test. Frames go through `renderOnce`, so the post chain (when armed)
+ * is included: the measurement is of the DELIVERED picture, not of a raw pass
+ * nobody sees.
+ *
+ * @param {{t?:number, cameras?:object[], maxMaterials?:number, threshold?:number, frames?:boolean}} opts
+ */
+function ablation(opts = {}) {
+ if (!state.booted) throw new Error('host not booted');
+ const t = Number.isFinite(opts.t) ? opts.t : 1.5;
+ advanceTo(t);
+ state.scene.updateMatrixWorld(true);
+ const cameras = (Array.isArray(opts.cameras) && opts.cameras.length) ? opts.cameras : state.cameras;
+ const sample = frameSampler(state.canvas);
+ const renderFrame = (spec) => { renderOnce(buildCamera(spec)); return sample(); };
+ const snapshot = opts.frames ? () => state.canvas.toDataURL('image/png') : null;
+ const report = ablationReport(state.scene, THREE, {
+ renderFrame, snapshot, cameras, grid: sample.grid,
+ maxMaterials: opts.maxMaterials, threshold: opts.threshold, maxRenders: opts.maxRenders,
+ });
+ report.sim_time = state.simTime;
+ return report;
+}
+
/** Per-asset placement table (host_placement.mjs) — never throws: a failure is `{error}`. */
function placement() {
try {
@@ -491,6 +568,7 @@ function census() {
if (state.settleInfo) c.settle = state.settleInfo;
if (state.cameraRepairs.length) c.camera_repair = state.cameraRepairs.slice();
if (state.autoExposureInfo) c.auto_exposure = state.autoExposureInfo;
+ if (state.postInfo) c.post = state.postInfo;
state.contentBox = c.content_bbox;
state.fullBox = c.bbox;
c.cameras = state.cameras.length;
@@ -506,8 +584,14 @@ window.__c3v = {
compileAll,
census,
placement,
+ ablation,
fps,
- setViewport(w, h) { state.width = w; state.height = h; state.renderer.setSize(w, h, false); },
+ setViewport(w, h) {
+ state.width = w; state.height = h;
+ state.renderer.setSize(w, h, false);
+ if (state.post) state.post.setSize(w, h);
+ },
+ post: () => (state.postInfo ? { ...state.postInfo } : null),
shaderErrors: () => state.shaderErrors.slice(),
loadErrors: () => state.loadErrors.slice(),
updateErrors: () => state.updateErrors.slice(),
diff --git a/harness/runtime_js/probe_scene.mjs b/harness/runtime_js/probe_scene.mjs
index 957bfbfa..f09219cf 100644
--- a/harness/runtime_js/probe_scene.mjs
+++ b/harness/runtime_js/probe_scene.mjs
@@ -31,6 +31,11 @@ const args = parseCli({
'no-settle': { type: 'boolean', default: false },
'camera-repair': { type: 'boolean', default: false },
'auto-exposure': { type: 'boolean', default: false },
+ // The probe is a 320x180 GEOMETRY instrument, never a judged picture: it runs raw
+ // so its shader report names the scene's own programs and nothing of ours. The
+ // flags parse (drivers share a switch list) but only `--post` turns the chain on.
+ 'no-post': { type: 'boolean', default: false },
+ post: { type: 'boolean', default: false },
ws: {}, out: {}, gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' }, 'timeout-ms': { default: '60000' },
'create-timeout-ms': { default: '' }, 'update-steps': { default: '10' }, scene: { default: 'src/scene.js' },
compile: { type: 'boolean', default: false }, 'shaders-out': { default: '' }, 'sun-azimuth': { default: '' },
@@ -62,6 +67,7 @@ async function main() {
settle: !args['no-settle'],
cameraRepair: !!args['camera-repair'],
autoExposure: !!args['auto-exposure'],
+ post: !!args.post && !args['no-post'],
});
} catch (e) {
return fail(`host failed: ${e.message}`);
diff --git a/harness/runtime_js/render_scene.mjs b/harness/runtime_js/render_scene.mjs
index 9631d8b7..d89509e6 100644
--- a/harness/runtime_js/render_scene.mjs
+++ b/harness/runtime_js/render_scene.mjs
@@ -8,6 +8,7 @@
* [--bounds '{"min":[x,y,z],"max":[x,y,z]}'|none] (plan bounds: orbit framing guard)
* [--times 0,1.5] [--width 1024] [--height 576] [--gpu auto|on|off]
* [--fps-seconds 2] [--timeout-ms 240000]
+ * [--no-post] [--post-options '{"ao":0.45,"bloomStrength":0.22}']
*
* Writes PNG per (camera, time), views.json, metrics.json
* {console_errors, shader_errors, fps, census, camera_checks, ...}.
@@ -15,7 +16,7 @@
*/
import path from 'node:path';
-import { armWatchdog, dataUrlToPng, ensureDir, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';
+import { armWatchdog, dataUrlToPng, ensureDir, envFlag, fail, finish, parseCli, readJsonArg, safeName, writeJson } from './lib/cli.mjs';
import { createTimeoutMs, errorSummary, openHost } from './lib/host_page.mjs';
import { fitOrbitCameras, framingBox } from './lib/orbit.mjs';
@@ -23,6 +24,10 @@ const args = parseCli({
'no-settle': { type: 'boolean', default: false },
'camera-repair': { type: 'boolean', default: false },
'auto-exposure': { type: 'boolean', default: false },
+ // post chain (GTAO + soft bloom + grade): ON for scene pictures, `--no-post` /
+ // CV3D_POST=0 to render raw. Object renders never come through here.
+ 'no-post': { type: 'boolean', default: false },
+ 'post-options': { default: '' },
ws: {}, out: {}, cameras: { default: 'authored' }, 'orbit-views': { default: 'none' }, bounds: { default: 'none' },
times: { default: '0,1.5' }, width: { default: '1024' }, height: { default: '576' },
gpu: { default: process.env.CV3D_RENDER_GPU || 'auto' }, 'fps-seconds': { default: '2' },
@@ -59,6 +64,8 @@ async function main() {
settle: !args['no-settle'],
cameraRepair: !!args['camera-repair'],
autoExposure: !!args['auto-exposure'],
+ post: args['no-post'] ? false : envFlag('CV3D_POST', true),
+ postOptions: readJsonArg(args['post-options'], 'post-options'),
});
} catch (e) {
return fail(`host failed: ${e.message}`);
@@ -128,6 +135,12 @@ async function main() {
const reps = await page.evaluate(() => window.__c3v.cameraRepairs());
if (reps.length && metrics.census) metrics.census.camera_repair = reps;
} catch (e) { sceneErr('camera repair readback failed', e); }
+ // same story for the post chain: it counts its bloom sources while RENDERING,
+ // so the census captured above always reported zero of them
+ try {
+ const post = await page.evaluate(() => window.__c3v.post());
+ if (post && metrics.census) metrics.census.post = post;
+ } catch (e) { sceneErr('post readback failed', e); }
metrics.shader_errors = (await page.evaluate(() => window.__c3v.shaderErrors())).map(({ _key, ...e }) => e);
metrics.update_errors = await page.evaluate(() => window.__c3v.updateErrors());
Object.assign(metrics, errorSummary(host.errors, boot));
diff --git a/harness/tests/scene_runtime/test_driver_flags.py b/harness/tests/scene_runtime/test_driver_flags.py
index 7de8d9e4..9639895f 100644
--- a/harness/tests/scene_runtime/test_driver_flags.py
+++ b/harness/tests/scene_runtime/test_driver_flags.py
@@ -19,7 +19,7 @@ from tests.scene_runtime.conftest import needs_node
pytestmark = [pytest.mark.node, needs_node]
-FLAGS = ["--no-settle", "--camera-repair", "--auto-exposure"]
+FLAGS = ["--no-settle", "--camera-repair", "--auto-exposure", "--no-post"]
@pytest.mark.parametrize("driver", ["render_scene.mjs", "probe_scene.mjs"])
diff --git a/harness/tests/scene_runtime/test_post.py b/harness/tests/scene_runtime/test_post.py
new file mode 100644
index 00000000..db28c280
--- /dev/null
+++ b/harness/tests/scene_runtime/test_post.py
@@ -0,0 +1,156 @@
+"""The scene post chain (runtime_js/lib/browser/post.js): GTAO + selective bloom + grade.
+
+The three properties that must not regress, each pinned against a raw render of
+the SAME scene:
+
+ * the chain is colour-neutral by itself — with AO and bloom off, a post render
+ matches `--no-post` (only MSAA separates them). This is what lets the grade
+ default to the identity and lets us attribute any shift to AO or bloom.
+ * bloom is SELECTIVE: it fires on an emissive material and does nothing at all
+ on a scene whose brightest thing is merely bright. A global luminance
+ bright-pass (what the reference chain used) cannot tell those apart on our
+ renderer — the sky dome outshines every authored emissive — and fogged a
+ daylit frame, so the mask is the whole design and this is its guard.
+ * `scene.userData.grade` reaches the shader and is clamped.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from codeverse.spatial.render_scene import post_chain_args, read_metrics, run_scene_script
+from codeverse.workspace import Workspace
+from tests.scene_runtime.conftest import needs_browser, needs_node
+
+pytestmark = [pytest.mark.node]
+
+CAMERA = "{ name: 'cam', position: [0, 0, 6], lookAt: [0, 0, 0], fov: 45 }"
+
+SCENE = """
+import * as THREE from 'three';
+
+export function createScene() {
+ const scene = new THREE.Scene();
+ scene.background = new THREE.Color(0x000000);
+ scene.add(new THREE.AmbientLight(0xffffff, 1.2));
+ const mat = new THREE.MeshStandardMaterial(__MATERIAL__);
+ scene.add(new THREE.Mesh(new THREE.BoxGeometry(1.2, 1.2, 1.2), mat));
+ __EXTRA__
+ return { scene, cameras: [__CAMERA__], update(t, dt) {} };
+}
+"""
+
+# same albedo, same lighting: the ONLY difference is that one of them emits
+EMISSIVE = "{ color: 0x202020, emissive: 0xffffff, emissiveIntensity: 3.0 }"
+BRIGHT = "{ color: 0xffffff, emissive: 0x000000 }"
+
+
+def make_ws(tmp_path: Path, name: str, material: str, extra: str = "") -> Workspace:
+ w = Workspace(tmp_path / name).create()
+ src = SCENE.replace("__MATERIAL__", material).replace("__CAMERA__", CAMERA).replace("__EXTRA__", extra)
+ (w.root / "src").mkdir(parents=True, exist_ok=True)
+ (w.root / "src" / "scene.js").write_text(src)
+ return w
+
+
+def mean_lum(path: Path) -> float:
+ """Mean luminance of a render, on the host's own 96x54 sampling grid."""
+ im = Image.open(path).convert("RGB").resize((96, 54), Image.BILINEAR)
+ a = np.asarray(im, dtype=float)
+ return float((0.2126 * a[..., 0] + 0.7152 * a[..., 1] + 0.0722 * a[..., 2]).mean()) / 255
+
+
+def render(ws: Workspace, out: Path, *extra_args: str) -> Path:
+ """One authored-camera frame at t=0, straight through the driver so the test
+ can pass --post-options / --no-post (render_scene() owns neither)."""
+ out.mkdir(parents=True, exist_ok=True)
+ run_scene_script("render_scene.mjs", [
+ "--ws", str(ws.root), "--out", str(out), "--cameras", "authored",
+ "--orbit-views", "none", "--times", "0", "--width", "256", "--height", "144",
+ "--fps-seconds", "0", "--no-settle", "--timeout-ms", "120000", *extra_args,
+ ], timeout_s=150)
+ return out / "cam_t0.png"
+
+
+def test_post_chain_args_follow_the_env_switch(monkeypatch):
+ monkeypatch.delenv("CV3D_POST", raising=False)
+ assert post_chain_args() == [] # ON by default for scene pictures
+ monkeypatch.setenv("CV3D_POST", "0")
+ assert post_chain_args() == ["--no-post"]
+ monkeypatch.setenv("CV3D_POST", "on")
+ assert post_chain_args() == []
+
+
+@needs_node
+@needs_browser
+def test_chain_alone_is_colour_neutral(tmp_path):
+ """AO off, bloom off, grade at its defaults → the same picture as no chain.
+
+ Without this the grade could drift and nobody would notice: every later
+ measurement of AO or bloom is a delta against a raw render.
+ """
+ ws = make_ws(tmp_path, "neutral", BRIGHT)
+ raw = render(ws, tmp_path / "raw", "--no-post")
+ chain = render(ws, tmp_path / "chain", "--post-options", '{"ao":0,"bloom":0}')
+ assert abs(mean_lum(chain) - mean_lum(raw)) < 0.005, (mean_lum(raw), mean_lum(chain))
+
+
+@needs_node
+@needs_browser
+def test_bloom_is_selective_not_a_brightness_threshold(tmp_path):
+ """An EMISSIVE box blooms; an equally bright NON-emissive box does not.
+
+ Both scenes are lit the same and the plain box is the brighter of the two in
+ the raw render — so anything that keys off frame luminance fails this test,
+ which is exactly the reference chain's failure mode.
+ """
+ emissive = make_ws(tmp_path, "emissive", EMISSIVE)
+ plain = make_ws(tmp_path, "plain", BRIGHT)
+
+ e_raw, e_post = render(emissive, tmp_path / "e_raw", "--no-post"), render(emissive, tmp_path / "e_post")
+ p_raw, p_post = render(plain, tmp_path / "p_raw", "--no-post"), render(plain, tmp_path / "p_post")
+
+ assert read_metrics(tmp_path / "e_post")["census"]["post"]["bloom_sources"] >= 1
+ assert read_metrics(tmp_path / "p_post")["census"]["post"]["bloom_sources"] == 0
+
+ assert mean_lum(e_post) - mean_lum(e_raw) > 0.004, "emissive box did not bloom"
+ assert abs(mean_lum(p_post) - mean_lum(p_raw)) < 0.005, "a merely bright box must not bloom"
+
+
+@needs_node
+@needs_browser
+def test_scene_grade_hint_reaches_the_shader_and_is_clamped(tmp_path):
+ """`scene.userData.grade` is the scene's only lever on the grade; a value far
+ outside the sane range is clamped rather than obeyed or ignored."""
+ ws = make_ws(tmp_path, "graded", BRIGHT, extra="scene.userData.grade = { exposure: 99, warmth: 0.4 };")
+ out = tmp_path / "graded_out"
+ render(ws, out, "--post-options", '{"ao":0,"bloom":0}')
+ grade = read_metrics(out)["census"]["post"]["grade"]
+ assert grade["exposure"] == 8.0 # clamped from 99
+ assert grade["warmth"] == pytest.approx(0.4)
+ assert read_metrics(out)["census"]["post"]["grade_neutral"] is False
+
+
+@needs_node
+@needs_browser
+def test_no_post_leaves_the_chain_off(tmp_path):
+ ws = make_ws(tmp_path, "off", BRIGHT)
+ out = tmp_path / "off_out"
+ render(ws, out, "--no-post")
+ assert read_metrics(out)["census"]["post"] == {"enabled": False}
+
+
+@needs_node
+@needs_browser
+def test_ungraded_scene_reports_a_neutral_grade(tmp_path):
+ ws = make_ws(tmp_path, "ungraded", BRIGHT)
+ out = tmp_path / "ungraded_out"
+ render(ws, out)
+ post = read_metrics(out)["census"]["post"]
+ assert post["enabled"] is True and post["grade_neutral"] is True
+ assert post["warnings"] == [] and json.dumps(post) # serialisable into metrics.json