Official Codebase of 3DCodeVerse
Python
cleanup: eight effect modules no scene imported leave the library (D74)
gaoypeng58ecb6020474
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/building.jsindex fa7a813d..b50f5a0f 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js@@ -138,8 +138,8 @@ function revealMat() {* with `userData.forward` and `userData.floors`. Meshes are named* `Walls`, `Trim`, `Glazing`, `Reveals` and — only when `lit` — one* `LitRooms*` per lit class. `LitRooms` deliberately does NOT match- * `mirror.js` `glazeFacade`'s `/glaz|pane/` sweep, so mirroring a- * facade leaves its lit windows glowing.+ * a `/glaz|pane/` sweep, so re-glazing a facade leaves its lit+ * windows glowing.*/export function block(opts = {}) {const rand = opts.rand || (() => 0.5);diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.jsindex 8bf2a86b..850bccc0 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js@@ -9,7 +9,7 @@* one never emits a pixel of its own: it grabs the frame drawn so far* into a texture and resamples it at displaced coordinates. That grab* is a framebuffer COPY, not a second scene render, so it does not- * touch the one RTT budget `lib/mirror.js` enforces (a `Reflector`+ * touch the scene's one RTT budget (a `Reflector`* re-renders the WHOLE scene at +48 ms/frame on SwiftShader; a copy of* a frame already drawn is a blit). What it costs and what it cannot* do is written out on `makeHeatShimmer`.@@ -72,7 +72,7 @@ function prng(seed) {* three allocates SRGB8_ALPHA8 and the copy is refused again.** This is a resolve of a frame already drawn, not a second pass over- * the scene: it does not spend the RTT budget `lib/mirror.js` counts.+ * the scene: it does not spend the scene's one RTT budget.*/function frameGrabber(mat) {let tex = null;diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.jsdeleted file mode 100644index 8e7cab0d..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.js+++ /dev/null@@ -1,684 +0,0 @@-/**- * Cartoon creatures: round, two-and-a-half heads tall, with real- * three-layer eyes (sclera, iris, offset glint — flat dots read as a- * toy). NOT figure.js's human proportions shrunk: head 40-50% of- * height, egg body, stubby limbs. Every creature rests on y=0 and- * faces -Z, so `seat()` and `alignAlong()` from place.js work on it.- *- * Colour contract (this host renders ACES + sRGB at exposure 1 with no- * post chain): every author colour goes through `toonAlbedo`, which- * holds it inside the 0.02..0.78 LINEAR band a lit surface can live in,- * and every part carries its own noise seed and variant, so a body is a- * range of one hue rather than one flat value.- */--import * as THREE from 'three';-import * as MAT from './materials.js';--/**- * Clamp an author colour into the albedo band and keep its hue.- *- * A cartoon palette is written as ink — `0xfdfdfd` eyes, `0xfff0a8`- * bellies, `0x151515` pupils. Those are not albedos: at exposure 1- * the near-whites clip to paper and the near-blacks have no linear- * lightness left for the sun to lift, so the creature reads as a- * sticker with two holes in it. Lightness is clamped in LINEAR space- * (that is where 0.02..0.78 means anything), the hue is untouched, and- * a colour that had to be pulled down off white keeps a little- * saturation so it still belongs to the body's family.- */-function toonAlbedo(hex) {- const c = new THREE.Color(hex);- const hsl = c.getHSL({ h: 0, s: 0, l: 0 });- const l = Math.min(0.78, Math.max(0.02, hsl.l));- const s = hsl.l > 0.78 ? Math.max(hsl.s, 0.06) : hsl.s;- c.setHSL(hsl.h, s, l);- return c.getHex();-}--/** Blend two author colours in linear space; k=0 is `a`, k=1 is `b`. */-function mixHex(a, b, k) {- return new THREE.Color(a).lerp(new THREE.Color(b), k).getHex();-}--/**- * A belly/underside tone derived from the body colour.- *- * A fixed cream belly on every creature is what makes a set of them- * read as one toy line in three colours: the underside belongs to the- * body's hue, lifted and washed out, not to a separate palette.- */-function bellyFrom(hex) {- const c = new THREE.Color(hex);- const hsl = c.getHSL({ h: 0, s: 0, l: 0 });- c.setHSL((hsl.h + 0.015) % 1, hsl.s * 0.42,- Math.min(0.72, hsl.l * 1.7 + 0.20));- return c.getHex();-}--/**- * One part's tone, graded off the creature's base colour.- *- * @param {number} hex Base colour.- * @param {number} dl Lightness step (linear, signed).- * @param {number} dh Hue step; + is warm here, - is cool.- * @param {number} [ks] Saturation multiplier (default 1).- *- * This — not surface noise — is where a creature's colour variance- * belongs. A body is a set of clean parts in one hue FAMILY: the face- * carries the author's colour, the chest a step under it and warmer,- * the limbs a step under that and cooler because the body shades them.- * Painters do it on every toy; this renderer will not invent it, and- * a creature without it is one flat value with a shadow on it.- */-function partColor(hex, dl, dh, ks) {- const c = new THREE.Color(hex);- const hsl = c.getHSL({ h: 0, s: 0, l: 0 });- c.setHSL((hsl.h + dh + 1) % 1,- Math.min(1, hsl.s * (ks === undefined ? 1 : ks)),- Math.max(0.02, hsl.l + dl));- return c.getHex();-}--/**- * Toon-friendly body material: saturated, matte, no metal.- *- * The noise is a GRAIN, not a pattern. `noiseTexture` multiplies- * contrast by an fBm that sits within about +-0.08 of 0.5 and clamps- * the product at 1, so a caller's contrast reaches the albedo at about- * a twelfth of its face value: fabric's own 0.22 measured a map with- * std 4.4/255 (1.7%) — one flat plastic value. Spending that back is- * only half the fix, because FREQUENCY decides what the swing reads as.- * Rendered and looked at, in order: 11 cells at 0.70 came back as- * stains on a yellow creature, 34 cells at 0.55 as speckled lichen.- * 34 at 0.28 is a grain the eye integrates into one richer colour, and- * the creature's real variance comes from `partColor` instead.- */-function skinMat(color, rough, o = {}) {- return MAT.fabric({- color: toonAlbedo(color),- roughness: rough === undefined ? 0.72 : rough,- bump: o.bump === undefined ? 0.006 : o.bump,- scale: o.scale === undefined ? 34 : o.scale,- contrast: o.contrast === undefined ? 0.28 : o.contrast,- hueBreak: o.hueBreak === undefined ? 0.16 : o.hueBreak,- variant: o.variant === undefined ? 0.5 : o.variant,- spread: 0.45,- seed: o.seed === undefined ? 1 : o.seed,- });-}--/** A tapered stub limb hanging down -Y from its pivot, with a paw. */-function stub(len, r0, r1, mat, name, pawMat) {- const g = new THREE.Group();- g.name = name;- const geo = new THREE.CylinderGeometry(r1, r0, len, 10, 1);- geo.translate(0, -len / 2, 0);- const m = new THREE.Mesh(geo, mat);- m.castShadow = true;- g.add(m);- // The paw's BOTTOM sits at the end of the limb, not its centre —- // centring it buries a third of the foot under the ground plane.- const pawR = r1 * 1.35;- const paw = new THREE.Mesh(new THREE.SphereGeometry(pawR, 10, 8),- pawMat || mat);- paw.scale.set(1, 0.8, 1.25);- paw.position.y = -len + pawR * 0.8;- paw.castShadow = true;- g.add(paw);- return g;-}--function pivot(name, x, y, z) {- const o = new THREE.Object3D();- o.name = name;- o.position.set(x, y, z);- return o;-}--/**- * Build one eye: sclera, iris, and the glint that makes it alive.- *- * @param {number} r Eye radius in metres.- * @param {number} irisColor- * @returns {THREE.Group}- */-function eye(r, irisColor) {- const g = new THREE.Group();- // An eyeball is not a light source: paper-white sclera blew out- // against every body colour and killed the iris's contrast with it.- const white = new THREE.Mesh(- new THREE.SphereGeometry(r, 14, 12),- MAT.plaster({ color: toonAlbedo(0xf2efe8), roughness: 0.26, bump: 0,- contrast: 0.05, hueBreak: 0.02 }));- white.scale.set(0.85, 1, 0.7);- g.add(white);- // The creature faces -Z, so iris and glint belong on the -Z side:- // shipped at +Z once, every creature had blank white blobs for eyes.- // The iris is dark but never black — a pupil with no albedo left is a- // hole in the face, and the env's cool bounce is what makes it wet.- const iris = new THREE.Mesh(- new THREE.SphereGeometry(r * 0.62, 12, 10),- MAT.plaster({ color: toonAlbedo(irisColor === undefined- ? 0x1b2430 : irisColor),- roughness: 0.18, bump: 0, contrast: 0.05 }));- iris.position.z = -r * 0.45;- iris.scale.set(0.9, 1, 0.6);- g.add(iris);- // Glint offset up and to one side, never centred — centred reads- // as a painted dot, offset reads as wet. Emissive 2.2 is inside the- // bloom-friendly band (1.5-4) on a surface this small: at 0.55 the- // tone map folded it into the sclera and the eye went dead.- const glint = new THREE.Mesh(- new THREE.SphereGeometry(r * 0.19, 8, 6),- MAT.plaster({ color: 0xdedad2, roughness: 0.1, bump: 0,- extra: { emissive: new THREE.Color(0xfff4e2),- emissiveIntensity: 2.2 } }));- glint.position.set(-r * 0.28, r * 0.32, -r * 0.74);- g.add(glint);- return g;-}--const BODIES = {- // headRatio: head diameter as a fraction of total height.- // bodyW/bodyD: body width and depth as a fraction of height.- biped: { headRatio: 0.46, bodyW: 0.62, bodyD: 0.52, legs: 2, legLen: 0.24 },- quadruped: { headRatio: 0.42, bodyW: 0.70, bodyD: 1.05, legs: 4,- legLen: 0.30 },- blob: { headRatio: 0.52, bodyW: 0.85, bodyD: 0.80, legs: 2, legLen: 0.10 },- serpent: { headRatio: 0.40, bodyW: 0.42, bodyD: 1.5, legs: 0, legLen: 0 },-};--/**- * Build a cartoon creature.- *- * @param {object} [opts]- * `height` overall metres (default 0.6 -- most are knee-high, and- * getting that wrong is why creature scenes read as monsters);- * `body` one of `biped | quadruped | blob | serpent`;- * `bodyColor`, `bellyColor`, `accentColor`, `irisColor` hex- * (`bellyColor` defaults to the body's own hue, lifted);- * `eyeScale` multiplier on the default eye size (default 1);- * `rand` seeded PRNG; `name`.- * @returns {THREE.Group} Feet at y=0, facing -Z, with `userData.forward`,- * `userData.height`, `userData.joints` (`head`, `body`, `legFL` ...)- * and `userData.headR` so attachments can size themselves.- */-export function creature(opts = {}) {- const rand = opts.rand || (() => 0.5);- const h = (opts.height || 0.6) * (0.94 + rand() * 0.12);- const spec = BODIES[opts.body] || BODIES.biped;-- const bodyC = opts.bodyColor === undefined ? 0x7fc4e8 : opts.bodyColor;- const bellyC = opts.bellyColor === undefined ? bellyFrom(bodyC)- : opts.bellyColor;- // The head carries the author's colour — it is the part a viewer- // reads — and every other part is graded off it: chest a step under- // and warmer, limbs a step under that and cooler, because the body- // shades them and skylight is what is left when the sun is blocked.- const mat = skinMat(bodyC);- const torsoMat = skinMat(partColor(bodyC, -0.045, 0.008), undefined,- { seed: 2 });- const limbMat = skinMat(partColor(bodyC, -0.10, -0.012, 0.94), undefined,- { seed: 3 });- // A big pale underside takes a gentler grain than a saturated body:- // at full strength the same speckle reads as grime on near-white.- const belly = skinMat(bellyC, 0.78,- { seed: 4, scale: 28, contrast: 0.20, hueBreak: 0.12 });- // A pure belly-coloured paw reads as a sock pulled over the leg;- // half-way to the body colour keeps the two-tone and loses the seam.- const pawMat = skinMat(mixHex(bodyC, bellyC, 0.55), 0.75, { seed: 5 });-- const root = new THREE.Group();- root.name = opts.name || 'Creature';-- const headR = spec.headRatio * h * 0.5;- const legLen = spec.legLen * h;- let bodyH = h - legLen - headR * 2 * 0.82; // heads overlap bodies- // A legless body is an egg lying ON the ground: the torso sphere is- // scaled 1.12 in Y about its own centre, so its underside dips 6% of- // bodyH below the pivot and a serpent shipped buried to the waist.- const lift = spec.legs === 0 ? bodyH * 0.06 : 0;- bodyH -= lift; // keep the total at h- const baseY = legLen + lift;- const bodyW = spec.bodyW * h;- const bodyD = spec.bodyD * h;- const bodyY = baseY + bodyH / 2;-- // BODY: an egg, wider than tall for the round silhouette. A cylinder- // or a box here is the difference between a creature and a prop.- const bodyPivot = pivot('body', 0, baseY, 0);- const torso = new THREE.Mesh(new THREE.SphereGeometry(0.5, 24, 18),- torsoMat);- torso.scale.set(bodyW, bodyH * 1.12, bodyD);- torso.position.y = bodyH / 2;- torso.castShadow = true;- torso.name = 'torso';- bodyPivot.add(torso);-- // Belly patch: a flattened cap on the front, which is what gives a- // round creature a readable front at any distance. It has to stand- // CLEARLY proud of the torso: at the shipped 0.66 depth the two- // ellipsoids were near-tangent over a wide ring and the patch's edge- // was a band of z-fighting speckle, not a bib.- const bp = new THREE.Mesh(new THREE.SphereGeometry(0.5, 18, 12), belly);- bp.scale.set(bodyW * 0.62, bodyH * 0.70, bodyD * 0.60);- bp.position.set(0, bodyH * 0.44, -bodyD * 0.27);- bp.name = 'belly';- bodyPivot.add(bp);- root.add(bodyPivot);-- // HEAD: oversized, sitting low into the body so there is no neck gap.- const headY = baseY + bodyH * 0.94 + headR * 0.42;- const headPivot = pivot('head', 0, headY - baseY, 0);- const head = new THREE.Mesh(new THREE.SphereGeometry(headR, 22, 18), mat);- head.scale.set(1.06, 1, 0.98);- head.castShadow = true;- head.name = 'headMesh';- headPivot.add(head);-- // EYES: wide apart, below the head's equator. High, close-set eyes- // read as an adult face; low and wide reads as a young creature, and- // that is the whole of "cute" as a measurable quantity.- const er = headR * 0.30 * (opts.eyeScale || 1);- for (const s of [-1, 1]) {- const e = eye(er, opts.irisColor);- e.position.set(s * headR * 0.46, -headR * 0.06, -headR * 0.80);- e.name = 'eye' + (s < 0 ? 'L' : 'R');- headPivot.add(e);- }- // A small muzzle keeps the face from being a flat sphere, and the- // nose is the one dark accent that stops it reading as a white blob.- const muzzle = new THREE.Mesh(new THREE.SphereGeometry(headR * 0.30, 12, 10),- belly);- muzzle.scale.set(1.2, 0.72, 0.9);- muzzle.position.set(0, -headR * 0.36, -headR * 0.88);- muzzle.name = 'muzzle';- headPivot.add(muzzle);- // Same material call as the iris, so it is a cache hit rather than a- // thirteenth material and a thirteenth texture pair per palette.- const nose = new THREE.Mesh(new THREE.SphereGeometry(headR * 0.085, 8, 6),- MAT.plaster({ color: toonAlbedo(opts.irisColor === undefined- ? 0x1b2430 : opts.irisColor),- roughness: 0.18, bump: 0, contrast: 0.05 }));- nose.scale.set(1.25, 0.85, 0.8);- nose.position.set(0, -headR * 0.30, -headR * 1.10);- nose.name = 'nose';- headPivot.add(nose);- bodyPivot.add(headPivot);-- const joints = { body: bodyPivot, head: headPivot };-- // LEGS. Quadrupeds get four under the body's corners; bipeds get two- // stubs directly under the egg.- const legR = h * 0.055;- if (spec.legs === 4) {- for (const [nm, sx, sz] of [['FL', -1, -1], ['FR', 1, -1],- ['BL', -1, 1], ['BR', 1, 1]]) {- const p = pivot('leg' + nm, sx * bodyW * 0.34, legLen,- sz * bodyD * 0.30);- p.add(stub(legLen, legR * 1.25, legR, limbMat, 'legMesh' + nm, pawMat));- root.add(p);- joints['leg' + nm] = p;- }- } else if (spec.legs === 2) {- for (const s of [-1, 1]) {- const nm = s < 0 ? 'L' : 'R';- const p = pivot('leg' + nm, s * bodyW * 0.30, legLen, 0);- p.add(stub(legLen, legR * 1.4, legR * 1.1, limbMat, 'legMesh' + nm,- pawMat));- root.add(p);- joints['leg' + nm] = p;- }- // Bipeds also get little arms off the body.- for (const s of [-1, 1]) {- const nm = s < 0 ? 'L' : 'R';- const p = pivot('arm' + nm, s * bodyW * 0.46, bodyH * 0.62, 0);- p.rotation.z = s * 0.35;- p.add(stub(h * 0.16, legR, legR * 0.8, limbMat, 'armMesh' + nm, pawMat));- bodyPivot.add(p);- joints['arm' + nm] = p;- }- }-- root.userData.forward = '-Z';- root.userData.height = h;- root.userData.headR = headR;- root.userData.bodyW = bodyW;- root.userData.bodyD = bodyD;- root.userData.bodyY = bodyY;- root.userData.joints = joints;- root.userData.mat = mat;- root.userData.colors = { body: bodyC, belly: bellyC };- return root;-}--/** The author colour a creature was built from, for ears and tails. */-function baseColor(c) {- return c.userData.colors ? c.userData.colors.body- : c.userData.mat.color.getHex();-}--/**- * Add a pair of ears to a creature's head.- *- * @param {THREE.Group} c From `creature()`.- * @param {object} [opts] `type` `point | round | long | fin`, `length`- * as a multiple of head radius (default 0.9), `tipColor` hex for a- * contrasting tip (an inner-ear pad on `round`), `spread` 0..1 across- * the skull (default 0.55), `tilt` radians outward (default 0.35),- * `color`.- * @returns {THREE.Group} c- */-export function ear(c, opts = {}) {- const hr = c.userData.headR;- const head = c.userData.joints.head;- const len = hr * (opts.length === undefined ? 0.9 : opts.length) * 2;- const type = opts.type || 'point';- const col = opts.color === undefined ? baseColor(c) : opts.color;- // Ears sit a step under the face: they are thin, backlit and- // mostly in the skull's own shadow.- const mat = skinMat(partColor(col, -0.03, -0.006), undefined, { seed: 7 });- for (const s of [-1, 1]) {- const g = new THREE.Group();- g.name = 'ear' + (s < 0 ? 'L' : 'R');- let geo;- if (type === 'round') {- geo = new THREE.SphereGeometry(len * 0.42, 12, 10);- const m = new THREE.Mesh(geo, mat);- m.scale.set(0.55, 1, 0.9);- m.position.y = len * 0.35;- g.add(m);- if (opts.tipColor !== undefined) {- // `tipColor` was silently ignored on round ears. An inner pad- // is what it means here, and it is the cheapest cute signal- // there is: two warm ovals inside two body-coloured discs.- const pad = new THREE.Mesh(- new THREE.SphereGeometry(len * 0.42, 10, 8),- skinMat(opts.tipColor, 0.7, { seed: 8 }));- pad.scale.set(0.30, 0.74, 0.66);- pad.position.set(-s * len * 0.10, len * 0.36, 0);- g.add(pad);- }- } else if (type === 'fin') {- // A fin is a BLADE. Unflattened, this 4-gon cone rendered as a- // pyramid the size of the skull sitting on the creature's head.- geo = new THREE.ConeGeometry(len * 0.42, len, 4);- const m = new THREE.Mesh(geo, mat);- m.scale.set(0.30, 1, 1.15);- m.position.y = len / 2;- m.rotation.x = -0.22;- g.add(m);- } else {- const taper = type === 'long' ? 0.16 : 0.30;- const rTip = hr * 0.06, rBase = hr * taper;- geo = new THREE.CylinderGeometry(rTip, rBase, len, 10);- const m = new THREE.Mesh(geo, mat);- m.position.y = len / 2;- g.add(m);- if (opts.tipColor !== undefined) {- // The tip has to CAP the cone it sits on. Shipped with fixed- // radii it flared out of a `long` ear (which is only 0.087 hr- // wide there) and read as an orange wedge between the ears.- const tl = len * 0.30, y0 = len - tl;- const rAt = rBase + (rTip - rBase) * (y0 / len);- const tip = new THREE.Mesh(- new THREE.CylinderGeometry(rTip * 1.03, rAt * 1.03, tl, 10),- skinMat(opts.tipColor, undefined, { seed: 8 }));- tip.position.y = y0 + tl / 2;- g.add(tip);- }- }- g.traverse((o) => { if (o.isMesh) o.castShadow = true; });- const spread = opts.spread === undefined ? 0.55 : opts.spread;- g.position.set(s * hr * spread, hr * 0.72, hr * 0.1);- g.rotation.z = -s * (opts.tilt === undefined ? 0.35 : opts.tilt);- head.add(g);- }- return c;-}--/**- * Add a tail. Tails are most of a creature's silhouette from behind.- *- * @param {THREE.Group} c- * @param {object} [opts] `type` `bolt | flame | leaf | curl | fin |- * stub`, `length` as a multiple of the body's span (default 1),- * `color`, `tipColor`.- * @returns {THREE.Group} c- */-export function tail(c, opts = {}) {- const ud = c.userData;- // The span is the body depth CAPPED BY THE CREATURE'S OWN HEIGHT: a- // serpent's bodyD is 1.5 h, and taking it neat gave a 1.9 m serpent a- // 3.4 m tail — a green pyramid taller than the animal wearing it.- const span = Math.min(ud.bodyD, ud.height * 0.85);- const len = span * (opts.length === undefined ? 1 : opts.length);- const col = opts.color === undefined ? baseColor(c) : opts.color;- const mat = skinMat(partColor(col, -0.05, 0.006), undefined, { seed: 9 });- const g = new THREE.Group();- g.name = 'tail';- const type = opts.type || 'stub';- if (type === 'bolt') {- // A flat zig-zag: three plates, each rotated off the last.- let y = 0, z = 0, a = 0;- for (let i = 0; i < 3; i++) {- const seg = len * (0.5 - i * 0.08);- a += (i % 2 ? -1 : 1) * 0.8;- // The last plate takes the tip colour when there is one: a bolt- // that fades to a lighter point reads as a bolt, not a bracket.- const pm = (i === 2 && opts.tipColor !== undefined)- ? skinMat(opts.tipColor, undefined, { seed: 10 }) : mat;- const m = new THREE.Mesh(- new THREE.BoxGeometry(ud.bodyW * 0.16, seg, seg * 0.42), pm);- m.position.set(0, y + Math.cos(a) * seg / 2, z + Math.sin(a) * seg / 2);- m.rotation.x = -a;- g.add(m);- y += Math.cos(a) * seg; z += Math.sin(a) * seg;- }- } else if (type === 'flame') {- const m = new THREE.Mesh(- new THREE.CylinderGeometry(len * 0.08, len * 0.17, len, 10), mat);- m.position.y = len / 2;- m.rotation.x = -0.5;- g.add(m);- const tipC = opts.tipColor === undefined ? 0xff8a2b : opts.tipColor;- // ONE cone, because two opaque ones are two cones: a concentric hot- // core is never seen (the sheath tapers faster at every height) and- // a stacked one reads as a party hat on a party hat. Both were- // built and looked at. What DOES read is the emissive being a- // deeper, more saturated colour than the surface: by the time the- // tone map sees an orange flame its red is already clipped at 250,- // so intensity spent on the surface hue only lifts green and blue- // and the fire comes back cream (measured, 1.2 -> 2.3: the flame's- // own pixels went from saturation 0.62 to 0.50). Emissive 1.8 on- // the deepened hue sits in the bloom band AND stays orange.- const f = new THREE.Mesh(new THREE.ConeGeometry(len * 0.18, len * 0.50, 12),- MAT.fabric({ color: toonAlbedo(tipC), bump: 0, scale: 5,- contrast: 0.24, hueBreak: 0.22,- extra: { emissive: new THREE.Color(- partColor(tipC, -0.07, -0.012, 1.35)),- emissiveIntensity: 1.8 } }));- f.position.set(0, len * 0.92, -len * 0.24);- g.add(f);- // The throat: a hot bead where the flame leaves the stem. Offset in- // the SILHOUETTE, not buried inside the cone, so it is visible.- const core = new THREE.Mesh(new THREE.SphereGeometry(len * 0.085, 10, 8),- MAT.fabric({ color: toonAlbedo(mixHex(tipC, 0xffdc9a, 0.6)),- bump: 0, scale: 5, contrast: 0.1,- extra: { emissive: new THREE.Color(mixHex(tipC, 0xffc878, 0.5)),- emissiveIntensity: 2.6 } }));- core.position.set(0, len * 0.71, -len * 0.19);- g.add(core);- } else if (type === 'leaf') {- const m = new THREE.Mesh(new THREE.SphereGeometry(len * 0.42, 12, 8), mat);- m.scale.set(0.35, 1, 0.55);- m.position.y = len * 0.4;- g.add(m);- // A stalk: the blade alone floats a hand's width off the rump.- const stalk = new THREE.Mesh(- new THREE.CylinderGeometry(len * 0.035, len * 0.055, len * 0.32, 8),- skinMat(partColor(col, -0.10, -0.012, 0.94), undefined,- { seed: 11 }));- stalk.position.y = len * 0.13;- g.add(stalk);- } else if (type === 'curl') {- // ONE tapered tube, not a row of spheres. Seven separated balls read- // as a bubble trail leaving the creature — and cost 980 triangles- // doing it; this is 288, it starts INSIDE the rump so it grows out- // of the animal, and it thins toward the tip the way a tail does- // (an untapered tube is a suitcase handle).- const pts = [];- for (let i = -2; i <= 12; i++) {- const t = i / 12;- pts.push(new THREE.Vector3(0, len * 0.5 * Math.sin(t * 3.4),- len * 0.42 * (1 - Math.cos(t * 3.4)) - len * 0.10));- }- const curve = new THREE.CatmullRomCurve3(pts);- const TUB = 20, RAD = 8;- const geo = new THREE.TubeGeometry(curve, TUB, len * 0.135, RAD, false);- const pos = geo.attributes.position;- for (let i = 0; i <= TUB; i++) {- const c0 = curve.getPointAt(i / TUB);- const k = 1 - 0.66 * (i / TUB);- for (let j = 0; j <= RAD; j++) {- const vi = i * (RAD + 1) + j;- pos.setXYZ(vi, c0.x + (pos.getX(vi) - c0.x) * k,- c0.y + (pos.getY(vi) - c0.y) * k,- c0.z + (pos.getZ(vi) - c0.z) * k);- }- }- pos.needsUpdate = true;- geo.computeVertexNormals();- g.add(new THREE.Mesh(geo, mat));- const tip = new THREE.Mesh(new THREE.SphereGeometry(len * 0.05, 8, 6),- opts.tipColor === undefined ? mat- : skinMat(opts.tipColor, undefined, { seed: 12 }));- tip.position.copy(pts[pts.length - 1]);- g.add(tip);- } else if (type === 'fin') {- // Flattened, or it is a pyramid: a 3-gon cone at full width was the- // single loudest wrong shape in the whole module.- const m = new THREE.Mesh(new THREE.ConeGeometry(len * 0.44, len, 3), mat);- m.scale.set(0.20, 1, 1);- m.rotation.x = -1.75;- m.position.set(0, len * 0.24, len * 0.16);- g.add(m);- } else {- const m = new THREE.Mesh(new THREE.SphereGeometry(len * 0.22, 12, 10), mat);- m.position.y = len * 0.15;- g.add(m);- }- g.traverse((o) => { if (o.isMesh) o.castShadow = true; });- g.position.set(0, ud.bodyY - (c.userData.joints.body.position.y),- ud.bodyD * 0.44);- c.userData.joints.body.add(g);- c.userData.joints.tail = g;- return c;-}--/**- * Add coloured cheek patches -- a cheap, very legible face marking.- *- * @param {THREE.Group} c- * @param {number} color- * @param {number} [size] Multiple of head radius (default 0.26).- * @returns {THREE.Group} c- */-export function cheeks(c, color, size) {- const hr = c.userData.headR;- const r = hr * (size === undefined ? 0.26 : size);- for (const s of [-1, 1]) {- // Slightly rounder and a touch further out than the flat disc that- // shipped: at 0.35 depth the rim grazed the skull and speckled.- const m = new THREE.Mesh(new THREE.SphereGeometry(r, 12, 10),- skinMat(color, 0.62, { seed: 13, contrast: 0.13 }));- m.scale.set(1, 1, 0.22);- // ON the skull, not in it: at x = 0.62r the sphere surface is at- // z = -0.78r, so the patch has to sit there or it is half buried.- // It must not stand far PROUD either: a deep disc reads as a beak- // from three-quarters, which is what a profile camera catches.- m.position.set(s * hr * 0.62, -hr * 0.28, -hr * 0.79);- m.name = 'cheek' + (s < 0 ? 'L' : 'R');- c.userData.joints.head.add(m);- }- return c;-}--/**- * Attach an arbitrary prop to a named joint -- a bulb, a shell, a horn.- *- * @param {THREE.Group} c- * @param {THREE.Object3D} obj- * @param {string} joint Joint name (`head`, `body`, `tail`, `legFL` ...).- * @param {number[]} [offset] Local [x, y, z] in metres.- * @returns {THREE.Group} c- */-export function attach(c, obj, joint, offset) {- const j = c.userData.joints[joint] || c.userData.joints.body;- if (offset) obj.position.set(offset[0], offset[1], offset[2]);- j.add(obj);- return c;-}--/**- * Walk cycle. Give every creature its own phase or the village marches.- *- * @param {THREE.Group} c- * @param {number} t Seconds.- * @param {object} [opts] `stride` radians (default 0.5), `rate` Hz- * (default 2.4 -- small creatures step fast).- * @returns {THREE.Group} c- */-export function walk(c, t, opts = {}) {- const j = c.userData.joints;- const a = opts.stride === undefined ? 0.5 : opts.stride;- const p = t * (opts.rate === undefined ? 2.4 : opts.rate) * Math.PI * 2;- const sw = Math.sin(p);- if (j.legFL) {- j.legFL.rotation.x = sw * a;- j.legBR.rotation.x = sw * a;- j.legFR.rotation.x = -sw * a;- j.legBL.rotation.x = -sw * a;- } else if (j.legL) {- j.legL.rotation.x = sw * a;- j.legR.rotation.x = -sw * a;- if (j.armL) { j.armL.rotation.x = -sw * a * 0.6;- j.armR.rotation.x = sw * a * 0.6; }- }- if (j.body) j.body.position.y = (j.body.userData.y0 !== undefined- ? j.body.userData.y0 : (j.body.userData.y0 = j.body.position.y))- + Math.abs(sw) * c.userData.height * 0.018;- if (j.tail) j.tail.rotation.y = sw * 0.25;- return c;-}--/**- * Idle: a breathing bob and a slow head turn. A perfectly still- * creature reads as a statue in every frame the judge sees.- *- * @param {THREE.Group} c- * @param {number} t Seconds.- * @returns {THREE.Group} c- */-export function idle(c, t) {- const j = c.userData.joints;- if (j.body) {- const s = 1 + Math.sin(t * 1.6) * 0.035;- j.body.scale.y = s;- // The head is a CHILD of the body pivot, so the breath stretched- // the skull with the chest and the creature's face pulsed. The- // counter-scale keeps the head round while it still rides the bob.- if (j.head) j.head.scale.y = 1 / s;- }- if (j.head) {- j.head.rotation.y = Math.sin(t * 0.7) * 0.28;- j.head.rotation.x = Math.sin(t * 1.1) * 0.06;- }- if (j.armL) {- j.armL.rotation.x = Math.sin(t * 1.4 + 0.4) * 0.10;- j.armR.rotation.x = Math.sin(t * 1.4 - 0.4) * 0.10;- }- if (j.tail) j.tail.rotation.y = Math.sin(t * 1.9) * 0.3;- return c;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.jsindex d7a29cfa..10fca781 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js@@ -21,8 +21,8 @@import * as THREE from 'three';import { patchStandard, composeRoughness } from './shader.js';-// The day rig's sun (azimuth 35, elevation 48), matching water.js and-// river.js, so a surface that was not told where the sun is agrees.+// The day rig's sun (azimuth 35, elevation 48), matching water.js,+// so a surface that was not told where the sun is agrees.const _AZ = 35 * Math.PI / 180;const _EL = 48 * Math.PI / 180;const DAY_SUN = new THREE.Vector3(diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/foliage_shade.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/foliage_shade.jsindex 3e0248cd..36b2a6e7 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/foliage_shade.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/foliage_shade.js@@ -241,7 +241,7 @@ export function patchWind(material, opts = {}) {' float wP = uTime * uWindSpeed + astraStagger(wO.x + wO.z * 0.37);',' float wS = (sin(wP) + 0.35 * sin(wP * 2.3 + 1.7)) / 1.35;',// The wind blows ONE way over the whole scene, so its world- // direction is carried into the plant's own frame — scatter.js+ // direction is carried into the plant's own frame — a scatter// gives every instance a different yaw.' vec3 wD = astraFolLocalDir(vec3(uWindDir.x, 0.0, uWindDir.y));',' transformed += wD * (uWindAmp * wB * wB * wS);',@@ -261,7 +261,7 @@ export function patchWind(material, opts = {}) {** @param {THREE.Material} material Trunk material, patched in place.* Height is measured from the object's ORIGIN, so the asset's base- * must sit at y = 0 (the same contract `scatter.js` states).+ * must sit at y = 0.* @param {object} [opts] `band` metres above the contact plane that the* shading fades over (default 0.5); `darken` (default 0.45) how much* darker the very base goes; `litter` (THREE.Color) the fallen-leafdiff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.jsdeleted file mode 100644index 201ff314..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.js+++ /dev/null@@ -1,835 +0,0 @@-/**- * Interiors: the light a room bounces, and the marks hands leave on it.- *- * Two things separate a room that is LIT from a room that is FILLED with- * ambient. The first is colour bleed — every surface indoors is also a- * light, so a red wall throws red on the ceiling beside it and a green- * lawn throws green up under an eave. Nothing here did that:- * `neon.js`'s `patchNeonSpill` throws light from an EMITTER, a point- * that is itself the brightest thing in frame, which is the outdoor- * night case. A bouncer emits nothing; it returns what already landed on- * it, it is usually a PLANE (a wall, a floor, a table top) rather than a- * point, and its colour is its own albedo times how lit it is.- *- * The second is that the surfaces people touch are never clean.- * `patchFingerprints` is grease, not paint: it moves GLOSS, so it is- * invisible head-on and obvious against a lamp — the other grazing-angle- * effect, `finish.js`'s `patchIridescence`, shifts HUE with angle where- * this one shifts only how the surface catches a highlight.- *- * `makeCrowdImposters` is the third: distant people on cards, one draw- * call, so a square or a platform can be populated at all.- *- * Neither patch writes `diffuseColor.rgb`. Both ADD to- * `totalEmissiveRadiance`, blended with the albedo that is already- * there, for the reason `windows.js` and `caustics.js` state: the only- * fragment hook runs at `<color_fragment>`, so a patch may tint albedo —- * capped at the light already landing — or add light. Bounce and a- * smudge-lit haze are both brighter than the surface's own front- * lighting, so neither can be albedo.- */--import * as THREE from 'three';--import { mulberry32 } from './noise.js';-import {- composeRoughness, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,- patchStandard, tickShaders,-} from './shader.js';--// How many bounce sources one material can carry. A room needs a wall,-// a floor and a window's worth; past that the loop costs more than the-// cue is worth.-const BOUNCE_MAX = 6;--// Named as surface_wear, finish, caustics and waterside name them, so a-// material wearing several libraries declares ONE pair; the vertex-// locals are idr* because those libraries already own wrP, fnP and cauWp.-const WORLD_VARYINGS = [- 'varying vec3 vAstraWorld;',- 'varying vec3 vAstraWorldN;',-].join('\n');--// `transformed` is still object-space after <begin_vertex>, so an-// instanced railing takes the origin's position unless this is folded in.-const BASE = {- name: 'indoor:base',- vertexHead: WORLD_VARYINGS,- vertexBody: [- ' vec4 idrP = vec4(transformed, 1.0);',- ' vec3 idrN = normal;',- '#ifdef USE_INSTANCING',- ' idrP = instanceMatrix * idrP;',- ' idrN = mat3(instanceMatrix) * idrN;',- '#endif',- ' vAstraWorld = (modelMatrix * idrP).xyz;',- ' vAstraWorldN = normalize((modelMatrix * vec4(idrN, 0.0)).xyz);',- ].join('\n'),- fragmentHead: WORLD_VARYINGS,-};--/** Take a THREE.Color, a hex or nothing, never sharing the instance. */-function toColor(value, fallback) {- return new THREE.Color(- value === undefined || value === null ? fallback : value);-}--/** Read a Vector3, an array or an {x,y,z} into a Vector3. */-function toVec(p, fx, fy, fz) {- if (!p) return new THREE.Vector3(fx, fy, fz);- if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);- return new THREE.Vector3(p.x, p.y, p.z);-}--/** Clamp to 0..1 without importing MathUtils for three calls. */-function unit(v) {- return Math.max(0, Math.min(1, v));-}--/** fract(), which JS's % gets wrong for a negative seed. */-function frac(x) {- return x - Math.floor(x);-}--/** astraHash11 from GLSL_UTIL, so CPU and shader agree on a seed. */-function hash11(x) {- let p = frac(x * 0.1031);- p *= p + 33.33;- return frac(p * (p + p));-}--/**- * Turn a seed into a noise-space offset, so two panes differ.- *- * The offset is a UNIFORM: a seed baked into the GLSL would be fixed for- * every other material sharing this patch's cache key, because the first- * one to compile a key decides the source for all of them.- */-function seedOffset(seed) {- return new THREE.Vector3(- hash11(seed + 0.41), hash11(seed + 4.13), hash11(seed + 8.77))- .multiplyScalar(52);-}--const BOUNCE_HEAD = [- 'uniform vec3 uBncPos[' + BOUNCE_MAX + '];',- 'uniform vec3 uBncNrm[' + BOUNCE_MAX + '];',- 'uniform vec3 uBncCol[' + BOUNCE_MAX + '];',- // x metres of reach, y 1 for a plane and 0 for a point.- 'uniform vec2 uBncSpan[' + BOUNCE_MAX + '];',- 'uniform float uBncCount;',- 'uniform float uBncGain;',- // Windowed: 1 at the source and EXACTLY 0 at the reach. A bare- // inverse square never reaches zero, so every surface keeps a wash of- // every bouncer — ambient again. A plane's knee is the softer one.- 'float astraBncFall(float d, float r, float plane) {',- ' float x = clamp(d / max(r, 1e-4), 0.0, 1.0);',- ' float w = 1.0 - x * x;',- ' return w * w / (1.0 + mix(12.0, 2.5, plane) * x * x);',- '}',-].join('\n');--const BOUNCE_BODY = [- ' vec3 bncSum = vec3(0.0);',- ' vec3 bncN = normalize(vAstraWorldN);',- ' for (int i = 0; i < ' + BOUNCE_MAX + '; i++) {',- ' if (float(i) >= uBncCount) break;',- ' vec3 bncD = vAstraWorld - uBncPos[i];',- ' float bncPl = uBncSpan[i].y;',- ' float bncSide = dot(bncD, uBncNrm[i]);',- // A bouncer has a front: a lawn does not light the cellar under it,- // and a wall throws nothing through itself.- ' float bncFront = step(1e-4, bncSide);',- ' float bncR = length(bncD);',- // A plane is measured PERPENDICULAR to itself, so a long wall reddens- // a BAND of ceiling along its whole length; a point falls off- // radially, so a rug or a lit patch of lawn stays local.- ' float bncDist = mix(bncR, bncSide, bncPl);',- ' vec3 bncL = mix(-bncD / max(bncR, 1e-4), -uBncNrm[i], bncPl);',- // Half lambert: a bouncer is an AREA seen over most of the receiver's- // hemisphere, so a hard terminator would cut the ceiling off in a line- // above a wall that in truth lights all of it.- ' float bncLam = clamp(dot(bncN, bncL) * 0.5 + 0.5, 0.0, 1.0);',- // A PLANE takes it UN-squared, because un-squared is the exact form- // factor at both limits of a Lambertian half-space: a ceiling facing a- // lit floor sees it over its whole hemisphere (lam 1, factor 1), and a- // WALL over exactly half of it (lam 0.5, factor 0.5). Squaring lands- // the wall at 0.25 — half the bleed, on the one geometry every room- // has. A POINT keeps the square: a small source really is directional.- ' float bncWrap = mix(bncLam * bncLam, bncLam, bncPl);',- ' float bncX = clamp(bncDist / max(uBncSpan[i].x, 1e-4), 0.0, 1.0);',- // Light that has come further has bounced off more than one thing on- // the way, so the wash loses the bouncer's hue as it spreads. Without- // this the far edge of a red bleed is as red as the skirting under the- // wall, which reads as a coloured LAMP rather than as a red wall.- ' vec3 bncTint = mix(uBncCol[i],',- ' vec3(dot(uBncCol[i], vec3(0.2126, 0.7152, 0.0722))), 0.32 * bncX);',- ' bncSum += bncTint * (bncFront * bncWrap',- ' * astraBncFall(bncDist, uBncSpan[i].x, bncPl));',- ' }',- // Bounce is the smoothest gradient in a room and plaster is the widest- // flat it lands on: without a dither the wash climbs the 8-bit ladder- // in visible bands. Half a code, hashed per pixel, only where there is- // bleed to band.- ' float bncLvl = max(max(bncSum.r, bncSum.g), bncSum.b);',- ' bncSum += (astraHash11(gl_FragCoord.x * 3.13 + gl_FragCoord.y * 71.7)',- ' - 0.5) * 0.005 * step(1e-4, bncLvl);',- // Arriving light is REFLECTED, so it takes the receiver's own colour- // — but never all of it, or a dark ceiling swallows the room.- ' totalEmissiveRadiance += bncSum * uBncGain',- ' * mix(vec3(0.35), diffuseColor.rgb, 0.65);',-].join('\n');--/**- * Read one source into the four parallel uniform slots.- *- * A source that states a `normal` is a PLANE (a wall, a floor, a table- * top); one that does not is a POINT, and `up` is the side it throws- * toward.- */-function readSource(s, up, slot) {- const raw = (s && (s.position || s.point)) || s;- slot.pos.push(toVec(raw, 0, 0, 0));- const plane = !!(s && s.normal);- const n = plane ? toVec(s.normal, 0, 1, 0) : up.clone();- slot.nrm.push(n.lengthSq() < 1e-9 ? up.clone() : n.normalize());- slot.col.push(toColor(s && s.color, 0x808080));- const reach = s && s.reach !== undefined ? s.reach : 3;- slot.span.push(new THREE.Vector2(Math.max(1e-3, reach), plane ? 1 : 0));-}--/**- * Colour bleed: light that has already hit something else on its way in.- *- * This is the cue that says a room is LIT rather than filled with a flat- * ambient term, and it is the one an author cannot fake with a lamp: a- * white ceiling beside a red wall goes pink, the underside of an eave- * over a lawn goes green, a wooden floor warms every face turned down- * toward it. Each source is a surface that already caught the light and- * is handing it on, so its `color` is its own ALBEDO times how lit it- * is, not a lamp colour.- *- * A source with a `normal` is a PLANE and is measured PERPENDICULAR to- * itself, which is what makes a long wall bleed onto a band of ceiling- * along its whole length instead of near one point. A source without one- * is a POINT and falls off radially, which is right for a rug, a lit- * patch of lawn or a poster. Both are exactly ZERO past `reach` and- * neither lights anything behind its own face, so a lawn cannot light- * the cellar under it.- *- * A plane's strength is its FORM FACTOR, which is the half-lambert- * un-squared: a ceiling facing a lit floor sees it over its whole- * hemisphere (1.0) and a wall standing on one sees it over exactly half- * (0.5). A point keeps the squared, tighter response.- *- * Measured on THIS renderer (exposure 1.0, no post chain) in a loggia- * with white plaster walls, a sunlit terracotta floor as a plane source- * (reach 3.6 m) and a red rug and teal table as points (3.2 / 2.8 m),- * against a control render with `strength: 0` — mean absolute difference- * over each region, of 255: the wall's skirting 5.7, the wall above the- * rug 7.6, a free-standing pillar 6.2, the soffit underside 2.1, and the- * same wall at 2.5-3.1 m up — past what a 3.6 m floor reach carries —- * 0.7, which is the effect ending where it says it ends. In hue: the- * skirting's R-B goes -14.5 to -7.7, the wall over the rug -2.1 to +6.9,- * the pillar -4.5 to +3.0.- *- * WHICH PATCH: `patchNeonSpill` is the outdoor cousin and the two are- * not interchangeable. Its sources EMIT — a tube that is itself the- * brightest thing in the frame — so it is always a point, always an- * inverse square, and its gain is cut back as the surroundings brighten- * because emissive added to a sunlit wall clips. This one's sources- * REFLECT, at a fraction of what fell on them, so it holds up in- * daylight and its geometry is a plane as often as a point. A neon sign- * on an interior wall wants both; they chain.- *- * It ADDS to `totalEmissiveRadiance` through the receiver's own albedo- * and never touches `diffuseColor`: bounce is LIGHT, and an albedo lift- * is capped at the light already landing, so the shaded soffit that- * needs this most would take none of it. That needs a LIT material —- * MeshStandard / MeshPhysical, not Basic, which has no emissive term.- *- * The constraint it cannot solve, the same one `patchNeonSpill` states:- * nothing is OCCLUDED. A plane is infinite in its own plane, so it- * bleeds through a partition as readily as across the room. Keep `reach`- * to what the bounce really carries — a metre or three indoors — and put- * the source on the face that is lit.- *- * @param {THREE.Material} material A lit built-in material, patched in- * place. A shared `materials.js` instance patches every mesh wearing- * it, so clone it first (and clone BEFORE patching).- * @param {object} [opts] `sources` up to 6 bouncers, each a Vector3, an- * `[x,y,z]`, or `{ position, normal, color, reach }` — stating- * `normal` makes it a plane through `position` throwing that way,- * `color` is the bouncer's albedo times how lit it is (default a mid- * grey), `reach` is metres, zero beyond (default 3); `up` the side a- * source with no normal of its own throws toward (default +Y — a- * floor, a lawn and a rug all bounce upward); `strength` how hard the- * bleed reads (default 1); `name` the program cache key (default- * 'indoor:bounce' — every option here is a UNIFORM, so one name is- * correct and two differently lit rooms still share one program).- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms` so a scene can dim the bleed at dusk- * or move a source with the surface that casts it.- */-export function patchBounceLight(material, opts = {}) {- const up = toVec(opts.up, 0, 1, 0);- if (up.lengthSq() < 1e-9) up.set(0, 1, 0);- up.normalize();- const list = (Array.isArray(opts.sources) ? opts.sources- : (opts.sources ? [opts.sources] : [])).slice(0, BOUNCE_MAX);- const slot = { pos: [], nrm: [], col: [], span: [] };- for (let i = 0; i < BOUNCE_MAX; i++) {- if (i < list.length) readSource(list[i], up, slot);- else {- slot.pos.push(new THREE.Vector3());- slot.nrm.push(up.clone());- slot.col.push(new THREE.Color(0, 0, 0));- slot.span.push(new THREE.Vector2(1, 0));- }- }- if (material && material.emissive === undefined) {- console.warn(- 'patchBounceLight: ' + (material.name || material.type) + ' has '- + 'no emissive term — bounce is LIGHT and lands on '- + 'totalEmissiveRadiance, which a MeshBasicMaterial and a raw '- + 'ShaderMaterial do not have. Patch a lit material instead.');- }- patchStandard(material, BASE);- return patchStandard(material, {- name: opts.name || 'indoor:bounce',- uniforms: {- uBncPos: { value: slot.pos },- uBncNrm: { value: slot.nrm },- uBncCol: { value: slot.col },- uBncSpan: { value: slot.span },- uBncCount: { value: list.length },- uBncGain: { value: Math.max(0, opts.strength === undefined- ? 1 : opts.strength) },- },- vertexHead: WORLD_VARYINGS,- fragmentHead: [WORLD_VARYINGS, BOUNCE_HEAD].join('\n'),- fragmentBody: BOUNCE_BODY,- });-}--const FPR_HEAD = [- 'uniform float uFprAmt;',- 'uniform float uFprSmear;',- 'uniform vec3 uFprSeed;',- // Metres across one unit of the field. A greasy arc comes out about- // 2 cm across and a scratch about 2 mm, which is what each is.- 'const float ASTRA_FPR_SPAN = 0.42;',- // Grease sits in ARCS because a hand sweeps, and the contours of a- // warped field are curved bands where a straight streak reads as a- // wiper blade.- 'float astraFprField(vec2 p) {',- ' return astraFbm2(p * 0.8, 3) * 6.0',- ' + astraFbm2(p * 2.6 + 5.3, 2) * 2.0;',- '}',- // One soft band per period of v, squared so it has no edge of its- // own: grease has no boundary and a top-hat reads as paint. It drops- // once a pixel spans a band, so the pane cleans itself at distance.- 'float astraFprArc(float v, float w) {',- ' float g = abs(fract(v) - 0.5);',- ' float aa = clamp(fwidth(v), 0.0008, 0.5);',- ' float m = 1.0 - smoothstep(0.0, max(w, aa), g);',- ' return m * m * (1.0 - smoothstep(w * 0.8, w * 3.0, aa));',- '}',- // The two world axes least aligned with the normal, because a pane, a- // screen and a rail all carry grease and none carries a usable UV. It- // steps at 45 degrees: for a flat surface, not for a sphere.- 'vec2 astraFprPlane(vec3 p, vec3 n) {',- ' vec3 a = abs(n);',- ' if (a.y > max(a.x, a.z)) return p.xz;',- ' return a.x > a.z ? p.zy : p.xy;',- '}',- // A smudge does not reflect an image, it SCATTERS one: a tight core- // where the clean surface puts its highlight, inside the halo that is- // why a fingerprint shows against a lamp and nowhere else.- 'float astraFprLobe(vec3 n, vec3 v, vec3 l) {',- ' float h = max(dot(n, normalize(l + v)), 0.0);',- ' return pow(h, 30.0) * 0.55 + pow(h, 8.0) * 0.45;',- '}',-].join('\n');--const FPR_BODY = [- ' vec3 fprV = normalize(cameraPosition - vAstraWorld);',- ' vec3 fprN = normalize(vAstraWorldN);',- ' fprN *= sign(dot(fprN, fprV) + 1e-6);',- ' vec2 fprP = astraFprPlane(vAstraWorld, fprN) / ASTRA_FPR_SPAN',- ' + uFprSeed.xy;',- // A drag stretches the grease along the way the hand went; without it- // `smear` could only make the arcs fatter, which reads as fog.- ' vec2 fprQ = vec2(fprP.x / (1.0 + 3.0 * uFprSmear), fprP.y);',- // Hands land in patches, so a slow blotch decides WHERE there is- // grease at all and `amount` is how much of the surface that covers.- ' float fprWhere = smoothstep(0.72 - 0.5 * uFprAmt,',- ' 0.94 - 0.5 * uFprAmt, astraFbm2(fprQ * 0.55 + uFprSeed.yz, 3));',- // A hand leaves a broken arc, never a ribbon, so the bands are cut by- // a second field at their own scale.- ' float fprArcs = astraFprArc(astraFprField(fprQ) * 2.2,',- ' 0.10 + 0.10 * uFprSmear) * fprWhere',- ' * smoothstep(0.30, 0.72, astraNoise2(fprQ * 1.3 + uFprSeed.xy));',- // Finer, straighter, broken: the scratch field a polished rail or a- // shop window carries, which only ever shows at grazing.- ' float fprScr = astraFprArc(dot(fprP, vec2(0.86, 0.51)) * 9.0',- ' + astraFbm2(fprP * 0.5 + 3.1, 2) * 4.0, 0.060)',- ' * step(0.52, astraNoise2(fprP * 3.1 + uFprSeed.zx));',- // A dielectric returns a few percent head-on and everything at- // grazing, so the same weight that makes a clean pane a window at- // your feet and a mirror at the horizon hides the grease head-on.- ' float fprGrz = astraFresnel(fprN, fprV, 4.0);',- ' float fprW = mix(0.06, 1.0, fprGrz);',- // The FILM between the arcs. Grease is a continuous layer with ridges- // in it, not a set of isolated bands: with the arcs alone a touched- // pane is a few bright stripes on clean glass, and the eye reads- // stripes as paint. The film is where the blotch says a hand has been,- // at a third of the arcs' weight and with its own slow variation, so- // the pane clouds where it is handled and stays clean where it is not.- ' float fprFilm = fprWhere * (0.34 + 0.46',- ' * astraNoise2(fprQ * 0.85 + uFprSeed.zx));',- ' float fprMask = clamp(fprArcs * 0.85 + fprScr * fprGrz',- ' + fprFilm * 0.52, 0.0, 1.0);',- ' vec3 fprHaze = vec3(0.0);',- '#if NUM_DIR_LIGHTS > 0',- ' for (int i = 0; i < NUM_DIR_LIGHTS; i++) {',- // three keeps light vectors in VIEW space; v * mat3(viewMatrix) is- // that matrix's transpose applied, which is its inverse rotation.- ' vec3 fprL = directionalLights[i].direction * mat3(viewMatrix);',- ' fprHaze += directionalLights[i].color',- ' * astraFprLobe(fprN, fprV, fprL);',- ' }',- '#endif',- '#if NUM_POINT_LIGHTS > 0',- ' for (int i = 0; i < NUM_POINT_LIGHTS; i++) {',- ' vec3 fprPp = pointLights[i].position * mat3(viewMatrix)',- ' + cameraPosition;',- ' vec3 fprPd = fprPp - vAstraWorld;',- ' float fprPr = length(fprPd);',- ' fprHaze += pointLights[i].color * getDistanceAttenuation(',- ' fprPr, pointLights[i].distance, pointLights[i].decay)',- ' * astraFprLobe(fprN, fprV, fprPd / max(fprPr, 1e-4));',- ' }',- '#endif',- '#if NUM_HEMI_LIGHTS > 0',- // The sky is an AREA source, so there is no lobe to aim — only the- // direction the pane reflects. Without it a vertical shopfront under- // a high sun shows nothing: its mirror direction points at the ground.- ' vec3 fprR = reflect(-fprV, fprN);',- ' for (int i = 0; i < NUM_HEMI_LIGHTS; i++) {',- ' vec3 fprHd = hemisphereLights[i].direction * mat3(viewMatrix);',- ' fprHaze += mix(hemisphereLights[i].groundColor,',- ' hemisphereLights[i].skyColor,',- ' dot(fprR, fprHd) * 0.5 + 0.5) * 0.35;',- ' }',- '#endif',- // The haze takes the LIGHT's colour, never a colour of its own:- // grease is only a change in how the surface catches a highlight.- ' totalEmissiveRadiance += fprHaze',- ' * (fprMask * fprW * uFprAmt * 0.55);',-].join('\n');--/**- * The smudges on glass, a screen, a polished rail: gloss, not paint.- *- * A pane nobody has touched is the tell that a room was assembled rather- * than lived in, and the cue is not a stain — it is that the grease- * SCATTERS a highlight the clean surface reflects sharply. So the pane- * is clean until it is REFLECTING something: greasy arcs bloom out of a- * lamp's own reflection, and a fine scratch field comes up as the- * surface turns toward grazing. Three layers carry it: broken ARCS where- * a hand has swept, a fine SCRATCH field that only shows at grazing, and- * the FILM between them — grease is a continuous layer with ridges in it,- * and with the arcs alone a touched pane is a few bright bands on clean- * glass, which the eye reads as paint rather than as use.- *- * Measured on THIS renderer (exposure 1.0, no post chain) on a dark- * polished counter top seen ~12 degrees off grazing with the sun in its- * mirror, at `amount` 0.62, against the same material unpatched: mean- * absolute difference 3.0/255 with 55% of the surface moved by more than- * 1/255 and peaks near 12 — the halo of arcs inside the cloud of film. A- * tilted vitrine lid three metres away in the same frame, whose blotch- * field says few hands have been on it, comes back at 1.3/255 over 17%:- * that is the effect saying the pane is clean, and at `amount` 0.95 the- * same lid carries the full set of arcs. The scratches are millimetres- * wide and are a close-range detail; they drop out on their own once a- * pixel spans one, which is why the pane does not crawl at distance.- *- * It never touches `diffuseColor` — a smudge that changes the COLOUR of- * glass is a stain, and the surface would read as dirty rather than- * used. Two things carry it instead. Per pixel it ADDS the scattered- * light to `totalEmissiveRadiance`, summed over the scene's own- * `directionalLights` and `pointLights` as a lobe, plus the- * `hemisphereLights` the pane happens to be reflecting — the sky is an- * AREA and has no lobe to aim, and without it a vertical shopfront- * under a high sun shows nothing, its mirror direction pointing at the- * ground. A scene lit ONLY by an AmbientLight shows nothing either:- * that light has no direction, so there is nothing to reflect. And per- * MATERIAL it composes a roughness factor through- * `composeRoughness`: `<color_fragment>` runs before- * `<roughnessmap_fragment>`, so per-pixel gloss is unreachable and the- * reachable half is that a smudged surface is a little less glossy- * overall (see `surface_wear.js`, which states the same limit).- *- * WHICH PATCH: `finish.js`'s `patchIridescence` is the other- * grazing-angle effect and answers a different question — it shifts HUE- * with the angle, because a thin film's optical path shortens toward- * grazing. This shifts no hue at all; it only changes how the surface- * catches a light. An oiled rail can carry both.- *- * The field is projected on the two world axes least aligned with the- * normal, so no UV is needed — and it steps where that choice flips, at- * 45 degrees. That makes it right for a pane, a screen, a table top or a- * flat rail, and wrong for a sphere.- *- * @param {THREE.Material} material A lit built-in material (it needs- * `totalEmissiveRadiance`), patched in place — a shared material- * smudges every mesh wearing it.- * @param {object} [opts] `amount` how much of the surface hands have- * reached and how hard the grease catches the light, 0..1 (default- * 0.5 — a door that gets used; 0.15 is a wiped shopfront, 0.9 a bus- * shelter); `smear` 0 crisp arcs to 1 dragged and stretched, as a- * cloth or a sleeve leaves it (default 0.35); `seed` moves the field,- * so two panes are not one pane twice (default 1); `name` the program- * cache key (default 'indoor:fingerprints' — every option is a- * UNIFORM, so one name is correct for every smudged surface).- * @returns {THREE.Material} The same material, its uniforms live on- * `material.userData.uniforms`.- */-export function patchFingerprints(material, opts = {}) {- const amount = unit(opts.amount === undefined ? 0.5 : opts.amount);- const smear = unit(opts.smear === undefined ? 0.35 : opts.smear);- const seed = opts.seed === undefined ? 1 : opts.seed;- if (material && material.emissive === undefined) {- console.warn(- 'patchFingerprints: ' + (material.name || material.type) + ' has '- + 'no emissive term — a smudge is light SCATTERED off grease and '- + 'lands on totalEmissiveRadiance. Patch a lit material instead.');- }- // Grease scatters, so the surface loses gloss where it is not- // reflecting a light — the half of the effect that is per material.- composeRoughness(material, 'indoor:fingerprints',- 1 + 0.5 * amount * (0.6 + 0.4 * smear));- patchStandard(material, BASE);- return patchStandard(material, {- name: opts.name || 'indoor:fingerprints',- uniforms: {- uFprAmt: { value: amount },- uFprSmear: { value: smear },- uFprSeed: { value: seedOffset(seed) },- },- vertexHead: WORLD_VARYINGS,- fragmentHead: [WORLD_VARYINGS, FPR_HEAD].join('\n'),- fragmentBody: FPR_BODY,- });-}--/**- * Seat `count` people on a jittered grid, knotted toward gathering- * points.- *- * The grid is shuffled before it is cut to `count`, or a crowd that does- * not fill its last row loses a rectangular corner of itself. People- * then stand in knots rather than on a lattice, which is most of what- * separates a crowd from a car park.- */-function gather(count, extent, height, seed, ground) {- const cells = Math.max(1, Math.ceil(Math.sqrt(count)));- const step = extent / cells;- const rand = mulberry32(seed);- const order = [];- for (let i = 0; i < cells * cells; i++) order.push(i);- for (let i = order.length - 1; i > 0; i--) {- const j = Math.floor(rand() * (i + 1));- const t = order[i]; order[i] = order[j]; order[j] = t;- }- const knots = [];- for (let i = 0; i < 5; i++) {- knots.push([(rand() * 2 - 1) * extent * 0.36,- (rand() * 2 - 1) * extent * 0.36]);- }- const pos = new Float32Array(count * 3);- const card = new Float32Array(count * 4);- let low = Infinity, high = -Infinity, tall = 0;- for (let i = 0; i < count; i++) {- const c = order[i % order.length];- let x = -extent / 2 + ((c % cells) + rand()) * step;- let z = -extent / 2 + (Math.floor(c / cells) + rand()) * step;- const k = knots[Math.floor(rand() * knots.length)];- x += (k[0] - x) * 0.35;- z += (k[1] - z) * 0.35;- const y = ground ? ground(x, z) : 0;- pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z;- // A crowd is adults, children and the odd tall one — one height is- // a rank of soldiers seen from behind.- const a = rand(), b = rand();- const s = a < 0.14 ? 0.60 + 0.24 * b : 0.90 + 0.17 * b;- card[i * 4] = rand();- card[i * 4 + 1] = s;- card[i * 4 + 2] = (rand() * 2 - 1) * 0.55;- card[i * 4 + 3] = rand();- low = Math.min(low, y); high = Math.max(high, y);- tall = Math.max(tall, s);- }- return { pos, card, low, top: high + height * tall, tall };-}--/** Person, silhouette and light — the whole crowd in one program. */-function crowdMaterial(cfg) {- return makeShaderMaterial({- name: 'CrowdImposters',- uniforms: {- uCrwSize: { value: new THREE.Vector2(cfg.width, cfg.height) },- uCrwSway: { value: cfg.sway },- uCrwWarm: { value: cfg.warm },- uCrwCool: { value: cfg.cool },- uCrwLeg: { value: cfg.leg },- uCrwSkin: { value: cfg.skin },- uCrwSun: { value: cfg.sun },- uCrwSunColor: { value: cfg.sunColor },- uCrwAmbient: { value: cfg.ambient },- },- varyings: 'varying vec2 vCrwUv; varying vec3 vCrwVar;'- + ' varying vec3 vCrwN; varying vec2 vCrwRim;',- vertexHead: [- 'attribute vec3 aCorner;',- 'attribute vec3 aPos;',- 'attribute vec4 aCrowd;',- 'uniform vec2 uCrwSize;',- 'uniform float uCrwSway;',- 'uniform vec3 uCrwSun;',- ].join('\n'),- vertexMain: [- ' vCrwUv = uv;',- // Camera axes in LOCAL space (rows of modelViewMatrix), so a moved- // or rotated parent cannot tear the crowd off the camera.- ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',- ' modelViewMatrix[2][0]);',- ' vec3 up = vec3(0.0, 1.0, 0.0);',- // A person yaws to face the camera and never tips: a card that- // also pitches lifts the whole crowd off the ground together.- ' vec3 right = normalize(camR - up * dot(camR, up)',- ' + vec3(1e-5, 0.0, 0.0));',- ' float hf = aCorner.y + 0.5;',- ' vec3 p = aPos + right * (aCorner.x * uCrwSize.x * aCrowd.y)',- ' + up * (hf * uCrwSize.y * aCrowd.y);',- // Nobody stands still: a slow weight shift, decorrelated by more- // than a full turn so the crowd does not sway as one body.- ' float sw = uTime * 0.8 + astraStagger(aPos.x + aPos.z * 0.31);',- ' p += right * (uCrwSway * hf * hf * sin(sw));',- ' transformed = p;',- // A body is round and the card is not: the fake normal bows away- // from the centre line, which is what puts a lit and a shaded side- // on a figure instead of one flat tone.- ' vec3 fwd = cross(right, up);',- ' vCrwN = right * (aCorner.x * 1.35) + up * ((hf - 0.55) * 0.20',- ' + 0.10) + fwd * 0.90;',- ' vCrwVar = vec3(aCrowd.x, aCrowd.z, aCrowd.w);',- // Which way the light lies ACROSS the card, and how far behind it:- // a backlit figure is a silhouette with a lit edge, and the edge is- // the whole reason a distant crowd separates from the ground it- // stands on. The card has no depth for a normal to find this in.- ' vCrwRim = vec2(dot(right, uCrwSun), clamp(-dot(fwd, uCrwSun),',- ' 0.0, 1.0));',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uCrwWarm;',- 'uniform vec3 uCrwCool;',- 'uniform vec3 uCrwLeg;',- 'uniform vec3 uCrwSkin;',- 'uniform vec3 uCrwSun;',- 'uniform vec3 uCrwSunColor;',- 'uniform vec3 uCrwAmbient;',- ].join('\n'),- fragmentMain: [- // iq.x spans HALF the card and iq.y the whole height, so a round- // head is an ellipse here.- ' vec2 iq = vec2(vCrwUv.x * 2.0 - 1.0, vCrwUv.y);',- ' float cPh = vCrwVar.z * 37.0;',- // Weight on one leg: a rank of perfectly upright figures is a- // fence, and the lean costs one add.- ' iq.x += (fract(cPh * 0.61) - 0.5) * 0.14 * iq.y;',- // Ankles, hips, shoulders, neck: four widths off the standard- // 7.5-head figure, because a person is not a rectangle and the- // eye knows every one of these numbers by heart.- ' float cW = 0.30 + 0.12 * smoothstep(0.05, 0.50, iq.y)',- ' + 0.16 * smoothstep(0.50, 0.72, iq.y)',- ' - 0.45 * smoothstep(0.80, 0.87, iq.y);',- ' float cBody = min(min(cW - abs(iq.x), 0.90 - iq.y), iq.y);',- // The gap between the legs, which is where the eye decides person- // or bollard; its width is the figure's stance.- ' float cGap = 0.06 + 0.06 * fract(cPh * 0.37);',- ' cBody = min(cBody, max(abs(iq.x) - cGap, iq.y - 0.50));',- ' float cHead = (0.175 + 0.02 * fract(cPh * 0.13))',- ' - length(vec2(iq.x, (iq.y - 0.935) * 2.6));',- ' float iS = max(cHead, cBody);',- // A card is antialiased by its own gradient or a distant crowd- // stipples in and out of the frame as the camera turns.- ' float iAA = fwidth(iS) + 1e-4;',- ' float iA = clamp(iS / iAA + 0.5, 0.0, 1.0);',- // Dropped whole, never faded: a card that still writes depth at- // 5% alpha punches a sky-coloured hole through the one behind it.- ' if (iA < 0.02) discard;',- // Clothing is the whole variety a crowd has at this size: a ramp- // between two tones, then a hue swing per person on top.- ' vec3 iAlb = astraHueShift(mix(uCrwWarm, uCrwCool, vCrwVar.x),',- ' vCrwVar.y);',- // Hue alone is not a crowd: a street is pale coats and dark ones,- // and value is what the eye counts heads by at 40 m.- ' iAlb *= 0.72 + 0.62 * fract(cPh * 0.29);',- ' iAlb = mix(uCrwLeg, iAlb, smoothstep(0.50, 0.55, iq.y));',- ' iAlb = mix(iAlb, uCrwSkin, smoothstep(0.86, 0.89, iq.y));',- // Hair over the crown, and shoes: two dark caps that stop a figure- // reading as a mannequin. Not BLACK caps — an albedo under about- // 0.02 is a hole in the frame that no light can open again.- ' iAlb = mix(iAlb, uCrwLeg * 0.72,',- ' smoothstep(0.945, 0.975, iq.y));',- ' iAlb = mix(uCrwLeg * 0.68, iAlb, smoothstep(0.0, 0.035, iq.y));',- // WRAPPED, not clamped: a body is round and this normal is a coarse- // bow across a flat card, so a hard terminator prints the whole- // backlit half of the crowd as one flat ambient tone.- ' float iNdL = clamp((dot(normalize(vCrwN), uCrwSun) + 0.30)',- ' / 1.30, 0.0, 1.0);',- // Irradiance over PI, the arithmetic a built-in Lambert does, so a- // card sits at the brightness its geometry would. Ankles see less- // sky than heads, which is what seats a figure ON the ground.- ' vec3 iIrr = (uCrwAmbient + uCrwSunColor * iNdL)',- ' * mix(0.55, 1.0, smoothstep(0.0, 0.55, iq.y));',- // The rim: the sun-side edge of a BACKLIT figure, in the light's own- // colour. `cW` is the body half-width, so the ramp rides the real- // silhouette rather than the card's rectangle, and the head — where- // cW is narrow — takes the whole of it, which is where a rim reads.- ' float iRim = smoothstep(0.66, 1.04, abs(iq.x) / max(cW, 0.02))',- // The 0.25 floor is the sun straight BEHIND a figure, where both- // edges light and neither side wins.- ' * clamp(vCrwRim.x * sign(iq.x) * 2.0 + 0.25, 0.0, 1.0)',- ' * vCrwRim.y;',- ' gl_FragColor = vec4(iAlb * iIrr / PI',- ' + uCrwSunColor * (iRim * 0.075), iA);',- ].join('\n'),- transparent: true,- depthWrite: true,- side: THREE.DoubleSide,- });-}--/**- * A crowd on cards: distant people for one draw call.- *- * DO NOT USE THESE INSIDE 20 m. Measured against the same person built- * as real geometry (`figure.js`; one figure, 512 px, fov 50, daylight,- * mean absolute pixel difference over the frame): 6 m 0.87/255 and- * plainly a cut-out — no arms, no thickness, one flat gradient where a- * body has a lit and a shaded side; 12 m 0.21/255, still readable as- * flat if you look for it; 20 m 0.07/255, where a still frame stops- * separating them; 40 m 0.02/255, indistinguishable. Across that range- * the card's silhouette runs about a fifth smaller than the geometry's- * (it has no arms) and its mean brightness sits within 8/255 of it,- * which is what keeps the join invisible where the two meet. A person- * is small and the eye is a specialist at people, so the crossover sits- * far nearer than the ~35 m `woodland.js` measures for a tree — but the- * rule is the same: real figures in the near field, cards for everyone- * behind them, and the same clothing tones on both.- *- * Every card is seated on `heightAt` with its FEET at the ground, faces- * the camera in yaw only (never pitch, or the crowd lifts off the- * ground together), and carries its own height, stance, lean, clothing- * hue AND clothing VALUE — a field of identical figures is wallpaper at- * any distance, and hue alone is not a crowd: a street is pale coats and- * dark ones. One in seven is a child.- *- * A card has no depth, so the two things that stop a distant crowd- * printing as flat stumps are built here. Its diffuse is WRAPPED, because- * a hard terminator on a coarse bowed normal has no gradient to show; and- * a BACKLIT figure gets a RIM in the light's own colour along the- * sun-side edge of its silhouette, which is the cue the eye separates a- * person from the ground by at 40 m. Measured on this renderer, 90 cards- * at ~35 m with the sun behind them: the darkest crowd pixels went from- * 15.9 to 24.7 of 255 and the crowd's distinct colours from 4337 to 4726.- * The rim is gated on the sun being behind — a front-lit crowd grows no- * halo — so it costs nothing in the frames that do not want it.- *- * The whole crowd is ONE `InstancedBufferGeometry`: `position` stays at- * zero (the GTAO reason `instancedQuad` documents) and the cards are- * built in the vertex shader, so the stated bounding SPHERE — computed- * here from the real placements, about the group origin — is the only- * thing three can cull by; the BOX is left stating the real ground and- * the real heads, because that is what measures the asset.- * The mesh is guarded by `keepOutOfDepthPasses`, because an override- * material draws a transparent card as a solid wall; that also means- * these cards cast no shadow, and their contact with the ground is the- * darkened foot in the silhouette itself.- *- * @param {object} [opts] `count` people (default 60 — one draw call at- * any count); `extent` metres of the square the crowd fills, centred- * on the group's origin (default 40); `height` metres of the average- * adult (default 1.72 — every figure is scaled off it); `heightAt`- * (x, z) => y, the ground the crowd stands on (default y = 0);- * `seed` PRNG seed (default 11); `warm`/`cool` the two ends of the- * clothing ramp, `legColor` trousers, hair and shoes (default a dark- * navy, not a black: hair and shoes are taken to about 0.7 of it, and- * an albedo under ~0.02 linear is a hole in the frame that no light- * reopens), `skin` faces- * and hands; `sunDir`/`sunColor`/`ambient` the scene's own light, so- * the cards land at the brightness real geometry does — pass the- * values you lit the scene with; `sway` metres of idle weight shift- * (default 0.03; 0 stands the crowd still); `name` group name.- * @returns {THREE.Group} Named `Crowd`, resting on the ground, holding- * ONE mesh, with `userData.tick(t)` driving the idle. Add it at the- * scene ROOT: the cards billboard against WORLD axes.- */-export function makeCrowdImposters(opts = {}) {- const count = Math.max(1, Math.round(- opts.count === undefined ? 60 : opts.count));- const extent = Math.max(1, opts.extent === undefined ? 40 : opts.extent);- const height = Math.max(0.05,- opts.height === undefined ? 1.72 : opts.height);- const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;- const seed = opts.seed === undefined ? 11 : opts.seed;- const width = height * 0.52;-- const field = gather(count, extent, height, seed, ground);- const half = 0.5 * width * field.tall;- const box = new THREE.Box3(- new THREE.Vector3(-extent / 2 - half, field.low, -extent / 2 - half),- new THREE.Vector3(extent / 2 + half, field.top, extent / 2 + half));- // The REAL radius, from the group ORIGIN because that is where- // `instancedQuad` centres the sphere. `position` is all zeros, so it- // is all three can cull by, and the 10 km default frames empty air.- const far = new THREE.Vector3(- Math.max(Math.abs(box.min.x), Math.abs(box.max.x)),- Math.max(Math.abs(box.min.y), Math.abs(box.max.y)),- Math.max(Math.abs(box.min.z), Math.abs(box.max.z)));- const geom = instancedQuad(count, 1, 1, far.length());- geom.setAttribute('aPos',- new THREE.InstancedBufferAttribute(field.pos, 3));- geom.setAttribute('aCrowd',- new THREE.InstancedBufferAttribute(field.card, 4));- // The BOX is what measures the asset, so it states the real ground- // and the real heads; the sphere is only what three culls by.- geom.boundingBox = box;-- const mesh = new THREE.Mesh(geom, crowdMaterial({- width, height,- sway: Math.max(0, opts.sway === undefined ? 0.03 : opts.sway),- warm: toColor(opts.warm, 0xb8a893),- cool: toColor(opts.cool, 0x4b5566),- leg: toColor(opts.legColor, 0x39404a),- skin: toColor(opts.skin, 0xb08668),- sun: toVec(opts.sunDir, 0.45, 0.78, 0.35).normalize(),- // Irradiance, not a screen colour: the defaults are the daylight rig- // the asset renderer lights an outdoor scene with.- sunColor: opts.sunColor === undefined- ? new THREE.Color(0xfff0d6).multiplyScalar(3.0)- : toColor(opts.sunColor, 0xffffff),- ambient: opts.ambient === undefined- ? new THREE.Color(0x9fb2c4).multiplyScalar(0.85)- : toColor(opts.ambient, 0xffffff),- }));- mesh.name = 'CrowdCards';- const g = new THREE.Group();- g.name = opts.name || 'Crowd';- g.add(keepOutOfDepthPasses(mesh));- g.userData.tick = (t) => tickShaders(g, t);- return g;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.jsdeleted file mode 100644index 2d7a7c5e..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.js+++ /dev/null@@ -1,287 +0,0 @@-/**- * Panel lights: a RectAreaLight fused with its visible glowing panel.- * Closes RectAreaLight's silent traps: renders black without the LTC- * init, lights only Standard/Physical materials with NO shadows, and- * emits along local -Z (pre-rotated here so the group's +Z emits).- */--import * as THREE from 'three';-import { RectAreaLightUniformsLib }- from 'three/addons/lights/RectAreaLightUniformsLib.js';--let _inited = false;--/**- * Install the LTC lookup tables RectAreaLight needs, exactly once.- * Safe to call any number of times; `makePanelLight` calls it for you.- */-export function initRectAreaLights() {- if (_inited) return;- RectAreaLightUniformsLib.init();- _inited = true;-}--/**- * Colour of a black-body at `kelvin` — the Tanner Helland fit.- *- * The realism of a night street is largely its light classes- * SEPARATING: sodium amber over the road, tungsten in the homes,- * fluorescent in the shop, cool LED headlights. One generic warm- * white over everything is the giveaway of a rendered scene.- *- * COLOUR SPACE (the trap this closes): the Helland fit is an 8-bit- * **sRGB** triple — it is what you would type into a paint program.- * three's working space is srgb-linear and `new THREE.Color(r,g,b)`- * writes its arguments there RAW, so handing the fit's numbers to- * that constructor states a gamma-encoded value as a linear one and- * every class comes out washed toward white: measured on this- * renderer, tungsten 2700 K landed at linear (1.00, 0.65, 0.34) and- * its panel read (158,152,145) on screen — a grey card, not a warm- * bulb. Decoding through SRGBColorSpace gives (1.00, 0.39, 0.10) and- * the class split the table exists for. A hex colour (`0xffdca8`)- * already takes that decode inside three, so this is also the only- * way the two colour paths into `makePanelLight` agree.- *- * @param {number} kelvin Temperature, clamped to 1000-12000 K.- * @returns {THREE.Color} That temperature in three's working- * (linear-sRGB) space, ready for a light or an emissive.- */-export function kelvinColor(kelvin) {- const t = THREE.MathUtils.clamp(kelvin, 1000, 12000) / 100;- let r;- let g;- let b;- if (t <= 66) {- r = 255;- g = 99.4708025861 * Math.log(t) - 161.1195681661;- b = t <= 19 ? 0 : 138.5177312231 * Math.log(t - 10) - 305.0447927307;- } else {- r = 329.698727446 * Math.pow(t - 60, -0.1332047592);- g = 288.1221695283 * Math.pow(t - 60, -0.0755148492);- b = 255;- }- // Floor every channel a hair above zero. Below 1900 K the fit snaps- // blue to a hard 0 — a discontinuity in the fit, not physics — and a- // dead channel makes a light pool clip to a pure hue and band.- const c = (v) => Math.max(2, THREE.MathUtils.clamp(v, 0, 255)) / 255;- return new THREE.Color().setRGB(c(r), c(g), c(b), THREE.SRGBColorSpace);-}--/**- * The light classes a night scene is built from, by name.- *- * Pick per FIXTURE CLASS, never one hue for the whole scene: roads- * sodium or led_cool, homes tungsten, shopfronts fluorescent, works- * floodlights metal_halide. `moon` is perceptual (matches sunRig's- * night sun), not a black body — moonlight photographs blue.- * Values: `{ kelvin, color }`, colours precomputed.- */-export const LIGHT_CLASSES = {- sodium: { kelvin: 1900, color: kelvinColor(1900) },- tungsten: { kelvin: 2700, color: kelvinColor(2700) },- halogen: { kelvin: 3200, color: kelvinColor(3200) },- fluorescent: { kelvin: 4300, color: kelvinColor(4300) },- metal_halide: { kelvin: 4800, color: kelvinColor(4800) },- led_cool: { kelvin: 6300, color: kelvinColor(6300) },- moon: { kelvin: 4100, color: new THREE.Color(0xb5c7e8) },-};--/** Deterministic 0..1 hash — dither, so an 8-bit ramp cannot band. */-function _hash(i) {- const s = Math.sin(i * 12.9898 + 78.233) * 43758.5453;- return s - Math.floor(s);-}--let _diffuserTex = null;-let _haloTex = null;--/**- * The luminance profile of a real diffuser: a broad flat core with the- * last fifth of the panel rolling off into its frame. Used as an- * emissiveMap, so it is a LINEAR multiplier (NoColorSpace, no decode).- *- * Without it every panel is one clipped value — flat white regardless- * of its class, and a solid modal block in the frame statistics. The- * roll-off also hands the rim a dimmer, hence MORE saturated version- * of the same colour once ACES has desaturated the core, which is what- * makes an amber lamp read amber next to a white one.- */-function diffuserTexture() {- if (_diffuserTex) return _diffuserTex;- const N = 64;- const d = new Uint8Array(N * N * 4);- for (let y = 0; y < N; y++) {- for (let x = 0; x < N; x++) {- const a = Math.abs((x + 0.5) / N * 2 - 1);- const b = Math.abs((y + 0.5) / N * 2 - 1);- // superellipse radius: a rounded rectangle, not a circle, so a- // long sign rolls off along its length as well as its height- const e = Math.pow(a ** 6 + b ** 6, 1 / 6);- // never to zero: a rim that reaches 0 uncovers the panel's dark- // base colour and draws a black bezel around every luminaire.- // 0.32 leaves the rim a dimmer — hence more saturated, ACES- // desaturates the core — version of the same light.- const roll = 0.32 + 0.68 * (1 - THREE.MathUtils.smoothstep(e, 0.72, 1.0));- // gentle centre lift — a diffuser is brightest over its lamp- const v = roll * (0.88 + 0.12 * (1 - e * e));- const dith = (_hash(y * N + x) - 0.5) * (1.6 / 255);- const u8 = Math.round(THREE.MathUtils.clamp(v + dith, 0, 1) * 255);- const o = (y * N + x) * 4;- d[o] = d[o + 1] = d[o + 2] = u8;- d[o + 3] = 255;- }- }- const t = new THREE.DataTexture(d, N, N, THREE.RGBAFormat);- t.colorSpace = THREE.NoColorSpace;- t.wrapS = t.wrapT = THREE.ClampToEdgeWrapping;- t.minFilter = THREE.LinearMipmapLinearFilter;- t.magFilter = THREE.LinearFilter;- t.generateMipmaps = true;- t.needsUpdate = true;- _diffuserTex = t;- return t;-}--/** Alpha falloff for the spill quad: 1 at the panel, 0 at the rim. */-function haloTexture() {- if (_haloTex) return _haloTex;- const N = 96;- const d = new Uint8Array(N * N * 4);- for (let y = 0; y < N; y++) {- for (let x = 0; x < N; x++) {- const a = Math.abs((x + 0.5) / N * 2 - 1);- const b = Math.abs((y + 0.5) / N * 2 - 1);- const e = Math.min(1, Math.pow(a ** 4 + b ** 4, 1 / 4));- const v = Math.pow(1 - e, 2.4);- const dith = (_hash(y * N + x + 7919) - 0.5) * (2.0 / 255);- const o = (y * N + x) * 4;- d[o] = d[o + 1] = d[o + 2] = 255;- d[o + 3] = Math.round(THREE.MathUtils.clamp(v + dith, 0, 1) * 255);- }- }- const t = new THREE.DataTexture(d, N, N, THREE.RGBAFormat);- t.colorSpace = THREE.NoColorSpace;- t.wrapS = t.wrapT = THREE.ClampToEdgeWrapping;- t.minFilter = THREE.LinearMipmapLinearFilter;- t.magFilter = THREE.LinearFilter;- t.generateMipmaps = true;- t.needsUpdate = true;- _haloTex = t;- return t;-}--/**- * A rectangular area light with its visible emissive panel.- * The group emits along its LOCAL +Z, so `group.lookAt()` aims the- * glowing face; pair with the scene's shadow sun for grounding.- *- * @param {number} w Panel width in metres.- * @param {number} h Panel height in metres.- * @param {number|string} [color] Light + glow colour, or a- * LIGHT_CLASSES name — 'sodium', 'tungsten', 'fluorescent'...- * (default 0xffffff).- * @param {number} [intensity] RectAreaLight intensity (default 6).- * Re-measured on THIS pipeline (ACES, exposure 1.0, no post chain,- * no other light): a 4x2 m white panel washing a matte 0.6-grey- * wall, read at the point facing the panel centre —- * intensity 6 at 3 m -> 186/255 · 3 at 3 m -> 138/255- * intensity 6 at 6 m -> 103/255 · 20 at 6 m -> 188/255- * so 6 is a room light at arm's length and a billboard read from- * 20 m wants tens, not units. A WARM class also carries less- * luminance per unit intensity than a cool one (the colour- * multiplies the radiance: sodium ~0.38, tungsten ~0.49,- * fluorescent ~0.72, led_cool ~0.97 of white) — swapping a shop- * from 'led_cool' to 'sodium' needs roughly 2.5x the intensity to- * hold the same road brightness.- * @param {object} [opts] `panel: false` skips the visible mesh (an- * invisible area fill); `glow` panel emissiveIntensity (default- * 2.2); `halo` the soft spill quad behind the panel — `false` to- * drop it, or a number for its strength (default 0.6). There is no- * bloom pass in this pipeline, so the halo IS the glow around a- * luminaire; it hides behind the panel and only shows as spill.- * @returns {THREE.Group} Group named `PanelLight`; the light, panel- * and halo are exposed as `group.userData.light` /- * `group.userData.panel` / `group.userData.halo`.- */-export function makePanelLight(w, h, color, intensity, opts = {}) {- initRectAreaLights();- // A LIGHT_CLASSES name is a colour: 'fluorescent' for the shop,- // 'sodium' for the forecourt — the class split is the realism.- const col = typeof color === 'string' && LIGHT_CLASSES[color]- ? LIGHT_CLASSES[color].color- : (color === undefined ? 0xffffff : color);- const inten = intensity === undefined ? 6 : intensity;-- const group = new THREE.Group();- group.name = 'PanelLight';- // A luminaire hangs where the author hung it. This host runs a- // deterministic settle pass over every placed asset before the first- // frame (runtime_js/lib/host_placement.mjs, --no-settle to disable):- // a group whose meshes float is dropped onto whatever is beneath it.- // Measured: a 1.5x1.2 window panel authored at y=4.4 on a wall was- // seated at y=0.60 (its own half-height) and rendered lying at the- // kerb. `placement: 'free'` is the documented opt-out — the same one- // a bird or a hanging lantern uses.- group.userData.placement = 'free';-- const light = new THREE.RectAreaLight(col, inten, w, h);- // RectAreaLight emits along its local -Z; flip it so the GROUP's +Z- // is the emitting direction and a plain group.lookAt() aims it.- light.rotation.y = Math.PI;- group.add(light);-- let panel = null;- let halo = null;- if (opts.panel === undefined || opts.panel) {- panel = new THREE.Mesh(- new THREE.PlaneGeometry(w, h),- new THREE.MeshStandardMaterial({- // A diffuser is a pale grey object when it is OFF; 0x111111- // sits under the 0.02 linear floor and reads as a dead hole- // in daylight, where these panels also have to appear.- color: 0x2b2b28,- // not perfectly matte — the sheen off a plastic diffuser is- // what keeps an unlit panel from being a flat cutout- roughness: 0.72,- emissive: new THREE.Color(col),- emissiveIntensity: opts.glow === undefined ? 2.2 : opts.glow,- emissiveMap: diffuserTexture(),- }));- panel.position.z = -0.01;- panel.name = 'PanelGlow';- group.add(panel);-- const hs = opts.halo === undefined || opts.halo === true- ? 0.6- : (opts.halo === false ? 0 : opts.halo);- if (hs > 0) {- // margin scales with the SHORT side (a thin sign gets a thin- // halo) plus a little of the long one, so aspect is preserved- const m = 0.5 * Math.min(w, h) + 0.16 * Math.max(w, h);- halo = new THREE.Mesh(- new THREE.PlaneGeometry(w + 2 * m, h + 2 * m),- new THREE.MeshBasicMaterial({- color: new THREE.Color(col),- map: haloTexture(),- transparent: true,- opacity: hs,- blending: THREE.AdditiveBlending,- depthWrite: false,- // additive + fog would ADD the fog colour instead of- // fading the glow into it- fog: false,- }));- // BEHIND the panel: the depth test hides the blown centre and- // leaves exactly the spill around the edges.- halo.position.z = -0.02;- halo.renderOrder = 2;- halo.name = 'PanelHalo';- group.add(halo);- }- }-- group.userData.light = light;- group.userData.panel = panel;- group.userData.halo = halo;- return group;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.jsdeleted file mode 100644index e3f504cc..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.js+++ /dev/null@@ -1,597 +0,0 @@-/**- * Reflections: ONE real planar mirror, everything else by environment.- * A Reflector re-renders the whole scene, and a second RTT surface the- * first can SEE nests inside that pass — measured on SwiftShader at- * 1024x576, a mirror floor costs +48 ms/frame and adding one wall- * mirror to it +148 ms. The budget is enforced HERE, not left to the- * caller: over budget `makeMirror` degrades to an envMap mirror.- * Glass facades never get an RTT — `bakeSkylineEnvironment` +- * `glazeFacade` give a whole city reflective for one bake.- */--import * as THREE from 'three';-import { Reflector } from 'three/addons/objects/Reflector.js';-import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';-import * as MAT from './materials.js';-import { mulberry32 } from './noise.js';--// The Reflector shader OVERLAY-blends its `color` over the reflection,-// and overlay's identity is linear 0.5 = 0xbc in sRGB. Its own default-// 0x7f7f7f (linear 0.21) multiplies darks by 0.42 — dim, dirty glass.-const NEUTRAL = 0xbcbcbc;--// The reflection target holds a SCREEN-space image of the mirrored-// scene, so its aspect must match the FRAME, not the mirror's shape —-// a square one oversamples vertically and costs 1.8x the pixels.-const FRAME_ASPECT = 16 / 9;--// Same axis convention as sunRig()/makeOcean: azimuth 35, elevation 48.-const _AZ = 35 * Math.PI / 180;-const _EL = 48 * Math.PI / 180;-const _DAY_SUN = new THREE.Vector3(- Math.cos(_EL) * Math.cos(_AZ), Math.sin(_EL),- Math.cos(_EL) * Math.sin(_AZ));--let _limit = 1;-let _used = 0;-const _ours = new WeakSet();--/**- * Set how many REAL reflection surfaces this scene may build.- *- * Default 1. Set 0 when the scene already spends its one RTT on- * `makeOcean()` (lib/water.js) or `makeMirrorFloor()` (lib/wetground.js)- * and you did not hand `makeMirror` the scene to count them itself.- *- * @param {number} n Allowed RTT surfaces (clamped to >= 0).- * @returns {number} The limit now in force.- */-export function setReflectionBudget(n) {- _limit = Math.max(0, Math.floor(n));- _used = 0;- return _limit;-}--/**- * Report the RTT reflection budget.- *- * @param {THREE.Scene} [scene] Counted for RTT surfaces this module did- * not build (an ocean, a mirror floor) so they charge the budget too.- * @returns {{limit: number, used: number, left: number}} Counts of- * whole-scene reflection passes allowed, spent and remaining.- */-export function reflectionBudget(scene) {- const used = _used + _foreignRtt(scene);- return { limit: _limit, used, left: Math.max(0, _limit - used) };-}--/** Count RTT surfaces in `scene` that this module did not build. */-function _foreignRtt(scene) {- if (!scene || !scene.traverse) return 0;- let n = 0;- scene.traverse((o) => {- const u = o.material && o.material.uniforms;- if (u && (u.mirrorSampler || u.tDiffuse) && !_ours.has(o)) n++;- });- return n;-}--/**- * A mirror-bright material that costs NOTHING per frame: it reflects- * `scene.environment` (or `envMap`) instead of re-rendering the scene.- * The honest trade — it cannot show the objects in front of it, so use- * it for chrome props, distant glass and every mirror past the first.- *- * @param {object} [opts]- * `envMap` texture to reflect (default: whatever `scene.environment`- * holds at render time); `scene` to take that environment from now;- * `tint` hex (default 0xf0f3f5, near-white chrome);- * `roughness` (default 0.05 — never 0: a perfect mirror with a low- * resolution environment reads as a flat colour patch);- * `envMapIntensity` (default 1.15).- * @returns {THREE.MeshPhysicalMaterial} Metallic, opaque, no RTT.- */-export function envMirrorMaterial(opts = {}) {- const env = opts.envMap ||- (opts.scene && opts.scene.environment) || null;- return new THREE.MeshPhysicalMaterial({- color: opts.tint === undefined ? 0xf0f3f5 : opts.tint,- metalness: 1,- roughness: opts.roughness === undefined ? 0.05 : opts.roughness,- envMap: env,- envMapIntensity:- opts.envMapIntensity === undefined ? 1.15 : opts.envMapIntensity,- });-}--/**- * The scene's planar mirror: wall mirror, mirrored panel, mirror wall.- * Built as a real `Reflector` while the budget holds and as an envMap- * mirror after that — check `userData.mode` if it matters.- *- * @param {number} w Width in metres.- * @param {number} h Height in metres.- * @param {object} [opts]- * `scene` the scene it will join — passing it lets the budget count- * an ocean / mirror floor already in there (STRONGLY recommended);- * `mode` `'auto'` (default, degrade when over budget), `'rtt'` (force- * a real reflection) or `'env'` (force the free one);- * `rttSize` reflection width in px (default 768; height follows- * `aspect`); `aspect` frame aspect (default 16/9);- * `multisample` MSAA samples in the reflection (default 0: the- * addon's 4 costs 28 ms/frame on SwiftShader for a difference- * invisible at 1:1, since the reflection is minified onto the- * mirror and the composer antialiases the frame anyway);- * `tint` hex over the reflection (default 0xbcbcbc = untinted;- * BELOW that darkens, above brightens — overlay blend, not multiply);- * `standoff` metres the glass stands proud of the mount plane- * (default 0.05 — see @returns, do not set 0);- * `frame` false for a frameless mirrored panel (default true);- * `frameColor` hex (default 0x64492f, walnut), `frameWidth` metres- * (default 5% of the short side), `frameDepth` metres (default- * standoff + 0.8 * frameWidth); `backColor` hex of the backing plate- * (default 0x39332c); `envMap` / `roughness` forwarded to the fallback;- * `name`.- * @returns {THREE.Group} Centred on its own origin, which is the MOUNT- * PLANE (put it ON the wall): the glass stands `standoff` in front,- * facing +Z (`userData.forward`). Geometry coplanar with the glass- * leaks through the reflection's oblique clip plane and fills the- * mirror with a black slab at oblique angles — the standoff is what- * buys the clearance. `userData.mode` is `'rtt'` or `'env'`,- * `userData.surface` the reflective mesh.- */-export function makeMirror(w, h, opts = {}) {- const mode = opts.mode || 'auto';- const left = reflectionBudget(opts.scene).left;- const rtt = mode === 'rtt' || (mode !== 'env' && left > 0);- if (mode === 'auto' && !rtt) {- console.warn(- 'makeMirror: reflection budget spent (limit ' + _limit + ') — ' +- 'this mirror falls back to an envMap reflection. A real ' +- 'mirror re-renders the WHOLE scene, and a second one it can ' +- 'see nests inside that pass.');- }- if (mode === 'rtt' && left <= 0) {- console.warn(- 'makeMirror: forced mode:"rtt" past the budget — this frame ' +- 'now costs another full scene pass, nested if the surfaces ' +- 'can see each other.');- }-- const group = new THREE.Group();- group.name = opts.name || 'Mirror';-- let surface;- if (rtt) {- const tw = opts.rttSize === undefined ? 768 : opts.rttSize;- const th = Math.max(- 64, Math.round(tw / (opts.aspect || FRAME_ASPECT)));- surface = new Reflector(new THREE.PlaneGeometry(w, h), {- clipBias: 0.003,- textureWidth: tw,- textureHeight: th,- color: opts.tint === undefined ? NEUTRAL : opts.tint,- multisample:- opts.multisample === undefined ? 0 : opts.multisample,- });- _used++;- _ours.add(surface);- } else {- surface = new THREE.Mesh(- new THREE.PlaneGeometry(w, h), envMirrorMaterial(opts));- }- const stand = opts.standoff === undefined ? 0.05 : opts.standoff;- surface.name = 'MirrorSurface';- surface.position.z = stand;- // An RTT plane must never cast: it would shadow the very scene it- // resamples. Receiving would paint shadows onto the reflection.- surface.castShadow = false;- surface.receiveShadow = false;- group.add(surface);-- // A mirror is not a hole in the wall. The plate faces away, and it- // sits on the MOUNT plane, not against the glass: measured, anything- // within 1 cm behind the glass leaks past the oblique clip plane and- // fills the mirror with a dark slab from 20 degrees off-axis.- const back = new THREE.Mesh(- new THREE.PlaneGeometry(w, h),- MAT.paintedIron({- // 0x2a2724 is linear 0.024 — at the very floor of a legal albedo,- // and under ACES at exposure 1.0 the plate came back as a hole in- // the wall wherever the frame did not cover it. This still reads- // as dark painted steel and still has somewhere to fall in shade.- color: opts.backColor === undefined ? 0x39332c : opts.backColor,- }));- back.rotation.y = Math.PI;- back.position.z = 0.004;- back.name = 'MirrorBack';- back.castShadow = true;- back.receiveShadow = true;- group.add(back);-- if (opts.frame !== false) {- const fw = opts.frameWidth === undefined- ? Math.max(0.03, Math.min(w, h) * 0.05) : opts.frameWidth;- const fd = opts.frameDepth === undefined- ? stand + Math.max(0.03, fw * 0.8) : opts.frameDepth;- const zc = fd / 2;- const bars = [- _bx(w + 2 * fw, fw, fd, 0, h / 2 + fw / 2, zc),- _bx(w + 2 * fw, fw, fd, 0, -h / 2 - fw / 2, zc),- _bx(fw, h, fd, -w / 2 - fw / 2, 0, zc),- _bx(fw, h, fd, w / 2 + fw / 2, 0, zc),- ];- const frame = new THREE.Mesh(- mergeGeometries(bars, false),- MAT.paintedWood({- // The frame is the only lit thing next to a mirror full of the- // scene's own brightness, so it decides whether the mirror reads- // as an object or as a hole cut in the wall. 0x4a3a2a is linear- // 0.068: measured on our host it rendered as a black border with- // no grain in it at all. Walnut sits at 0.13/0.07/0.03 — still a- // dark frame, but one with a wood hue and a visible streak.- color: opts.frameColor === undefined ? 0x64492f : opts.frameColor,- }));- frame.name = 'MirrorFrame';- frame.castShadow = true;- frame.receiveShadow = true;- group.add(frame);- }-- group.userData.forward = '+Z';- group.userData.mode = rtt ? 'rtt' : 'env';- group.userData.surface = surface;- return group;-}--/** A box as geometry, positioned by its centre. */-function _bx(w, h, d, x, y, z) {- const g = new THREE.BoxGeometry(w, h, d);- g.translate(x, y, z);- return g;-}--/** Deterministic 0..1 hash — the per-window lit draw, no PRNG order. */-function _hash(a, b, seed) {- const t = Math.sin(a * 127.1 + b * 311.7 + seed * 74.7) * 43758.5453;- return t - Math.floor(t);-}--// THE BAKE'S TRANSFER FUNCTION. Every colour below is mixed in the LINEAR-// working space a THREE.Color holds (`new THREE.Color(0x5d8fd6)` stores-// 0.110/0.275/0.672, not 0.365/0.561/0.839), while the DataTexture is-// flagged SRGBColorSpace and is therefore DECODED as sRGB when sampled.-// Writing the linear numbers straight into the bytes ran the transfer-// backwards: the intended zenith 0x5d8fd6 shipped as byte (28,70,171) and-// came back as linear (0.011,0.061,0.415) — a sixth of the light, and blue-// pulled far ahead of red because the error is a power curve, not a scale.-// Measured on our host BEFORE this line existed: the baked horizon band sat-// at byte 98 with a hue spread of 0.002, and every facade `glazeFacade`-// touched rendered as a flat navy slab (mean_lum 0.145, saturation 0.72).-function _srgb(v) {- if (!(v > 0)) return 0;- return v <= 0.0031308 ? v * 12.92 : 1.055 * Math.pow(v, 1 / 2.4) - 0.055;-}--/** Radians to degrees. */-function _deg(r) {- return r * 180 / Math.PI;-}--// NO DITHER HERE, AND THAT IS A MEASUREMENT, NOT AN OVERSIGHT. A smooth-// 8-bit ramp usually needs +-0.5 LSB of ordered noise or it lays contour-// bands across every mirror-smooth surface that reflects it. This one does-// not: encoded to sRGB the sky half crosses only 9 byte levels over 80-// rows, so each step is 1 LSB (0.4%) spread over ~9 texels — under ACES at-// exposure 1.0 that is below the visible floor. A 4x4 Bayer pattern was-// built, shipped into the render and measured against no dither: after a-// 2x2 / 4x4 / 8x8 minification blur (what PMREM and the reflection itself-// do) the two column profiles were IDENTICAL to four decimals, max step-// 0.25 either way, while the un-blurred second difference went 0.21 -> 1.60.-// It bought high-frequency noise and nothing else, so it was deleted.--/**- * Bake the equirect a reflective city needs: sky gradient, the rig's- * sun glow, a seeded band of NEIGHBOURING TOWERS with window grids,- * and ground. Assign it to `scene.environment` (it is a superset of- * `sunRig().envTex`) or pass it as `envMap` per material.- *- * @param {object} [opts]- * `seed` (default 7) shapes the skyline; `size` equirect width in px- * (default 512, height is half); `sunDir` normalized THREE.Vector3 —- * pass the SAME vector the key light uses (default: the day rig's);- * `zenith` / `horizon` / `ground` / `sunColor` hex — defaults follow- * `sunDir`: the lib/environment.js DAY mood while the sun is up, and- * the NIGHT mood (deep-blue zenith over a lighter horizon band, moon- * for the glow) the moment it sets, so an evening scene does not- * reflect a noon sky off every window; `skylineColor` hex (day- * 0x39424e); `skylineHeightDeg` tallest neighbour in degrees of- * elevation (default 30 — a street canyon; 8 is a distant skyline);- * `lit` 0..1 fraction of reflected windows glowing (default 0 by day,- * 0.3 once the sun is down — a dark city with every window out is a- * ruin); `haze` 0..1 of aerial perspective mixed into the neighbours,- * heaviest at the street (default 0.18 — a city block is never the- * flat swatch its own albedo would make it, and this is what keeps- * the reflected band off the black floor); `hueVar` per-building hue- * jitter in turns (default 0.035 — concrete, brick and glass- * neighbours, not one stamped tone); `skyline` false for open sky.- * @returns {THREE.DataTexture} Equirect reflection mapping, sRGB,- * LINEAR filtered (a DataTexture defaults to Nearest, which prints- * the bake's pixel grid across every reflective facade).- */-export function bakeSkylineEnvironment(opts = {}) {- const w = opts.size || 512;- const h = w >> 1;- const rand = mulberry32(opts.seed === undefined ? 7 : opts.seed);- const seed = opts.seed === undefined ? 7 : opts.seed;- const sun = (opts.sunDir ? opts.sunDir.clone()- : _DAY_SUN.clone()).normalize();- // THE HOUR IS NOT A SEPARATE ARGUMENT. `sunDir` already carries it, and- // a scene that hands its night sun vector in while the bake keeps noon- // hexes gets a noon sky mirrored off every pane at midnight — the one- // "hardcoded light colour" failure this module could still commit.- // Below the horizon the palette flips to the night mood the rest of the- // library uses: a deep-blue zenith over a LIGHTER horizon band, moonlight- // for the glow, and the lights on in the reflected city.- const dark = sun.y <= 0;- // The night zenith is the scene's own (sky.js measures [26,36,64] there).- // The other two are NOT the sky at all and must not be scaled down with- // it: the horizon carries a city's skyglow and the ground carries what- // its own street lamps throw back. Left at a fraction of the zenith, the- // lower half of every night facade reflected a black floor — measured- // 11.1% of the close frame under the harness's crushed-pixel threshold.- const M = dark- ? { zen: 0x1a2440, hor: 0x384765, gnd: 0x2c2620, wall: 0x212734,- glow: 0xb6c6e2, lit: 0.3 }- : { zen: 0x5d8fd6, hor: 0xdce9f2, gnd: 0x8a7f6a, wall: 0x39424e,- glow: 0xfff6e0, lit: 0 };- const zenith = new THREE.Color(- opts.zenith === undefined ? M.zen : opts.zenith);- const horizon = new THREE.Color(- opts.horizon === undefined ? M.hor : opts.horizon);- const ground = new THREE.Color(- opts.ground === undefined ? M.gnd : opts.ground);- const wallC = new THREE.Color(- opts.skylineColor === undefined ? M.wall : opts.skylineColor);- const sunC = new THREE.Color(- opts.sunColor === undefined ? M.glow : opts.sunColor);- // Interior light is never one bulb: a night city is tungsten rooms,- // warm-white rooms and the cold fluorescent floor nobody went home from.- const litC = [- new THREE.Color(0xffb45f), new THREE.Color(0xffd7a0),- new THREE.Color(0xf2e2c0), new THREE.Color(0xcfe0dc),- ];- const lit = opts.lit === undefined ? M.lit : opts.lit;- // A night city is FARTHER through the same air, not less hazy: the haze- // just carries the horizon's own colour, which is now blue.- const haze = opts.haze === undefined ? (dark ? 0.26 : 0.18) : opts.haze;- const hueVar = opts.hueVar === undefined ? 0.035 : opts.hueVar;- const maxRad = (opts.skylineHeightDeg === undefined- ? 30 : opts.skylineHeightDeg) * Math.PI / 180;- // WHAT ACTUALLY LIGHTS THIS BAKE. By day it is the sun. Once the sun is- // under the horizon the key light is the MOON, and lib/environment.js- // puts it opposite the sun, 30-55 deg up (deeper sun, higher moon) — the- // same construction, so the reflected sky's glow sits where the scene's- // own moon is instead of leaving a sun-shaped blot in the ground half.- const keyDir = dark- ? (() => {- const az = Math.atan2(sun.z, sun.x) + Math.PI;- const el = Math.max(30, Math.min(55, 25 + _deg(Math.asin(-sun.y))))- * Math.PI / 180;- return new THREE.Vector3(Math.cos(el) * Math.cos(az), Math.sin(el),- Math.cos(el) * Math.sin(az));- })()- : sun;- // A moon's disc is as bright as a sun's but its halo is a tenth of it —- // the wide term is what would otherwise wash the night sky back to grey.- const wideGlow = dark ? 0.05 : 0.22;- // The key light's azimuth, so a facade's shading agrees with the light- // instead of being a second random number.- const sunAz = Math.atan2(keyDir.z, keyDir.x);-- // Skyline profile, one entry per column: roof elevation, tone, the- // window row pitch, and a per-building hue offset. Buildings span whole- // runs of columns, so every array below is constant across a facade.- const top = new Float32Array(w);- const tone = new Float32Array(w);- const pitch = new Float32Array(w);- const hue = new Float32Array(w);- const wsat = new Float32Array(w);- if (opts.skyline !== false) {- let x = 0;- while (x < w) {- const bw = 4 + Math.floor(rand() * Math.max(4, w / 24));- const bh = (0.18 + 0.82 * Math.pow(rand(), 1.7)) * maxRad;- const bt = 0.75 + rand() * 0.5;- const bp = 3 + Math.floor(rand() * 4);- // Hue AND saturation move together: the pale end reads as concrete- // and the warm end as brick, which is what a mixed block looks like.- const bhue = (rand() - 0.5) * 2 * hueVar;- const bsat = 0.7 + rand() * 0.7;- for (let i = 0; i < bw && x < w; i++, x++) {- top[x] = bh;- tone[x] = bt;- pitch[x] = bp;- hue[x] = bhue;- wsat[x] = bsat;- }- }- }- const below = maxRad * 0.25; // the street the towers stand in- const wall = new THREE.Color();-- const data = new Uint8Array(w * h * 4);- const c = new THREE.Color();- const px = new THREE.Vector3();- for (let row = 0; row < h; row++) {- const lat = ((row + 0.5) / h - 0.5) * Math.PI;- const y = Math.sin(lat);- for (let col = 0; col < w; col++) {- const lon = ((col + 0.5) / w - 0.5) * Math.PI * 2;- if (y >= 0) {- c.copy(horizon).lerp(zenith, Math.pow(y, 0.62));- } else {- c.copy(horizon).lerp(ground, Math.min(1, -y * 3));- }- if (lat < top[col] && lat > -below) {- // Facade: darker at the base, window grid on top of it, and the- // side the sun is on brighter than the side it is not — the same- // `sunDir` the key light uses, so a reflected city cannot be lit- // from a direction nothing else in the scene is.- const f = (lat + below) / (top[col] + below);- const face = 0.72 + 0.42 * Math.max(0, Math.cos(lon - sunAz));- wall.copy(wallC).offsetHSL(hue[col], (wsat[col] - 1) * 0.35, 0);- c.copy(wall).multiplyScalar(tone[col] * face * (0.62 + 0.38 * f));- const p = pitch[col];- if (col % 3 < 2 && row % p < p - 1 && lat > -below * 0.5) {- const winRow = Math.floor(row / p);- if (lit && _hash(col / 3 | 0, winRow, seed) < lit) {- const k = _hash(winRow, col / 3 | 0, seed + 19);- c.lerp(litC[Math.min(3, (k * 4) | 0)], 0.62 + 0.3 * k);- } else {- // An unlit pane is a slice of the sky it faces, and no two- // panes hold the same slice: blinds, a curtain, an empty- // room. One flat lerp is what makes a bake read as wallpaper.- const v = _hash(col / 3 | 0, winRow, seed + 5);- c.lerp(horizon, 0.16 + 0.30 * v);- }- }- // Aerial perspective: heaviest at the street, gone by the roofline.- // Without it the band's darkest facades bottom out near black and- // every mirror that reflects the horizon reads as a hole.- c.lerp(horizon, haze * (1 - 0.72 * f));- } else {- px.set(Math.cos(lat) * Math.cos(lon), y,- Math.cos(lat) * Math.sin(lon));- const ang = Math.acos(- Math.max(-1, Math.min(1, px.dot(keyDir))));- const glow = 1.1 * Math.exp(-(ang * ang) / 0.0128) +- wideGlow * Math.exp(-(ang * ang) / 0.245);- c.r += sunC.r * glow;- c.g += sunC.g * glow;- c.b += sunC.b * glow;- }- const i = (row * w + col) * 4;- data[i] = Math.min(255, Math.round(_srgb(c.r) * 255));- data[i + 1] = Math.min(255, Math.round(_srgb(c.g) * 255));- data[i + 2] = Math.min(255, Math.round(_srgb(c.b) * 255));- data[i + 3] = 255;- }- }-- const tex = new THREE.DataTexture(data, w, h, THREE.RGBAFormat);- tex.mapping = THREE.EquirectangularReflectionMapping;- tex.colorSpace = THREE.SRGBColorSpace;- // Nearest is the DataTexture default and prints the bake's texel grid- // straight onto every mirror-smooth facade; PMREM blurs only by- // roughness, so it cannot rescue an unfiltered source.- tex.minFilter = THREE.LinearFilter;- tex.magFilter = THREE.LinearFilter;- tex.generateMipmaps = false;- tex.wrapS = THREE.RepeatWrapping;- tex.needsUpdate = true;- return tex;-}--/**- * The curtain-wall material: a coated glass that mirrors the sky and- * its neighbours off `envMap` for zero per-frame cost. Untinted glass- * with only fresnel reflects ~4% head-on and renders as a black hole;- * `coating` is what real reflective glazing adds on top of that.- *- * @param {object} [opts]- * `envMap` the equirect to reflect — pass `bakeSkylineEnvironment()`- * or leave null to inherit `scene.environment`; `scene` to read that- * environment now; `color` glass tint hex (default 0x2f4250, the- * blue-green of a real curtain wall); `roughness` (default 0.06 —- * raise to 0.15+ for older, wavier glazing); `metalness` (default- * 0.22, the coating's tinted mirror component); `coating` 0..1 of- * dielectric reflectance, ior 1.5 to 2.33 (default 0.9);- * `clearcoat` 0..1 of the UNTINTED outer lacquer (default 0.9) and- * `clearcoatRoughness` (default 0.05); `envMapIntensity` (default- * 1.5); `opacity` < 1 to see the reveals behind the glass (default 1,- * opaque — it writes depth and casts); `extra` merged last.- * @returns {THREE.MeshPhysicalMaterial} Ready for a facade's glazing.- */-export function glassFacadeMaterial(opts = {}) {- const env = opts.envMap ||- (opts.scene && opts.scene.environment) || null;- const op = opts.opacity === undefined ? 1 : opts.opacity;- const m = new THREE.MeshPhysicalMaterial({- color: opts.color === undefined ? 0x2f4250 : opts.color,- roughness: opts.roughness === undefined ? 0.06 : opts.roughness,- // METALNESS TINTS THE MIRROR AND DIMS IT. A metal's F0 IS its colour,- // and this colour is linear (0.031, 0.058, 0.088) — at 0.35 metalness- // over a third of the reflection was being multiplied by a near-black- // blue. Measured on our host: a glazed block's panes rendered at- // mean_lum 0.145 with saturation 0.72, a flat navy hole. The mirror a- // curtain wall actually shows lives in the COATING, not the metal.- metalness: opts.metalness === undefined ? 0.22 : opts.metalness,- // The lacquer over the tint: an untinted dielectric layer with its own- // fresnel, so the sky arrives on the glass in the sky's own colour and- // brightens toward grazing exactly where a real facade does.- clearcoat: opts.clearcoat === undefined ? 0.9 : opts.clearcoat,- clearcoatRoughness:- opts.clearcoatRoughness === undefined ? 0.05- : opts.clearcoatRoughness,- envMap: env,- envMapIntensity:- opts.envMapIntensity === undefined ? 1.5 : opts.envMapIntensity,- transparent: op < 1,- opacity: op,- });- // reflectivity drives ior (0.5 -> 1.5, 1 -> 2.33): the coating that- // lifts head-on reflectance from 4% toward 16%.- m.reflectivity = opts.coating === undefined ? 0.9 : opts.coating;- return Object.assign(m, opts.extra || {});-}--/**- * Point a `lib/building.js` facade at the sky: swaps the glazing- * material on every `Glazing` / `Pane` mesh under `root` (what- * `block()`, `tower()`, `cityFabric()` and `casement()` name theirs).- * Lit windows live on the `Reveals` mesh and are left glowing.- *- * @param {THREE.Object3D} root A building from lib/building.js, or any- * subtree whose glazed meshes are named `Glazing` / `Pane`.- * @param {object} [opts] `material` to apply as-is — one material on every- * pane, no variants — otherwise every `glassFacadeMaterial()` option- * (`envMap` is the one that matters).- * @returns {THREE.Object3D} The same `root`, with `userData.glazed`- * set to the number of meshes retargeted.- */-export function glazeFacade(root, opts = {}) {- const mat = opts.material || glassFacadeMaterial(opts);- // lib/building.js ALREADY splits its panes into two batches (`Glazing`- // and `Glazing2`) for exactly this reason — "real glazing is never one- // value: blinds, curtains, a room behind one pane and none behind the- // next". Retargeting both to a single material threw that away and- // handed back the flat glass tower the split exists to prevent. The- // second batch keeps the same coating and moves only tint and- // roughness, by a hair; batch 0 is `mat` itself, untouched.- const variants = [mat];- if (!opts.material) {- const alt = mat.clone();- alt.color = mat.color.clone().offsetHSL(-0.02, 0.06, -0.03);- alt.roughness = Math.min(1, mat.roughness + 0.05);- alt.envMapIntensity = mat.envMapIntensity * 0.92;- variants.push(alt);- }- let n = 0;- root.traverse((o) => {- if (o.isMesh && /glaz|pane/i.test(o.name || '')) {- // Deterministic: the batch's own name picks the variant, so a fix- // round that rebuilds the tower reproduces the same facade.- const k = /2$/.test(o.name) ? 1 : 0;- o.material = variants[Math.min(k, variants.length - 1)];- n++;- }- });- if (n === 0) {- console.warn(- 'glazeFacade: no Glazing/Pane mesh under "' + (root.name || '?') +- '" — nothing was made reflective.');- }- root.userData.glazed = n;- return root;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/neon.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/neon.jsindex 76f6acc9..0c9ca266 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/neon.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/neon.js@@ -16,8 +16,7 @@* picks when handed "0 to 1" is the mode that cannot clip.** Composes with `windows.js` (the rooms behind the facade this spills- * onto) and `lights.js` (`makePanelLight` when the sign must light a- * passer-by — no emissive term can do that).+ * onto).*/import * as THREE from 'three';diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.jsindex c317f938..5413c05b 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js@@ -5,7 +5,7 @@* no post pass. Delivery frames are STILLS, so every effect must read* FROZEN: streaks are drawn long, splash phases are spread across the* field so all radii show at once, and puddle ripples displace real- * geometry. World-space like ./scatter.js — add the returned objects+ * geometry. World-space — add the returned objects* at the scene ROOT and drive them from `tick`: `obj.userData.update(t)`.*/diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/river.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/river.jsdeleted file mode 100644index 10f770b8..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/river.js+++ /dev/null@@ -1,529 +0,0 @@-/**- * A river whose surface flows along its OWN course.- *- * Scroll a UV on a curved ribbon and the whole sheet translates one- * way: round a bend the water keeps going the way it went before the- * bend, which is the single tell that turns a river back into a moving- * texture. So the ribbon carries a flow field of its own — the- * centreline tangent times the local speed, per vertex — and the- * fragment samples its noise in a frame ADVECTED along that field,- * cross-fading two phases half a period apart so the shear of a- * curving flow never stretches the pattern without bound.- *- * The channel is read from the same field: pale where the water runs- * thin over a bank or a rock, deep mid-channel, broken white where it- * narrows (the same water through a smaller gap runs faster) or where- * something stands proud of the bed. Depth and rocks are measured on- * the CPU from `heightAt` and handed over as attributes — GLSL_UTIL's- * value noise is not the Perlin field the terrain is built from, so- * the shader could never find those rocks itself.- *- * NOT a second reflective surface: `water.js` owns the scene's one RTT- * plane, and this ribbon lies 12 mm above the water it joins.- */--import * as THREE from 'three';--import { makeShaderMaterial, tickShaders } from './shader.js';--// Above the surface it lies on: clears z-fighting with a coplanar-// water plane, and stays inside the 2 cm an asset's base is allowed.-const LIFT = 0.012;--// Metres of course per row, and columns across the channel.-const ROW_M = 0.55;-const COLS = 15;--// Metres a broken patch keeps foaming downstream of what broke it.-const WAKE_M = 3.0;--// Metres of sideways drift per unit curvature per metre travelled:-// surface water at a bend crowds the outer bank (helical secondary-// flow), which is what stops the advection being one rigid scroll.-const DRIFT = 0.8;--// The day rig's sun (azimuth 35, elevation 48), same as water.js, so a-// river that was not told where the sun is still agrees with it.-const _AZ = 35 * Math.PI / 180;-const _EL = 48 * Math.PI / 180;-const DAY_SUN = new THREE.Vector3(- Math.cos(_EL) * Math.cos(_AZ), Math.sin(_EL),- Math.cos(_EL) * Math.sin(_AZ)).normalize();--// The day rig's own intensities, used only to normalise what is read-// off a scene: a key light at 5.4 and a fill at 1.4 are "full daylight",-// and a 2.2 moon has to arrive as 0.41 of it or the night river glows.-const DAY_KEY = 5.4;-const DAY_FILL = 1.4;--/**- * Take the light from the scene the ribbon was added to.- *- * The surface is UNLIT — it writes its own light out — so every colour- * in it is a decision, and three daylight constants baked into a- * factory are three ways for a river to disagree with the scene around- * it. Measured on this harness's night rig: with the defaults the- * channel came back at luminance 0.40/0.54 over a frame whose mean was- * 0.21/0.31 — a strip of white plastic lying in the dark. So the- * material reads the key light (direction, colour, strength), the sky- * half of the hemisphere fill, and the fog, at the first render.- * Anything the CALLER passed wins and is never overwritten.- */-function adoptSceneLight(mesh, u, given) {- let done = false;- mesh.onBeforeRender = (renderer, scene) => {- if (done || !scene || !scene.isScene) return;- done = true;- let key = null, hemi = null;- scene.traverse((o) => {- if (o.isDirectionalLight && o.visible && o.intensity > 0- && (!key || o.intensity > key.intensity)) key = o;- if (o.isHemisphereLight && o.visible && o.intensity > 0- && (!hemi || o.intensity > hemi.intensity)) hemi = o;- });- if (key) {- if (!given.sunDir) {- const a = key.getWorldPosition(new THREE.Vector3());- const b = key.target- ? key.target.getWorldPosition(new THREE.Vector3())- : new THREE.Vector3();- const d = a.sub(b);- if (d.lengthSq() > 1e-9) u.uSun.value.copy(d.normalize());- }- if (!given.sunColor) {- u.uSunCol.value.copy(key.color).multiplyScalar(- Math.min(1.35, Math.max(0.12, key.intensity / DAY_KEY)));- }- }- // What the water reflects is the SKY, not the haze: the- // hemisphere's sky half is that colour in one number, and the- // fog is the fallback for a scene lit some other way.- const skyScale = hemi- ? Math.min(1.4, Math.max(0.3, hemi.intensity / DAY_FILL)) : 1;- if (!given.sky && (hemi || scene.fog)) {- u.uSky.value.copy(hemi ? hemi.color : scene.fog.color)- .multiplyScalar(skyScale);- }- if (!given.ambient && hemi) {- u.uAmb.value.copy(hemi.color).lerp(hemi.groundColor, 0.35)- .multiplyScalar(skyScale);- } else if (!given.ambient && scene.fog) {- u.uAmb.value.copy(scene.fog.color);- }- };-}--const DEFAULT_COURSE = [- [-16, 0, -13], [-7, 0, -6], [0, 0, 1], [-2, 0, 9], [3, 0, 16],-];--/** Deterministic 0..1 stream — no Math.random in a shipped factory. */-function rng(seed) {- let s = (seed >>> 0) || 1;- return () => ((s = (s * 16807) % 2147483647) / 2147483647);-}--/** GLSL's smoothstep, for the parts measured on the CPU. */-function smooth01(e0, e1, x) {- const t = Math.max(0, Math.min(1, (x - e0) / (e1 - e0 || 1e-6)));- return t * t * (3 - 2 * t);-}--/** Accept [x, y, z], [x, z] or Vector3 waypoints, all as Vector3. */-function toCourse(points) {- const ok = Array.isArray(points) && points.length >= 2;- if (points !== undefined && !ok) {- console.warn('makeRiver: `points` needs two or more waypoints '- + '— falling back to the default course.');- }- const src = ok ? points : DEFAULT_COURSE;- return src.map((p) => (p && p.isVector3 ? p.clone()- : new THREE.Vector3(p[0], p.length > 2 ? p[1] : 0,- p.length > 2 ? p[2] : p[1])));-}--/**- * The ribbon: positions, the flow field, and the channel it measured.- *- * `aFlow` is the world flow VELOCITY (unit centreline tangent times- * the local speed) and `aChan` is (metres across, water depth, how- * broken, sideways drift) — everything the fragment needs that only- * the CPU can know.- */-function channelGeometry(course, o) {- const curve =- new THREE.CatmullRomCurve3(course, false, 'catmullrom', 0.5);- const len = Math.max(curve.getLength(), 0.5);- const rows = Math.max(8, Math.min(400, Math.round(len / ROW_M)));- const ds = len / rows;- const p1 = o.rand() * 6.2832;- const p2 = o.rand() * 6.2832;- const widthAt =- typeof o.width === 'function' ? o.width : () => o.width;-- const cp = [], ct = [], cw = [], cs = [], cd = [];- let wSum = 0;- for (let j = 0; j <= rows; j++) {- const u = j / rows;- const t = curve.getTangentAt(u);- t.y = 0;- if (t.lengthSq() < 1e-9) t.set(1, 0, 0);- cp.push(curve.getPointAt(u));- ct.push(t.normalize());- // The banks are not ruled lines; two seeded tones wander them.- cw.push(Math.max(0.25, widthAt(u)- * (1 + 0.055 * Math.sin(u * 7.3 + p1)- + 0.035 * Math.sin(u * 15.9 + p2))));- wSum += cw[j];- }- const wRef = wSum / (rows + 1);- for (let j = 0; j <= rows; j++) {- // Flux: the same water through a smaller gap runs faster,- // which is what makes a narrows both race and break.- cs.push(o.flow * Math.max(0.5, Math.min(2.4, wRef / cw[j])));- }- for (let j = 0; j <= rows; j++) {- const a = ct[Math.max(0, j - 1)];- const b = ct[Math.min(rows, j + 1)];- const dth = Math.atan2(b.z, b.x) - Math.atan2(a.z, a.x);- const span = ds * (Math.min(rows, j + 1) - Math.max(0, j - 1));- // +s is right of travel and a positive turn is to the right,- // so the outer bank of that turn is -s.- cd.push(-Math.atan2(Math.sin(dth), Math.cos(dth)) / span- * cs[j] * DRIFT);- }-- const nV = (rows + 1) * COLS;- const pos = new Float32Array(nV * 3);- const uv = new Float32Array(nV * 2);- const flow = new Float32Array(nV * 3);- const chan = new Float32Array(nV * 4);- const bed = o.heightAt;- const row = new Float32Array(COLS);- for (let j = 0; j <= rows; j++) {- const p = cp[j], t = ct[j], w = cw[j];- const sx = -t.z, sz = t.x;- const narrow = smooth01(1.10, 1.55, cs[j] / o.flow);- // The bed this row is measured against is its own deepest- // point: a boulder ON the centreline must not raise the datum- // it is a boulder above.- let bedC = 0;- for (let i = 0; bed && i < COLS; i++) {- const s = ((i / (COLS - 1)) * 2 - 1) * w * 0.5;- row[i] = bed(p.x + sx * s, p.z + sz * s);- bedC = i ? Math.min(bedC, row[i]) : row[i];- }- for (let i = 0; i < COLS; i++) {- const q = (i / (COLS - 1)) * 2 - 1;- const s = q * w * 0.5;- const x = p.x + sx * s, z = p.z + sz * s;- const k = j * COLS + i;- pos[k * 3] = x;- pos[k * 3 + 1] = p.y + LIFT;- pos[k * 3 + 2] = z;- uv[k * 2] = i / (COLS - 1);- uv[k * 2 + 1] = j / rows;- flow[k * 3] = t.x * cs[j];- flow[k * 3 + 2] = t.z * cs[j];- // Whatever stands proud of that bed is a rock: the water- // over it runs thin, then breaks.- const prot = bed ? Math.max(0, row[i] - bedC) : 0;- const dp = o.depth * (1 - q * q);- chan[k * 4] = s;- chan[k * 4 + 1] = Math.max(0, dp - prot);- chan[k * 4 + 2] = Math.max(narrow,- smooth01(0.45 * o.depth, 0.95 * o.depth, prot));- chan[k * 4 + 3] = cd[j];- }- }- // Foam does not stop at the rock that made it — it streams away- // downstream and dies over a few metres.- const decay = Math.exp(-ds / WAKE_M);- for (let j = 1; j <= rows; j++) {- for (let i = 0; i < COLS; i++) {- const k = (j * COLS + i) * 4 + 2;- chan[k] = Math.max(chan[k], chan[k - COLS * 4] * decay);- }- }-- const idx = [];- for (let j = 0; j < rows; j++) {- for (let i = 0; i < COLS - 1; i++) {- const a = j * COLS + i, b = a + 1, c = a + COLS;- idx.push(a, b, c, b, c + 1, c);- }- }- const g = new THREE.BufferGeometry();- g.setAttribute('position', new THREE.BufferAttribute(pos, 3));- g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));- g.setAttribute('aFlow', new THREE.BufferAttribute(flow, 3));- g.setAttribute('aChan', new THREE.BufferAttribute(chan, 4));- g.setIndex(idx);- g.computeVertexNormals();- return { geometry: g, length: len, width: wRef };-}--/**- * Build a river ribbon that follows `points` and flows along it.- *- * @param {object} [opts]- * `points` the course, [[x, y, z], ...] (or [[x, z], ...], or- * Vector3s) — y is the WATER SURFACE there, so a river that descends- * is just a polyline that descends; `width` channel width in metres,- * a number or f(u in 0..1) for a reach that narrows (default 6);- * `depth` mid-channel depth in metres, which is what the deep colour- * MEANS — this ribbon is a surface, not a solid (default 1.2);- * `flow` surface speed in m/s at the nominal width, driving both the- * advection and the foam (default 1.2); `heightAt` (x, z) => bed- * height, sampled per vertex to find what stands proud of the bed- * under the channel; `deep` / `shallow` / `foam` THREE.Color or- * hex; `sky` what the surface reflects at grazing angles; `sunDir`- * normalized Vector3 toward the sun — pass the key light's, or the- * glitter disagrees with the shadows (default: the day rig's);- * `sunColor` / `ambient` THREE.Color or hex overriding what is read- * off the scene; `seed` PRNG seed (default 5).- *- * Everything about the LIGHT is optional because the ribbon reads it- * from the scene it is added to at the first render — key light- * direction, colour and strength, the sky half of the hemisphere- * fill, the fog — so a river dropped into a night scene goes dark- * with it. Pass any of them to override that scene reading.- * @returns {THREE.Group} Named `River`, resting on the water surface- * (12 mm above the course's own y), with `userData.tick(t)` driving- * the flow. One ordinary transparent mesh: it must NOT be a second- * reflective Water, which would re-render the whole scene again.- */-export function makeRiver(opts = {}) {- const o = {- width: opts.width === undefined ? 6 : opts.width,- depth: opts.depth === undefined ? 1.2 : opts.depth,- flow: opts.flow === undefined ? 1.2 : opts.flow,- heightAt: typeof opts.heightAt === 'function'- ? opts.heightAt : null,- rand: rng(opts.seed === undefined ? 5 : opts.seed),- };- o.depth = Math.max(o.depth, 0.05);- o.flow = Math.max(Math.abs(o.flow), 0.02);- const built = channelGeometry(toCourse(opts.points), o);-- const g = new THREE.Group();- g.name = 'River';- const mat = riverMaterial(o, built, opts);- const mesh = new THREE.Mesh(built.geometry, mat);- mesh.name = 'Channel';- mesh.renderOrder = 1;- adoptSceneLight(mesh, mat.uniforms, opts);- g.add(mesh);- g.userData.tick = (t) => tickShaders(g, t);- return g;-}--/** The surface: two-phase flow-map advection, depth, foam, glitter. */-function riverMaterial(o, built, opts) {- // Cycles per metre. Across is tied to the channel so a brook and a- // river both get ~6 streaks bank to bank; along is a sixth of it,- // because structure runs ACROSS a flow, never ranked down it.- const across = Math.max(0.35, Math.min(2.5, 6 / built.width));- return makeShaderMaterial({- name: 'RiverSurface',- uniforms: {- uDeep: { value: new THREE.Color(- opts.deep === undefined ? 0x0e3f5c : opts.deep) },- uShallow: { value: new THREE.Color(- opts.shallow === undefined ? 0xa8c49a : opts.shallow) },- uFoam: { value: new THREE.Color(- opts.foam === undefined ? 0xeef4f5 : opts.foam) },- uSky: { value: new THREE.Color(- opts.sky === undefined ? 0x9cc3e2 : opts.sky) },- // The key light's colour and the sky's own ambient, both- // replaced by the scene's at the first render unless the- // caller pinned them (see `adoptSceneLight`).- uSunCol: { value: new THREE.Color(- opts.sunColor === undefined ? 0xfff0d8 : opts.sunColor) },- uAmb: { value: new THREE.Color(- opts.ambient === undefined ? 0x9db8e8 : opts.ambient) },- uSun: { value: (opts.sunDir ? opts.sunDir.clone()- : DAY_SUN.clone()).normalize() },- uFreq: { value: new THREE.Vector2(across, across * 0.16) },- // Where this river's noise sits, and where its cycle- // starts: two rivers in one scene must not beat together.- uPhase: { value: new THREE.Vector2(- o.rand() * 37, o.rand() * 37) },- uLength: { value: built.length },- // Metres of water it takes to swallow the bed. Absolute, so- // a brook stays pale and a channel goes deep; normalising- // by the river's own depth divides that difference out.- // 1.1, not 2.4: a real river is 1-2 m deep, and at 2.4 the- // whole of one rendered as its shallow colour — pale sage- // bank to bank, with the ground washing through it.- uOpaqueM: { value: 1.1 },- // Seconds before the advected frame is reset. Long enough- // to read as travel, short enough that the shear of a bend- // has not yet smeared the pattern.- uPeriod: { value: 2.6 },- // 0.62, not 0.85: at 0.85 the finite-difference normals- // swung ~37 degrees off vertical everywhere, so the tight- // specular lobe fired over the WHOLE sheet and the channel- // came back as crumpled foil (measured: 19-23% of the- // channel below saturation 0.05). The crests are still- // there; they are now facets, not a mirror.- uBump: { value: 0.62 },- },- varyings: [- 'varying vec2 vUv; varying vec3 vN; varying vec3 vW;',- 'varying vec3 vFlow; varying vec4 vChan;',- ].join('\n'),- vertexHead: 'attribute vec3 aFlow;\nattribute vec4 aChan;',- vertexMain: [- ' vUv = uv;',- ' vFlow = aFlow;',- ' vChan = aChan;',- // World, not view: the sun and the camera are both given- // in world space below.- ' vN = normalize(mat3(modelMatrix) * normal);',- ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uDeep; uniform vec3 uShallow;',- 'uniform vec3 uFoam; uniform vec3 uSky; uniform vec3 uSun;',- 'uniform vec3 uSunCol; uniform vec3 uAmb;',- 'uniform vec2 uFreq; uniform vec2 uPhase;',- 'uniform float uLength; uniform float uOpaqueM;',- 'uniform float uPeriod; uniform float uBump;',- // One sample of the surface, in the ribbon frame (metres- // across, metres along). Anisotropic on purpose: the grain- // of a current is lengthwise streaks.- 'float rvField(vec2 q) {',- ' vec2 p = q * uFreq + uPhase;',- ' float streak = astraFbm2(p, 3);',- ' float chop = astraNoise2(p * vec2(2.9, 6.0) + uPhase.yx);',- ' return streak + 0.42 * chop;',- '}',- // The flow map: the frame is carried along the flow and- // reset every period, and two copies half a period apart- // cross-fade, so a curving flow never stretches it without- // bound. ph is (offset A, offset B, blend).- 'float rvWave(vec2 q, vec2 f, vec3 ph) {',- ' return mix(rvField(q - f * ph.x),',- ' rvField(q - f * ph.y), ph.z);',- '}',- ].join('\n'),- fragmentMain: [- ' vec2 T = vFlow.xz;',- ' float sp = length(T);',- ' T = sp > 1e-4 ? T / sp : vec2(1.0, 0.0);',- ' vec2 S = vec2(-T.y, T.x);',- // The ribbon's own frame: metres across, metres along.- ' vec2 Q = vec2(vChan.x, vUv.y * uLength);',- ' vec2 F = vec2(vChan.w, sp);',- ' float k0 = fract(uTime / uPeriod + uPhase.x);',- ' vec3 ph = vec3((k0 - 0.5) * uPeriod,',- ' (fract(k0 + 0.5) - 0.5) * uPeriod,',- ' abs(2.0 * k0 - 1.0));',- ' float h = rvWave(Q, F, ph);',- // Finite differences in the same frame: the crests are- // built from the flow, so they run across it.- ' float E = 0.06;',- ' vec2 gr = vec2(rvWave(Q + vec2(E, 0.0), F, ph) - h,',- ' rvWave(Q + vec2(0.0, E), F, ph) - h) / E;',- ' vec3 wg = vec3(S.x, 0.0, S.y) * gr.x',- ' + vec3(T.x, 0.0, T.y) * gr.y;',- ' vec3 n = normalize(vN - wg * uBump);',- ' vec3 V = normalize(cameraPosition - vW);',- ' float hn = clamp((h - 0.30) / 0.75, 0.0, 1.0);',- ' float dep = clamp(vChan.y / uOpaqueM, 0.0, 1.0);',- // The pale margin belongs to the shelving bank, not to half- // the channel — but it is a RAMP, not a rim: at 0.34 the- // colour saturated the moment the bed dropped away and the- // whole channel was one value.- ' vec3 c = mix(uShallow, uDeep, smoothstep(0.03, 0.62, dep));',- // Broken colour, in the ribbon's OWN frame so the patches- // travel with the reach: silt, weed and depth never leave a- // channel one flat hue, and two scales keep it reading at- // 20 m and at 2 m.- ' c = astraHueBreak(c, Q, 0.16, 0.30);',- ' c = astraHueBreak(c, Q, 0.75, 0.13);',- // Unlit, so the light is written out — and it is written- // out ONCE, as sky ambient plus key, so the body of the- // water darkens with the scene instead of glowing at- // daylight values under a moon. (The old `0.70 + 0.80*ndl`- // was a pure geometry term: measured on this harness's- // night rig, the channel came back at luminance 0.40/0.54- // over a frame whose mean was 0.21/0.31.) The ambient half- // never reaches zero, so no crest has a black shadow side.- ' float ndl = max(dot(n, uSun), 0.0);',- ' vec3 lit = uAmb * (0.62 + 0.34 * max(n.y, 0.0))',- ' + uSunCol * 0.95 * ndl;',- ' c *= lit;',- // The sky comes back by REFLECTION, not by washing the- // albedo: Schlick with water's own F0 (2%), so looking into- // a river you see the river, and only a grazing view turns- // it into a mirror. The old flat 0.22 + 0.50*fres put a- // fifth of the sky over even the deepest pixel.- ' float f5 = pow(1.0 - clamp(dot(n, V), 0.0, 1.0), 5.0);',- ' float fr = clamp(0.02 + 0.98 * f5, 0.0, 0.90);',- // What comes back is a sky GRADIENT sampled by the mirror- // direction, not one number: a flat sky colour turned every- // grazing view into a smooth wash with no wave left in it,- // and the whole point of a reflection is that the crests- // and the troughs look at different parts of the dome.- ' vec3 R = reflect(-V, n);',- ' float ry = clamp(R.y * 0.5 + 0.5, 0.0, 1.0);',- ' vec3 skyC = mix(uAmb * 0.95, uSky * 1.14,',- ' smoothstep(0.34, 0.78, ry));',- ' c = mix(c, skyC * (0.90 + 0.22 * hn), fr);',- ' vec3 H = normalize(uSun + V);',- ' float nh = max(dot(n, H), 0.0);',- // Glitter is POINTS on the water, not a sheen over all of- // it: the tight lobe is gated by a coarse mask riding the- // same advected frame, and both lobes are scaled by the- // same Fresnel the reflection uses, so nothing specular- // survives a look straight down into the channel.- ' float glint = smoothstep(0.52, 0.90,',- ' rvWave(Q * 5.0, F * 5.0, ph));',- ' c += uSunCol * (0.05 + 0.95 * f5)',- ' * (pow(nh, 60.0) * 0.07',- ' + pow(nh, 420.0) * (0.15 + 2.60 * glint));',- ' float brk = clamp(vChan.z, 0.0, 1.0);',- ' float thin = 1.0 - smoothstep(0.02, 0.22, dep);',- // Foam is torn, never a wash — and it travels, so the tear- // rides the same advected frame three times finer.- ' float tear = clamp((rvWave(Q * 3.0, F * 3.0, ph) - 0.30)',- ' / 0.75, 0.0, 1.0);',- // Capped at 0.9, and carried almost entirely by the TEAR:- // a broken reach is white threads on water, not a lid over- // it. The old floor of 0.25 meant every metre a wake- // reached went a quarter white whatever the surface was- // doing, and three boulders' wakes chained into one opaque- // sheet that hid the whole lower river (measured: the- // channel's saturation fell to 0.12 and a fifth of it was- // colourless). The bank term is halved for the same reason.- ' float foamK = clamp(brk * (0.16 + 1.20 * tear)',- ' + thin * hn * 0.26, 0.0, 0.90);',- // Aerated water is white the way snow is — LIT by the same- // ambient and key as the water it came out of, not a lamp- // buried in the river. Under a moon this is what keeps the- // whitewater a soft grey-blue instead of blazing.- ' vec3 foamC = uFoam * (0.84 + 0.26 * tear)',- ' * (uAmb * 0.75 + uSunCol * 0.85 * ndl);',- ' foamC = mix(foamC, uSky * 0.85, 0.18);',- ' c = mix(c, foamC, foamK);',- // Hands over to the bank and to whatever is upstream of it- // instead of ending at a cut edge. The shallows are the- // THINNEST water there is: letting the bed show through- // them is where a channel gets its gravel colour.- ' float edge = 1.0 - abs(2.0 * vUv.x - 1.0);',- ' float a = mix(0.16, 0.94, smoothstep(0.0, 0.55, dep));',- ' a = max(a, foamK * 0.95);',- ' a *= smoothstep(0.0, 0.07, edge);',- ' a *= smoothstep(0.0, 0.03, vUv.y)',- ' * (1.0 - smoothstep(0.97, 1.0, vUv.y));',- // A depth ramp that crosses tens of metres of channel is- // exactly the gradient an 8-bit target bands.- ' c += (astraHash21(gl_FragCoord.xy) - 0.5) * (1.6 / 255.0);',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- });-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.jsdeleted file mode 100644index 221c504c..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.js+++ /dev/null@@ -1,176 +0,0 @@-/**- * Surface scatter engine: stamp one prototype across a mesh's actual- * surface as a single InstancedMesh (one draw call). Closes- * MeshSurfaceSampler's two traps: LOCAL-space samples (baked to world- * here) and its Math.random default (seeded mulberry32 instead).- * Caller contract: author `protoGeom` with its BASE at y = 0, and add- * the returned mesh at the scene ROOT — matrices are WORLD space.- */--import * as THREE from 'three';-import { MeshSurfaceSampler } from 'three/addons/math/MeshSurfaceSampler.js';-import { mulberry32 } from './noise.js';--// The scene contract's albedo band for a non-emissive surface. Colour-// jitter that multiplies a copy past the ceiling blows it out under-// ACES before the sun even lands on it; jitter that drops one under the-// floor punches a black hole in the field. Both ends are scaled back.-const ALBEDO_CEIL = 0.82;-const ALBEDO_FLOOR = 0.02;--/**- * Scatter `count` copies of a prototype over a mesh's surface.- *- * Samples are area-weighted (big triangles get proportionally more- * instances), seeded, and land exactly ON the surface in world space.- * Each instance gets a random yaw plus uniform scale jitter; the whole- * spread renders as one draw call.- *- * @param {THREE.Mesh} surface The mesh to scatter over (its current- * world transform is baked into the instances - transform it BEFORE- * calling, and add the returned mesh at the scene root).- * @param {THREE.BufferGeometry} protoGeom Prototype geometry, base at- * y = 0.- * @param {THREE.Material} protoMat Prototype material (shared by all- * instances; per-instance tint via `colorJitter` needs no clone).- * @param {number} count Instances to place (capped at `maxCount`,- * default 1000 - overdraw is the one measured scatter footgun).- * @param {object} [opts] Options:- * `alignToNormal` (default false) tilt each copy's +Y onto the- * surface normal - trees and posts stay upright (false), grass,- * rocks and moss follow the slope (true). A NUMBER 0..1 leans them- * part way: real grass on a bank leans downhill without lying flat,- * so 0.6-0.8 reads better than a hard 1 on anything that grows;- * `scaleJitter` (default 0.3) uniform scale spread, 1 +- jitter;- * `seed` (default 1) the mulberry32 seed - same seed, same field;- * `maxSlopeDeg` (default none) reject samples whose surface normal- * tilts more than this from vertical, keeping grass off cliff- * faces (rejected draws are re-sampled; if the surface cannot- * supply enough flat ground the mesh returns with fewer, drawn- * `.count` telling the truth);- * `colorJitter` (default 0) 0..1 per-instance colour variation- * multiplied onto the material colour via `setColorAt` - breaks- * the wallpaper read of identical copies. CENTRED on the authored- * albedo (a field's mean is the colour you picked) and it varies- * HUE, not just brightness: each copy is nudged along a warm/cool- * axis, which is what stops a thousand leaves reading as one flat- * green. The product is held inside the 0.02..0.82 albedo band;- * `hueJitter` (default `colorJitter * 0.8`) the warm/cool half-width- * on its own - raise it for foliage and lichened stone, drop it to- * 0 for painted or dyed copies that must hold one hue. Capped by- * the albedo's own saturation, and asymmetric (the cool side runs- * at 0.45 of the warm side): both because a full symmetric axis on- * grey stone comes back half orange and half blue;- * `maxCount` (default 1000) the hard cap;- * `name` (default 'Scatter') the returned mesh's name.- * @returns {THREE.InstancedMesh} One instanced mesh, world-space- * matrices, shadows on, ready to add at the scene root.- */-export function scatter(surface, protoGeom, protoMat, count, opts = {}) {- const align = opts.alignToNormal === true ? 1- : (opts.alignToNormal || 0);- const scaleJitter = opts.scaleJitter === undefined ? 0.3 : opts.scaleJitter;- const seed = opts.seed === undefined ? 1 : opts.seed;- const maxCount = opts.maxCount === undefined ? 1000 : opts.maxCount;- const colorJitter = opts.colorJitter || 0;- const base = protoMat && protoMat.color ? protoMat.color : null;- // A SATURATED albedo can absorb a wide hue push - leaves really do- // run lime to blue-green. A near-neutral one cannot: it has no hue to- // nudge, so the same push INVENTS one and a grey stone field comes- // back half orange and half blue. Cap the chroma the axis may add.- const peakCh = base ? Math.max(base.r, base.g, base.b) : 1;- const sat = base && peakCh > 0- ? (peakCh - Math.min(base.r, base.g, base.b)) / peakCh- : 1;- const hueJitter = Math.min(- opts.hueJitter === undefined ? colorJitter * 0.8 : opts.hueJitter,- 0.5 * sat + 0.06);- const n = Math.max(0, Math.min(count, maxCount));- const minNy = opts.maxSlopeDeg === undefined- ? -Infinity- : Math.cos(THREE.MathUtils.degToRad(opts.maxSlopeDeg));-- const rand = mulberry32(seed);- // Hue rides its OWN stream, so adding hue variation to a field costs- // the main stream nothing and cannot move a single instance.- const crand = mulberry32((seed * 2654435761 + 0x9e3779b9) >>> 0);- const sampler = new MeshSurfaceSampler(surface)- .setRandomGenerator(rand)- .build();- // FACE normals, not vertex normals: smoothed vertex normals- // under-report slope on fBm terrain, so the slope gate would lie.- // Clearing normalAttribute flips the sampler to its face-normal path.- sampler.normalAttribute = undefined;-- // The sampler works in the surface's LOCAL space; bake the world- // transform so the instances hold true world positions.- surface.updateWorldMatrix(true, false);- const toWorld = surface.matrixWorld;- const normalM = new THREE.Matrix3().getNormalMatrix(toWorld);-- const mesh = new THREE.InstancedMesh(protoGeom, protoMat, n);- const pos = new THREE.Vector3();- const nrm = new THREE.Vector3();- const up = new THREE.Vector3(0, 1, 0);- const IDENT = new THREE.Quaternion();- const quat = new THREE.Quaternion();- const yaw = new THREE.Quaternion();- const scl = new THREE.Vector3();- const m = new THREE.Matrix4();- const tint = new THREE.Color();- let placed = 0;- // Slope rejection re-samples; the attempt budget keeps a surface- // that is all cliff from looping forever.- const attempts = Math.max(1, n) * 40;- for (let a = 0; a < attempts && placed < n; a++) {- sampler.sample(pos, nrm);- nrm.applyMatrix3(normalM).normalize();- if (nrm.y < minNy) continue;- pos.applyMatrix4(toWorld);- yaw.setFromAxisAngle(up, rand() * Math.PI * 2);- if (align > 0) {- quat.setFromUnitVectors(up, nrm);- // a partial lean is a slerp from world-up towards the normal,- // so 0.7 on a 40 deg bank stands the tuft at 28 deg, not flat- if (align < 1) quat.slerp(IDENT, 1 - align).normalize();- quat.multiply(yaw);- } else {- quat.copy(yaw);- }- const s = 1 + (rand() - 0.5) * 2 * scaleJitter;- m.compose(pos, quat, scl.setScalar(s));- mesh.setMatrixAt(placed, m);- // Drawn whether or not it is USED: turning colorJitter on to break- // a wallpaper read must not also re-roll the layout underneath it.- const vr = rand();- if (colorJitter > 0 || hueJitter > 0) {- // Asymmetric on purpose: sun-bleached, dusty and dead go a long- // way WARM, while the cool end is shade the lighting already- // supplies - a symmetric axis turns half a stone field blue.- let c = (crand() - 0.5) * 2 * hueJitter; // + warm/dry, - cool- if (c < 0) c *= 0.45;- // Divide the hue axis back out of the multiplier's luma, so the- // warm end is not also the bright end: value and hue vary- // independently and the peak stays bounded by colorJitter alone.- const v = (1 + (vr - 0.5) * 2 * colorJitter * 0.85)- / (1 + 0.2477 * c);- let r = v * (1 + c), g = v * (1 + c * 0.15), b = v * (1 - c);- if (base) {- const peak = Math.max(base.r * r, base.g * g, base.b * b);- const k = peak > ALBEDO_CEIL ? ALBEDO_CEIL / peak- : (peak > 0 && peak < ALBEDO_FLOOR ? ALBEDO_FLOOR / peak : 1);- r *= k; g *= k; b *= k;- }- mesh.setColorAt(placed, tint.setRGB(r, g, b));- }- placed++;- }- mesh.count = placed;- mesh.instanceMatrix.needsUpdate = true;- if (mesh.instanceColor) mesh.instanceColor.needsUpdate = true;- mesh.castShadow = true;- mesh.receiveShadow = true;- mesh.frustumCulled = false; // one bbox for the whole spread- mesh.name = opts.name || 'Scatter';- return mesh;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/season.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/season.jsdeleted file mode 100644index e1b5025e..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/season.js+++ /dev/null@@ -1,463 +0,0 @@-/**- * The two knobs a built scene is POSED with: one that turns its- * vegetation through the year, one that puts its light at an hour.- *- * `patchSeasonTint` goes through `patchStandard`, so the material keeps- * its lighting, shadows, fog and depth chunks, and it chains with- * `patchLeafSSS`, `patchWind` and `patchMicroBreakup`. What it does to- * a colour already in place: it MIXES, never assigns. The season's- * colour is taken at the surface's OWN brightness, so an earlier- * patch's light, shade, grain and hue jitter all survive the turn and- * a sibling patch stays visible — at `amount` 1 only that brightness- * structure is left of the base, which is why the default is 0.85.- * Chain it AFTER anything that assigns the base colour (grass.js and- * flowers.js both write `diffuseColor.rgb =`, so a season tint applied- * before them is erased).- *- * `dayCycle` touches no material and no light. It returns a plain- * object whose keys are `sunRig()`'s and `worldShell()`'s own option- * names, so a composer applies it by spreading it into them, and- * nothing it was handed is mutated.- */--import * as THREE from 'three';-import { patchStandard } from './shader.js';--const DEG = Math.PI / 180;--// One palette per kind, plus the numbers that decide how the turn is-// BROKEN UP: `grain` metres per leaf cluster, `spread` the width in-// years of the per-leaf date jitter, `twist` the warm/cool chroma-// wobble between neighbours and `keep` how much of the hue an earlier-// patch left here survives the turn. Autumn is TWO anchors — a canopy-// turns to gold AND to red on the same date, and one uniform orange is-// the tell that a global lerp did the work.-//-// Regraded 2026-09-01 for OUR pipeline (ACES, exposure 1.0, no post-// chain, sun 5.4). The reference's autumn pair was a pure yellow and a-// near-pure brick — 0x8f2410 is linear (0.274, 0.018, 0.005), a red-// with no green and no blue at all, so its shade side took nothing-// from the sky and the canopy came back as chocolate. The pair is now-// an amber (hue 40 deg) and a scarlet (hue 10 deg), both with a-// dielectric floor in the channels they do not own; the ground's two-// anchors were 6 degrees of hue apart, which is why an autumn floor-// measured a hue spread of 2.3 degrees over a whole field.-const PALETTES = {- leaf: { spring: 0x8fbc4a, summer: 0x2f5a24, gold: 0xdca63a,- red: 0xa23520, winter: 0x685741, grain: 0.34, spread: 0.10,- pick: [0.30, 0.70], twist: 0.13, keep: 0.40 },- grass: { spring: 0x7cad35, summer: 0x44631f, gold: 0xab8f3d,- red: 0x7d4a22, winter: 0x6f6539, grain: 0.20, spread: 0.07,- pick: [0.10, 0.90], twist: 0.10, keep: 0.35 },- ground: { spring: 0x5c5238, summer: 0x6b5d3c, gold: 0x7d6630,- red: 0x5e3823, winter: 0x4e463a, grain: 1.40, spread: 0.05,- pick: [-0.35, 1.35], twist: 0.12, keep: 0.30 },-};-const KINDS = { leaf: 0, grass: 1, ground: 2 };--const SEASON_VERTEX_HEAD = [- 'uniform vec2 uSeaSeed;',- 'varying vec3 vAstraSeaP;',- 'varying vec3 vAstraSeaW;',- 'varying float vAstraSeaI;',- 'varying float vAstraSeaD;',- // three applies instanceMatrix in <project_vertex>, after this hook,- // so a per-INSTANCE date has to fold it in by hand.- 'vec3 astraSeasonWorld(vec3 p) {',- '#ifdef USE_INSTANCING',- ' return (modelMatrix * instanceMatrix * vec4(p, 1.0)).xyz;',- '#else',- ' return (modelMatrix * vec4(p, 1.0)).xyz;',- '#endif',- '}',-].join('\n');--const SEASON_VERTEX_BODY = [- ' vec3 seO = astraSeasonWorld(vec3(0.0));',- ' vAstraSeaI = astraHash21(seO.xz * 0.71 + seO.y * 0.13 + uSeaSeed);',- // The MODEL position, not `transformed`: wind edits transformed, and- // a leaf whose date came from a moving point swims as it sways.- ' vAstraSeaP = position;',- ' vAstraSeaW = astraSeasonWorld(transformed);',- // Does this asset HAVE a model position to cell a leaf off? A crown- // whose leaf cards are built in the vertex shader from instance- // attributes (canopy.js, grass.js) ships `position` as a zeroed- // attribute, so every card in the draw call lands in one cell and- // the turn goes flat. Measured 2026-09-01: hue spread 1.3 deg over a- // whole autumn crown. The flag is per VERTEX and constant over such- // a card, so the fallback cannot split one leaf in half.- ' vAstraSeaD = 1.0 - step(1e-8, dot(position, position));',-].join('\n');--const SEASON_FRAGMENT_HEAD = [- 'uniform float uSeaPhase;',- 'uniform float uSeaKind;',- 'uniform float uSeaAmt;',- 'uniform float uSeaGrain;',- 'uniform float uSeaSpread;',- 'uniform vec2 uSeaSeed;',- 'uniform vec2 uSeaPick;',- 'uniform float uSeaTwist;',- 'uniform float uSeaKeep;',- 'uniform vec3 uSeaSpring;',- 'uniform vec3 uSeaSummer;',- 'uniform vec3 uSeaGold;',- 'uniform vec3 uSeaRed;',- 'uniform vec3 uSeaWinter;',- 'varying vec3 vAstraSeaP;',- 'varying vec3 vAstraSeaW;',- 'varying float vAstraSeaI;',- 'varying float vAstraSeaD;',- 'const vec3 ASTRA_SEA_LUMA = vec3(0.2126, 0.7152, 0.0722);',- // One anchor's share of the year at ring position f (0..4). The- // S-curve keeps two neighbouring shares summing to 1 while pulling- // leaves onto the anchors, which is what makes the turn bimodal- // instead of a smooth wash through orange.- 'float astraSeasonRing(float f, float c) {',- ' float d = abs(fract((f - c) * 0.25 + 0.5) - 0.5) * 4.0;',- ' return smoothstep(0.0, 1.0, max(0.0, 1.0 - d));',- '}',- // Three decorrelated randoms — date, pigment, value — as cells on- // the MODEL for a leaf and as a world field for grass and ground,- // which have no per-leaf geometry to cell off. uSeaKind chooses.- 'vec3 astraSeasonGrain() {',- ' vec2 c = floor(vAstraSeaP.xz / uSeaGrain)',- ' + floor(vAstraSeaP.y / uSeaGrain) * vec2(17.0, 41.0);',- ' vec3 h = vec3(astraHash21(c + uSeaSeed),',- ' astraHash21(c * 1.73 + uSeaSeed + 7.31),',- ' astraHash21(c * 2.91 + uSeaSeed + 19.7));',- // An InstancedMesh shares ONE geometry, so the model cell is the- // same card for every copy: without this every leaf of a stand- // picks the same pigment and the only thing that varies is its date.- ' h = fract(h + vAstraSeaI * vec3(0.618, 0.379, 0.827));',- // World fallback for an asset with no model position of its own- // (vAstraSeaD), coarsened to branch scale there so one leaf card- // still carries one colour and the wind cannot make it swim.- ' float sw = max(clamp(uSeaKind, 0.0, 1.0), vAstraSeaD);',- ' float sg = uSeaGrain * (1.0 + 0.8 * vAstraSeaD',- ' * (1.0 - clamp(uSeaKind, 0.0, 1.0)));',- ' vec2 w = vAstraSeaW.xz / sg;',- ' vec3 f = vec3(astraFbm2(w + uSeaSeed, 2),',- ' astraFbm2(w.yx * 1.31 + uSeaSeed + 13.0, 2),',- ' astraFbm2(w * 0.61 + uSeaSeed + 29.0, 2));',- // Value noise clusters hard around 0.5; stretched, or grass and- // ground turn as one piece while a leaf canopy breaks up.- ' f = clamp((f - 0.5) * 2.3 + 0.5, 0.0, 1.0);',- ' return mix(h, f, sw);',- '}',- 'vec3 astraSeasonHue(float s, float k) {',- // uSeaPick sharpens the choice: a LEAF commits to one pigment or- // the other, so a canopy is gold AND red rather than a continuum of- // orange, while ground litter is the mixture and stays soft.- ' vec3 aut = mix(uSeaGold, uSeaRed,',- ' smoothstep(uSeaPick.x, uSeaPick.y, k));',- ' float f = fract(s) * 4.0;',- ' return uSeaSpring * astraSeasonRing(f, 0.0)',- ' + uSeaSummer * astraSeasonRing(f, 1.0)',- ' + aut * astraSeasonRing(f, 2.0)',- ' + uSeaWinter * astraSeasonRing(f, 3.0);',- '}',-].join('\n');--const SEASON_FRAGMENT_BODY = [- ' vec3 seG = astraSeasonGrain();',- // Three scales of unevenness: this copy, this leaf, and a crown-wide- // drift so a single un-instanced tree still turns from one side.- ' float seC = astraFbm2(vAstraSeaW.xz * 0.09 + uSeaSeed, 2) - 0.5;',- ' float seJ = (vAstraSeaI - 0.5) * 1.3 + (seG.x - 0.5) + seC * 0.9;',- // A leaf turns LATE, never early — the stragglers in a turning- // canopy are the ones still green — so the jitter LAGS the date and- // a winter tree carries no spring.- ' float sePh = uSeaPhase - uSeaSpread * (abs(seJ) - 0.28);',- ' vec3 seCol = astraSeasonHue(sePh, seG.y);',- // No two neighbours land on exactly the anchor: a warm/cool wobble- // about the season's own hue, a few degrees either way. Without it- // spring, summer and winter are ONE value per date and only autumn- // (which has a second anchor) carries any hue spread at all.- //- // Both this and the value below are CONTINUOUS combinations of the- // grain. For grass and ground that grain is a smooth world field,- // and a `fract` on anything drawn from it lays its own contour rings- // over the terrain — measured, six sawtooth rings per unit of field,- // a floor that read as plywood.- ' float seTw = clamp((seG.z - 0.5) * 1.3 + (seG.y - 0.5) * 0.7,',- ' -0.5, 0.5) * 2.0;',- ' seCol *= vec3(1.0 + uSeaTwist * seTw, 1.0, 1.0 - uSeaTwist * seTw);',- ' float seV = 0.80 + 0.40 * seG.z;',- ' float seL = dot(diffuseColor.rgb, ASTRA_SEA_LUMA);',- ' float seCl = dot(seCol, ASTRA_SEA_LUMA);',- // Taken at the surface's own brightness and MIXED in: everything an- // earlier patch put here survives the turn as light and shade — and- // `uSeaKeep` of it survives as HUE too. Brightness alone was not- // enough: canopy.js spreads its leaves over 0.3 rad of hue and- // grass.js splits lush from dry, and a turn that kept only their- // luminance flattened both to one colour per date. The tilt is- // renormalised to unit luminance, so it moves hue, never level.- ' vec3 seN = seCol / max(seCl, 1e-4)',- ' * pow(max(diffuseColor.rgb / max(seL, 1e-4), vec3(0.06)),',- ' vec3(uSeaKeep));',- ' seN /= max(dot(seN, ASTRA_SEA_LUMA), 1e-4);',- ' vec3 seT = seN * seCl * seV * (0.4 + 0.6 * seL / max(seCl, 1e-4));',- ' diffuseColor.rgb = mix(diffuseColor.rgb, seT, uSeaAmt);',-].join('\n');--/**- * Turn a vegetation material through the year, unevenly.- *- * `season` is one number a whole scene can share, but a canopy that- * takes it as a global lerp reads as one sheet of orange. Here the- * date is jittered per INSTANCE (each tree on its own date), per LEAF- * (cells on the model, so wind does not make them swim) and by a- * crown-wide drift, and autumn's anchor is a gold/red PAIR picked per- * leaf — so a stand at the turn carries green, gold and red at once.- * The jitter widens at the turn and closes in high summer, because a- * canopy in full leaf really is one green. What an earlier patch left- * on the surface comes through it: its light and shade, and a share of- * its hue jitter too, so `makeCanopy`'s broken colour survives the turn- * instead of being flattened to one brightness per date.- *- * A crown whose leaf cards are BUILT in the vertex shader — canopy.js,- * grass.js — has no model position to cell a leaf off (`position` is a- * zeroed attribute for the whole draw call), so the per-leaf random- * falls back to a branch-scale world field there. Without it those- * crowns turned as one flat sheet: measured on this renderer, 1.3- * degrees of hue over an entire autumn tree.- *- * Winter browns and dulls; it cannot make a tree BARE — no fragment- * patch removes geometry — so drop the leaf density in the asset for- * that, and let this colour what is left.- *- * Deterministic in `seed`: no PRNG, no time. `season` and `kind` are- * uniforms, never baked GLSL, so every material in a scene shares one- * compiled program and one cache key.- *- * @param {THREE.Material} material Leaf, grass or ground material,- * patched in place — a shared material from `materials.js` takes- * every mesh wearing it with it, so clone it first if that is not- * what you want. Re-applying retunes rather than chaining twice.- * @param {object} [opts] `season` 0..1 through the year, wrapping — 0- * spring, 0.25 summer, 0.5 autumn, 0.75 winter (default 0.25);- * `kind` 'leaf' | 'grass' | 'ground', which picks the palette, the- * size of a patch of one colour and how wide the dates spread- * (default 'leaf'); `amount` 0..1 how far the turn goes, and how- * much of the material's own colour is left (default 0.85 — 1 keeps- * only its brightness); `seed` decorrelates two stands (default 1);- * `spread` override for the width in years of the date jitter.- * @returns {THREE.Material} The same material. Its uniforms stay live- * on `material.userData.uniforms` for a scene that animates the- * year.- */-export function patchSeasonTint(material, opts = {}) {- const kind = PALETTES[opts.kind] ? opts.kind : 'leaf';- const pal = PALETTES[kind];- const season = opts.season === undefined ? 0.25 : opts.season;- const amount = opts.amount === undefined ? 0.85 : opts.amount;- const base = opts.spread === undefined ? pal.spread : opts.spread;- // Widest at the turn, tight in full leaf: the same jitter all year- // would put stray gold leaves through high summer.- const turn = 0.30 + 1.5 * Math.max(nearSeason(season, 0.5),- 0.45 * nearSeason(season, 0.75));- return patchStandard(material, {- name: 'season:tint',- uniforms: {- uSeaPhase: { value: season },- uSeaKind: { value: KINDS[kind] },- uSeaAmt: { value: clamp01(amount) },- uSeaGrain: { value: Math.max(1e-3, pal.grain) },- uSeaSpread: { value: Math.max(0, base) * turn },- uSeaSeed: { value: seedOffset(opts.seed === undefined ? 1- : opts.seed) },- uSeaPick: { value: new THREE.Vector2(pal.pick[0], pal.pick[1]) },- uSeaTwist: { value: pal.twist },- uSeaKeep: { value: pal.keep },- uSeaSpring: { value: new THREE.Color(pal.spring) },- uSeaSummer: { value: new THREE.Color(pal.summer) },- uSeaGold: { value: new THREE.Color(pal.gold) },- uSeaRed: { value: new THREE.Color(pal.red) },- uSeaWinter: { value: new THREE.Color(pal.winter) },- },- vertexHead: SEASON_VERTEX_HEAD,- vertexBody: SEASON_VERTEX_BODY,- fragmentHead: SEASON_FRAGMENT_HEAD,- fragmentBody: SEASON_FRAGMENT_BODY,- });-}--// worldShell()'s and sunRig()'s own day / golden / night anchors, so a-// posed scene and an un-posed one meet at noon and at midnight instead-// of drifting apart. Re-read off environment.js MOODS 2026-09-01 (the-// day horizon had drifted to 0xdce9f2, a sixth of a stop paler than-// the dome a caller who does NOT pose gets).-const DAY_ZENITH = 0x5d8fd6;-const DAY_HORIZON = 0xdbe3ea;-const DUSK_ZENITH = 0x3f5a9e;-const DUSK_HORIZON = 0xf2c17e;-const NIGHT_ZENITH = 0x060a18;-const NIGHT_HORIZON = 0x1d2a4a;--// The levels this renderer is calibrated at. environment.js measured-// OUR pipeline (ACES, exposure 1.0, no post chain) and its rigs land-// at day 5.4 key / 1.4 fill, golden 5.6 / 1.1, night 2.2 / 1.0, with-// sunRig clamping anything under 4.5 (day key) or 0.8 (night fill) UP-// because under-filling is the measured failure here. The reference's-// pose was graded for a post chain at exposure 1.1 and asked for 3.3 /-// 1.1 at noon and 0.75 / 0.58 at night: every daylight hour came back-// clamped to the same 4.5 — one flat key from breakfast to dusk — and-// a posed night rendered a third of the brightness of the very rig it-// was meant to replace.-const DAY_KEY = 5.4;-const DUSK_LIFT = 0.35;-const NIGHT_KEY = 2.2;-const DAY_FILL = 1.36;-const NIGHT_FILL = 1.0;--/**- * Pose a scene's light at an hour — the whole rig, from one number.- *- * Colour TEMPERATURE is the cue, so it is computed rather than picked:- * the sun's colour is a blackbody that runs from ~1900 K on the- * horizon to ~5800 K overhead, and the SKY that fills its shadows runs- * the other way, up past 10000 K when the sun is lowest — which is why- * a low sun is warm and its shadows are blue. Temperature is the whole- * cue: the LEVELS are this renderer's (`DAY_KEY` below), they hold- * across the working day and fall only as the sun goes out, because a- * dimmer noon is not an evening — an evening is a warmer one.- *- * Elevation comes from `hour` and `latitude` at the equinox, and the- * bearing sweeps a half-turn from morning to evening THROUGH the rig's- * own azimuth, which is taken as noon — so the scene's composition- * (cameras placed off the sun) still holds at midday and dawn and dusk- * are not the same frame. Below the horizon the rig becomes a moon on- * the same bearing: a directional light at a negative elevation lights- * every surface from underneath.- *- * @param {object} [rig] A `sunRig()` result. READ ONLY — only its- * `sunDir` is used, for the noon bearing, and it is not mutated.- * Absent, the noon bearing is `sunRig()`'s own default of 35 deg.- * @param {object} [opts] `hour` 0..24, fractional (default 12);- * `latitude` degrees, +N (default 40).- * @returns {object} A plain description, in `sunRig()`'s and- * `worldShell()`'s option names so it can be spread into them:- * `elevation`/`azimuth` degrees, `sunColor`, `intensity`, `fill`- * (= `ambient`), `zenith`/`horizon`, `fogDensity`, `mood`; plus- * `sunDir` (normalized, for `makeSky({ sunDir })`), `fogColor`,- * `ambient` the ambient level, `ambientColor` the blue a low sun's- * shadows take, `kelvin`, `contrast` key over key-plus-fill, `night`,- * `hour` and `latitude`. Every colour and vector is a fresh object.- */-export function dayCycle(rig, opts = {}) {- const hour = opts.hour === undefined ? 12 : opts.hour;- const lat = (opts.latitude === undefined ? 40 : opts.latitude) * DEG;- const h = ((((hour % 24) + 24) % 24) - 12) * Math.PI / 12;- // Equinox sun in the local horizon frame: south / west / up. Unit by- // construction, so the elevation is the up component's arcsine.- const south = Math.sin(lat) * Math.cos(h);- const west = Math.sin(h);- const up = Math.cos(lat) * Math.cos(h);- const sunEl = Math.asin(Math.max(-1, Math.min(1, up))) / DEG;- const night = sunEl < 0;- const noonAz = rigAzimuth(rig);- const azimuth = noonAz + Math.atan2(west, south) / DEG;- // At night the scene still needs somewhere to light FROM, so the key- // becomes the moon: the sun's own elevation reflected above the- // horizon and held between 12 and 58 degrees. That is a KEY, not the- // sun — reporting it as `elevation` told a caller at 20:00 that the- // sun stood 22 degrees up.- const keyElevation = night- ? Math.max(12, Math.min(58, -sunEl)) : sunEl;- const elevation = sunEl;-- const day = clamp01(Math.sin(Math.max(0, sunEl) * DEG));- const low = 1 - clamp01(sunEl / 16);- const kelvin = night ? 8200- : 1900 + 3900 * Math.pow(clamp01(sunEl / 50), 0.55);- const sunColor = blackbody(kelvin);- // The sky fills what the sun cannot reach, and it runs the OTHER way:- // the lower and warmer the key, the bluer the shadow it leaves.- const ambientColor = blackbody(- night ? 9000 : 6200 + 6000 * (1 - Math.pow(day, 0.45)));- // Level holds through the working day and falls only in the last- // three degrees, where the sun really is going out; the cue that- // says WHICH hour it is, on this pipeline, is temperature, not- // brightness — golden hour is measurably the more contrasty rig, not- // the dimmer one (5.6 over 1.1 against 5.4 over 1.4).- const intensity = night ? NIGHT_KEY- : (DAY_KEY + DUSK_LIFT * low)- * (0.35 + 0.65 * clamp01(sunEl / 3.5));- const ambient = night ? NIGHT_FILL- : DAY_FILL - 0.34 * (1 - Math.pow(day, 0.6));-- const lit = Math.pow(day, 0.42);- const zenith = new THREE.Color(NIGHT_ZENITH)- .lerp(new THREE.Color(DAY_ZENITH), lit)- .lerp(new THREE.Color(DUSK_ZENITH), low * lit * 0.5);- // The low-sun band is worldShell's own golden horizon pulled a third- // of the way to the sun's measured colour, so the dome and the key- // cannot disagree about how warm the hour is. The old target was the- // sun mixed with WHITE, which washed the one band of a dusk frame- // that is supposed to carry its colour.- const horizon = new THREE.Color(NIGHT_HORIZON)- .lerp(new THREE.Color(DAY_HORIZON), lit)- .lerp(new THREE.Color(DUSK_HORIZON).lerp(sunColor, 0.33),- low * lit * 0.85);- return {- hour, latitude: lat / DEG, night,- mood: night ? 'night' : (sunEl < 12 ? 'golden' : 'day'),- elevation, keyElevation, azimuth, sunColor, intensity,- fill: ambient, ambient, ambientColor,- zenith, horizon, fogColor: horizon.clone(),- fogDensity: 0.0018 + 0.0004 * low * lit + 0.0007 * (1 - lit),- // The direction to light FROM — the moon once the sun is down.- sunDir: new THREE.Vector3(- Math.cos(keyElevation * DEG) * Math.cos(azimuth * DEG),- Math.sin(keyElevation * DEG),- Math.cos(keyElevation * DEG) * Math.sin(azimuth * DEG)),- kelvin, contrast: intensity / (intensity + ambient),- };-}--/** Clamp to 0..1 without importing MathUtils for four calls. */-function clamp01(v) {- return Math.max(0, Math.min(1, v));-}--/** 1 at season `c`, falling to 0 a quarter-year either side. */-function nearSeason(s, c) {- const d = Math.abs((((s - c) % 1) + 1.5) % 1 - 0.5);- return Math.max(0, 1 - d * 4);-}--/** A stable vec2 field offset per seed — no PRNG, no clock. */-function seedOffset(seed) {- const h = (n) => {- const x = Math.sin(n * 127.1 + 311.7) * 43758.5453;- return x - Math.floor(x);- };- return new THREE.Vector2(h(seed) * 64, h(seed * 1.7 + 3.3) * 64);-}--/** The rig's noon bearing, in `sunRig()`'s azimuth convention. */-function rigAzimuth(rig) {- const d = rig && rig.sunDir;- if (!d || (d.x === 0 && d.z === 0)) return 35;- return Math.atan2(d.z, d.x) / DEG;-}--/**- * Planckian locus as an sRGB colour, normalized to its brightest- * channel — the colour of the light, not its level, which `intensity`- * carries. Approximation good over 1000-12000 K.- */-function blackbody(kelvin) {- const t = Math.max(1000, Math.min(12000, kelvin)) / 100;- let r = 1, g, b = 1;- if (t <= 66) {- g = 0.3900816 * Math.log(t) - 0.6318414;- b = t <= 19 ? 0 : 0.5432068 * Math.log(t - 10) - 1.1962541;- } else {- r = 1.2929362 * Math.pow(t - 60, -0.1332048);- g = 1.1298909 * Math.pow(t - 60, -0.0755149);- }- return new THREE.Color().setRGB(- clamp01(r), clamp01(g), clamp01(b), THREE.SRGBColorSpace);-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.jsindex 766971db..c406d2a9 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js@@ -12,9 +12,8 @@* billboard without its structure is a floating decal.** COST CONTRACT: `patchCurtainWall` spends NO render target. The scene- * has exactly one (`lib/mirror.js` `makeMirror`, `lib/wetground.js`- * `makeMirrorFloor` or an ocean), and a facade is never what should- * spend it — see the patch's own JSDoc for what it does instead.+ * has exactly one (`lib/wetground.js` `makeMirrorFloor` or an ocean),+ * and a facade is never what should spend it — see the patch's own JSDoc for what it does instead.*/import * as THREE from 'three';@@ -214,13 +213,12 @@ const CW_BODY = [** NO RENDER TARGET, which is the constraint that shapes it. The scene* gets ONE whole-scene reflection pass and a facade must never be what- * spends it: `mirror.js` `makeMirror` re-renders the scene into a- * Reflector (+48 ms/frame measured, and it enforces a budget of one),- * and `wetground.js` `makeMirrorFloor` spends that one on the ground.- * The other two ways out both cost something this does not:- * `envMirrorMaterial` / `glassFacadeMaterial` need an equirect BAKE and- * hand three's IBL a roughness-blurred lookup that cannot show the- * per-panel break-up, and neither shows the room behind the glass. Here+ * spends it: a Reflector re-renders the scene (+48 ms/frame+ * measured), and `wetground.js` `makeMirrorFloor` spends that one on+ * the ground. The other way out costs something this does not: an+ * envMap material needs an equirect BAKE and hands three's IBL a+ * roughness-blurred lookup that cannot show the per-panel break-up,+ * and it does not show the room behind the glass. Here* the reflection is an ANALYTIC sky evaluated per fragment from the* reflected ray — no target, no texture, no bake. The honest trade: it* reflects sky, haze and ground, never the building across the street.diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.jsdeleted file mode 100644index bf9bb52f..00000000--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.js+++ /dev/null@@ -1,568 +0,0 @@-/**- * A waterfall that reads as one from every angle.- *- * Four things decide that, and none of them is the noise function.- * The water leaves a lip as a PROJECTILE, so the sheet is a parabola- * bulging downstream, not a plane — a plane collapses to a line the- * moment the eye moves off its face. It has a CROSS-SECTION, so the- * sheet is a closed shell swept along that parabola rather than stacked- * cards. It ACCELERATES, so features ride a sqrt-of-drop age instead of- * a linear scroll. And it is threads, not a wash: structure varies- * hard ACROSS the sheet and barely along it, with neighbouring threads- * decorrelated by several full turns or their fronts weave a- * herringbone.- *- * A fifth thing decides whether it looks like WATER: how much air is in- * it. At the lip the flow is coherent — a thin glass sheet you see the- * cliff through, blue where it is thick and sky-coloured at grazing- * angles. By the foot it is torn into white spray. Everything here that- * is not geometry rides that one aeration ramp: colour, opacity, how- * mirror-like the surface is, how much sun scatters THROUGH it. The- * three materials are unlit, so all of that light is written out by- * hand — and it is read off the scene the fall was added to- * (`adoptSceneLight`), never baked in, or a waterfall glows at noon- * values under a moon.- *- * Everything else — foam where it lands, mist off the impact, the- * plunge pool — exists so the fall does not simply END at a seam.- */--import * as THREE from 'three';--import {- instancedQuad, makeShaderMaterial, sweepProfile, tickShaders, keepOutOfDepthPasses } from './shader.js';--// The rig this library ships (`environment.js`): a day key at 5.4 and a-// hemisphere fill at 1.4. Both are DIVISORS below, so what the material-// adopts is a light's strength RELATIVE to daylight, not its raw watts.-const DAY_KEY = 5.4;-const DAY_FILL = 1.4;-// Fallback key direction for a scene with no directional light at all.-const DAY_SUN = new THREE.Vector3(0.42, 0.72, 0.55).normalize();--/**- * Build a waterfall, its plunge pool and its mist.- *- * @param {object} [opts]- * `height` drop in metres (default 8); `width` sheet width at the lip- * (default 3.2); `throw_` how far downstream it lands, defaults to a- * fifth of the height (water leaves a lip with the river's speed);- * `bow` curvature across the sheet in metres (default width/6, 0 for- * flat); `color` deep water colour; `foam` colour of the broken- * water; `mist` billboard count (default 55, 0 to omit); `pool` draw- * the plunge pool (default true); `seed` PRNG seed (default 7).- * The light is taken from the scene unless pinned here: `sunDir`- * (THREE.Vector3 toward the key), `sunColor`, `sky` what the water- * reflects at grazing angles, `ambient` the sky's own fill.- * @returns {THREE.Group} Named `Waterfall`, resting on y = 0, with- * `userData.tick(t)` driving every shader in it.- */-export function makeWaterfall(opts = {}) {- const h = opts.height === undefined ? 8 : opts.height;- const w = opts.width === undefined ? 3.2 : opts.width;- const thr = opts.throw_ === undefined ? h * 0.2 : opts.throw_;- const bow = opts.bow === undefined ? w / 6 : opts.bow;- // Teal, not navy: the water at a lip is a metre of it seen edge-on,- // and a metre of water is green-blue. 0x0d3550 multiplied by a sky- // ambient came out as a black band under the foam.- const deep = opts.color || new THREE.Color(0x11566b);- const foam = opts.foam || new THREE.Color(0xdfeaf1);- const nMist = opts.mist === undefined ? 55 : opts.mist;- const seed = opts.seed === undefined ? 7 : opts.seed;-- // ONE light bundle, shared by the sheet, the pool and the mist:- // three materials that disagree about where the sun is are three- // separate objects standing in the same place.- const light = {- uSun: { value: (opts.sunDir ? opts.sunDir.clone()- : DAY_SUN.clone()).normalize() },- uSunCol: { value: new THREE.Color(- opts.sunColor === undefined ? 0xfff0d8 : opts.sunColor) },- uSky: { value: new THREE.Color(- opts.sky === undefined ? 0x9cc3e2 : opts.sky) },- uAmb: { value: new THREE.Color(- opts.ambient === undefined ? 0x9db8e8 : opts.ambient) },- };-- const g = new THREE.Group();- g.name = 'Waterfall';-- // The sheet. t runs 0 at the lip to 1 at the pool; the fall is- // t-squared in y and linear in z, which is what a projectile does.- const sheet = new THREE.Mesh(- sweepProfile(- (t) => ({ x: 0, y: h - h * t * t, z: thr * t }),- (a, t) => {- const u = Math.cos(a); // -1..1 across the sheet- // Closes into the pool instead of ending as an open- // tube, and the bow is a symmetric arc across the- // width — an asymmetric one grew a beak at the lip.- const k = Math.min(1, (1 - t) / 0.10);- return {- x: u * w * 0.5,- y: 0,- z: Math.sin(a) * (0.18 + 1.5 * t) * (0.12 + 0.88 * k)- + bow * (1 - u * u),- };- },- // 56 around, not 40: the silhouette of a closed shell is- // the outline of its SECTION, and at 40 the near edge of- // the sheet showed its facets as a 6 px staircase from 5 m.- { nu: 56, nv: 64 }),- waterMaterial(deep, foam, light));- sheet.name = 'Sheet';- sheet.renderOrder = 2;- g.add(sheet);-- if (opts.pool !== false) {- const disc = new THREE.Mesh(- new THREE.CircleGeometry(w * 1.15, 48),- poolMaterial(deep, foam, light));- disc.rotation.x = -Math.PI / 2;- disc.position.set(0, 0.02, thr);- disc.name = 'PlungePool';- disc.renderOrder = 1;- g.add(disc);- }-- if (nMist > 0) {- g.add(mistCloud(nMist, w, thr, seed, light));- }-- g.userData.tick = (t) => tickShaders(g, t);- const built = keepOutOfDepthPasses(g);- adoptSceneLight(sheet, light, {- sunDir: opts.sunDir !== undefined,- sunColor: opts.sunColor !== undefined,- sky: opts.sky !== undefined,- ambient: opts.ambient !== undefined,- });- return built;-}--/**- * Take the light from the scene the fall was added to.- *- * All three materials here are UNLIT — every photon in them is written- * out by hand — so a daylight constant baked into the factory is a way- * for the water to disagree with the scene around it: on this- * harness's night rig the old sheet came back at luminance 0.70 over a- * frame whose mean was 0.12, a sheet of white plastic hanging in the- * dark. The key light's direction, colour and strength, the sky half of- * the hemisphere fill and the fog are read at the FIRST render, and- * anything the caller pinned is never overwritten.- *- * `keepOutOfDepthPasses` has already claimed `onBeforeRender` on every- * mesh to guard the override passes, so this CHAINS onto it rather than- * replacing it — replacing it puts the sheet back into ambient- * occlusion as a solid wall.- */-function adoptSceneLight(mesh, u, given) {- const prev = mesh.onBeforeRender;- let done = false;- mesh.onBeforeRender = (renderer, scene, camera, geometry, material,- group) => {- if (prev) prev(renderer, scene, camera, geometry, material, group);- if (done || !scene || !scene.isScene) return;- done = true;- let key = null, hemi = null;- scene.traverse((o) => {- if (o.isDirectionalLight && o.visible && o.intensity > 0- && (!key || o.intensity > key.intensity)) key = o;- if (o.isHemisphereLight && o.visible && o.intensity > 0- && (!hemi || o.intensity > hemi.intensity)) hemi = o;- });- if (key) {- if (!given.sunDir) {- const a = key.getWorldPosition(new THREE.Vector3());- const b = key.target- ? key.target.getWorldPosition(new THREE.Vector3())- : new THREE.Vector3();- const d = a.sub(b);- if (d.lengthSq() > 1e-9) u.uSun.value.copy(d.normalize());- }- if (!given.sunColor) {- u.uSunCol.value.copy(key.color).multiplyScalar(- Math.min(1.35, Math.max(0.12, key.intensity / DAY_KEY)));- }- }- // Water reflects the SKY, not the haze between it and the- // camera: the hemisphere's sky half is that colour in one- // number, and the fog is the fallback for a scene lit some- // other way.- const skyScale = hemi- ? Math.min(1.4, Math.max(0.3, hemi.intensity / DAY_FILL)) : 1;- if (!given.sky && (hemi || scene.fog)) {- u.uSky.value.copy(hemi ? hemi.color : scene.fog.color)- .multiplyScalar(skyScale);- }- if (!given.ambient && hemi) {- u.uAmb.value.copy(hemi.color).lerp(hemi.groundColor, 0.30)- .multiplyScalar(skyScale);- } else if (!given.ambient && scene.fog) {- u.uAmb.value.copy(scene.fog.color);- }- };-}--/** The falling sheet: threads, acceleration, aeration, foam at the foot. */-function waterMaterial(deep, foam, light) {- return makeShaderMaterial({- name: 'WaterfallSheet',- uniforms: Object.assign({- uDeep: { value: deep.clone() },- uFoam: { value: foam.clone() },- }, light),- varyings: 'varying vec2 vUv; varying vec3 vN; varying vec3 vW;',- vertexMain: [- ' vUv = uv;',- // World, not view: both consumers below take a world-space- // view vector, and normalMatrix is the modelVIEW inverse- // transpose — mixing them keys the rim to the camera's yaw.- ' vN = normalize(mat3(modelMatrix) * normal);',- ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uDeep; uniform vec3 uFoam;',- 'uniform vec3 uSun; uniform vec3 uSunCol;',- 'uniform vec3 uSky; uniform vec3 uAmb;',- ].join('\n'),- fragmentMain: [- // v runs 0 at the lip to 1 at the pool, so drop is v.- ' float drop = clamp(vUv.y, 0.0, 1.0);',- ' float age = astraFallAge(drop);',- ' float stag = astraStagger(vUv.x);',- // Threads: high frequency ACROSS the sheet, almost none- // along it, or the strands read as ranks marching at you.- ' float fil = astraStroke(vUv.x * 26.0 + stag * 0.08, 0.34);',- ' float grain = 0.62 + 0.38 * astraStroke(vUv.x * 61.0',- ' + stag * 0.4, 0.42);',- // Travel: the thread pattern itself moves down, or only the- // packet brightness changes and nothing reads as flowing.- ' float travel = 0.42 + 0.58 * astraStroke(',- ' drop * 6.5 - uTime * 2.4 + stag * 0.02, 0.38);',- // Packets ride a constant rate in AGE, so they speed up.- ' float pk = pow(0.5 + 0.5 * sin((age * 7.0 - uTime * 3.1)',- ' * 6.2831 + stag), 3.0);',- ' float body = 0.30 + 0.52 * fil * grain * travel',- ' + 0.24 * pk;',- // WHERE ON THE SECTION this fragment sits. u runs once round- // the closed shell, so |sin| is 1 down the middle of either- // face and 0 at the two side edges — and a fall frays at its- // side edges long before its middle goes white.- ' float faceMid = abs(sin(vUv.x * 6.2831));',- ' float edge = 1.0 - faceMid;',- // AERATION is the one ramp everything below rides. A lip is- // a coherent glass sheet (blue, see-through, mirror-like at- // grazing); a foot is white spray (opaque, matte, lit by- // scatter). Making the whole sheet the second thing is what- // turned this into a white curtain: measured on the close- // camera, mean saturation 0.099 with 24.2% of the sheet's- // pixels above 0.85 luminance — one flat value. With the- // ramp: 0.118 and 0.14%.- ' float aer = clamp(smoothstep(0.16, 0.94, drop)',- ' * (0.45 + 0.55 * body) + 0.10 * pk',- ' + 0.40 * edge * edge, 0.0, 1.0);',- ' float foamK = smoothstep(0.86, 1.0, drop);',- ' vec3 V = normalize(cameraPosition - vW);',- // A closed shell shows its back face half the time, and a- // normal pointing away from the eye dots to zero against- // everything: face the one we can actually see.- ' float far = dot(vN, V) < 0.0 ? 1.0 : 0.0;',- ' vec3 n = normalize(vN) * (far > 0.5 ? -1.0 : 1.0);',- ' float ndl = max(dot(n, uSun), 0.0);',- // BROKEN COLOUR, across the threads rather than along them:- // river water is never one hue, and neither is its foam —- // silt warms it where it is thick, sky cools it where it is- // thin. Two scales so it reads at 20 m and at 2 m.- ' vec3 deepC = astraHueBreak(uDeep,',- ' vec2(vUv.x * 22.0 + stag * 0.02, drop * 3.0), 1.0, 0.75);',- ' deepC = astraHueBreak(deepC, vec2(vUv.x * 5.0, drop), 1.0,',- ' 0.30);',- ' vec3 airC = astraHueBreak(uFoam,',- ' vec2(vUv.x * 9.0, drop * 2.2 - uTime * 0.15), 1.0, 0.30);',- ' vec3 c = mix(deepC, airC, aer);',- ' c = mix(c, airC, foamK * 0.7);',- // Which way a thread is turned decides its colour as much as- // how much air is in it: the half of the shell turned toward- // the key takes its warmth even in shade, the half turned- // away takes the sky. Small (12%), and it is the difference- // between a plume of one grey and a plume with a lit side.- ' float turn = 0.5 + 0.5 * dot(n, uSun);',- ' c *= mix(normalize(uSky + 1e-4) * 1.732,',- ' normalize(uSunCol + 1e-4) * 1.732, turn) * 0.12',- ' + 0.88;',- // The far wall of the shell is seen THROUGH the near one, so- // it must not arrive at the same brightness: two coats of- // white at 0.5 composite to 0.75 and the whole fall reads as- // one opaque lid (this is what the close camera was showing).- ' c *= mix(1.0, 0.78, far);',- // Unlit, so the light is written out ONCE: sky ambient- // everywhere, key where the sheet turns into it. Spray takes- // more of both than deep water does, because light does not- // stop at a cloud's first droplet — the extra 0.40 of- // ambient is that multiple scattering, and it is what makes- // broken water the brightest thing in a shaded gorge.- ' vec3 lit = uAmb * (0.55 + 0.45 * clamp(n.y * 0.5 + 0.5,',- ' 0.0, 1.0) + 0.40 * aer)',- ' + uSunCol * ndl * (0.35 + 0.75 * aer);',- ' c *= lit;',- // The emerald in the lip. Sky enters the top of a coherent- // sheet and leaves through its face a metre later, having- // lost its red on the way — this is the ONE thing that- // makes the upper third of a fall read as water rather than- // as dark glass, and it dies as the water breaks up.- ' c += uAmb * vec3(0.06, 0.26, 0.22) * (1.0 - aer)',- ' * (0.45 + 0.55 * body);',- // TRANSMISSION. The best-looking waterfall in the world is- // a backlit one: the sun behind the sheet scatters forward- // through the air in it and the whole fall lights up. The- // lobe is on the VIEW ray, so it appears exactly when the- // camera is looking through the water at the sun.- ' float fwd = max(dot(-V, uSun), 0.0);',- // What comes through COHERENT water is green — that is the- // colour of a metre of it — and what comes through spray is- // white, because spray is a cloud. One mix, not two terms.- ' c += uSunCol * mix(vec3(0.34, 0.86, 0.74), vec3(1.0), aer)',- ' * pow(fwd, 2.6) * (0.12 + 0.42 * aer)',- ' * (0.35 + 0.65 * body);',- // The sky arrives by REFLECTION with water's own F0 (2%),- // so only a grazing view turns the sheet into a mirror —- // and torn white water is not a mirror at all.- ' float f5 = pow(1.0 - clamp(dot(n, V), 0.0, 1.0), 5.0);',- ' float fr = clamp(0.02 + 0.98 * f5, 0.0, 0.86)',- ' * (1.0 - 0.65 * aer);',- ' vec3 R = reflect(-V, n);',- ' vec3 skyC = mix(uAmb * 0.95, uSky * 1.12,',- ' smoothstep(0.34, 0.78, clamp(R.y * 0.5 + 0.5, 0.0, 1.0)));',- ' c = mix(c, skyC, fr);',- // Threads have GAPS: alpha carries the strands, or the- // sheet is a solid lid with a pattern painted on it.- ' float thread = clamp(0.16 + 0.92 * fil * grain * travel',- ' + 0.22 * pk, 0.0, 1.0);',- ' float veil = smoothstep(0.0, 0.10, drop);',- // A closed shell piles front and back into one pixel at the- // silhouette; without this it stacks into a bright rib.- ' float face = astraFacing(n, cameraPosition - vW);',- // Coherent water is not gauze: a lip is 0.55 opaque and it- // is the THREADS that let the cliff through, not a global- // fade. At 0.30 the upper sheet read as a net curtain.- ' float a = mix(0.55, 0.92, aer) * mix(0.42, 1.0, thread)',- ' * veil * smoothstep(0.04, 0.34, face)',- // Thin where it frays, and the far wall arrives through the- // near one.- ' * mix(0.45, 1.0, smoothstep(0.0, 0.5, faceMid))',- ' * mix(1.0, 0.55, far);',- ' a = mix(a, 0.90, foamK * 0.5);',- // The sweep ends on a straight cut across the pool. Water- // does not: the last fifth of the drop is torn away by its- // own turbulence so the sheet dies INTO the basin rather- // than at a seam the eye finds in one frame.- ' float tear = astraFbm2(vec2(vUv.x * 34.0,',- ' drop * 18.0 - uTime * 2.6), 3);',- ' a *= mix(1.0, clamp(tear * 2.1, 0.0, 1.0),',- ' smoothstep(0.82, 1.0, drop));',- // A sheet is a long smooth ramp in both colour and alpha,- // which is exactly what an 8-bit buffer bands. One LSB of- // ordered-free noise costs nothing and removes the rings.- ' c += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- side: THREE.DoubleSide,- depthWrite: false,- });-}--/** Where it lands: churn at the impact, rings leaving it, sky on top. */-function poolMaterial(deep, foam, light) {- return makeShaderMaterial({- name: 'WaterfallPool',- uniforms: Object.assign({- uDeep: { value: deep.clone() },- uFoam: { value: foam.clone() },- }, light),- varyings: 'varying vec2 vUv; varying vec3 vW;',- vertexMain: [- ' vUv = uv;',- ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',- ].join('\n'),- fragmentHead: [- 'uniform vec3 uDeep; uniform vec3 uFoam;',- 'uniform vec3 uSun; uniform vec3 uSunCol;',- 'uniform vec3 uSky; uniform vec3 uAmb;',- ].join('\n'),- fragmentMain: [- ' float d = length(vUv * 2.0 - 1.0);',- ' if (d > 1.0) discard;',- ' float turb = astraFbm2(vUv * 9.0 + vec2(0.0, uTime * 0.45), 4);',- ' float fine = astraFbm2(vUv * 26.0 - vec2(uTime * 0.7, 0.0), 3);',- ' float rings = 0.5 + 0.5 * sin(d * 22.0 - uTime * 3.0);',- // Churn belongs where the sheet HITS, and it is torn, not a- // wash: the old material mixed 85% of the noise straight to- // foam over the whole disc, which is a lid of grey milk- // sitting on the dirt (measured: saturation 0.17, and the- // deep colour never appeared at all).- ' float impact = 1.0 - smoothstep(0.04, 0.88, d);',- ' float tear = clamp((turb - 0.34) / 0.40, 0.0, 1.0);',- // Foam LEAVES a boil: streaks radiate, so the pattern lives- // in (angle, radius - time) and travels outward. Without- // them the basin is a static stain and the only thing that- // moves in it is a ripple nobody reads at 8 m.- ' vec2 q = vUv * 2.0 - 1.0;',- // The +1e-5 is not decoration: CircleGeometry carries a- // centre vertex at uv (0.5, 0.5), so q is exactly (0, 0)- // there and atan(0, 0) is undefined — one NaN fragment in- // the middle of the boil.- ' float streak = astraFbm2(vec2(atan(q.y, q.x + 1e-5) * 3.6,',- ' d * 5.0 - uTime * 0.55), 3);',- ' float churn = clamp(impact * (0.22 + 0.95 * tear)',- ' + 0.42 * impact * smoothstep(0.34, 0.72, streak)',- ' + 0.24 * tear * rings * (1.0 - smoothstep(0.25, 0.95, d)),',- ' 0.0, 1.0);',- ' vec3 deepC = astraHueBreak(uDeep, vUv * 6.0, 1.0, 0.42);',- ' vec3 foamC = astraHueBreak(uFoam, vUv * 14.0, 1.0, 0.14);',- ' vec3 c = mix(deepC, foamC, churn);',- // Flat water tilted by its own turbulence, so the sun does- // not land as one even sheen over the whole disc.- ' vec3 n = normalize(vec3((fine - 0.375) * 0.9, 1.0,',- ' (turb - 0.375) * 0.9));',- ' vec3 V = normalize(cameraPosition - vW);',- ' float ndl = max(dot(n, uSun), 0.0);',- // Churn is AIR in water: it scatters the sky back out- // instead of swallowing it, so the same ambient buys a lot- // more light there than it does over the deep water.- ' c *= uAmb * (0.80 + 0.95 * churn)',- ' + uSunCol * ndl * (0.30 + 0.70 * churn);',- ' float f5 = pow(1.0 - clamp(dot(n, V), 0.0, 1.0), 5.0);',- ' float fr = clamp(0.02 + 0.98 * f5, 0.0, 0.80)',- ' * (1.0 - 0.6 * churn);',- ' vec3 R = reflect(-V, n);',- ' vec3 skyC = mix(uAmb * 0.95, uSky * 1.12,',- ' smoothstep(0.34, 0.78, clamp(R.y * 0.5 + 0.5, 0.0, 1.0)));',- ' c = mix(c, skyC, fr);',- ' vec3 H = normalize(uSun + V);',- ' c += uSunCol * pow(max(dot(n, H), 0.0), 90.0) * 0.35 * f5;',- // Feathered to nothing at the rim, or the disc draws its own- // circle on the ground.- ' float a = smoothstep(1.0, 0.15, d)',- ' * (0.40 + 0.50 * churn + 0.10 * tear);',- ' c += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',- ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',- ].join('\n'),- transparent: true,- depthWrite: false,- });-}--/** Mist rising off the impact, as GTAO-safe instanced billboards. */-function mistCloud(n, w, thr, seed, light) {- const geom = instancedQuad(n, 1, 1, w * 1.5 + thr);- const s0 = { v: (seed >>> 0) || 1 };- const rnd = () => ((s0.v = (s0.v * 16807) % 2147483647) / 2147483647);- const data = new Float32Array(n * 4);- for (let i = 0; i < n; i++) {- data[i * 4] = (rnd() * 2 - 1) * w * 0.75;- data[i * 4 + 1] = thr + (rnd() * 2 - 1) * w * 0.55;- data[i * 4 + 2] = rnd();- data[i * 4 + 3] = 0.6 + rnd() * 1.7;- }- geom.setAttribute('iSeed', new THREE.InstancedBufferAttribute(data, 4));- // A billboard needs its own gl_Position in view space, which the- // assembled vertex cannot express — so this one is raw, and carries- // the depth and fog chunks itself.- const mat = makeShaderMaterial({- name: 'WaterfallMist',- uniforms: Object.assign({}, light),- vertexShader: [- '#include <common>',- '#include <logdepthbuf_pars_vertex>',- '#include <fog_pars_vertex>',- 'attribute vec3 aCorner;',- 'attribute vec4 iSeed;',- 'uniform float uTime;',- 'varying vec2 vUv;',- 'varying float vLife;',- 'varying float vSeed;',- 'varying vec3 vW;',- 'void main() {',- ' vUv = uv;',- ' float k = fract(iSeed.z + uTime * 0.15);',- ' vLife = k;',- ' vSeed = iSeed.z;',- // Spray off an impact does not rise in a column: it lifts,- // spreads and drifts off downstream as it goes.- ' vec3 c = vec3(iSeed.x + (iSeed.z - 0.5) * k * 1.6,',- ' 0.10 + k * 2.6,',- ' iSeed.y + k * 0.9);',- ' vec4 mvPosition = modelViewMatrix * vec4(c, 1.0);',- ' mvPosition.xy += aCorner.xy * iSeed.w * (0.7 + k * 1.7);',- ' vW = (modelMatrix * vec4(c, 1.0)).xyz;',- ' gl_Position = projectionMatrix * mvPosition;',- '#include <logdepthbuf_vertex>',- '#include <fog_vertex>',- '}',- ].join('\n'),- fragmentShader: [- '#include <common>',- '#include <logdepthbuf_pars_fragment>',- '#include <fog_pars_fragment>',- 'uniform vec3 uSun; uniform vec3 uSunCol;',- 'uniform vec3 uSky; uniform vec3 uAmb;',- 'varying vec2 vUv;',- 'varying float vLife;',- 'varying float vSeed;',- 'varying vec3 vW;',- // The raw route gets no GLSL_UTIL — that is injected only- // into shaders shader.js assembles — so the two lines of- // value noise this needs live here.- 'float wfHash(vec2 p) {',- ' vec3 q = fract(vec3(p.xyx) * 0.1031);',- ' q += dot(q, q.yzx + 33.33);',- ' return fract((q.x + q.y) * q.z);',- '}',- 'float wfNoise(vec2 p) {',- ' vec2 i = floor(p), f = fract(p);',- ' f = f * f * (3.0 - 2.0 * f);',- ' return mix(mix(wfHash(i), wfHash(i + vec2(1.0, 0.0)), f.x),',- ' mix(wfHash(i + vec2(0.0, 1.0)),',- ' wfHash(i + vec2(1.0, 1.0)), f.x), f.y);',- '}',- 'void main() {',- '#include <logdepthbuf_fragment>',- ' float d = length(vUv - 0.5) * 2.0;',- ' float soft = smoothstep(1.0, 0.05, d);',- // A perfect airbrushed disc is a smudge, not spray: break- // the puff with its own noise, coarse enough to survive- // being 40 px wide and different for every instance.- ' float lump = wfNoise(vUv * 3.4 + vSeed * 31.0)',- ' * 0.65 + wfNoise(vUv * 8.0 - vSeed * 17.0) * 0.35;',- ' soft *= 0.45 + 1.05 * lump;',- // Fade IN as well as out: at 0.17 * (1 - life) every puff- // was born at full opacity and popped on the frame it- // appeared, which is the one artefact a still frame shows.- ' float life = smoothstep(0.0, 0.16, vLife)',- ' * (1.0 - smoothstep(0.34, 1.0, vLife));',- ' float a = soft * soft * 0.26 * life;',- ' if (a < 0.004) discard;',- // A cloud of droplets is lit by the SKY from above and lights- // up when the sun is behind it — the same forward lobe the- // sheet uses, so plume and sheet agree about where the sun- // is. Per-puff warmth keeps the plume from being one grey.- ' vec3 V = normalize(vW - cameraPosition);',- ' float fwd = max(dot(V, uSun), 0.0);',- ' vec3 c = uAmb * (1.05 + 0.25 * vSeed)',- ' + uSunCol * (0.18 + 0.85 * pow(fwd, 3.0));',- ' gl_FragColor = vec4(c, a);',- '#include <fog_fragment>',- '}',- ].join('\n'),- transparent: true,- depthWrite: false,- });- const mist = new THREE.Mesh(geom, mat);- mist.name = 'Mist';- mist.frustumCulled = false;- mist.renderOrder = 3;- return mist;-}diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/watermist.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/watermist.jsindex 322f1b2e..a571546b 100644--- a/harness/codeverse/languages/scene_threejs/starter/src/lib/watermist.js+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/watermist.js@@ -35,13 +35,6 @@* toward the water, so a view from above integrates the profile* instead of a single slice of it.*- * `waterfall.js` builds a mist inline (billboards on a fixed rise, one- * plume, no drift). To use these instead: `makeWaterfall({ mist: 0 })`,- * then `makeWaterMist({ extent: width * 4, height: 2.5, drift: [0,- * 0.6], density: 0.6 })` moved to the plunge pool, plus- * `makeSpray({ origin: [0, 0, throw_], radius: width * 0.55 })` for the- * droplets the inline mist never had.- ** Both billboard against the WORLD camera axes, so add them at the* scene root or under a translated parent — a rotated or scaled parent* tilts the cards.diff --git a/harness/codeverse/prompts/scene_threejs/contract.md b/harness/codeverse/prompts/scene_threejs/contract.mdindex 4e65fced..ee5fa285 100644--- a/harness/codeverse/prompts/scene_threejs/contract.md+++ b/harness/codeverse/prompts/scene_threejs/contract.md@@ -8,7 +8,7 @@ src/env.js export const BOUNDS; export function heightAt(x, z); exportsrc/zones/<snake>.js export function build<Zone>(THREE, ctx) → THREE.Group (ctx = { heightAt, loaders, ... })src/assets/<snake>.js export function build<Asset>(THREE, opts = {}) → THREE.Group (procedural, Y-up, on y = 0)src/shaders/<snake>.js export function make<Name>Material(THREE, opts = {}) → THREE.ShaderMaterial | patched material-src/lib/*.js HARNESS-OWNED effect library (52 modules) — import and call, never rewrite+src/lib/*.js HARNESS-OWNED effect library (44 modules) — import and call, never rewritepublic/assets/<snake>.glb (optional) Blender-built assets — the assembled scene.js preloads each into ctx.assets['<snake>']; zones clone it (its clips play by themselves)```The harness serves the workspace root over http (`public/assets/` is mounted atdiff --git a/harness/codeverse/prompts/scene_threejs/effects_catalog.md b/harness/codeverse/prompts/scene_threejs/effects_catalog.mdindex a2d1ab0d..0a48cb3a 100644--- a/harness/codeverse/prompts/scene_threejs/effects_catalog.md+++ b/harness/codeverse/prompts/scene_threejs/effects_catalog.md@@ -1,6 +1,6 @@# The shipped effect library — call these before writing your own-`src/lib/` is in your workspace already: 52 modules, every one of them compiled+`src/lib/` is in your workspace already: 44 modules, every one of them compiledand rendered on THIS renderer. They carry the depth and fog chunks ahand-written shader silently loses, and they are not an outside package — theyare harness code shipped into the workspace, so importing them is allowed where@@ -25,15 +25,12 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says| midges, butterflies, fireflies; reeds in water | `makeInsects` · `makeReeds` — `lib/smalllife.js` || birds or fish in motion | `makeFlock({ count, kind, extent, height, path })` — `lib/flock.js` || a sizeable water body | `makeOcean(w, d, { sunDir })` — `lib/water.js`; ONE reflective surface per scene |-| a river, a stream, a creek | `makeRiver({ points, width, depth, flow, heightAt })` — `lib/river.js`; a WATERCOURSE, which `makeOcean` is not: a sea-sized plane at one level floods relief terrain into islands |-| falling water | `makeWaterfall({ height, width, throw_, bow, color, foam, mist })` — `lib/waterfall.js` || mist over moving water, spray where it lands | `makeWaterMist` · `makeSpray` — `lib/watermist.js` || a waterline | `patchShoreWet` · `patchShoreFoam` · `patchShallowWater` — `lib/waterside.js` || anything BELOW the water, rain rings, thin ice | `patchUnderwater` · `makeRainRings` · `patchThinIce` — `lib/submerged.js` || the moving net of light under water | `patchCaustics(material, { level, sunDir })` — `lib/caustics.js`; goes on the surface being LIT, not on the water || moss, damp near water, dried mud | `patchMoss` · `patchMoisture` · `patchCrackedMud` — `lib/damp.js` || a polished or wet floor | `makeMirrorFloor(w, d)` — `lib/wetground.js`; spends the same one-RTT budget as `makeOcean` |-| a mirror, a glazed facade | `makeMirror` · `envMirrorMaterial` — `lib/mirror.js` || rock, cliff, ground | `patchTriplanar` · `patchSlopeSplat` — `lib/terrain_shade.js` || ground and cliff geometry | `ground({ size, heightAt })` · `cliff` — `lib/terrain.js` || placing a camera or a prop by intent | `seat` · `establishingShot` · `faceToward` · `alongPath` · `crowdOn` — `lib/place.js` |@@ -50,12 +47,9 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says| rain sheets at distance, snowfall, motes | `makeRainVeil` · `makeSnowfall` · `makeMotes` — `lib/veils.js`; weather you see ACROSS the valley, not the drops by the lens || rain, splashes, puddles | `makeRain` · `makeSplashes` · `wetten` · `makePuddle` — `lib/rain.js` || snow or drifted sand lying on things | `patchSnow` · `patchSand` — `lib/accumulation.js`; one deposit rule across the whole scene is what makes weather read |-| the season, and the hour of the day | `patchSeasonTint` · `dayCycle(rig, { hour })` — `lib/season.js`; `dayCycle` returns a pose to apply, and at night `elevation` goes negative while `keyElevation` is the moon you light from || a building, a cottage, a city block | `block` · `cottage` · `cityFabric` — `lib/building.js` || lit windows at night | `makeNightWindows(mesh)` · `patchWindowInteriors` — `lib/windows.js` || a glazed facade, power lines, a hoarding | `patchCurtainWall` · `makePowerLines` · `makeBillboard` — `lib/urban.js`; the facade spends no second render target |-| a room that is LIT, smudged glass, a distant crowd | `patchBounceLight` · `patchFingerprints` · `makeCrowdImposters` — `lib/indoor.js`; bounce is what makes an interior read as lit rather than filled with ambient |-| a glowing panel or sign | `makePanelLight(w, h, color, intensity)` — `lib/lights.js`; `color` takes a LIGHT_CLASSES name — `'sodium'`, `'tungsten'`, `'fluorescent'`, `'led_cool'`… — and the class SPLIT (sodium road, tungsten homes, fluorescent shop) is what makes a night street read; `kelvinColor(k)` for anything else || a neon sign, and the light it throws | `makeNeonTube` · `patchNeonSpill` · `makeLightTrails` — `lib/neon.js`; a sign that does not light its own wall is a decal || readable lettering on a sign | `makeText` (async — await ONCE at module top level, `.clone()` per copy) — `lib/signage.js` || a road, a path, a worn surface | `patchRoadSurface` · `patchSeamBand` · `patchTracks` — `lib/roadway.js` |@@ -63,8 +57,7 @@ says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says| a surface that has stood somewhere | `patchDripStains` · `patchRust` · `patchDust` — `lib/aging.js` || any surface at all | `patchMicroBreakup` · `patchEdgeWear` — `lib/surface_wear.js` || paper, wax, jade, petals; oil film, beetle shell | `patchTranslucency` · `patchIridescence` — `lib/finish.js` |-| a person, an animal | `figure({ pose })` · `sit` · `walk` · `carry` — `lib/figure.js` · `creature` · `ear` · `tail` · `attach` — `lib/creature.js` |-| scattering many copies over ground | `scatter({ count, extent, heightAt, make })` — `lib/scatter.js` |+| a person | `figure({ pose })` · `sit` · `walk` · `carry` — `lib/figure.js` || the same asset hundreds of times, in one draw call | `instanceAsset` · `scatterGrid` — `lib/instancing.js` · `mergeStatic(meshes)` — `lib/merge.js` || a textured standard material without a texture file | `brick` · `granite` · `cobble` · `asphalt` · `weatheredWood` · `brushedSteel` · `fabric` · `foliage` · `soil` · `skin` · `glass` (21 in all) · `tint(mat, variant)` — `lib/materials.js` || noise on the CPU (heightfields the shader must agree with) | `fbm2` · `fbm3` · `mulberry32` · `displaceY` — `lib/noise.js` |diff --git a/harness/docs/ARCHITECTURE.md b/harness/docs/ARCHITECTURE.mdindex ed45d544..e30f19eb 100644--- a/harness/docs/ARCHITECTURE.md+++ b/harness/docs/ARCHITECTURE.md@@ -326,10 +326,10 @@ summary:* **scene_threejs**: `src/scene.js` `createScene({THREE, renderer, loaders}) → {scene, cameras, update(t,dt)}`;`src/env.js`, `src/zones/*.js`, `src/assets/*.js`, `src/shaders/*.js`; GLBs at`public/assets/<name>.glb`. The harness assembles `scene.js` deterministically.- Plus the harness-owned, read-only **effect library** `src/lib/*.js` — 52 modules,- 28.8k lines, shipped into every workspace by BOTH skeleton paths and listed in+ Plus the harness-owned, read-only **effect library** `src/lib/*.js` — 44 modules,+ 24.8k lines, shipped into every workspace by BOTH skeleton paths and listed in`HARNESS_OWNED_SRC` so agent writes to it are reverted (D51). The starter tree is- therefore 60 `.js` files / 29.3k lines, of which 8 are the example scene. The+ therefore 52 `.js` files / 25.2k lines, of which 8 are the example scene. Thewant → call table the prompts carry is `prompts/scene_threejs/effects_catalog.md`.* **glsl_shader**: `src/shader.frag` (+ optional `src/common.glsl`,`src/buffer_a.frag` for feedback; the harness-owned, read-only `src/recipes.glsl`diff --git a/harness/docs/INTERFACES.md b/harness/docs/INTERFACES.mdindex 5167fbdc..50de1aea 100644--- a/harness/docs/INTERFACES.md+++ b/harness/docs/INTERFACES.md@@ -186,7 +186,7 @@ session may read but never write — `contracts.common.HARNESS_OWNED_SRC[languagsets it on every job of the run and `agents/cli_common._enforce_scope` reverts apost-session write to one and fails that session. **Δ** an entry ending in `/` is aDIRECTORY prefix — `contracts.common.is_harness_owned(rel, owned)` is the predicate, and-it is what names the 52-module effect library without listing 52 paths). **Δ legacy lift**: the job keys (`round`, `kind`, `language`,+it is what names the 44-module effect library without listing 44 paths). **Δ legacy lift**: the job keys (`round`, `kind`, `language`,`track`, `files_hint`, `mcp_command`) passed inside `extra={...}` are lifted intothe typed fields at validation (extra itself is left untouched), so old constructorsand serialized jobs keep working; `extra` stays for one-off backend hints.diff --git a/harness/tests/scene_runtime/lib/test_building.py b/harness/tests/scene_runtime/lib/test_building.pyindex 7cce63ef..e31e49a9 100644--- a/harness/tests/scene_runtime/lib/test_building.py+++ b/harness/tests/scene_runtime/lib/test_building.py@@ -193,7 +193,7 @@ def test_a_facade_has_walls_trim_glazing_and_a_dark_interior(facade):"""Four named parts, because the complaints name four things.Unlit, the two glazing batches collapse to whichever ones drew — the- part names an agent (and mirror.js's glazeFacade) targets are stable.+ part names an agent targets are stable."""m = facadefor part in ("Walls", "Trim", "Glazing", "Reveals"):@@ -358,8 +358,8 @@ def test_lit_windows_stay_in_the_bloom_friendly_band(lit_block):def test_lit_windows_are_not_matched_by_the_mirror_sweep(lit_block):- """mirror.js `glazeFacade` retargets every `/glaz|pane/i` mesh and- documents that lit windows are left glowing. Naming the lit cards+ """mirror.js `glazeFacade` (removed, D74) retargeted every `/glaz|pane/i`+ mesh and documented that lit windows are left glowing. Naming the lit cards`LitGlazing` (as cottage did) walked them straight into that sweep."""m = lit_blockimport re@@ -692,7 +692,7 @@ def test_a_village_can_afford_a_cottage(cot):def test_cottage_lit_rooms_are_their_own_meshes(cot):"""Its lit panes used to be named `LitGlazing`, which walks straight into- mirror.js `glazeFacade`'s `/glaz|pane/i` sweep."""+ a `/glaz|pane/i` sweep (mirror.js `glazeFacade`, removed in D74)."""m = cotlit = [n for n in m["litNames"] if n.startswith("LitRooms")]assert lit, m["litNames"]diff --git a/harness/tests/scene_runtime/lib/test_creature.py b/harness/tests/scene_runtime/lib/test_creature.pydeleted file mode 100644index 6aadb72f..00000000--- a/harness/tests/scene_runtime/lib/test_creature.py+++ /dev/null@@ -1,390 +0,0 @@-"""Cartoon creatures are their own shape, not small humans.--Cute-ifying figure.js's 7.5-head human yields a small adult; head 40-50%-of height, egg body and three-layer wide-low eyes are what read as alive.--Ported from the scene_multifile_graphics reference (tests/test_creature_lib.py)-and extended with what this port had to fix on OUR renderer: albedos inside-the band ACES at exposure 1 can light, colour graded BETWEEN parts instead of-one flat value, a belly patch that stands proud of the torso rather than-z-fighting along it, tails scaled by the creature rather than by a serpent's-1.5x body depth, and a curl tail that is one piece instead of seven balls.-"""--from __future__ import annotations--import pytest--from tests.scene_runtime.lib._probe import measure--pytestmark = pytest.mark.node---_PROBE = """-import * as THREE from 'three';-import { creature, ear, tail, cheeks, walk, idle } from './lib/creature.js';--const rand = (() => { let s = 5;- return () => (s = (s * 16807) % 2147483647) / 2147483647; })();--const c = creature({ height: 0.45, body: 'biped', bodyColor: 0xf5d547,- bellyColor: 0xfff0a8, rand });-ear(c, { type: 'point', length: 0.9, tipColor: 0x2b2b2b });-tail(c, { type: 'bolt' });-cheeks(c, 0xe8543f);-c.updateMatrixWorld(true);--const whole = new THREE.Box3().setFromObject(c);-const named = {};-c.traverse((o) => {- if (!o.name) return;- const b = new THREE.Box3().setFromObject(o);- if (!b.isEmpty()) named[o.name] = {- c: b.getCenter(new THREE.Vector3()).toArray(),- s: b.getSize(new THREE.Vector3()).toArray(),- };-});-const triCount = (o) => o.geometry.index ? o.geometry.index.count / 3- : o.geometry.attributes.position.count / 3;-let tris = 0;-c.traverse((o) => { if (o.isMesh) tris += triCount(o); });--// Eye layer count: sclera + iris + glint = 3 meshes under each eye.-let eyeMeshes = 0;-c.traverse((o) => { if (o.name === 'eyeL') o.traverse((m) => {- if (m.isMesh) eyeMeshes++; }); });--// A quadruped's legs must alternate diagonally, never in lockstep.-const q = creature({ height: 0.7, body: 'quadruped' });-walk(q, 0.11);-const j = q.userData.joints;-const diag = [j.legFL.rotation.x, j.legBR.rotation.x];-const other = [j.legFR.rotation.x, j.legBL.rotation.x];--// The three eye layers must be visible FROM THE FRONT, not merely-// present: they shipped with the iris and glint at +Z, behind the-// eyeball, and every creature had two blank white blobs for eyes.-const ray = new THREE.Raycaster();-const wpos = (o) => new THREE.Vector3().setFromMatrixPosition(o.matrixWorld);-let eyeObj = null, cheekObj = null;-c.traverse((o) => { if (o.name === 'eyeL') eyeObj = o;- if (o.name === 'cheekL') cheekObj = o; });-const pe = wpos(eyeObj);-ray.set(new THREE.Vector3(pe.x, pe.y, -5), new THREE.Vector3(0, 0, 1));-const eyeHit = ray.intersectObject(c, true)[0];-const irisFirst = eyeHit- ? eyeHit.object.material.color.getHexString() : null;-let cheekFirst = null;-if (cheekObj) {- const pc2 = wpos(cheekObj);- ray.set(new THREE.Vector3(pc2.x, pc2.y, -5), new THREE.Vector3(0, 0, 1));- const h = ray.intersectObject(c, true)[0];- if (h) { let o = h.object; while (!o.name && o.parent) o = o.parent;- cheekFirst = o.name; }-}--// Idle must actually move something -- and must not stretch the skull-// with the chest, which is what scaling the shared body pivot did.-const i0 = creature({ height: 0.5 });-const restY = i0.userData.joints.head.rotation.y;-idle(i0, 1.3);-const idleY = i0.userData.joints.head.rotation.y;-i0.updateMatrixWorld(true);-const headScaleY = new THREE.Vector3().setFromMatrixScale(- i0.userData.joints.head.matrixWorld).y;--// ALBEDO BAND. A cartoon palette is written as ink; at exposure 1 with-// no post chain, a 0.99 sclera clips to paper and a 0x151515 pupil has-// no linear lightness for the sun to lift. Every non-emissive surface-// has to land inside 0.02..0.80 linear lightness.-const albedo = [];-const emissives = [];-const seen = new Set();-for (const o of [c, q]) o.traverse((m) => {- if (!m.isMesh || seen.has(m.material.uuid)) return;- seen.add(m.material.uuid);- const mt = m.material;- const hsl = mt.color.getHSL({ h: 0, s: 0, l: 0 });- const lit = mt.emissive && mt.emissive.getHex() !== 0- && mt.emissiveIntensity > 0;- if (lit) emissives.push(mt.emissiveIntensity);- else albedo.push(+hsl.l.toFixed(4));-});--// COLOUR GRADED BETWEEN PARTS: head, torso and limb are one hue family-// at three lightnesses, not one flat value repeated.-const lin = (mesh) => {- let m = null;- c.traverse((o) => { if (o.name === mesh) o.traverse((x) => {- if (x.isMesh && !m) m = x.material; }); });- return m ? m.color.getHSL({ h: 0, s: 0, l: 0 }) : null;-};-const headL = lin('headMesh'), torsoL = lin('torso'), legL = lin('legMeshL');--// The BELLY PATCH has to stand clearly proud of the torso. Expressed in-// the torso ellipsoid's own normalised space, its front pole was at-// 1.04 -- near-tangent over a wide ring, which renders as a band of-// z-fighting speckle instead of a bib.-let torsoM = null, bellyM = null;-c.traverse((o) => { if (o.name === 'torso') torsoM = o;- if (o.name === 'belly') bellyM = o; });-const bellyProud = (Math.abs(bellyM.position.z - torsoM.position.z)- + bellyM.scale.z * 0.5) / (torsoM.scale.z * 0.5);--// A LEGLESS body still rests on y = 0 (the torso sphere is scaled 1.12-// about its own centre, so it used to dip below the pivot).-const serp = creature({ height: 1.0, body: 'serpent' });-tail(serp, { type: 'fin', length: 1.2 });-serp.updateMatrixWorld(true);-const sBox = new THREE.Box3().setFromObject(serp);-let serpTailH = 0;-serp.traverse((o) => { if (o.name === 'tail') {- const b = new THREE.Box3().setFromObject(o);- serpTailH = b.max.y - b.min.y; } });--// The CURL tail is one connected piece, not a row of separated balls.-const cu = creature({ height: 0.7, body: 'quadruped' });-tail(cu, { type: 'curl' });-let curlMeshes = 0, curlTris = 0;-cu.userData.joints.tail.traverse((o) => {- if (o.isMesh) { curlMeshes++; curlTris += triCount(o); } });--// A `long` ear's coloured tip must CAP the cone it sits on, never flare-// out of it -- it shipped with fixed radii and read as a wedge.-// ONE ear: measured across both, the two shafts pair off against each-// other and the ratio is 1 whatever the tip does.-const le = creature({ height: 0.6 });-ear(le, { type: 'long', length: 1.2, tipColor: 0xffd9a0 });-let earL = null;-le.userData.joints.head.traverse((o) => { if (o.name === 'earL') earL = o; });-const cyl = [];-earL.traverse((o) => {- if (o.isMesh && o.geometry.parameters- && o.geometry.parameters.radiusBottom !== undefined) {- cyl.push({ p: o.geometry.parameters, y: o.position.y });- }-});-cyl.sort((a, b) => b.p.height - a.p.height);-let tipShaft = null;-if (cyl.length === 2) {- const shaft = cyl[0].p, tip = cyl[1];- const y0 = tip.y - tip.p.height / 2;- const rAt = shaft.radiusBottom- + (shaft.radiusTop - shaft.radiusBottom) * (y0 / shaft.height);- tipShaft = tip.p.radiusBottom / rAt;-}--console.log(JSON.stringify({- height: whole.max.y - whole.min.y,- hUser: c.userData.height,- baseY: whole.min.y,- headH: named.headMesh ? named.headMesh.s[1] : null,- headRatio: named.headMesh- ? named.headMesh.s[1] / c.userData.height : null,- eyeL: named.eyeL ? named.eyeL.c : null,- eyeR: named.eyeR ? named.eyeR.c : null,- eyeMeshes,- headCy: named.headMesh ? named.headMesh.c[1] : null,- hasTail: !!named.tail,- hasEars: !!named.earL && !!named.earR,- hasCheeks: !!named.cheekL,- bodyW: named.torso ? named.torso.s[0] : null,- bodyH: named.torso ? named.torso.s[1] : null,- forward: c.userData.forward,- tris,- diagLockstep: Math.abs(diag[0] - diag[1]) < 1e-9,- gaitOpposed: diag[0] * other[0] < 0,- idleMoves: Math.abs(idleY - restY) > 1e-6,- headScaleY,- irisFirst,- cheekFirst,- albedoMin: Math.min(...albedo),- albedoMax: Math.max(...albedo),- emissives,- headL: headL ? +headL.l.toFixed(4) : null,- torsoL: torsoL ? +torsoL.l.toFixed(4) : null,- legL: legL ? +legL.l.toFixed(4) : null,- headHue: headL ? +headL.h.toFixed(4) : null,- legHue: legL ? +legL.h.toFixed(4) : null,- bellyProud: +bellyProud.toFixed(3),- serpBaseY: sBox.min.y,- serpH: serp.userData.height,- serpTailH,- curlMeshes,- curlTris,- tipShaft: tipShaft === null ? null : +tipShaft.toFixed(3),-}));-"""--[email protected](scope="module")-def probe() -> dict:- """One node launch of _PROBE, shared by every test that reads it."""- return measure(_PROBE, ("creature.js", "materials.js"))---def test_the_head_is_oversized_the_way_a_cartoon_creature_is(probe):- """40-50% of total height. A human is 13%.-- This single number is what separates a creature from a small adult,- and it is the thing a builder gets wrong when handed figure.js.- """- assert 0.36 < probe["headRatio"] < 0.56, probe["headRatio"]---def test_the_eyes_have_three_layers(probe):- """Sclera, iris, and an offset glint.-- A sphere with two flat dark dots is exactly what makes a low-poly- creature read as a toy instead of as something alive.- """- assert probe["eyeMeshes"] == 3, probe["eyeMeshes"]---def test_the_pupil_is_what_the_camera_sees_first(probe):- """Layers present is not layers visible: a front ray must hit the iris.-- The iris/glint shipped at +Z, behind the eyeball (creatures face -Z);- the owner caught it on a blank-eyed mascot while every test passed.- """- r, g, b = (int(probe["irisFirst"][i:i + 2], 16) for i in (0, 2, 4))- assert max(r, g, b) < 90, (- f"the frontmost thing at the eye centre is #{probe['irisFirst']}, "- "not a dark pupil")---def test_the_cheek_patch_is_on_the_skull_not_inside_it(probe):- """At x = 0.74r the sphere surface is only at z = -0.67r.-- The patch sat at -0.56r and was half buried, showing as two red- slivers beside the eyes instead of round cheeks.- """- assert probe["cheekFirst"] == "cheekL", probe["cheekFirst"]---def test_the_eyes_are_wide_and_low_on_the_head(probe):- """High close-set eyes read adult; low wide eyes read young."""- gap = abs(probe["eyeL"][0] - probe["eyeR"][0])- assert gap > 0.25 * probe["headH"], f"eyes too close together: {gap}"- assert probe["eyeL"][1] < probe["headCy"] + 0.02, "eyes above head centre"- assert probe["eyeL"][2] < 0, "eyes must face -Z, the creature's forward"---def test_the_body_is_an_egg_not_a_torso(probe):- """Wider than it is tall is the round silhouette."""- assert probe["bodyW"] > probe["bodyH"] * 0.85, (probe["bodyW"],- probe["bodyH"])---def test_attachments_land_and_are_findable(probe):- assert probe["hasEars"] and probe["hasTail"] and probe["hasCheeks"], probe---def test_it_rests_on_zero_and_faces_minus_z(probe):- """Same contract as every other asset, so place.js works on it."""- assert abs(probe["baseY"]) < 0.02, probe["baseY"]- # The bbox includes the ears, which stand above the skull.- assert abs(probe["hUser"] - 0.45) < 0.05, probe["hUser"]- assert probe["height"] >= probe["hUser"] * 0.95, (probe["height"],- probe["hUser"])- assert probe["forward"] == "-Z"---def test_a_legless_body_rests_on_the_ground_too(probe):- """A serpent's torso is scaled 1.12 in Y about its own centre.-- Taken from the pivot, its underside dips 6% of the body height below- zero, and the animal shipped buried to the waist.- """- assert abs(probe["serpBaseY"]) < 0.02 * probe["serpH"], probe["serpBaseY"]---def test_a_quadruped_walks_on_diagonal_pairs(probe):- """Legs moving in lockstep is the classic toy-animal tell."""- assert probe["diagLockstep"], "diagonal pairs must move together"- assert probe["gaitOpposed"], "the other diagonal must be out of phase"---def test_idle_actually_moves_something(probe):- """A perfectly still creature is a statue in every judged frame."""- assert probe["idleMoves"]---def test_idle_breathes_with_the_chest_and_not_with_the_skull(probe):- """The head is a CHILD of the body pivot that idle() squashes.-- Without the counter-scale the face pulses along with the chest,- which reads as a bug in every frame the judge sees. It cancels to- 1e-4 rather than exactly, because idle also TILTS the head and a- rotated child under a non-uniform parent scale is sheared, not- scaled; the defect this guards is 3.5%, two orders above that.- """- assert abs(probe["headScaleY"] - 1) < 2e-3, probe["headScaleY"]---def test_a_village_can_afford_a_crowd_of_them(probe):- assert probe["tris"] < 6000, probe["tris"]---def test_every_albedo_is_inside_the_band_this_renderer_can_light(probe):- """No post chain: ACES at exposure 1 clips a 0.99 sclera to paper.-- And a near-black pupil has no linear lightness left for the sun to- lift, so it reads as a hole punched in the face rather than an eye.- """- assert probe["albedoMin"] >= 0.02, probe["albedoMin"]- assert probe["albedoMax"] <= 0.80, probe["albedoMax"]---def test_emissives_stay_in_the_bloom_friendly_band(probe):- """1.5-4: below it the tone map folds the highlight into its own- surface, above it every emissive is the same white blob."""- assert probe["emissives"], "the eye glint is emissive"- assert all(1.5 <= e <= 4.0 for e in probe["emissives"]), probe["emissives"]---def test_the_parts_are_graded_not_one_flat_value(probe):- """Face at the author's colour, chest under it, limbs under that.-- A painter does this on every toy; the renderer will not invent it,- and without it a body is one flat value with a shadow on it.- """- assert probe["headL"] > probe["torsoL"] > probe["legL"], probe- assert probe["headL"] - probe["legL"] > 0.04, probe- # ... and the hue moves too: shaded parts go cool, not just dark.- assert abs(probe["headHue"] - probe["legHue"]) > 0.004, probe---def test_the_belly_patch_stands_proud_of_the_torso(probe):- """Two near-tangent ellipsoids render as a ring of z-fight speckle.-- At the shipped depth the bib's front pole reached 1.04 of the torso- radius and its edge was noise, not an outline.- """- assert probe["bellyProud"] > 1.10, probe["bellyProud"]---def test_a_tail_is_scaled_by_the_creature_not_by_its_body_depth(probe):- """A serpent's bodyD is 1.5x its height.-- Taken neat as the tail's span it gave a 1.9 m serpent a 3.4 m fin —- a pyramid taller than the animal wearing it.- """- assert probe["serpTailH"] < probe["serpH"], (probe["serpTailH"],- probe["serpH"])---def test_the_curl_tail_is_one_piece(probe):- """Seven separated balls read as a bubble trail leaving the animal.-- One tapered tube also costs 400 triangles instead of 980.- """- assert probe["curlMeshes"] <= 2, probe["curlMeshes"]- assert probe["curlTris"] < 700, probe["curlTris"]---def test_a_long_ears_tip_caps_the_cone_it_sits_on(probe):- """Fixed tip radii flared out of a `long` ear (0.087 hr wide there)- and read as a coloured wedge stuck between the ears."""- assert probe["tipShaft"] is not None- assert probe["tipShaft"] <= 1.1, probe["tipShaft"]diff --git a/harness/tests/scene_runtime/lib/test_foliage_shade.py b/harness/tests/scene_runtime/lib/test_foliage_shade.pyindex c3274c2c..cbecf082 100644--- a/harness/tests/scene_runtime/lib/test_foliage_shade.py+++ b/harness/tests/scene_runtime/lib/test_foliage_shade.py@@ -271,7 +271,7 @@ def test_wind_reaches_an_instanced_mesh_and_a_plain_mesh_alike():in at <begin_vertex>, so world space here is hand-built behind aUSE_INSTANCING guard — and three declares that attribute itself, so asecond declaration would fail every instanced plant. The wind direction- is carried into the plant's own frame too: scatter.js yaws every instance,+ is carried into the plant's own frame too: a scatter yaws every instance,and an object-space wind would blow a different way for each one."""out = _probe("""const m = std();diff --git a/harness/tests/scene_runtime/lib/test_indoor.py b/harness/tests/scene_runtime/lib/test_indoor.pydeleted file mode 100644index 36d4c1c5..00000000--- a/harness/tests/scene_runtime/lib/test_indoor.py+++ /dev/null@@ -1,798 +0,0 @@-"""An interior that is LIT, the surfaces hands have been on, and a crowd.--Ported from the reference suite 2026-09-01. `indoor.js` answers three-failures. A room filled with ambient reads as a MODEL of a room: nothing-bleeds, so a white ceiling beside a red wall stays white and the eye is-told there is no light in here, only exposure. A pane nobody has touched-says the same about the props. A square with nobody in it is a set.--Each export loses its whole point if one property goes. The bounce must-fall to EXACTLY zero at its reach — a wash that never ends is ambient-again, the thing it replaces — and it must be LIGHT, because an albedo-lift is capped at what already lands on the surface and the shaded soffit-that needs it most would take none. The smudge must move GLOSS and not-colour, or it is a stain. The crowd must stay one draw call, seated on-the ground, and out of the override passes that draw a transparent card-as a solid wall.--THE PORT'S OWN LAWS, each measured on our host (fx/out/indoor/, exposure-1.0, no post chain) against a control render of the same frame with the-patches off:--1. A PLANE'S FORM FACTOR IS THE UN-SQUARED HALF-LAMBERT. Squaring it is- exact for neither limit of a Lambertian half-space: a ceiling facing a- lit floor sees it over its whole hemisphere (factor 1, which squaring- also gives) and a WALL over exactly half of it (factor 0.5, where- squaring gives 0.25). The wall above a floor is the geometry every- room has, and it was getting half its bleed. Measured on the white- plaster of the showcase loggia, mean absolute difference against the- unpatched control: skirting 3.22 -> 5.74 (close) and 3.87 -> 6.91- (mid) of 255, red-rug bleed 4.34 -> 7.55, and the SOFFIT — the- parallel case, already correct — 1.86 -> 2.14, unchanged as the- theory says it must be.--2. A WASH THAT KEEPS ITS HUE TO THE LAST CENTIMETRE IS A LAMP. Light- that has travelled further has bounced off more than one thing, so the- tint desaturates across the reach (32% at the far edge).--3. BOUNCE IS THE SMOOTHEST GRADIENT IN A ROOM. On the widest flat it- lands on it climbs the 8-bit ladder in bands; half a code of hashed- dither, only where there is bleed, took the gradient strip from 136 to- 156 distinct colours (row-to-row noise 0.452 -> 0.566).--4. GREASE IS A FILM WITH RIDGES, NOT A SET OF STRIPES. With the arcs- alone a touched pane is a few bright bands on clean glass and the eye- reads bands as paint. The film term took the smudge on the showcase's- polished counter from 0.91 to 3.01 mean absolute difference and from- 23% to 55% of the surface changed by more than 1/255.--5. A BACKLIT CARD IS A SILHOUETTE WITH A LIT EDGE. A crowd with the sun- behind it had a hard `max(dot, 0)` terminator on a coarse bowed- normal, so every figure printed as one flat ambient tone. Wrapped- diffuse plus a rim on the sun-side edge: the darkest crowd pixels rose- from 15.9 to 24.7 of 255, distinct colours over the crowd from 4337 to- 4726. Plus per-person VALUE (a street is pale coats and dark ones,- not one value in two hues) and a `legColor` default off the floor —- an albedo under about 0.02 linear is a hole no light reopens.-"""--from __future__ import annotations--import re--from tests.scene_runtime.lib._probe import LIB_DIR, compile_scene, measure--_LIBS = ("shader.js", "noise.js", "indoor.js", "surface_wear.js")-_SRC = LIB_DIR / "indoor.js"--# One material carrying BOTH patches under two more from another library —-# the GLSL namespace collision that only shows up when three libraries share-# one material — plus an InstancedMesh (whose world position needs-# instanceMatrix folded in by hand) and the crowd field.-_BODY = """- const mat = new THREE.MeshStandardMaterial({- color: 0xd8d2c6, roughness: 0.45, metalness: 0.1 });- patchMicroBreakup(mat, { scale: 0.6, strength: 0.12, seed: 5 });- patchEdgeWear(mat, { strength: 0.4, seed: 6 });- patchBounceLight(mat, {- sources: [{ position: [-3, 1.4, 0], normal: [1, 0, 0],- color: 0xa8201a, reach: 3.5 },- { position: [0, 0, 0], normal: [0, 1, 0],- color: 0x3f7a2a, reach: 2.2 },- { position: [2, 0.8, 1], color: 0xffcc88, reach: 1.5 }],- up: [0, 1, 0], strength: 1.2 });- patchFingerprints(mat, { amount: 0.6, smear: 0.4, seed: 3 });- const wall = new THREE.Mesh(new THREE.BoxGeometry(6, 3, 0.3), mat);- wall.position.set(0, 1.5, -2);- HOST.add(wall);- const posts = new THREE.InstancedMesh(- new THREE.BoxGeometry(0.12, 1.1, 0.12), mat, 8);- const m4 = new THREE.Matrix4();- for (let i = 0; i < 8; i++) {- m4.makeTranslation(-3 + i * 0.9, 0.55, 0.6);- posts.setMatrixAt(i, m4);- }- posts.instanceMatrix.needsUpdate = true;- HOST.add(posts);- HOST.add(makeCrowdImposters({- count: 40, extent: 20, heightAt: (x, z) => 0.05 * Math.sin(x * 0.3),- seed: 5 }));-"""--# A SCENE, not an asset: the reference's asset mode built its own unfogged,-# point-light-free scene, so USE_FOG was never defined and NUM_POINT_LIGHTS-# was zero — two whole branches of this library never reached a compiler.-# A room is exactly where both exist. Ours boots a scene either way, so the-# two reference compile tests are one test here.-_SCENE = """-import * as THREE from 'three';-import { makeCrowdImposters, patchBounceLight, patchFingerprints }- from './lib/indoor.js';-import { patchEdgeWear, patchMicroBreakup } from './lib/surface_wear.js';--export const BOUNDS = { min: [-20, 0, -20], max: [20, 20, 20] };-export function heightAt() { return 0; }--export async function createScene() {- const scene = new THREE.Scene();- scene.fog = new THREE.FogExp2(0xb9c6d4, 0.012);- scene.add(new THREE.HemisphereLight(0xc8d6e6, 0x8a8478, 1.0));- const sun = new THREE.DirectionalLight(0xfff1da, 2.4);- sun.position.set(14, 9, 5);- scene.add(sun);- const lamp = new THREE.PointLight(0xfff4e2, 30, 0, 2);- lamp.position.set(1.2, 2.4, 2.0);- scene.add(lamp);-""" + _BODY.replace("HOST", "scene") + """- return {- scene,- cameras: [{ name: 'a', position: [8, 4, 10], lookAt: [0, 1.5, 0],- fov: 45 }],- update() {},- };-}-"""--# Pull a scalar GLSL helper out of the SHIPPED source and run it as JS. The-# two dialects agree on everything here except the declarations, so the-# numbers below are the numbers the GPU computes — not a second-# implementation that could drift from the one that renders.-_GLSL_AS_JS = """-const glslFn = (src, name, args) => {- const re = new RegExp('float ' + name + '\\\\(([\\\\s\\\\S]*?)\\\\)\\\\s*\\\\{');- const m = re.exec(src);- if (!m) throw new Error('no ' + name + '() in the shipped source');- let depth = 0, end = -1;- for (let i = src.indexOf('{', m.index); i < src.length; i++) {- if (src[i] === '{') depth++;- else if (src[i] === '}' && --depth === 0) { end = i; break; }- }- const body = src.slice(src.indexOf('{', m.index) + 1, end)- .replace(/\\bfloat\\b/g, 'let');- const fn = new Function(...args, 'clamp', 'max', 'min', 'fract',- 'step', 'mix', 'pow', 'exp', 'sin', 'floor',- body);- return (...v) => fn(...v,- (x, a, b) => Math.min(Math.max(x, a), b), Math.max, Math.min,- (x) => x - Math.floor(x),- (e, x) => (x < e ? 0 : 1),- (a, b, t) => a + (b - a) * t,- Math.pow, Math.exp, Math.sin, Math.floor);-};-"""--# The same trick for the ONE helper here that takes vectors: astraFresnel is-# shader.js's, shared by every grazing-angle effect in the library, so the-# smudge's angle response is read out of the shipped GLSL_UTIL.-_FRESNEL_AS_JS = """-const fresnelOf = (src) => {- const i = src.indexOf('float astraFresnel(');- if (i < 0) throw new Error('no astraFresnel() in GLSL_UTIL');- const open = src.indexOf('{', i);- let depth = 0, end = -1;- for (let k = open; k < src.length; k++) {- if (src[k] === '{') depth++;- else if (src[k] === '}' && --depth === 0) { end = k; break; }- }- const fn = new Function('n', 'v', 'power', 'pow', 'clamp', 'dot',- 'normalize', src.slice(open + 1, end));- const dot3 = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];- const norm3 = (a) => {- const l = Math.hypot(a[0], a[1], a[2]);- return [a[0] / l, a[1] / l, a[2] / l];- };- return (n, v, p) => fn(n, v, p, Math.pow,- (x, a, b) => Math.min(Math.max(x, a), b), dot3, norm3);-};-"""---def test_all_three_compile_in_a_room_with_fog_and_a_point_light():- """Both patches chained under two from another library, on one- material, plus an InstancedMesh and the crowd field — in a FOGGED- scene with a point light, because the smudge sums point lights and- every custom shader here has a fog branch. `patchStandard` THROWS on- two patches defining one function name, which only the GPU, or this,- can settle."""- code, out = compile_scene(_SCENE, _LIBS)- assert code == 0, out- # A WARN here is the fog trap or the GTAO trap, either of which ships- # an effect that looks wrong rather than one that errors.- assert "WARN" not in out, out- assert "no fog chunks" not in out, out---def test_the_bounce_falls_off_and_is_zero_beyond_its_reach():- """Read straight out of the GLSL the patch ships. A bare inverse- square never reaches zero, so every surface in the scene would keep a- wash of every bouncer in it — ambient light again, the one thing- colour bleed exists to replace. A plane must also lose its light more- slowly than a point, or a wall bleeds like a bulb."""- out = measure(_GLSL_AS_JS + """-import * as THREE from 'three';-import { patchBounceLight } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial({ color: 0x888888 });-patchBounceLight(m, { sources: [[0, 0, 0]], strength: 1 });-const patch = m.userData.astraPatches.find(- (p) => p.name === 'indoor:bounce');-const fall = glslFn(patch.fragmentHead, 'astraBncFall',- ['d', 'r', 'plane']);-const curve = (plane) => {- const out = [];- for (let i = 0; i <= 40; i++) out.push(fall(i * 0.1, 3, plane));- return out;-};-console.log(JSON.stringify({- point: curve(0), plane: curve(1),- at0: [fall(0, 3, 0), fall(0, 3, 1)],- atR: [fall(3, 3, 0), fall(3, 3, 1)],- beyond: [fall(3.5, 3, 0), fall(9, 3, 1), fall(400, 3, 0)],- half: [fall(1.5, 3, 0), fall(1.5, 3, 1)],-}));-""", _LIBS)- assert out["at0"] == [1, 1], out["at0"]- for name in ("point", "plane"):- curve = out[name]- for a, b in zip(curve, curve[1:], strict=False):- assert b <= a, f"{name} bounce rises with distance: {a} -> {b}"- inside = [c for c in curve[:30] if c > 0]- assert len(inside) > 25 and inside[0] > 8 * inside[-1], inside- # EXACTLY zero at the reach and past it, both shapes.- assert out["atR"] == [0, 0], out["atR"]- assert out["beyond"] == [0, 0, 0], out["beyond"]- # A wall is a broad source and a rug is not: at half the reach the- # plane must still be carrying several times what the point is.- assert out["half"][1] > 2.0 * out["half"][0], out["half"]---def test_a_plane_bounces_with_the_form_factor_and_a_point_does_not():- """THE PORT'S FIRST LAW. The half-lambert un-squared is the EXACT- cosine-weighted form factor at both limits of a Lambertian- half-space — 1.0 for a ceiling facing a lit floor, 0.5 for a wall- standing on one — and squaring it lands the wall at 0.25. That is- half the bleed on the one geometry every room has, and on our host it- was the difference between 3.9 and 6.9 of 255 on the plaster. A- POINT keeps the square: a rug really is directional."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial();-patchBounceLight(m, { sources: [{ position: [0, 0, 0], normal: [0, 1, 0],- reach: 4 }] });-const body = m.userData.astraPatches.find(- (p) => p.name === 'indoor:bounce').fragmentBody;-// the wrap the shipped body applies, run at the three geometries that-// matter: facing the source, perpendicular to it, turned away.-const wrap = (lam, plane) => {- const sq = lam * lam;- return plane * lam + (1 - plane) * sq;-};-console.log(JSON.stringify({- body,- plane: [wrap(1, 1), wrap(0.5, 1), wrap(0, 1)],- point: [wrap(1, 0), wrap(0.5, 0), wrap(0, 0)],-}));-""", _LIBS)- body = out["body"]- assert "float bncWrap = mix(bncLam * bncLam, bncLam, bncPl);" in body, body- assert "bncSum += bncTint * (bncFront * bncWrap" in body, body- # ceiling over a floor 1.0, wall on a floor 0.5, facing away 0.- assert out["plane"] == [1, 0.5, 0], out["plane"]- # and the point is still the tighter, squared response.- assert out["point"] == [1, 0.25, 0], out["point"]---def test_the_wash_loses_the_bouncer_hue_as_it_spreads_and_is_dithered():- """A red bleed as red at its far edge as it is under the wall reads as- a coloured LAMP: light that has come further has bounced off more than- one thing. And bounce is the smoothest gradient a room has, on the- widest flat in it — without a dither it climbs the 8-bit ladder in- bands (136 -> 156 distinct colours over the showcase's gradient- strip)."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial();-patchBounceLight(m, { sources: [{ position: [0, 0, 0], normal: [0, 1, 0],- color: 0xc23a2c, reach: 3 }] });-const body = m.userData.astraPatches.find(- (p) => p.name === 'indoor:bounce').fragmentBody;-const amp = /\\)\\s*\\*\\s*(0\\.\\d+)\\s*\\*\\s*step\\(/.exec(body);-console.log(JSON.stringify({- body,- desatAt: /0\\.32\\s*\\*\\s*bncX/.test(body),- ditherAmp: amp ? parseFloat(amp[1]) : null,-}));-""", _LIBS)- body = out["body"]- # the tint is mixed toward its own LUMA (a grey of the same- # brightness), so the wash goes pale, never dark, as it spreads.- assert "vec3 bncTint = mix(uBncCol[i]," in body, body- assert "vec3(0.2126, 0.7152, 0.0722))" in body, body- assert out["desatAt"], body- # gated on bncX, which is 0 at the source: the skirting under a red- # wall keeps the full hue.- assert "float bncX = clamp(bncDist / max(uBncSpan[i].x, 1e-4)" in body- # Half a code of hash, and only where there is bleed to band.- assert "astraHash11(gl_FragCoord.x" in body, body- assert "step(1e-4, bncLvl)" in body, body- assert 0.002 <= out["ditherAmp"] <= 0.012, out["ditherAmp"]---def test_the_bounce_is_light_and_never_repaints_the_albedo():- """A bounce lifted into ALBEDO is capped at the light already landing- on the surface, so the shaded soffit under an eave — the one place- colour bleed is the whole cue — would take none of it. It has to ADD,- tinted by the receiver's own colour because arriving light is- reflected, and it must never assign over diffuseColor, which would- delete every patch that ran before it."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial({ color: 0x445566 });-patchBounceLight(m, {- sources: [{ position: [0, 2, 0], normal: [0, 1, 0], color: 0x40ff40,- reach: 4 },- { position: [3, 0, 0], color: 0xff4040, reach: 2 }],- strength: 1.5 });-const p = m.userData.astraPatches.find((q) => q.name === 'indoor:bounce');-const base = m.userData.astraPatches.find((q) => q.name === 'indoor:base');-const u = m.userData.uniforms;-console.log(JSON.stringify({- body: p.fragmentBody,- vert: base.vertexBody,- names: m.userData.astraPatches.map((q) => q.name),- count: u.uBncCount.value,- gain: u.uBncGain.value,- spans: u.uBncSpan.value.map((v) => [v.x, v.y]),- colors: u.uBncCol.value.map((c) => c.getHex()),- normals: u.uBncNrm.value.map((v) => v.toArray()),- emissive: m.emissive !== undefined,-}));-""", _LIBS)- body = out["body"]- assert "totalEmissiveRadiance +=" in body, body- # Reads the albedo as a reflectance, never writes it.- assert "diffuseColor.rgb" in body, body- assert not re.search(r"diffuseColor(\.rgb)?\s*=[^=]", body), body- assert "astraBncFall(" in body, body- # An instanced post needs instanceMatrix folded in by hand, or every- # copy is lit as though it stood at the mesh origin.- assert "USE_INSTANCING" in out["vert"], out["vert"]- assert out["count"] == 2 and out["gain"] == 1.5, out- # Stating a normal makes a source a PLANE (span.y 1) and leaving it- # out makes it a POINT (0) — the whole geometry of the falloff.- assert out["spans"][0] == [4, 1], out["spans"]- assert out["spans"][1] == [2, 0], out["spans"]- # An unused slot is black, so a shorter list cannot leak light.- assert out["colors"][2:] == [0] * 4, out["colors"]- # A point with no normal of its own throws along `up`.- assert out["normals"][1] == [0, 1, 0], out["normals"]---def test_a_bouncer_only_lights_the_side_it_faces():- """A lawn does not light the cellar under it and a wall throws nothing- through itself: without the front gate, colour bleed leaks to the far- side of every surface that casts it — which is the one way this reads- as a coloured fog rather than as light."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial();-patchBounceLight(m, { sources: [{ position: [0, 0, 0],- normal: [0, 1, 0], reach: 3 }] });-const p = m.userData.astraPatches.find((q) => q.name === 'indoor:bounce');-console.log(JSON.stringify({ body: p.fragmentBody,- head: p.fragmentHead }));-""", _LIBS)- body = out["body"]- assert "float bncSide = dot(bncD, uBncNrm[i]);" in body, body- assert "step(1e-4, bncSide)" in body, body- # A plane is measured PERPENDICULAR to itself and a point radially:- # that is what makes a long wall bleed along a whole band of ceiling- # while a rug stays under the table.- assert "mix(bncR, bncSide, bncPl)" in body, body- assert "mix(-bncD / max(bncR, 1e-4), -uBncNrm[i], bncPl)" in body, body- # Half lambert: a hard terminator would cut the ceiling off in a line- # above a wall that in truth lights all of it.- assert "dot(bncN, bncL) * 0.5 + 0.5" in body, body---def test_fingerprints_move_gloss_and_never_colour():- """A smudge that changes the COLOUR of glass is a stain, and the pane- reads as dirty rather than used. Gloss is per MATERIAL here- (`<color_fragment>` runs before `<roughnessmap_fragment>`), so the- reachable half is a roughness factor composed through- `composeRoughness` — and it must compose, not re-base, or two- libraries on one material fight over the same number."""- out = measure("""-import * as THREE from 'three';-import { patchFingerprints } from './lib/indoor.js';--const rough = (amount, smear) => {- const m = new THREE.MeshStandardMaterial({ color: 0x224466,- roughness: 0.10 });- patchFingerprints(m, { amount, smear, seed: 2 });- return { r: m.roughness, color: m.color.getHex() };-};-const m = new THREE.MeshStandardMaterial({ color: 0x224466,- roughness: 0.10 });-patchFingerprints(m, { amount: 0.8, smear: 0.4, seed: 2 });-const once = m.roughness;-patchFingerprints(m, { amount: 0.8, smear: 0.4, seed: 2 });-const p = m.userData.astraPatches.find(- (q) => q.name === 'indoor:fingerprints');-console.log(JSON.stringify({- clean: rough(0, 0), light: rough(0.3, 0.4), heavy: rough(1, 1),- once, twice: m.roughness,- keys: Object.keys(m.userData.astraRoughness.factors),- base: m.userData.astraRoughness.base,- body: p.fragmentBody,-}));-""", _LIBS)- clean, light, heavy = out["clean"], out["light"], out["heavy"]- # Grease scatters: gloss goes DOWN (roughness up) with the amount.- assert clean["r"] == 0.10, clean- assert light["r"] > clean["r"], (clean, light)- assert heavy["r"] > light["r"], (light, heavy)- # And the albedo is untouched at every setting.- assert clean["color"] == light["color"] == heavy["color"] == 0x224466- # Re-applying retunes, never re-bases (composeRoughness).- assert out["twice"] == out["once"], out- assert out["keys"] == ["indoor:fingerprints"], out["keys"]- assert out["base"] == 0.10, out["base"]- body = out["body"]- assert "totalEmissiveRadiance +=" in body, body- assert "diffuseColor" not in body, body---def test_the_smudge_is_hidden_head_on_and_comes_up_at_grazing():- """The whole cue: grease is invisible until the surface starts- reflecting, then it takes the pane over. The weight is the- dielectric's own — a few percent head-on, everything at grazing — read- out of shader.js's `astraFresnel`, the same helper every grazing-angle- effect in this library shares."""- out = measure(_FRESNEL_AS_JS + """-import * as THREE from 'three';-import { GLSL_UTIL } from './lib/shader.js';-import { patchFingerprints } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial({ roughness: 0.08 });-patchFingerprints(m, { amount: 0.6, smear: 0.4, seed: 3 });-const p = m.userData.astraPatches.find(- (q) => q.name === 'indoor:fingerprints');-const fres = fresnelOf(GLSL_UTIL);-// A pane facing +Z, seen from `deg` off its normal — the weight the-// shipped body applies to the whole smudge.-const weight = (deg) => {- const a = deg * Math.PI / 180;- const v = [Math.sin(a), 0, Math.cos(a)];- return 0.06 + 0.94 * fres([0, 0, 1], v, 4.0);-};-console.log(JSON.stringify({- ladder: [0, 30, 60, 75, 82, 88].map((d) => +weight(d).toFixed(4)),- body: p.fragmentBody, head: p.fragmentHead,-}));-""", _LIBS)- ladder = out["ladder"]- # The numbers only mean anything if the shipped body applies them.- assert "float fprGrz = astraFresnel(fprN, fprV, 4.0);" in out["body"]- assert "float fprW = mix(0.06, 1.0, fprGrz);" in out["body"]- assert "fprW" in out["body"].split("totalEmissiveRadiance")[1]- for a, b in zip(ladder, ladder[1:], strict=False):- assert b > a, f"the smudge does not rise with the angle: {ladder}"- assert ladder[0] < 0.07, ladder- assert ladder[4] > 8 * ladder[0], ladder- # The scratches are the grazing-only layer, gated a second time.- assert "fprScr * fprGrz" in out["body"], out["body"]- # And there is a light to catch, or a smudge has nothing to show:- # both direct kinds plus the sky, which is what a shopfront reflects.- for token in ("directionalLights[i].color", "pointLights[i].color",- "hemisphereLights[i].skyColor"):- assert token in out["body"], token---def test_the_grease_is_a_film_and_not_a_set_of_stripes():- """THE PORT'S FOURTH LAW. Arcs alone are a few bright bands on clean- glass, and the eye reads bands as paint. The film rides the same- blotch that decides WHERE hands have been — so a wiped pane stays- wiped — at about half the arcs' weight, with its own slow variation- so it is cloud and not a wash."""- out = measure("""-import * as THREE from 'three';-import { patchFingerprints } from './lib/indoor.js';--const m = new THREE.MeshStandardMaterial();-patchFingerprints(m, { amount: 0.6, smear: 0.4, seed: 3 });-const body = m.userData.astraPatches.find(- (q) => q.name === 'indoor:fingerprints').fragmentBody;-const w = /fprFilm\\s*\\*\\s*(0\\.\\d+)/.exec(body);-console.log(JSON.stringify({ body, filmWeight: w ? parseFloat(w[1]) : null }));-""", _LIBS)- body = out["body"]- # It is gated on fprWhere — the same blotch as the arcs — so amount- # still means "how much of the surface hands have reached".- assert "float fprFilm = fprWhere * (" in body, body- assert "astraNoise2(fprQ" in body.split("fprFilm")[1], body- assert "+ fprFilm * " in body, body- assert 0.3 <= out["filmWeight"] <= 0.75, out["filmWeight"]- # and it is inside the mask, so the fresnel weight still hides it- # head-on: a film that ignored the angle would be a frosted pane.- mask = body.split("float fprMask")[1].split("\n")[0:3]- assert any("fprFilm" in ln for ln in mask), mask---def test_the_crowd_is_one_draw_call_seated_on_the_ground():- """A crowd is only affordable as one draw call, and it is only a crowd- if its people stand ON the ground with their own heights. The stated- bounding SPHERE is the other half: `position` is all zeros (the GTAO- reason `instancedQuad` documents), so without a real radius three- culls the whole square the moment the origin leaves frame — and with- the 10 km default it frames 10 km of empty air."""- out = measure("""-import { makeCrowdImposters } from './lib/indoor.js';--const heightAt = (x, z) => 1.4 + 0.25 * Math.sin(x * 0.21)- + 0.18 * Math.cos(z * 0.17);-const g = makeCrowdImposters({ count: 64, extent: 30, height: 1.72,- heightAt, seed: 4 });-const meshes = [];-g.traverse((o) => { if (o.isMesh) meshes.push(o); });-const geo = meshes[0].geometry;-const pos = geo.attributes.aPos.array;-const card = geo.attributes.aCrowd.array;-let offGround = 0, outside = 0;-const scales = [], tones = [];-for (let i = 0; i < 64; i++) {- const x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2];- if (Math.abs(y - heightAt(x, z)) > 1e-6) offGround++;- if (Math.abs(x) > 15 || Math.abs(z) > 15) outside++;- scales.push(card[i * 4 + 1]);- tones.push(card[i * 4]);-}-console.log(JSON.stringify({- meshes: meshes.length,- vertex: meshes[0].material.vertexShader,- instanced: !!geo.isInstancedBufferGeometry,- count: geo.instanceCount,- zeroPos: geo.attributes.position.array.every((v) => v === 0),- radius: geo.boundingSphere.radius,- lowY: geo.boundingBox.min.y, highY: geo.boundingBox.max.y,- offGround, outside,- scaleRange: [Math.min(...scales), Math.max(...scales)],- toneRange: [Math.min(...tones), Math.max(...tones)],- name: g.name, tick: typeof g.userData.tick,- ticked: g.userData.tick(3.5),-}));-""", _LIBS)- assert out["meshes"] == 1, out["meshes"]- assert out["instanced"] and out["count"] == 64, out- # The GTAO trap: a real quad left in `position` is drawn at the world- # origin by the override pass and burns a hole there.- assert out["zeroPos"], "the cards keep a real quad in position"- assert out["offGround"] == 0, f"{out['offGround']} people float"- assert out["outside"] == 0, out["outside"]- # A REAL radius, not the 10 km default and not a sphere so small three- # culls the square as soon as its centre leaves frame.- assert 15 < out["radius"] < 40, out["radius"]- assert out["lowY"] < 1.2 and out["highY"] > 2.9, out- # Varied heights and clothing, or a crowd is wallpaper: one in seven- # is a child, so the range has to reach well under an adult.- lo, hi = out["scaleRange"]- assert lo < 0.8 and hi > 1.0, out["scaleRange"]- assert out["toneRange"][1] - out["toneRange"][0] > 0.8, out- assert out["name"] == "Crowd" and out["tick"] == "function", out- assert out["ticked"] == 1, out["ticked"]- # Facing the camera, in YAW only: a card that also pitches lifts the- # whole crowd off the ground together as the camera looks down.- vs = out["vertex"]- assert "modelViewMatrix[0][0], modelViewMatrix[1][0]" in vs, vs- assert "camR - up * dot(camR, up)" in vs, vs- assert "vec3 up = vec3(0.0, 1.0, 0.0);" in vs, vs---def test_a_backlit_card_is_a_silhouette_with_a_lit_edge():- """THE PORT'S FIFTH LAW. With the sun behind it, a hard `max(dot, 0)`- on this card's coarse bowed normal prints the whole crowd as one flat- ambient tone — the frame our host rendered before this, where 90- people were 90 identical blue-grey stumps. Three things fix it and- all three are in the shipped shader: a WRAP so the terminator is not a- cliff, a RIM in the light's own colour on the sun-side edge of the- silhouette (gated on the sun being BEHIND, or a front-lit crowd grows- a halo), and per-person VALUE, because a street is pale coats and dark- ones and hue alone is not a crowd."""- out = measure("""-import { makeCrowdImposters } from './lib/indoor.js';--const g = makeCrowdImposters({ count: 8, extent: 10, seed: 3 });-const mat = g.children[0].material;-console.log(JSON.stringify({- vs: mat.vertexShader, fs: mat.fragmentShader,- leg: mat.uniforms.uCrwLeg.value.toArray().map((v) => +v.toFixed(4)),-}));-""", _LIBS)- vs, fs = out["vs"], out["fs"]- # The card has no depth for a normal to find the rim in, so the- # vertex stage hands the fragment which way the light lies ACROSS it- # and how far behind.- assert "vCrwRim = vec2(dot(right, uCrwSun), clamp(-dot(fwd, uCrwSun)" in vs- assert "uniform vec3 uCrwSun;" in vs, vs- # Wrapped, not clamped.- assert "float iNdL = clamp((dot(normalize(vCrwN), uCrwSun) + 0.30)" in fs- assert "max(dot(normalize(vCrwN), uCrwSun), 0.0)" not in fs, fs- # The rim rides the real silhouette (cW is the body half-width), is- # gated on the sun side and on backlight, and is the LIGHT's colour.- rim = fs.split("float iRim")[1].split(";")[0]- assert "abs(iq.x) / max(cW, 0.02)" in rim, rim- assert "vCrwRim.x * sign(iq.x)" in rim and "vCrwRim.y" in rim, rim- assert "uCrwSunColor * (iRim *" in fs, fs- # Value per person, on the clothing ramp.- assert "iAlb *= 0.72 + 0.62 * fract(cPh * 0.29);" in fs, fs- # Trousers, hair and shoes stay above the albedo floor: linear 0.02 is- # about where a surface stops being a colour and becomes a hole.- r, gr, b = out["leg"]- assert min(r, gr, b) > 0.02, out["leg"]- assert max(r, gr, b) < 0.10, out["leg"]---def test_the_crowd_is_kept_out_of_the_override_passes():- """GTAOPass redraws the scene with an OPAQUE override material, in- which a transparent card is a solid wall — measured elsewhere at- 50/255 of false darkening on ground the effect never touched. The- same guard stops the mesh casting a shadow, which is right: a card- that always faces the camera would cast a shadow that turns with- it."""- out = measure("""-import { makeCrowdImposters } from './lib/indoor.js';--const rows = [];-makeCrowdImposters({ count: 12, extent: 10, seed: 4 }).traverse((o) => {- if (!o.isMesh) return;- rows.push({ name: o.name,- guarded: o.userData.astraNoOverride === true,- shadow: !!o.castShadow,- transparent: !!o.material.transparent,- depthWrite: !!o.material.depthWrite });-});-console.log(JSON.stringify({ rows }));-""", _LIBS)- rows = out["rows"]- assert len(rows) == 1, rows- for r in rows:- assert r["transparent"], r- assert r["guarded"], f"{r['name']} would be a solid wall to GTAO"- assert not r["shadow"], f"{r['name']} casts a shadow"- # Still writes depth: a card that does not punches a- # sky-coloured hole through the one behind it.- assert r["depthWrite"], r---def test_every_option_is_a_uniform_and_not_baked_into_the_glsl():- """The first material to compile a cache key decides the GLSL every- material with that key gets. So two rooms tuned differently must- differ only in UNIFORM values — otherwise the second room silently- renders with the first one's sources, and nothing in the frame says- so."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight, patchFingerprints } from './lib/indoor.js';--const make = (opts, fpr) => {- const m = new THREE.MeshStandardMaterial();- patchBounceLight(m, opts);- patchFingerprints(m, fpr);- const b = m.userData.astraPatches.find((p) => p.name === 'indoor:bounce');- const f = m.userData.astraPatches.find(- (p) => p.name === 'indoor:fingerprints');- return {- key: m.customProgramCacheKey(),- glsl: [b.fragmentHead, b.fragmentBody, b.vertexHead,- f.fragmentHead, f.fragmentBody].join('|'),- bounce: [m.userData.uniforms.uBncGain.value,- m.userData.uniforms.uBncCount.value,- m.userData.uniforms.uBncNrm.value[0].toArray()],- smudge: [m.userData.uniforms.uFprAmt.value,- m.userData.uniforms.uFprSmear.value,- m.userData.uniforms.uFprSeed.value.toArray()],- };-};-const a = make({ sources: [[0, 0, 0]], strength: 1 },- { amount: 0.3, smear: 0.2, seed: 1 });-const b = make({ sources: [[4, 1, 0], [0, 2, 0]], strength: 2.5,- up: [0, 0, 1] },- { amount: 0.9, smear: 0.8, seed: 7 });-console.log(JSON.stringify({ a, b, same: a.glsl === b.glsl }));-""", _LIBS)- a, b = out["a"], out["b"]- assert out["same"], "an option was baked into the GLSL"- assert a["key"] == b["key"], (a["key"], b["key"])- assert "indoor:base" in a["key"] and "indoor:bounce" in a["key"]- assert "indoor:fingerprints" in a["key"], a["key"]- assert a["bounce"] != b["bounce"], a["bounce"]- assert b["bounce"][2] == [0, 0, 1], b["bounce"]- assert a["smudge"] != b["smudge"], a["smudge"]---def test_the_same_seed_builds_the_same_crowd_twice():- """No Math.random anywhere: two runs of one brief must be the same- frame, and a different seed must actually move the crowd rather than- renaming it."""- assert "Math.random" not in _SRC.read_text(encoding="utf-8")- out = measure("""-import * as THREE from 'three';-import { makeCrowdImposters, patchFingerprints } from './lib/indoor.js';--const field = (seed) => {- const g = makeCrowdImposters({ count: 30, extent: 20, seed,- heightAt: (x, z) => 0 });- const a = g.children[0].geometry.attributes;- return { pos: Array.from(a.aPos.array),- card: Array.from(a.aCrowd.array) };-};-const seedOf = (s) => {- const m = new THREE.MeshStandardMaterial();- patchFingerprints(m, { seed: s });- return m.userData.uniforms.uFprSeed.value.toArray();-};-const a = field(4), b = field(4), c = field(5);-console.log(JSON.stringify({- same: a.pos.every((v, i) => v === b.pos[i])- && a.card.every((v, i) => v === b.card[i]),- moved: a.pos.some((v, i) => v !== c.pos[i]),- smudge: [seedOf(1), seedOf(1), seedOf(2)],-}));-""", _LIBS)- assert out["same"], "the same seed built two different crowds"- assert out["moved"], "a new seed built the same crowd"- s = out["smudge"]- assert s[0] == s[1] and s[0] != s[2], s---def test_both_patches_chain_with_another_library_on_one_material():- """GLSL has one global namespace and `patchStandard` THROWS when two- patches define one function name with different bodies — a room's wall- wears wear, bounce and grease at once, so the prefixes are not- decoration. The chain must also run in CALL order and share one- uniform map."""- out = measure("""-import * as THREE from 'three';-import { patchBounceLight, patchFingerprints } from './lib/indoor.js';-import { patchEdgeWear, patchMicroBreakup } from './lib/surface_wear.js';--const m = new THREE.MeshStandardMaterial({ roughness: 0.3 });-patchMicroBreakup(m, { scale: 0.6, strength: 0.12, seed: 5 });-patchBounceLight(m, { sources: [[0, 1, 0]] });-patchEdgeWear(m, { strength: 0.4, seed: 6 });-patchFingerprints(m, { amount: 0.5, seed: 3 });-const heads = m.userData.astraPatches- .map((p) => p.fragmentHead || '').join('\\n');-const fns = [...heads.matchAll(/^\\s*(?:float|vec2|vec3)\\s+(\\w+)\\s*\\(/gm)]- .map((x) => x[1]);-console.log(JSON.stringify({- names: m.userData.astraPatches.map((p) => p.name),- key: m.customProgramCacheKey(),- fns, dupes: fns.filter((f, i) => fns.indexOf(f) !== i),- uniforms: Object.keys(m.userData.uniforms).sort(),- roughness: m.roughness,- factors: Object.keys(m.userData.astraRoughness.factors).sort(),-}));-""", _LIBS)- assert out["names"] == [- "wear:base", "wear:micro", "indoor:base", "indoor:bounce",- "wear:edge", "indoor:fingerprints"], out["names"]- assert out["dupes"] == [], out["dupes"]- # Every helper this library adds is prefixed to its own patch.- for fn in ("astraBncFall", "astraFprField", "astraFprArc",- "astraFprPlane", "astraFprLobe"):- assert fn in out["fns"], out["fns"]- for u in ("uBncCol", "uBncCount", "uBncGain", "uBncNrm", "uBncPos",- "uBncSpan", "uFprAmt", "uFprSeed", "uFprSmear"):- assert u in out["uniforms"], out["uniforms"]- # Three libraries, three roughness factors, one composed number.- assert out["factors"] == ["edge", "indoor:fingerprints", "micro"], out- assert 0.04 <= out["roughness"] <= 1, out["roughness"]diff --git a/harness/tests/scene_runtime/lib/test_lights.py b/harness/tests/scene_runtime/lib/test_lights.pydeleted file mode 100644index a7abf799..00000000--- a/harness/tests/scene_runtime/lib/test_lights.py+++ /dev/null@@ -1,347 +0,0 @@-"""lights.js: panel lights ship init-fused, pre-aimed, and un-settleable.--Ported 2026-09-01 from the scene_multifile_graphics reference-(tests/test_lights_lib.py). The reference's claims are kept — RectAreaLight-renders BLACK without one-time LTC init, emits along local -Z, and needs a-glow mesh — and three things this port had to add are pinned with them,-because each one was a defect measured on OUR host, not a style preference:--1. COLOUR SPACE. The Tanner Helland fit is an 8-bit *sRGB* triple and the- reference handed it to `new THREE.Color(r, g, b)`, which writes its- arguments into three's srgb-linear working space RAW. Every class came out- washed toward white: rendered through our pipeline the tungsten window read- (158,152,145) — a grey card — and the fluorescent shop, the LED sign and the- tungsten window were three copies of the same panel, which is precisely the- "class SPLIT" the module exists to sell. A hex colour already takes the- sRGB decode inside three, so the fit had to as well; measured after,- tungsten reads (239,205,148), saturation 0.176 -> 0.380.--2. SETTLE. This host seats floating assets on the ground before the first- frame (runtime_js/lib/host_placement.mjs). A `PanelLight` is a group of- meshes that floats by definition, so a window panel authored at y=4.4 on a- wall was moved to y=0.60 — its own half-height — and rendered lying at the- kerb. `userData.placement = 'free'` is the documented opt-out and a- luminaire is exactly what it is for.--3. NO POST CHAIN. There is no bloom pass here, so the panel has to carry its- own glow: an emissiveMap that keeps the rim off zero (a rim at zero uncovers- the dark base colour and draws a black bezel round every lamp) and an- additive spill quad *behind* the panel, where the depth test leaves only the- halo outside its edge.-"""-from __future__ import annotations--import pytest-from _probe import compile_scene, measure--pytestmark = pytest.mark.node--_LIBS = ("lights.js",)---def _measure(script: str) -> dict:- return measure(script, _LIBS)---_PROBE = """-import * as THREE from 'three';-import { makePanelLight, initRectAreaLights } from './lib/lights.js';--// LTC must be absent until the FIRST makePanelLight auto-inits it.-const before = !!(THREE.UniformsLib.LTC_FLOAT_1);-const g = makePanelLight(4, 2);-const after = !!(THREE.UniformsLib.LTC_FLOAT_1);-const ref1 = THREE.UniformsLib.LTC_FLOAT_1;-initRectAreaLights();-initRectAreaLights();-const stable = THREE.UniformsLib.LTC_FLOAT_1 === ref1;--const light = g.userData.light;-const panel = g.userData.panel;-const halo = g.userData.halo;--// Aiming contract: group.lookAt(target) must point the EMISSION-// (the raw light's local -Z) at the target.-const scene = new THREE.Scene();-scene.add(g);-g.position.set(0, 0, 0);-g.lookAt(new THREE.Vector3(0, 0, 7));-scene.updateMatrixWorld(true);-const m = light.matrixWorld.elements;-const emission = new THREE.Vector3(-m[8], -m[9], -m[10]).normalize();-const aimDot = emission.dot(new THREE.Vector3(0, 0, 1));--const custom = makePanelLight(3, 1, 0xffdca8, 11, { glow: 4 });-const bare = makePanelLight(2, 2, 0xffffff, 6, { panel: false });-const plain = makePanelLight(2, 1, 'sodium', 8, { halo: false });--// the emissive map is the diffuser profile: flat core, rim held off zero-const tex = panel.material.emissiveMap;-const N = tex.image.width;-const at = (u, v) => tex.image.data[((v * N + u) * 4)] / 255;--console.log(JSON.stringify({- before, after, stable,- isRect: light.isRectAreaLight === true,- w: light.width, h: light.height,- color: light.color.getHex(),- intensity: light.intensity,- aimDot,- free: g.userData.placement,- panelThere: !!panel,- panelBehind: panel.position.z < 0 && panel.position.z > -0.05,- glowHex: panel.material.emissive.getHex(),- glowI: panel.material.emissiveIntensity,- panelW: panel.geometry.parameters.width,- panelH: panel.geometry.parameters.height,- baseLin: panel.material.color.r,- roughness: panel.material.roughness,- texShared: makePanelLight(1, 1).userData.panel.material.emissiveMap === tex,- texLinear: tex.colorSpace === THREE.NoColorSpace,- texCore: at(N >> 1, N >> 1),- texRim: at(0, N >> 1),- texMid: at(Math.round(N * 0.88), N >> 1),- // dither: an undithered smoothstep row is MONOTONE, so count the- // sign changes along it — jitter is the only thing that makes any.- texFlips: (() => {- let f = 0, prev = 0;- for (let u = 1; u < N; u++) {- const d = at(u, N >> 1) - at(u - 1, N >> 1);- if (d === 0) continue;- if (prev !== 0 && Math.sign(d) !== prev) f++;- prev = Math.sign(d);- }- return f;- })(),- haloThere: !!halo,- haloBehindPanel: halo.position.z < panel.position.z,- haloAdditive: halo.material.blending === THREE.AdditiveBlending,- haloDepthWrite: halo.material.depthWrite,- haloFog: halo.material.fog,- haloOpacity: halo.material.opacity,- haloHex: halo.material.color.getHex(),- haloW: halo.geometry.parameters.width,- haloH: halo.geometry.parameters.height,- customColor: custom.userData.light.color.getHex(),- customI: custom.userData.light.intensity,- customGlowHex: custom.userData.panel.material.emissive.getHex(),- customGlowI: custom.userData.panel.material.emissiveIntensity,- bareNoPanel: bare.userData.panel === null,- bareNoHalo: bare.userData.halo === null,- plainNoHalo: plain.userData.halo === null,- plainHasPanel: !!plain.userData.panel,- name: g.name,-}));-"""--[email protected](scope="module")-def probe() -> dict:- """One node launch of _PROBE, shared by every test that reads it."""- return _measure(_PROBE)---def test_ltc_init_is_automatic_and_runs_exactly_once(probe):- """Without RectAreaLightUniformsLib.init() the light renders black- with no error; the wrapper installs it on first use and must never- rebuild the LTC tables on later calls."""- m = probe- assert not m["before"], "probe invalid: LTC preexisted"- assert m["after"], "makePanelLight did not init LTC"- assert m["stable"], "second init rebuilt the LTC tables"---def test_group_lookat_aims_the_emission_at_the_target(probe):- """RectAreaLight emits along local -Z while lookAt aims +Z; the- wrapper pre-rotates so group.lookAt(target) points the EMISSION at- the target — lose the flip and windows light the wrong wall."""- m = probe- assert m["aimDot"] > 0.999, f"emission misaimed: dot={m['aimDot']}"---def test_light_and_glow_panel_agree_and_options_are_alive(probe):- """Fused contract: the panel carries the light's colour, sits just- behind the emitting plane at its exact size, and every documented- option reaches the objects — else glow and cast light disagree."""- m = probe- assert m["isRect"] and (m["w"], m["h"]) == (4, 2), m- assert m["color"] == 0xffffff and m["intensity"] == 6, \- f"measured defaults drifted: {m['color']:x}/{m['intensity']}"- assert m["panelThere"] and m["panelBehind"], m- assert (m["panelW"], m["panelH"]) == (4, 2), "panel != light size"- assert m["glowHex"] == 0xffffff and m["glowI"] == 2.2, m- assert m["customColor"] == 0xffdca8 and m["customI"] == 11, m- assert m["customGlowHex"] == 0xffdca8 and m["customGlowI"] == 4, m- assert m["bareNoPanel"], "panel:false still built a panel"- assert m["bareNoHalo"], "panel:false left an orphan halo"- assert m["name"] == "PanelLight"---def test_the_panel_is_exempt_from_the_host_settle_pass(probe):- """A luminaire hangs where the author hung it. This host seats- floating assets before the first frame, and a PanelLight floats by- definition: unmarked, a 1.5x1.2 window authored at y=4.4 came back- at y=0.60 (its own half-height) and rendered lying at the kerb."""- assert probe["free"] == "free", \- "userData.placement lost — the host will settle panels to the ground"---def test_the_diffuser_map_is_a_shared_linear_profile_that_never_hits_zero(probe):- """No bloom pass here, so the panel's own falloff is the glow. The- map must be a LINEAR multiplier (a decoded sRGB one would lift the- rim and flatten the core), one texture across every panel, and its- rim must stay off zero: a rim at zero uncovers the dark base colour- and draws a black bezel around every lamp in the scene."""- m = probe- assert m["texLinear"], "emissiveMap would be sRGB-decoded"- assert m["texShared"], "a new diffuser texture per panel light"- assert m["texCore"] > 0.9, m["texCore"]- assert 0.25 < m["texRim"] < 0.45, f"rim {m['texRim']}: bezel or no falloff"- assert m["texMid"] < m["texCore"], "no roll-off at all"- assert m["texFlips"] > 4, \- f"monotone ramp ({m['texFlips']} flips) — an 8-bit gradient that bands"---def test_the_halo_is_additive_spill_hidden_behind_its_own_panel(probe):- """The spill quad sits BEHIND the panel so the depth test hides its- blown centre and leaves only the glow around the edges; additive and- fog-exempt, because additive fog ADDS the fog colour instead of- fading the glow into it."""- m = probe- assert m["haloThere"] and m["haloBehindPanel"], m- assert m["haloAdditive"] and not m["haloDepthWrite"], m- assert m["haloFog"] is False, "additive halo would add the fog colour"- assert m["haloOpacity"] == 0.6, m["haloOpacity"]- assert m["haloHex"] == m["glowHex"], "halo disagrees with the light"- assert m["haloW"] > m["panelW"] and m["haloH"] > m["panelH"], m- # aspect kept: a 4x2 panel must not get a square halo- assert m["haloW"] > m["haloH"], m- assert m["plainNoHalo"] and m["plainHasPanel"], "halo:false killed the panel"---def test_light_classes_separate_and_order_by_temperature():- """The realism of a night street is its light classes SEPARATING —- sodium amber, tungsten homes, fluorescent shops, cool LED. So the- class table must actually order by temperature (red/blue ratio- falls as kelvin rises), the classes a scene mixes must be visibly- apart, and 'moon' must lean blue: moonlight photographs blue, and a- black-body 4100 K would hand a night scene a WARM moon."""- out = _measure("""-import { kelvinColor, LIGHT_CLASSES, makePanelLight }- from './lib/lights.js';-const ratio = (c) => c.r / Math.max(c.b, 1e-4);-const classes = {};-for (const [k, v] of Object.entries(LIGHT_CLASSES)) {- classes[k] = { kelvin: v.kelvin, ratio: ratio(v.color),- hex: v.color.getHexString() };-}-const shop = makePanelLight(2, 1, 'fluorescent');-console.log(JSON.stringify({- classes,- k2000: ratio(kelvinColor(2000)),- k6500: ratio(kelvinColor(6500)),- clampLow: kelvinColor(200).getHexString()- === kelvinColor(1000).getHexString(),- panelHex: shop.userData.light.color.getHexString(),- fluorHex: LIGHT_CLASSES.fluorescent.color.getHexString(),- moonBlue: LIGHT_CLASSES.moon.color.b > LIGHT_CLASSES.moon.color.r,-}));-""")- cl = out["classes"]- # Warmer class, higher red/blue ratio — strictly, through the range.- order = ["sodium", "tungsten", "halogen", "fluorescent",- "metal_halide", "led_cool"]- ratios = [cl[k]["ratio"] for k in order]- assert all(a > b for a, b in zip(ratios, ratios[1:], strict=False)), cl- # The two classes one street mixes must be visibly apart. The- # reference put led_cool under 1.05; decoding the fit from sRGB- # deepens every ratio (its own point), and 6300 K lands at 1.10.- assert cl["sodium"]["ratio"] > 2.5, cl- assert cl["led_cool"]["ratio"] < 1.15, cl- assert out["k2000"] > out["k6500"], out- assert out["clampLow"], out- # A class NAME is a colour anywhere a colour goes.- assert out["panelHex"] == out["fluorHex"], out- assert out["moonBlue"], out---def test_the_kelvin_fit_is_decoded_from_srgb_like_every_other_colour():- """The fit is an 8-bit sRGB triple. Written raw into three's- srgb-linear working space it states a gamma-encoded value as a- linear one and every class washes toward white — measured on our- renderer, the tungsten window panel read (158,152,145), a grey card- beside a fluorescent one that read (218,215,214). A hex colour- takes the decode inside three, so the fit must take it too or the- module's two colour paths disagree with each other.-- The floor exists for the same reason: below 1900 K the fit snaps- blue to a hard 0, a discontinuity in the fit rather than physics,- and a dead channel makes a sodium pool clip to a pure hue and band.- """- out = _measure("""-import * as THREE from 'three';-import { kelvinColor, LIGHT_CLASSES } from './lib/lights.js';-// The Helland fit for 2700 K, in the 0-255 sRGB the formula produces.-const t = 27;-const raw = [255,- 99.4708025861 * Math.log(t) - 161.1195681661,- 138.5177312231 * Math.log(t - 10) - 305.0447927307];-const asLinear = new THREE.Color().setRGB(- raw[0] / 255, raw[1] / 255, raw[2] / 255, THREE.SRGBColorSpace);-const c = kelvinColor(2700);-// the hex path, which three has always decoded-const hex = new THREE.Color(0xffffff);-const white = kelvinColor(6600);-console.log(JSON.stringify({- decoded: [c.r, c.g, c.b],- expect: [asLinear.r, asLinear.g, asLinear.b],- hexWhiteR: hex.r,- whiteR: white.r,- sodiumB: LIGHT_CLASSES.sodium.color.b,- moonR: LIGHT_CLASSES.moon.color.r,-}));-""")- got, want = out["decoded"], out["expect"]- assert all(abs(a - b) < 1e-4 for a, b in zip(got, want, strict=True)), (got, want)- # the decode is what deepens the colour: raw, green would sit at 0.65- assert got[1] < 0.45, f"2700 K green {got[1]:.3f} — fit written raw"- # white still means white on both paths, so the default is unmoved- assert abs(out["whiteR"] - out["hexWhiteR"]) < 1e-6, out- # no dead channel anywhere in the table- assert 0 < out["sodiumB"] < 0.01, out["sodiumB"]- # moon was ALREADY a hex and must not have moved- assert abs(out["moonR"] - 0.4620) < 5e-3, out["moonR"]---_SCENE = """-import * as THREE from 'three';-import { makePanelLight } from './lib/lights.js';-export const BOUNDS = { min: [-8, 0, -8], max: [8, 8, 8] };-export function heightAt() { return 0; }-export async function createScene() {- const scene = new THREE.Scene();- const wall = new THREE.Mesh(new THREE.BoxGeometry(6, 4, 0.3),- new THREE.MeshStandardMaterial({ color: 0x8a8378, roughness: 0.9 }));- wall.position.set(0, 2, -2);- scene.add(wall);- const shop = makePanelLight(2.4, 1.2, 'fluorescent', 9);- shop.position.set(0, 2.2, -1.6);- shop.lookAt(0, 1.6, 4);- scene.add(shop);- const fill = makePanelLight(3, 2, 'tungsten', 5, { panel: false });- fill.position.set(2, 2, 2);- fill.lookAt(0, 2, -2);- scene.add(fill);- const cameras = [{ name: 'a', position: [0, 2, 5], lookAt: [0, 2, -2], fov: 45 }];- return { scene, cameras, update() {} };-}-"""---def test_a_panel_light_compiles_on_the_gpu():- """RectAreaLight is its own shader permutation (the LTC path), and a- missing LTC table is silent — black, no error. Boot a lit scene- headless so the permutation is proved to build on this host.- """- code, out = compile_scene(_SCENE, _LIBS, timeout_s=120.0)- assert code == 0, outdiff --git a/harness/tests/scene_runtime/lib/test_mirror.py b/harness/tests/scene_runtime/lib/test_mirror.pydeleted file mode 100644index c9e47ba2..00000000--- a/harness/tests/scene_runtime/lib/test_mirror.py+++ /dev/null@@ -1,545 +0,0 @@-"""mirror.js: the one real planar mirror, and the cheap route for everything-else — a baked equirect city that a whole facade can reflect for free.--Ported 2026-09-01 from the scene_multifile_graphics reference-(tests/test_mirror_lib.py). Their budget, standoff, target-shape and-retarget scenarios are kept as they stood; their `logarithmicDepthBuffer:-true` renderer contract is retargeted (ours has it OFF by default, but-`--log-depth` is still a host option and the addon's four chunks cost-nothing, so the "never hand the Reflector a replacement shader" law stays);-and their render probe is dropped in favour of the showcase harness, which-renders this module through OUR host at fx/out/mirror/{before,after}.--THE PORT'S OWN LAWS — each one a frame rendered on our host, looked at, and-measured, and each one a defect the reference shipped:--1. THE BAKE HAS TO SHIP sRGB BYTES. Every colour in `bakeSkylineEnvironment`- is mixed in the LINEAR working space a THREE.Color holds, and the- DataTexture it writes is flagged SRGBColorSpace — so it is DECODED as- sRGB when sampled. The reference wrote the linear numbers straight into- the bytes and ran the transfer backwards: the intended zenith 0x5d8fd6- shipped as (28,70,171) and came back as linear (0.011,0.061,0.415). A- sixth of the light, and blue pulled far ahead of red, because the error- is a power curve and not a scale. On our host every facade `glazeFacade`- touched rendered as a flat navy slab: mean_lum 0.145, saturation 0.72,- modal_frac 0.153 — the "black hole" the module's own docstring says the- cheap route exists to prevent. After the fix, 0.355 / 0.334 / 0.046,- with the reflected skyline legible in the frame.--2. A CURTAIN WALL'S MIRROR LIVES IN THE COATING, NOT THE METAL. A metal's- F0 IS its colour, and this glass tint is linear (0.031,0.058,0.088), so- the reference's metalness 0.35 multiplied a third of the reflection by a- near-black blue. An untinted `clearcoat` is what real reflective glazing- actually is: the sky arrives in the sky's own colour, with its own- fresnel. Measured together with law 1 on the glazed block: pane region- p05 0.063 -> 0.256.--3. A REFLECTED CITY IS NOT ONE SWATCH, AND IT KNOWS WHAT TIME IT IS. The- skyline was one hue scaled by one random number per building, unlit- unless asked, and lit by a hardcoded noon palette even when handed a- sun that had set. It now takes hue and saturation per building, shades- facades by the key light's own azimuth, hazes toward the horizon, and- flips to the night mood — moon where lib/environment.js puts the moon,- windows on — the moment `sunDir` goes below the horizon.-"""--from __future__ import annotations--import math--import pytest--from tests.scene_runtime.lib._probe import LIB_DIR, NODE_MODULES, measure--pytestmark = pytest.mark.node--_LIBS = ("mirror.js", "wetground.js", "building.js", "materials.js",- "noise.js")--_PROBE = """-import * as THREE from 'three';-import { makeMirror, envMirrorMaterial, bakeSkylineEnvironment,- glassFacadeMaterial, glazeFacade, reflectionBudget,- setReflectionBudget } from './lib/mirror.js';-import { makeMirrorFloor } from './lib/wetground.js';-import { block } from './lib/building.js';-import { mulberry32 } from './lib/noise.js';--// 1) The one real mirror, and what the Reflector was handed.-const scene = new THREE.Scene();-const m1 = makeMirror(4, 3, { scene });-scene.add(m1);-const surf = m1.userData.surface;-const rttTex = surf.material.uniforms.tDiffuse.value;-const rttSamples = surf.getRenderTarget().samples;-const tint = surf.material.uniforms.color.value;-const back = m1.getObjectByName('MirrorBack');-const frame = m1.getObjectByName('MirrorFrame');--// 2) A SECOND surface in the same scene must not get its own RTT.-const m2 = makeMirror(4, 3, { scene });--// 3) A mirror floor built by another module charges the same budget.-setReflectionBudget(1);-const wet = new THREE.Scene();-wet.add(makeMirrorFloor(20, 20));-const m3 = makeMirror(4, 3, { scene: wet });-const wetBudget = reflectionBudget(wet);--// 4) A fresh budget hands out a real mirror again; 'env' never takes one.-setReflectionBudget(1);-const forcedEnv = makeMirror(4, 3, { mode: 'env' });-const m4 = makeMirror(4, 3, {});--// 5) The baked environment: deterministic, filtered, structured, sRGB.-const e1 = bakeSkylineEnvironment({ seed: 3 });-const e2 = bakeSkylineEnvironment({ seed: 3 });-const flat = bakeSkylineEnvironment({ seed: 3, skyline: false });-const warm = bakeSkylineEnvironment({ seed: 3, lit: 0.6 });-// A sun straight DOWN leaves the upper hemisphere free of glow, so the top-// row is the requested zenith and nothing else: the transfer function is-// then the only thing between the hex asked for and the bytes shipped.-const clean = bakeSkylineEnvironment({- seed: 3, skyline: false, sunDir: new THREE.Vector3(0, -1, 0),- zenith: 0x5d8fd6, horizon: 0xdce9f2, ground: 0x8a7f6a });-const d1 = e1.image.data, d2 = e2.image.data;-let sameBake = d1.length === d2.length;-for (let i = 0; sameBake && i < d1.length; i++) {- if (d1[i] !== d2[i]) sameBake = false;-}-const W = e1.image.width, H = e1.image.height;-function rowMean(data, r0, r1) {- let s = 0, n = 0;- for (let y = r0; y < r1; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- s += (data[i] + data[i + 1] + data[i + 2]) / 3;- n++;- }- }- return s / n;-}-function rowMin(data, r0, r1) {- let m = 255;- for (let y = r0; y < r1; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- const l = (data[i] + data[i + 1] + data[i + 2]) / 3;- if (l < m) m = l;- }- }- return m;-}-// Circular spread of hue, in degrees, over the pixels with colour in them.-function hueStdDeg(data, r0, r1) {- let cx = 0, cy = 0, n = 0;- for (let y = r0; y < r1; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- const r = data[i], g = data[i + 1], b = data[i + 2];- const M = Math.max(r, g, b), mn = Math.min(r, g, b), c = M - mn;- if (M <= 0 || c / M <= 0.04) continue;- let h;- if (M === r) h = ((g - b) / c + 6) % 6;- else if (M === g) h = (b - r) / c + 2;- else h = (r - g) / c + 4;- const a = h * 60 * Math.PI / 180;- cx += Math.cos(a); cy += Math.sin(a); n++;- }- }- if (n < 64) return 0;- const R = Math.min(1, Math.hypot(cx, cy) / n);- return Math.sqrt(-2 * Math.log(Math.max(R, 1e-9))) * 180 / Math.PI;-}-// Rows just above the horizon (v = 0.5) are where the neighbours are.-const bandTop = (H >> 1) + 2, bandBot = (H >> 1) + 22;-let warmPx = 0;-for (let y = bandTop; y < bandBot; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- const wd = warm.image.data;- if (wd[i] > 110 && wd[i] - wd[i + 2] > 30) warmPx++;- }-}-const topRow = (H - 1) * W * 4;-const cd = clean.image.data;--// 6) The same bake once the sun has set: azimuth 215, elevation -20, the-// vector sunRig() reports as `sunDir` on a night scene.-const nEl = -20 * Math.PI / 180, nAz = 215 * Math.PI / 180;-const nightSun = new THREE.Vector3(- Math.cos(nEl) * Math.cos(nAz), Math.sin(nEl), Math.cos(nEl) * Math.sin(nAz));-const night = bakeSkylineEnvironment({ seed: 3, sunDir: nightSun });-const nd = night.image.data;-// Where is the brightest pixel of the night sky? The moon, and it has to be-// ABOVE the horizon: a set sun left as the glow source puts it underground.-let bestY = -1, bestV = -1;-for (let y = 0; y < H; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- const l = (nd[i] + nd[i + 1] + nd[i + 2]) / 3;- if (l > bestV) { bestV = l; bestY = y; }- }-}-let nightWarmPx = 0;-for (let y = bandTop; y < bandBot; y++) {- for (let x = 0; x < W; x++) {- const i = (y * W + x) * 4;- if (nd[i] > 90 && nd[i] - nd[i + 2] > 20) nightWarmPx++;- }-}--// 7) A facade from lib/building.js, retargeted.-// block() splits its panes on `rand()`, and its default rand is a-// constant 0.5 that always lands in bin 0 — a seeded one is what makes-// the second batch exist at all.-const b = block({ w: 16, d: 14, h: 30, style: 'glass',- rand: mulberry32(5) });-const glazing = b.getObjectByName('Glazing');-const glazing2 = b.getObjectByName('Glazing2');-const reveals = b.getObjectByName('Reveals');-const revealsBefore = reveals.material.uuid;-glazeFacade(b, { envMap: e1 });-const gm = glazing.material;-// The same tower, glazed with an explicit material: one value everywhere.-const b2 = block({ w: 16, d: 14, h: 30, style: 'glass',- rand: mulberry32(5) });-glazeFacade(b2, { material: glassFacadeMaterial({ envMap: e1 }) });--const chrome = envMirrorMaterial({ envMap: e1 });-const gTrans = glassFacadeMaterial({ opacity: 0.6 });--console.log(JSON.stringify({- mode1: m1.userData.mode, mode2: m2.userData.mode,- mode3: m3.userData.mode, mode4: m4.userData.mode,- modeForcedEnv: forcedEnv.userData.mode,- wetUsed: wetBudget.used, wetLeft: wetBudget.left,- tintLinear: tint.r,- rttW: rttTex.image.width, rttH: rttTex.image.height,- rttSamples,- standoff: surf.position.z, backZ: back.position.z,- surfCast: surf.castShadow, surfReceive: surf.receiveShadow,- forward: m1.userData.forward,- backLum: back.material.color.r * 0.2126 + back.material.color.g * 0.7152- + back.material.color.b * 0.0722,- frameLum: frame.material.color.r * 0.2126- + frame.material.color.g * 0.7152 + frame.material.color.b * 0.0722,- frameWarm: frame.material.color.r - frame.material.color.b,- sameBake,- envW: W, envH: H,- equirect: e1.mapping === THREE.EquirectangularReflectionMapping,- srgb: e1.colorSpace === THREE.SRGBColorSpace,- linearFiltered: e1.minFilter === THREE.LinearFilter- && e1.magFilter === THREE.LinearFilter,- zenith: rowMean(e1.image.data, H - 6, H - 1),- bandSkyline: rowMean(e1.image.data, bandTop, bandBot),- bandOpenSky: rowMean(flat.image.data, bandTop, bandBot),- bandMin: rowMin(e1.image.data, bandTop, bandBot),- bandHueStd: hueStdDeg(e1.image.data, bandTop, bandBot),- openHueStd: hueStdDeg(flat.image.data, bandTop, bandBot),- warmPx,- cleanTop: [cd[topRow], cd[topRow + 1], cd[topRow + 2]],- nightZenith: rowMean(nd, H - 6, H - 1),- dayZenith: rowMean(e1.image.data, H - 6, H - 1),- nightBandMin: rowMin(nd, bandTop, bandBot),- nightMoonAboveHorizon: bestY > (H >> 1),- nightWarmPx,- glazed: b.userData.glazed,- glazeIsPhysical: !!gm.isMeshPhysicalMaterial,- glazeEnv: gm.envMap === e1,- glazeIor: gm.ior, glazeTransparent: gm.transparent,- glazeClearcoat: gm.clearcoat, glazeMetalness: gm.metalness,- batchesDiffer: glazing.material.uuid !== glazing2.material.uuid,- batchEnvBoth: glazing2.material.envMap === e1,- forcedOneMaterial: b2.getObjectByName('Glazing').material.uuid- === b2.getObjectByName('Glazing2').material.uuid,- revealsUntouched: reveals.material.uuid === revealsBefore,- chromeMetal: chrome.metalness, chromeRough: chrome.roughness,- transFlag: gTrans.transparent, transOpacity: gTrans.opacity,-}));-"""--[email protected](scope="module")-def probe() -> dict:- """One node launch of _PROBE, shared by every test that reads it."""- return measure(_PROBE, _LIBS)---def test_the_scene_gets_one_real_mirror_and_no_more(probe):- """The budget is the module's reason to exist: a second RTT surface- renders INSIDE the first one's pass, so it cannot be left to the- caller's discipline. A mirror floor from wetground.js counts too --- the budget is per scene, not per module."""- m = probe- assert m["mode1"] == "rtt", "the first mirror must be a real one"- assert m["mode2"] == "env", (- "a second mirror in the same scene took its own render target"- )- assert m["mode3"] == "env", (- "a wetground makeMirrorFloor in the scene did not charge the "- "budget — two RTT surfaces ship whenever the modules differ"- )- assert (m["wetUsed"], m["wetLeft"]) == (1, 0), m- assert m["mode4"] == "rtt", "a fresh budget hands out a real mirror"- assert m["modeForcedEnv"] == "env", "mode:'env' still took an RTT"---def test_the_reflection_is_untinted_and_frame_shaped(probe):- """Two Reflector defaults are wrong for a mirror. Its 0x7f7f7f- OVERLAY-blends to ~0.42x on darks (dim, dirty glass) — overlay's- identity is linear 0.5. And its square target oversamples vertically at- 1.8x the pixel cost, because the target holds a SCREEN-space image, not- a picture of the mirror.-- Overlay's identity holds on OUR host for a second reason worth keeping- written down: the addon renders the reflection to a render target, where- three forces NoToneMapping and a linear output, and applies the tone map- and the sRGB encode in the mirror's OWN fragment tail instead. So the- values `color` blends against are linear radiance that can exceed 1, and- blendOverlay at 0.5 is the identity there too."""- m = probe- assert abs(m["tintLinear"] - 0.5) < 0.02, (- f"mirror tint is linear {m['tintLinear']:.3f}, not the overlay "- "identity 0.5 — the reflection is being darkened or blown out"- )- assert abs(m["rttW"] / m["rttH"] - 16 / 9) < 0.02, (- f"reflection target {m['rttW']}x{m['rttH']} is not frame-shaped"- )- assert m["rttW"] >= 640, f"reflection target too coarse: {m['rttW']}"- assert m["rttSamples"] == 0, (- f"MSAA {m['rttSamples']} on the reflection target: measured 28 "- "ms/frame on SwiftShader for a difference invisible at 1:1 — "- "the reflection is minified onto the mirror and the frame is "- "antialiased anyway"- )---def test_nothing_sits_within_a_centimetre_behind_the_glass(probe):- """Measured: geometry within 1 cm behind the glass leaks past the- Reflector's oblique clip plane and fills the mirror with a dark slab- from 20 degrees off-axis (2 cm is clean to 55 degrees). The standoff is- what buys that clearance, so it is not decoration."""- m = probe- assert m["standoff"] >= 0.02, (- f"glass stands only {m['standoff']} m off the mount plane"- )- assert m["standoff"] - m["backZ"] >= 0.02, (- f"backing plate is {m['standoff'] - m['backZ']:.3f} m behind "- "the glass — it will leak into the reflection"- )- assert not m["surfCast"] and not m["surfReceive"], (- "an RTT plane that casts shadows shadows the scene it resamples"- )- assert m["forward"] == "+Z", m["forward"]---def test_the_frame_is_the_only_lit_thing_next_to_the_reflection(probe):- """PORT LAW. A mirror is full of the scene's own brightness, so the two- surfaces around it decide whether it reads as an object or as a hole cut- in the wall — and the reference set both at the floor of a legal albedo- (frame 0x4a3a2a, linear 0.068; plate 0x2a2724, linear 0.024). Rendered- on our host at exposure 1.0 the frame came back as a black border with- no grain in it at all. Walnut keeps it a dark frame and gives it a hue:- the close view's frame band went p05 0.170 -> 0.217 and hue spread- 0.843 -> 0.928."""- m = probe- assert m["frameLum"] > 0.05, (- f"frame albedo is linear {m['frameLum']:.3f} — under ACES at "- "exposure 1.0 that is a black rectangle, not a frame"- )- assert m["frameWarm"] > 0.03, (- "the frame has no hue in it; wood is warmer than it is blue"- )- assert m["backLum"] > 0.025, (- f"backing plate is linear {m['backLum']:.3f} — it has nowhere "- "left to fall in shade"- )---def test_the_bake_ships_srgb_bytes_and_not_linear_ones(probe):- """PORT LAW 1, and the worst defect in the module. Every colour is mixed- in the LINEAR working space a THREE.Color holds, and the DataTexture is- flagged SRGBColorSpace, so it is DECODED as sRGB on sample. Writing the- linear numbers straight out runs the transfer backwards: 0x5d8fd6 left- as (28,70,171) instead of (93,143,214) and came back as a sixth of the- light with blue far ahead of red, because the error is a power curve and- not a scale. On our host that is what made every glazed facade a flat- navy slab."""- r, g, b = probe["cleanTop"]- for got, want, ch in ((r, 0x5d, "r"), (g, 0x8f, "g"), (b, 0xd6, "b")):- assert abs(got - want) <= 3, (- f"zenith {ch} shipped as byte {got}, asked for {want} — the "- f"bake wrote {ch} in the linear working space into a texture "- "that is decoded as sRGB"- )---def test_the_baked_environment_carries_a_city_not_a_gradient(probe):- """The cheap route only beats a plain sky gradient if the bake has- neighbours in it: a dark band of towers above the horizon is what a glass- facade actually mirrors. Deterministic, or a fix round re-rolls the- skyline; LINEAR filtered, or a DataTexture's Nearest default prints the- bake's texel grid across every facade.-- PORT LAW 3 adds the two floors under it. The band must not bottom out- near black — aerial perspective is what a city actually does to its own- contrast, and without it the darkest facades were the ones a mirror- turned into a hole. And it must carry more than one hue: the reference- scaled a single wall colour by one random number per building, which is- the "stamped asset" verdict in swatch form."""- m = probe- assert m["sameBake"], "two bakes of one seed differ"- assert m["equirect"] and m["srgb"], m- assert m["linearFiltered"], (- "environment left on the DataTexture Nearest default"- )- assert (m["envW"], m["envH"]) == (512, 256), m- assert m["bandSkyline"] < 0.7 * m["bandOpenSky"], (- f"the horizon band reads {m['bandSkyline']:.1f} with a skyline "- f"vs {m['bandOpenSky']:.1f} without — no neighbours were baked"- )- assert m["zenith"] > m["bandSkyline"], "the sky is darker than the city"- assert m["warmPx"] > 200, (- f"lit: 0.6 lit only {m['warmPx']} window pixels"- )- assert m["bandMin"] >= 40, (- f"darkest neighbour in the band is byte {m['bandMin']:.0f} — a "- "facade that mirrors it renders as a hole"- )- assert m["bandHueStd"] > 2.5 * max(m["openHueStd"], 0.8), (- f"the skyline's hue spread is {m['bandHueStd']:.2f} deg against "- f"{m['openHueStd']:.2f} for bare sky — every neighbour was baked "- "from one swatch"- )---def test_the_bake_knows_what_time_it_is(probe):- """PORT LAW 3. `sunDir` already carries the hour, so a bake that keeps- noon hexes while the scene hands it a set sun mirrors a noon sky off- every pane at midnight — the one hardcoded-light-colour failure this- module could still commit. Below the horizon the palette flips to the- night mood the rest of the library uses, the glow moves to where- lib/environment.js puts the MOON (opposite the sun, 30-55 deg up, not- underground), and the reflected city has its lights on without being- asked. The lower half stays off the floor on purpose: a night horizon- carries a city's skyglow and a night street carries its own lamps, and- neither is a fraction of the zenith."""- m = probe- assert m["nightZenith"] < 0.45 * m["dayZenith"], (- f"night zenith {m['nightZenith']:.1f} vs day "- f"{m['dayZenith']:.1f} — the palette did not follow sunDir down"- )- assert m["nightMoonAboveHorizon"], (- "the brightest pixel of the night sky is below the horizon — the "- "glow is still sitting on the set sun instead of the moon"- )- assert m["nightWarmPx"] > 150, (- f"only {m['nightWarmPx']} warm window pixels after dark — a city "- "with every light out is a ruin, not a night"- )- assert m["nightBandMin"] >= 18, (- f"darkest night neighbour is byte {m['nightBandMin']:.0f}"- )---def test_a_building_facade_is_retargeted_without_losing_its_lit_windows(- probe,-):- """The whole point of the cheap route: one call makes a lib/building.js- tower mirror the sky. Lit windows live on the Reveals mesh and must keep- glowing — glazing every mesh would put out the lights that make a dusk- city read as inhabited.-- PORT LAW 2 and its corollary. The mirror a curtain wall shows lives in- an UNTINTED coating, not in metalness: a metal's F0 is its colour, and- this tint is linear (0.031,0.058,0.088), so the reference multiplied a- third of every reflection by a near-black blue and got the flat navy- hole its own docstring warns about. And building.js already splits its- panes into two batches precisely because "real glazing is never one- value" — retargeting both to a single material threw that away."""- m = probe- assert m["glazed"] >= 2, "no Glazing/Pane mesh was retargeted"- assert m["glazeIsPhysical"] and m["glazeEnv"], m- assert m["glazeIor"] > 1.5, (- f"ior {m['glazeIor']:.2f}: uncoated glass reflects ~4% head-on "- "and renders as a black hole"- )- assert m["glazeClearcoat"] >= 0.5, (- f"clearcoat {m['glazeClearcoat']} — without an untinted coat the "- "sky arrives on the glass multiplied by the glass's own near-black"- )- assert m["glazeMetalness"] <= 0.25, (- f"metalness {m['glazeMetalness']} tints and dims that much of the "- "reflection with the pane's own colour"- )- assert not m["glazeTransparent"], (- "opaque by default — transparent glazing stops writing depth"- )- assert m["batchesDiffer"] and m["batchEnvBoth"], (- "both pane batches got one material: building.js splits Glazing "- "and Glazing2 to keep a facade off one flat value, and glazeFacade "- "collapsed the split"- )- assert m["forcedOneMaterial"], (- "opts.material must be applied as-is — no variants behind the "- "caller's back"- )- assert m["revealsUntouched"], "glazeFacade put out the lit windows"- assert m["chromeMetal"] == 1 and m["chromeRough"] > 0, m- assert m["transFlag"] and abs(m["transOpacity"] - 0.6) < 1e-9, m---def test_the_reflection_shader_is_the_addons_and_never_a_replacement():- """Retargeted, not dropped. Our renderer.js runs- `logarithmicDepthBuffer` OFF by default, but `--log-depth` is still a- host option, and a custom ShaderMaterial without the logdepthbuf chunks- is erased by any opaque geometry behind it under that flag. The addon- Reflector carries all four; this module must never hand it a- replacement shader, which is also why the glass tint below is a- material parameter and not a patched fragment."""- src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")- for banned in ("fragmentShader", "vertexShader", "onBeforeCompile",- "ShaderMaterial"):- assert banned not in src, (- f"mirror.js touches {banned} — a custom reflection shader "- "must include logdepthbuf_pars_vertex / logdepthbuf_vertex "- "/ logdepthbuf_pars_fragment / logdepthbuf_fragment"- )- addon = (NODE_MODULES / "three" / "examples" / "jsm" / "objects"- / "Reflector.js")- if not addon.is_file():- pytest.skip("no three.js addon install to read the Reflector from")- text = addon.read_text(encoding="utf-8")- for chunk in ("logdepthbuf_pars_vertex", "logdepthbuf_vertex",- "logdepthbuf_pars_fragment", "logdepthbuf_fragment"):- assert f"#include <{chunk}>" in text, (- f"the shipped Reflector lost <{chunk}> — every mirror will "- "vanish behind opaque geometry under --log-depth"- )---def test_the_module_stays_dom_free_and_seeded():- """Asset code runs in a headless page with no canvas and must re-render- identically every round: Math.random and any DOM API are banned outright- (mulberry32 from noise.js is the one PRNG)."""- src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")- for banned in ("Math.random", "document.", "createElement",- "new Image", "canvas"):- assert banned not in src, f"mirror.js uses {banned}"---def test_the_transfer_function_is_the_real_srgb_curve():- """A guard on the fix itself, cheap enough to keep. The encode has to be- the piecewise sRGB OETF, not a 1/2.2 power approximation: the two differ- by up to 4 bytes in the darks, which is exactly where the reflected city- lives."""- src = (LIB_DIR / "mirror.js").read_text(encoding="utf-8")- assert "0.0031308" in src and "1 / 2.4" in src, (- "mirror.js is not encoding with the piecewise sRGB transfer"- )- # and the curve it names is the right one, at the two ends and the knee- for lin, want in ((0.0, 0.0), (0.0031308, 0.04045), (1.0, 1.0)):- got = (lin * 12.92 if lin <= 0.0031308- else 1.055 * math.pow(lin, 1 / 2.4) - 0.055)- assert abs(got - want) < 1e-3, (lin, got, want)diff --git a/harness/tests/scene_runtime/lib/test_river.py b/harness/tests/scene_runtime/lib/test_river.pydeleted file mode 100644index 58a10def..00000000--- a/harness/tests/scene_runtime/lib/test_river.py+++ /dev/null@@ -1,497 +0,0 @@-"""A river is not a plane with a scrolling texture.--Scroll a UV on a curved ribbon and the whole sheet slides one way, so-round a bend the water stops following its own course — the one defect-that reads instantly as "moving texture" instead of "river". ``river.js``-carries the centreline tangent per vertex and advects its noise along-THAT, so the geometry half of these tests holds the claim (the flow field-is tangent to the course, and it turns where the course turns) rather-than any pixel.--Ported 2026-09-01 from the scene_multifile_graphics reference test. The-colour half is OURS: the surface is unlit, so every constant in it is a-decision, and the reference's were three daylight constants baked into a-factory. Measured on this harness's night rig with those defaults, the-channel came back at luminance 0.40/0.54 over a frame whose mean was-0.21/0.31 — a strip of white plastic lying in the dark. It now reads the-scene's own key light, hemisphere fill and fog at the first render, so-the tests below pin THAT as hard as they pin the flow field.-"""--from __future__ import annotations--from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401--_LIBS = ("shader.js", "river.js")--# One S-bend, so a flow field that did not turn cannot pass by accident.-_POINTS = "[[-14,0,-12],[-5,0,-6],[2,0,2],[-1,0,10],[4,0,16]]"--# Rows are arc-length uniform, so a row's centre IS the centreline-# there; this hands every probe the same frame to measure against.-_FRAME = """-const geom = (g) => g.getObjectByName('Channel').geometry;-function frame(g) {- const a = geom(g).attributes;- const P = a.position.array, UV = a.uv.array;- let cols = 0;- while (cols < a.position.count && UV[cols * 2 + 1] === 0) cols++;- const rows = a.position.count / cols - 1;- const centre = [];- for (let j = 0; j <= rows; j++) {- let x = 0, y = 0, z = 0;- for (let i = 0; i < cols; i++) {- const k = (j * cols + i) * 3;- x += P[k]; y += P[k + 1]; z += P[k + 2];- }- centre.push([x / cols, y / cols, z / cols]);- }- return { a, cols, rows, centre };-}-"""--# A scene the way `sunRig` builds one: a key directional light, a-# hemisphere fill and fog. `adoptSceneLight` runs off `onBeforeRender`,-# which a probe can call directly — no GPU needed to prove what it read.-_LIT_SCENE = """-function litScene(THREE, opts) {- const o = opts || {};- const scene = new THREE.Scene();- const key = new THREE.DirectionalLight(o.sunHex || 0xfff0d8,- o.sunI === undefined ? 5.4 : o.sunI);- // Direction is position -> target, so a light at +y+x shines DOWN and- // the adopted uSun must point back up at it.- key.position.set(30, 40, -10);- scene.add(key);- const hemi = new THREE.HemisphereLight(o.skyHex || 0x9db8e8, 0x8a7f6a,- o.fillI === undefined ? 1.4 : o.fillI);- scene.add(hemi);- scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);- return scene;-}-const adopt = (g, scene) => {- const m = g.getObjectByName('Channel');- m.onBeforeRender(null, scene);- return m.material.uniforms;-};-const hex = (c) => [+c.r.toFixed(4), +c.g.toFixed(4), +c.b.toFixed(4)];-"""---def test_the_ribbon_follows_the_given_points():- """The course is the contract: every waypoint the caller gave must- have channel under it, and the ribbon rests on the water surface- rather than sinking into it or floating over it."""- out = measure(_FRAME + """-import { makeRiver } from './lib/river.js';-const pts = __POINTS__;-const g = makeRiver({ points: pts, width: 6, depth: 1.2, seed: 3 });-const { a, centre } = frame(g);-const miss = pts.map((p) => Math.min(...centre.map(- (c) => Math.hypot(c[0] - p[0], c[2] - p[2]))));-let run = 0;-for (let j = 1; j < centre.length; j++) {- run += Math.hypot(centre[j][0] - centre[j - 1][0],- centre[j][2] - centre[j - 1][2]);-}-const P = a.position.array;-let minY = 1e9, maxY = -1e9;-for (let i = 1; i < P.length; i += 3) {- minY = Math.min(minY, P[i]); maxY = Math.max(maxY, P[i]);-}-let poly = 0;-for (let i = 1; i < pts.length; i++) {- poly += Math.hypot(pts[i][0] - pts[i - 1][0],- pts[i][2] - pts[i - 1][2]);-}-console.log(JSON.stringify({- worstMiss: +Math.max(...miss).toFixed(3),- run: +run.toFixed(2), poly: +poly.toFixed(2),- straight: +Math.hypot(pts[4][0] - pts[0][0],- pts[4][2] - pts[0][2]).toFixed(2),- minY: +minY.toFixed(3), maxY: +maxY.toFixed(3),- name: g.name, hasTick: typeof g.userData.tick === 'function',-}));-""".replace("__POINTS__", _POINTS), _LIBS)- # Sampled every ~0.55 m, so the nearest row centre to a waypoint is- # inside half that; a ribbon that cut the corner would miss by- # metres.- assert out["worstMiss"] < 0.35, out- # It runs the polyline's own length — neither shortcutting the- # corners nor wandering off between them.- assert out["poly"] <= out["run"] <= out["poly"] * 1.05, out- assert out["run"] > out["straight"] * 1.1, out- # Rests ON the surface: a hair above the water plane it joins, not- # a slab with thickness.- assert 0 < out["minY"] <= 0.02 and out["maxY"] - out["minY"] < 0.01- assert out["name"] == "River" and out["hasTick"]---def test_the_flow_direction_is_tangent_to_the_centreline():- """The whole claim. `aFlow` is the world flow velocity, and its- direction must be the course's own tangent at that vertex — that is- what makes the advected pattern go round a bend instead of sliding- sideways as one sheet. A constant direction would pass a straight- reach and fail here, so the turn is measured too."""- out = measure(_FRAME + """-import { makeRiver } from './lib/river.js';-const g = makeRiver({ points: __POINTS__, width: 6, flow: 1.5, seed: 3 });-const { a, cols, rows, centre } = frame(g);-const F = a.aFlow.array;-const ang = (v) => Math.atan2(v[1], v[0]) * 180 / Math.PI;-let worst = 1, slow = 1e9, fast = -1e9;-const flowH = [], courseH = [];-for (let j = 1; j < rows; j++) {- // Central difference: second-order, so a real bend does not read as- // a tangency error the way a forward chord would.- const d = [centre[j + 1][0] - centre[j - 1][0],- centre[j + 1][2] - centre[j - 1][2]];- const dl = Math.hypot(d[0], d[1]);- for (let i = 0; i < cols; i++) {- const k = (j * cols + i) * 3;- const f = [F[k], F[k + 2]];- const fl = Math.hypot(f[0], f[1]);- worst = Math.min(worst, (f[0] * d[0] + f[1] * d[1]) / (fl * dl));- slow = Math.min(slow, fl); fast = Math.max(fast, fl);- if (i === 0) { flowH.push(ang(f)); courseH.push(ang(d)); }- }-}-// How far the heading swings over the whole course — an S returns to-// where it started, so end-to-end would say a river never turns.-const swing = (h) => Math.max(...h) - Math.min(...h);-console.log(JSON.stringify({- worstDot: +worst.toFixed(5),- flowSwing: +swing(flowH).toFixed(1),- courseSwing: +swing(courseH).toFixed(1),- slow: +slow.toFixed(3), fast: +fast.toFixed(3),- y: Math.max(...[...F].filter((_, i) => i % 3 === 1).map(Math.abs)),-}));-""".replace("__POINTS__", _POINTS), _LIBS)- assert out["worstDot"] > 0.999, out- # It TURNS, and it turns by exactly what the course turns by.- assert out["flowSwing"] > 40, out- assert abs(out["flowSwing"] - out["courseSwing"]) < 3, out- # Magnitude is the surface speed, horizontal: the flow map advects- # in metres per second, so a wrong length is a wrong current.- assert out["slow"] > 1.2 and out["fast"] < 1.9, out- assert out["y"] == 0, out---def test_it_runs_thin_over_the_bank_and_over_a_rock():- """Depth is what tells the eye where the channel is, and only the- CPU can find it: GLSL_UTIL's value noise is not the field the- terrain was built from, so `heightAt` is measured here and handed- over as an attribute or the pale shallows never line up with the- ground the water actually runs over."""- out = measure(_FRAME + """-import { makeRiver } from './lib/river.js';-// Flat bed at -1.6 with one boulder standing 1.3 m proud of it.-const heightAt = (x, z) =>- Math.max(0, 1.3 - Math.hypot(x, z) * 1.2) - 1.6;-const g = makeRiver({ points: [[-12, 0, 0], [12, 0, 0]], width: 6,- depth: 1.4, flow: 1.0, heightAt, seed: 2 });-const { a, cols, rows, centre } = frame(g);-const C = a.aChan.array;-const at = (j, i, c) => C[(j * cols + i) * 4 + c];-let bank = 0, mid = 0, rockDeep = 9, rockBrk = 0, calmBrk = 0;-for (let j = 0; j <= rows; j++) {- bank = Math.max(bank, at(j, 0, 1), at(j, cols - 1, 1));- const c = at(j, (cols - 1) / 2, 1);- const onRock = Math.abs(centre[j][0]) < 0.6;- if (onRock) {- rockDeep = Math.min(rockDeep, c);- rockBrk = Math.max(rockBrk, at(j, (cols - 1) / 2, 2));- } else {- mid = Math.max(mid, c);- // Upstream only: the wake downstream of the rock keeps foaming.- if (centre[j][0] < -3) calmBrk = Math.max(calmBrk, at(j, 7, 2));- }-}-console.log(JSON.stringify({- bank: +bank.toFixed(3), mid: +mid.toFixed(3),- rockDeep: +rockDeep.toFixed(3), rockBrk: +rockBrk.toFixed(3),- calmBrk: +calmBrk.toFixed(3),-}));-""", _LIBS)- assert out["bank"] == 0 and 1.3 < out["mid"] <= 1.4, out- # The water over the boulder is thin, and it breaks there.- assert out["rockDeep"] < 0.25, out- assert out["rockBrk"] > 0.5, out- # ...and nowhere else: foam everywhere is foam nowhere.- assert out["calmBrk"] < 0.05, out---def test_a_narrows_runs_faster_and_breaks():- """Flux, not decoration: the same water through a smaller gap has- to run faster, and that is what makes a narrows both race and go- white — one number driving both, so they cannot disagree."""- out = measure(_FRAME + """-import { makeRiver } from './lib/river.js';-const pinch = (u) => 6 * (1 - 0.45 * Math.exp(-Math.pow(- (u - 0.5) / 0.10, 2)));-const g = makeRiver({ points: [[-12, 0, 0], [12, 0, 0]], width: pinch,- depth: 1.2, flow: 1.0, seed: 6 });-const { a, cols, rows, centre } = frame(g);-const F = a.aFlow.array, C = a.aChan.array;-let gap = 1e9, wide = 0, gapV = 0, wideV = 9, gapBrk = 0, wideBrk = 0;-for (let j = 0; j <= rows; j++) {- const k = (j * cols) * 3;- const v = Math.hypot(F[k], F[k + 2]);- const w = Math.hypot(- a.position.array[k] - a.position.array[k + (cols - 1) * 3],- a.position.array[k + 2] - a.position.array[k + (cols - 1) * 3 + 2]);- const brk = C[(j * cols + (cols - 1) / 2) * 4 + 2];- if (Math.abs(centre[j][0]) < 1.0) {- gap = Math.min(gap, w); gapV = Math.max(gapV, v);- gapBrk = Math.max(gapBrk, brk);- } else if (centre[j][0] < -6) {- wide = Math.max(wide, w); wideV = Math.min(wideV, v);- wideBrk = Math.max(wideBrk, brk);- }-}-console.log(JSON.stringify({- gap: +gap.toFixed(2), wide: +wide.toFixed(2),- gapV: +gapV.toFixed(3), wideV: +wideV.toFixed(3),- gapBrk: +gapBrk.toFixed(3), wideBrk: +wideBrk.toFixed(3),-}));-""", _LIBS)- assert out["gap"] < out["wide"] * 0.7, out- assert out["gapV"] > out["wideV"] * 1.4, out- assert out["gapBrk"] > 0.5 and out["wideBrk"] < 0.05, out---def test_two_rivers_with_one_seed_are_identical():- """Determinism is the contract for every shipped factory: a re-run- that re-wanders the banks is a re-run nobody can compare against."""- out = measure("""-import { makeRiver } from './lib/river.js';-const dump = (s) => {- const g = makeRiver({ points: [[-8, 0, 0], [0, 0, 3], [8, 0, 0]],- width: 5, seed: s });- const a = g.getObjectByName('Channel').geometry.attributes;- return JSON.stringify([...a.position.array, ...a.aChan.array]);-};-const a = dump(5), b = dump(5), c = dump(9);-console.log(JSON.stringify({ same: a === b, differs: a !== c }));-""", _LIBS)- assert out["same"] and out["differs"]---def test_tick_advances_the_material():- """An un-advanced uTime is a frozen river, and the flow map resets- every period — so the clock is not optional dressing."""- out = measure("""-import { makeRiver } from './lib/river.js';-const g = makeRiver({ width: 5 });-const before = [], after = [];-g.traverse((o) => {- for (const m of [].concat(o.material || [])) {- if (m && m.uniforms && m.uniforms.uTime) {- before.push(m.uniforms.uTime.value);- }- }-});-g.userData.tick(2.5);-g.traverse((o) => {- for (const m of [].concat(o.material || [])) {- if (m && m.uniforms && m.uniforms.uTime) after.push(m.uniforms.uTime.value);- }-});-console.log(JSON.stringify({ before, after }));-""", _LIBS)- assert out["before"] == [0] and out["after"] == [2.5]---def test_the_stated_depth_actually_changes_how_deep_the_water_looks():- """The depth ramp must be absolute, not relative to the river's own- depth. The geometry writes `aChan.y = depth * (1 - q*q)`, so a ramp- normalised by that same `depth` divides it straight back out and- every river — a 0.25 m brook and a 3 m channel alike — saturates to- the deep colour mid-stream behind a constant-width shallow rim. The- metre is the thing that decides how much light comes back up."""- out = measure("""-import { makeRiver } from './lib/river.js';-const mid = (r) => {- const g = r.getObjectByName('Channel').geometry;- const c = g.getAttribute('aChan');- let best = 0;- for (let i = 0; i < c.count; i++) best = Math.max(best, c.getY(i));- return best;-};-const pts = [[-8, 0, -8], [0, 0, 0], [8, 0, 8]];-const brook = makeRiver({ points: pts, width: 3, depth: 0.25, seed: 4 });-const deepR = makeRiver({ points: pts, width: 3, depth: 3.0, seed: 4 });-const src = brook.getObjectByName('Channel').material.fragmentShader;-console.log(JSON.stringify({- brookDepth: mid(brook),- riverDepth: mid(deepR),- dividesItOut: /vChan\\.y\\s*\\/\\s*uDepthM/.test(src),-}));-""", _LIBS)- assert out["brookDepth"] < 0.3 and out["riverDepth"] > 2.5, out- assert not out["dividesItOut"], (- "the shader divides the measured depth by the depth it was built "- "from, so `depth` cannot reach the eye")---def test_a_river_at_the_depth_people_actually_pass_is_not_pale():- """The ramp is absolute, which is right, but the metre it was set to- was picked from plausibility rather than from what callers pass. At- uOpaqueM 2.4 a river 1 m deep reached dep 0.42 at its deepest point- and the smoothstep floor kept nearly all of an 18 m channel in the- SHALLOW colour — a pale sage ribbon bank to bank. A river is 1-2 m- deep; the scale has to be near that, and the deep end of the ramp- has to sit inside where a real river ever gets."""- out = measure("""-import { makeRiver } from './lib/river.js';-const mid = (r) => {- const g = r.getObjectByName('Channel').geometry;- const c = g.getAttribute('aChan');- let best = 0;- for (let i = 0; i < c.count; i++) best = Math.max(best, c.getY(i));- return best;-};-const m = makeRiver({ width: 18, depth: 1.0, flow: 0.45, seed: 3 });-const mat = m.getObjectByName('Channel').material;-const edges = /mix\\(uShallow, uDeep, smoothstep\\(([0-9.]+), ([0-9.]+), dep\\)\\)/- .exec(mat.fragmentShader);-console.log(JSON.stringify({- deepest: mid(m),- opaque: mat.uniforms.uOpaqueM.value,- lo: edges ? parseFloat(edges[1]) : null,- hi: edges ? parseFloat(edges[2]) : null,-}));-""", _LIBS)- dep = out["deepest"] / out["opaque"]- assert dep >= 0.85, (- f"a 1 m river only reaches dep {dep:.2f}; it will render as its "- "shallow colour nearly everywhere")- assert out["hi"] is not None and out["hi"] <= dep, (- f"the deep end of the ramp ({out['hi']}) sits past where a real "- f"river ever gets ({dep:.2f})")- # ...and it is a RAMP: at 0.34 the colour saturated the moment the- # bed dropped away and the whole channel became one flat value.- assert out["hi"] - out["lo"] > 0.4, out---def test_the_surface_takes_its_light_from_the_scene():- """OURS. The surface is unlit — it writes its own light out — so a- daylight constant baked into the factory is a river that glows under- a moon. Measured on this harness's night rig with the reference- defaults, the channel came back at luminance 0.40/0.54 over a frame- whose mean was 0.21/0.31. It now reads the key light's direction,- colour and STRENGTH and the sky half of the hemisphere fill at the- first render, so a night scene darkens the water with it."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeRiver } from './lib/river.js';-const day = makeRiver({ width: 6, seed: 3 });-const dayU = adopt(day, litScene(THREE, {}));-// The same river in the night rig's own numbers: a 2.2 moon and a 1.0-// fill, both cool.-const night = makeRiver({ width: 6, seed: 3 });-const nightU = adopt(night, litScene(THREE, {- sunHex: 0xb5c7e8, sunI: 2.2, skyHex: 0x3f5378, fillI: 1.0 }));-const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;-console.log(JSON.stringify({- sun: [+dayU.uSun.value.x.toFixed(3), +dayU.uSun.value.y.toFixed(3),- +dayU.uSun.value.z.toFixed(3)],- daySunLum: +lum(dayU.uSunCol.value).toFixed(4),- nightSunLum: +lum(nightU.uSunCol.value).toFixed(4),- daySkyLum: +lum(dayU.uSky.value).toFixed(4),- nightSkyLum: +lum(nightU.uSky.value).toFixed(4),- nightSkyBlue: nightU.uSky.value.b > nightU.uSky.value.r,- dayAmbLum: +lum(dayU.uAmb.value).toFixed(4),- nightAmbLum: +lum(nightU.uAmb.value).toFixed(4),-}));-""", _LIBS)- # The light at (30, 40, -10) shines DOWN; uSun points back up at it.- d = out["sun"]- n = (d[0] ** 2 + d[1] ** 2 + d[2] ** 2) ** 0.5- assert abs(n - 1) < 1e-3, out- assert abs(d[0] / n - 0.588) < 0.01 and abs(d[1] / n - 0.784) < 0.01, out- # Strength, not just hue: the moon rig has to arrive dimmer than the- # sun rig in every one of the three terms the body colour is built- # from, or "night" is a colour swap and nothing else.- assert out["nightSunLum"] < out["daySunLum"] * 0.55, out- assert out["nightSkyLum"] < out["daySkyLum"] * 0.35, out- assert out["nightAmbLum"] < out["dayAmbLum"] * 0.35, out- # ...and the night sky it reflects is BLUE, not grey: dark but lit.- assert out["nightSkyBlue"], out---def test_a_colour_the_caller_pinned_survives_the_scene():- """Reading the scene is a DEFAULT, not a seizure: a caller who wrote- a sunset river down in hex has to get that river in a scene lit any- way at all, or the option is decoration."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeRiver } from './lib/river.js';-const dir = new THREE.Vector3(0, 1, 0);-const g = makeRiver({ width: 6, seed: 3, sky: 0xff0000,- sunColor: 0x00ff00, ambient: 0x0000ff,- sunDir: dir });-const u = adopt(g, litScene(THREE, {}));-// Nothing pinned: only these move.-const g2 = makeRiver({ width: 6, seed: 3 });-const u2 = adopt(g2, litScene(THREE, {}));-console.log(JSON.stringify({- sky: hex(u.uSky.value), sun: hex(u.uSunCol.value),- amb: hex(u.uAmb.value),- dir: [u.uSun.value.x, u.uSun.value.y, u.uSun.value.z],- freeSkyIsRed: u2.uSky.value.r > u2.uSky.value.b,-}));-""", _LIBS)- assert out["sky"] == [1, 0, 0] and out["sun"] == [0, 1, 0], out- assert out["amb"] == [0, 0, 1], out- assert out["dir"] == [0, 1, 0], out- # The control: with nothing pinned the scene's own pale-blue sky is- # what lands, so the assertions above are not passing vacuously.- assert not out["freeSkyIsRed"], out---_SCENE = """-import * as THREE from 'three';-import { makeRiver } from './lib/river.js';-import { tickShaders } from './lib/shader.js';--export const BOUNDS = { min: [-20, -2, -20], max: [20, 6, 20] };-export function heightAt() { return 0; }--export async function createScene() {- const scene = new THREE.Scene();- // Fogged, because the flow map is one custom shader on the raw route- // and the fog chunk is exactly what a hand-written shader forgets.- scene.fog = new THREE.FogExp2(0xcfd8e6, 0.004);- const key = new THREE.DirectionalLight(0xfff0d8, 5.4);- key.position.set(30, 40, -10);- scene.add(key);- scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));- const river = makeRiver({- points: __POINTS__, width: (u) => 5.6 * (1 - 0.4 * Math.exp(- -Math.pow((u - 0.5) / 0.08, 2))),- depth: 1.4, flow: 1.4, seed: 4,- heightAt: (x, z) => Math.max(0, 1.5 - Math.hypot(x - 1.4, z - 2.2))- - 1.6,- });- scene.add(river);- // A camera, because the host reports a scene with none as not booted- // and never reaches the compile stage at all.- return {- scene,- cameras: [{ name: 'a', position: [9, 3, 11], lookAt: [0, 0, 0],- fov: 45 }],- update(t) { tickShaders(scene, t); river.userData.tick(t); },- };-}-""".replace("__POINTS__", _POINTS)---def test_the_river_compiles_on_the_real_renderer():- """The flow map is one custom shader on the raw route, so the depth- and fog chunks are the difference between a river and nothing at- all — and only the GPU can say whether it compiled."""- code, out = compile_scene(_SCENE, _LIBS)- assert code == 0, out- assert "every program compiled" in out- assert "WARN" not in out, outdiff --git a/harness/tests/scene_runtime/lib/test_scatter.py b/harness/tests/scene_runtime/lib/test_scatter.pydeleted file mode 100644index 677b0e66..00000000--- a/harness/tests/scene_runtime/lib/test_scatter.py+++ /dev/null@@ -1,405 +0,0 @@-"""scatter.js: instances ON the surface, exact count, deterministic, GRADED.--Ported 2026-09-01 from the scene_multifile_graphics reference-(tests/test_scatter_lib.py). Their scaffolding is dropped; the placement-claims are kept verbatim in spirit — MeshSurfaceSampler's two traps-(LOCAL-space samples used raw, and its `Math.random` default) plus slope-gating on TRUE face normals rather than the smoothed vertex normals that-under-report a slope.--What this port ADDED, and the reason each assertion exists:--`colorJitter` shipped as `setScalar(1 - colorJitter * rand())` — a-one-sided GREY multiplier. Measured on 600 instances of a 0x537a36-tuft at colorJitter 0.45: mean multiplier 0.7783 (the authored albedo-was silently 22 % darker than the colour the author picked, and the-field's mean is never recoverable by choosing a brighter one, because-the bias scales with the jitter) and hue spread 0.000 degrees across-the whole field. A thousand copies varying only in brightness is the-wallpaper read the option exists to break. So the multiplier is now-CENTRED on the authored albedo and carries a warm/cool hue axis, and-the three properties that keeps it honest are pinned here:-- * centred — the field mean returns the colour that was authored;- * hue actually moves, and the axis is capped by the albedo's own- chroma: a near-neutral colour has no hue to nudge, so an unbounded- push INVENTS one and a grey field comes back half orange and half- blue (measured on 0x808080 at full jitter: peak saturation 0.888- with the cap removed, 0.113 with it);- * the product stays inside the scene contract's 0.02..0.82 albedo- band at any jitter, so a pale prototype cannot blow out under ACES- and a dark one cannot punch a black hole in the field.--And one workflow law: colour must not move the FIELD. Hue rides its-own PRNG stream and the value draw is taken whether or not it is used,-so turning colorJitter on to break a wallpaper read cannot also re-roll-every position out from under a layout that was already approved.--`alignToNormal` also takes a NUMBER now: real grass on a bank leans-downhill without lying flat on it, and true/false still mean 1/0.-"""--from __future__ import annotations--import pytest-from _probe import measure--pytestmark = pytest.mark.node---def _measure(script: str) -> dict:- return measure(script, ("scatter.js",))---_PLACEMENT = """-import * as THREE from 'three';-import { displaceY } from './lib/noise.js';-import { scatter } from './lib/scatter.js';--const makeTerrain = () => {- const g = new THREE.PlaneGeometry(160, 160, 96, 96);- g.rotateX(-Math.PI / 2);- displaceY(g, 12, 0.03, 7);- return new THREE.Mesh(g, new THREE.MeshStandardMaterial());-};--// Terrain nested in a transformed parent: scatter must bake the FULL-// world transform, not hand back local-space sample points.-const setup = () => {- const terrain = makeTerrain();- terrain.position.set(40, 5, -20);- terrain.rotation.y = 0.4;- const parent = new THREE.Group();- parent.position.set(-10, 2, 3);- parent.add(terrain);- new THREE.Group().add(parent);- parent.parent.updateMatrixWorld(true);- return terrain;-};--const cone = new THREE.ConeGeometry(0.3, 1.2, 6);-cone.translate(0, 0.6, 0);-const mat = new THREE.MeshStandardMaterial();--const t1 = setup();-const im = scatter(t1, cone, mat, 300, { seed: 11 });-const countExact = im.count === 300 && im.isInstancedMesh === true;--// On-surface: the vertical ray through each instance origin must hit-// the terrain at the origin's own height.-const ray = new THREE.Raycaster();-const down = new THREE.Vector3(0, -1, 0);-const p = new THREE.Vector3();-const q = new THREE.Quaternion();-const s = new THREE.Vector3();-const M = new THREE.Matrix4();-let maxGap = 0;-let sMin = 1e9, sMax = -1e9, nonUniform = 0;-for (let i = 0; i < im.count; i++) {- im.getMatrixAt(i, M);- M.decompose(p, q, s);- ray.set(new THREE.Vector3(p.x, p.y + 80, p.z), down);- const hits = ray.intersectObject(t1, false);- if (!hits.length) { maxGap = 1e9; break; }- maxGap = Math.max(maxGap, Math.abs(hits[0].point.y - p.y));- sMin = Math.min(sMin, s.x);- sMax = Math.max(sMax, s.x);- if (Math.abs(s.x - s.y) > 1e-6 || Math.abs(s.x - s.z) > 1e-6) nonUniform++;-}--// Determinism: fresh identical setup, same seed -> identical matrices;-// different seed -> a different field.-const im2 = scatter(setup(), cone, mat, 300, { seed: 11 });-const im3 = scatter(setup(), cone, mat, 300, { seed: 12 });-let maxSame = 0, maxOther = 0;-const a1 = im.instanceMatrix.array, a2 = im2.instanceMatrix.array,- a3 = im3.instanceMatrix.array;-for (let i = 0; i < a1.length; i++) {- maxSame = Math.max(maxSame, Math.abs(a1[i] - a2[i]));- maxOther = Math.max(maxOther, Math.abs(a1[i] - a3[i]));-}--// Colour must not move the FIELD: same seed, jitter off vs on.-const imPlain = scatter(setup(), cone, mat, 300, { seed: 11 });-const imTinted = scatter(setup(), cone, mat, 300,- { seed: 11, colorJitter: 0.6 });-let maxShift = 0;-const b1 = imPlain.instanceMatrix.array, b2 = imTinted.instanceMatrix.array;-for (let i = 0; i < b1.length; i++) {- maxShift = Math.max(maxShift, Math.abs(b1[i] - b2[i]));-}--// alignToNormal on a tilted plane: instance +Y must match the plane's-// world normal; without the flag it must stay world-up despite the-// tilt; a NUMBER must land part way between the two.-const TILT = 0.5;-const tilt = () => {- const g = new THREE.PlaneGeometry(40, 40, 4, 4);- g.rotateX(-Math.PI / 2);- const mSlope = new THREE.Mesh(g, new THREE.MeshStandardMaterial());- mSlope.rotation.z = TILT;- mSlope.updateMatrixWorld(true);- return mSlope;-};-const expectN = new THREE.Vector3(0, 1, 0).applyEuler(tilt().rotation);-const imA = scatter(tilt(), cone, mat, 60, { alignToNormal: true, seed: 2 });-const imU = scatter(tilt(), cone, mat, 60, { seed: 2 });-const imH = scatter(tilt(), cone, mat, 60, { alignToNormal: 0.5, seed: 2 });-const basisY = new THREE.Vector3();-let minDotAligned = 1, minDotUpright = 1;-let halfMin = Math.PI, halfMax = -Math.PI;-for (let i = 0; i < 60; i++) {- imA.getMatrixAt(i, M);- basisY.setFromMatrixColumn(M, 1).normalize();- minDotAligned = Math.min(minDotAligned, basisY.dot(expectN));- imU.getMatrixAt(i, M);- basisY.setFromMatrixColumn(M, 1).normalize();- minDotUpright = Math.min(minDotUpright, basisY.y);- imH.getMatrixAt(i, M);- basisY.setFromMatrixColumn(M, 1).normalize();- const ang = Math.acos(Math.min(1, basisY.y)); // lean from world up- halfMin = Math.min(halfMin, ang);- halfMax = Math.max(halfMax, ang);-}--// maxSlopeDeg against MEASURED face normals on steep fBm terrain-// (identity transform so raycast face normals are world-space).-const steepG = new THREE.PlaneGeometry(160, 160, 96, 96);-steepG.rotateX(-Math.PI / 2);-displaceY(steepG, 26, 0.05, 7);-const steepT = new THREE.Mesh(steepG, new THREE.MeshStandardMaterial());-steepT.updateMatrixWorld(true);-const measureMinNy = (mesh) => {- let minNy = 1;- for (let i = 0; i < mesh.count; i++) {- mesh.getMatrixAt(i, M);- M.decompose(p, q, s);- ray.set(new THREE.Vector3(p.x, p.y + 80, p.z), down);- const hits = ray.intersectObject(steepT, false);- if (!hits.length) return -1;- minNy = Math.min(minNy, hits[0].face.normal.y);- }- return minNy;-};-const imAll = scatter(steepT, cone, mat, 400, { seed: 5 });-const imFlat = scatter(steepT, cone, mat, 400, { seed: 5, maxSlopeDeg: 25 });--// Cap, zero jitter.-const imCap = scatter(makeTerrain(), cone, mat, 5000, { seed: 1 });-const imCap2 = scatter(makeTerrain(), cone, mat, 5000,- { seed: 1, maxCount: 50 });-const imRigid = scatter(makeTerrain(), cone, mat, 20,- { seed: 1, scaleJitter: 0 });-let rigidOk = true;-for (let i = 0; i < 20; i++) {- imRigid.getMatrixAt(i, M);- M.decompose(p, q, s);- if (Math.abs(s.x - 1) > 1e-6) rigidOk = false;-}--console.log(JSON.stringify({- countExact, maxGap, sMin, sMax, nonUniform,- maxSame, maxOther, maxShift,- minDotAligned, minDotUpright,- halfMinDeg: halfMin * 180 / Math.PI, halfMaxDeg: halfMax * 180 / Math.PI,- tiltDeg: TILT * 180 / Math.PI,- minNyAll: measureMinNy(imAll), minNyFlat: measureMinNy(imFlat),- flatCount: imFlat.count,- capCount: imCap.count, cap2Count: imCap2.count, rigidOk,- cos25: Math.cos(25 * Math.PI / 180),-}));-"""---_GRADE = """-import * as THREE from 'three';-import { scatter } from './lib/scatter.js';--const g = new THREE.PlaneGeometry(80, 80, 24, 24);-g.rotateX(-Math.PI / 2);-const surf = new THREE.Mesh(g, new THREE.MeshStandardMaterial());-surf.updateMatrixWorld(true);-const proto = new THREE.ConeGeometry(0.2, 0.5, 5);-proto.translate(0, 0.25, 0);--const N = 600;-const circStd = (hs) => {- const c = hs.reduce((s, h) => s + Math.cos(h), 0) / hs.length;- const s = hs.reduce((s2, h) => s2 + Math.sin(h), 0) / hs.length;- const R = Math.max(Math.hypot(c, s), 1e-9);- return Math.sqrt(-2 * Math.log(R)) * 180 / Math.PI;-};--// `hex` is a hue-carrying albedo (foliage) or a near-neutral one (stone).-const field = (hex, jitter, opts = {}) => {- const mat = new THREE.MeshStandardMaterial({ color: hex });- const im = scatter(surf, proto, mat, N, Object.assign(- { seed: 3, colorJitter: jitter }, opts));- if (!im.instanceColor) return { hasTint: false };- const a = im.instanceColor.array, col = new THREE.Color(), hsl = {};- const hs = [];- let lumSum = 0, peak = 0, floor = 1e9, satMax = 0;- for (let i = 0; i < N; i++) {- const R = a[i * 3] * mat.color.r;- const G = a[i * 3 + 1] * mat.color.g;- const B = a[i * 3 + 2] * mat.color.b;- col.setRGB(R, G, B);- col.getHSL(hsl);- hs.push(hsl.h * Math.PI * 2);- satMax = Math.max(satMax, (Math.max(R, G, B) - Math.min(R, G, B))- / Math.max(Math.max(R, G, B), 1e-9));- lumSum += 0.2126 * R + 0.7152 * G + 0.0722 * B;- peak = Math.max(peak, R, G, B);- floor = Math.min(floor, Math.max(R, G, B));- }- const baseLum = 0.2126 * mat.color.r + 0.7152 * mat.color.g- + 0.0722 * mat.color.b;- return {- hasTint: true,- lumRatio: (lumSum / N) / baseLum, // 1.0 == the authored albedo- hueStd: circStd(hs),- satMax, peak, floor,- };-};--console.log(JSON.stringify({- leaf: field(0x537a36, 0.45),- stone: field(0x7d786f, 0.45),- leafNoHue: field(0x537a36, 0.45, { hueJitter: 0 }),- // extremes: the albedo band must hold at the loudest legal jitter,- // and a flat grey at full jitter must not invent a hue wheel- pale: field(0xf2f2f2, 1.0),- dark: field(0x0a0a0a, 1.0),- greyLoud: field(0x808080, 1.0),- off: field(0x537a36, 0),-}));-"""--[email protected](scope="module")-def probe() -> dict:- """One node launch of the placement probe, shared by its tests."""- return _measure(_PLACEMENT)--[email protected](scope="module")-def grade() -> dict:- """One node launch of the colour-grading probe."""- return _measure(_GRADE)---def test_instances_sit_on_the_surface_in_world_space(probe):- """Every instance origin lies ON the surface even under a- transformed parent — raw sampler points are LOCAL-space, and used- raw they are the floating/buried cover the census red-flags."""- assert probe["countExact"], "count wrong or not an InstancedMesh"- assert probe["maxGap"] < 1e-3, f"instances off the surface: {probe['maxGap']}"---def test_same_seed_is_bit_identical_and_seed_moves_the_field(probe):- """Same seed must reproduce exact matrices (fix rounds re-render- untouched zones pixel-identically; Math.random would break this- silently) — and a different seed must actually move instances."""- assert probe["maxSame"] == 0, f"same seed diverged by {probe['maxSame']}"- assert probe["maxOther"] > 1, f"seed changes nothing: {probe['maxOther']}"---def test_colour_jitter_does_not_move_the_field(probe):- """Grading is not layout. Turning colorJitter on to break a- wallpaper read must leave every matrix bit-identical, or every- colour tweak silently re-rolls a field that was already approved."""- assert probe["maxShift"] == 0, (- f"colorJitter moved the instances by {probe['maxShift']}")---def test_align_to_normal_tilts_leans_or_stays_upright(probe):- """alignToNormal:true lays grass/rocks onto the slope; the default- keeps trees/posts world-vertical (each mode's +Y exposes the other's- failure). A NUMBER leans part way — 0.5 on a 28.6 deg bank must- land near half of it, not at either end."""- m = probe- assert m["minDotAligned"] > 0.999, f"not aligned: {m['minDotAligned']}"- assert m["minDotUpright"] > 0.999, f"not upright: {m['minDotUpright']}"- half = m["tiltDeg"] * 0.5- assert abs(m["halfMinDeg"] - half) < 1.0, m- assert abs(m["halfMaxDeg"] - half) < 1.0, m---def test_max_slope_deg_gates_on_true_face_normals(probe):- """maxSlopeDeg must gate on the TRUE face normal: interpolated- vertex normals let 60-degree faces through a 25-degree filter (the- measured bug this pins)."""- m = probe- assert m["minNyAll"] < 0.5, f"terrain not steep, test is void: {m}"- assert m["minNyFlat"] >= m["cos25"] - 1e-3, (- f"steep faces passed the filter: {m['minNyFlat']}")- assert m["flatCount"] >= 350, f"rejection starved: {m['flatCount']}"---def test_count_cap_and_scale_jitter(probe):- """The overdraw cap (1000 default, the one measured scatter- footgun) must clamp, maxCount must override it, scaleJitter must- spread uniformly inside 1 +- jitter and 0 must mean rigid."""- m = probe- assert m["capCount"] == 1000, f"default cap: {m['capCount']}"- assert m["cap2Count"] == 50, f"maxCount override: {m['cap2Count']}"- assert m["sMin"] >= 0.699 and m["sMax"] <= 1.301, m- assert m["sMax"] - m["sMin"] > 0.3, f"no scale spread: {m}"- assert m["nonUniform"] == 0, "scale jitter is non-uniform"- assert m["rigidOk"], "scaleJitter 0 still scaled"---def test_colour_jitter_is_centred_on_the_authored_albedo(grade):- """The shipped `1 - colorJitter * rand()` could only darken: at- jitter 0.45 the field's mean luminance measured 0.778 of the colour- the author picked, and the bias grows with the jitter. A field's- mean must BE the authored albedo."""- for name in ("leaf", "stone", "leafNoHue"):- assert grade[name]["hasTint"], f"{name}: no instanceColor written"- assert abs(grade[name]["lumRatio"] - 1.0) < 0.03, (- f"{name} field mean is {grade[name]['lumRatio']:.3f} of the "- "authored albedo")- assert not grade["off"]["hasTint"], "colorJitter 0 still wrote colours"---def test_colour_jitter_varies_hue_not_only_brightness(grade):- """Measured on the shipped version: 0.000 degrees of hue across 600- copies. A thousand leaves at one hue IS the wallpaper read the- option exists to break, so the axis must actually move."""- assert grade["leaf"]["hueStd"] > 3.5, (- f"foliage hue is flat: {grade['leaf']['hueStd']:.3f} deg")- assert grade["stone"]["hueStd"] > 1.0, (- f"stone hue is flat: {grade['stone']['hueStd']:.3f} deg")- assert grade["leafNoHue"]["hueStd"] < 0.01, (- f"hueJitter 0 still moved hue: {grade['leafNoHue']['hueStd']}")---def test_hue_axis_is_capped_by_the_albedos_own_saturation(grade):- """A near-neutral albedo has no hue to nudge — the axis INVENTS one,- and hue angle stops meaning anything (a pure grey at full jitter- measures 193 deg of hue spread while being, correctly, still grey).- So the guard is on CHROMA: whatever the jitter, a grey prototype may- come back a warm or cool grey, never an orange one."""- assert grade["greyLoud"]["satMax"] < 0.16, (- "flat grey at full jitter turned chromatic: peak saturation "- f"{grade['greyLoud']['satMax']:.3f}")- # 0x7d786f carries 0.225 of chroma; the warm tail measures 0.453,- # so the axis roughly doubles it at the extreme and no further.- assert grade["stone"]["satMax"] < 0.50, (- f"stone over-tinted: {grade['stone']['satMax']:.3f}")- assert grade["leaf"]["satMax"] > grade["stone"]["satMax"], (- "a saturated albedo must be allowed a WIDER axis than a neutral "- f"one: {grade['leaf']['satMax']:.3f} vs {grade['stone']['satMax']:.3f}")---def test_jitter_holds_the_albedo_band_at_any_setting(grade):- """The scene contract's non-emissive band is 0.02..0.82. A pale- prototype at full jitter must not multiply past the ceiling (it- blows out under ACES before the sun lands on it) and a dark one- must not fall through the floor (a black hole in the field)."""- for name in ("leaf", "stone", "pale", "dark"):- assert grade[name]["peak"] <= 0.821, (- f"{name} peak albedo {grade[name]['peak']:.4f} over the ceiling")- assert grade[name]["floor"] >= 0.0199, (- f"{name} floor albedo {grade[name]['floor']:.4f} under the floor")- assert grade["pale"]["peak"] > 0.5, "pale test is void, nothing near the cap"diff --git a/harness/tests/scene_runtime/lib/test_season.py b/harness/tests/scene_runtime/lib/test_season.pydeleted file mode 100644index 0e5a17af..00000000--- a/harness/tests/scene_runtime/lib/test_season.py+++ /dev/null@@ -1,382 +0,0 @@-"""season.js: the turn of the year, and the hour a scene is posed at.--Ported 2026-09-01 from the scene_multifile_graphics reference-(tests/test_season_lib.py). Their renderer-contract assertions are dropped;-the claims their JSDoc makes are kept — the spread is wider at the turn than-in high summer, the tint BLENDS rather than assigns, season and kind are-uniforms so one scene compiles one program, a low sun is warm and its fill is-blue, the pose mutates nothing it was handed, and one seed turns the same-canopy twice.--THE PORT'S OWN LAWS, each one a defect this file exists to stop coming back:--1. THE TURN MUST NOT GO FLAT ON A SHADER-BUILT CROWN. canopy.js and grass.js- draw a whole stand in one call and build every leaf card in the VERTEX- shader from instance attributes, so their ``position`` attribute is a- zeroed buffer. The reference celled the per-leaf random off exactly that- attribute: measured on our renderer 2026-09-01, a whole autumn crown came- back with a hue spread of 1.3 degrees — one sheet of chocolate, the single- failure the module's own doc says it exists to avoid. The grain now- carries a world fallback keyed on ``vAstraSeaD``, and an InstancedMesh- (which shares ONE geometry, so its model cell is the same card for every- copy) decorrelates on the instance.--2. NOTHING MAY WRAP THE SMOOTH FIELD. For grass and ground the grain IS a- continuous world field; a ``fract`` anywhere downstream of it draws its own- sawtooth contour rings across the terrain — measured, six rings per unit of- field, a floor that read as plywood.--3. THE PALETTE IS GRADED FOR THIS PIPELINE. Every anchor keeps a dielectric- floor in the channels it does not own (the reference's autumn red was- linear (0.274, 0.018, 0.005) — a red with no blue at all, whose shade side- could take nothing from the sky), and autumn's two anchors stay far enough- apart in hue to read as a PAIR rather than as one wash.--4. THE LEVELS ARE OURS. environment.js measured this renderer (ACES,- exposure 1.0, no post chain) at day 5.4 key / 1.4 fill and night 2.2 / 1.0,- and sunRig clamps anything under 4.5 (day key) or 0.8 (night fill) UP. The- reference's pose asked for 3.3 at noon and 0.75 at night: every daylight- hour came back clamped to the same 4.5 — one flat key from breakfast to- dusk — and a posed night rendered at a third of the rig it replaced.-"""-from __future__ import annotations--import pytest-from _probe import compile_scene, measure--pytestmark = pytest.mark.node--_LIBS = ("shader.js", "season.js")---# The probe's stand-in for three's own compile: a fragment shader that owns a-# `diffuseColor` the patch can land on, and a vertex shader that owns-# `transformed`.-_COMPILE = """-const compiled = (o) => {- const m = new THREE.MeshStandardMaterial();- patchSeasonTint(m, o);- const s = { uniforms: {},- vertexShader: 'void main() { #include <begin_vertex> }',- fragmentShader: '#include <color_fragment>' };- m.onBeforeCompile(s);- return { u: s.uniforms, vs: s.vertexShader, fs: s.fragmentShader,- key: m.customProgramCacheKey() };-};-"""---def test_autumn_is_a_spread_of_hues_and_not_one_orange():- """A canopy turns unevenly — tree by tree and leaf by leaf — so the- claim is the SPREAD, not the mean. A single lerp toward one autumn- colour is the failure this library exists to avoid, and it is the one a- mean-only test would pass."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const autumn = compiled({ season: 0.5, kind: 'leaf' });-const summer = compiled({ season: 0.25, kind: 'leaf' });-console.log(JSON.stringify({- autumnSpread: autumn.u.uSeaSpread.value,- summerSpread: summer.u.uSeaSpread.value,- phase: autumn.u.uSeaPhase.value,- // the spread has to be carried per FRAGMENT, not just held per material- readsGrain: /uSeaGrain/.test(autumn.fs),- readsSeed: /uSeaSeed/.test(autumn.fs),-}));-""", _LIBS)- assert out["autumnSpread"] > out["summerSpread"] * 1.5, (- "autumn must vary more than summer, not merely differ in hue")- assert out["phase"] == 0.5- assert out["readsGrain"] and out["readsSeed"]---def test_the_tint_blends_and_never_assigns_over_what_it_lands_on():- """A season tint lands on grass, leaves and ground that other patches have- already coloured, so it is the patch with the most to erase."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const c = compiled({});-const body = c.fs.slice(c.fs.indexOf('#include <color_fragment>'));-const writes = body.match(/diffuseColor\\.rgb\\s*=[^=]/g) || [];-console.log(JSON.stringify({- writes: writes.length,- allBlend: writes.every(() =>- /diffuseColor\\.rgb\\s*=\\s*mix\\(\\s*diffuseColor\\.rgb/.test(body)- || /diffuseColor\\.rgb\\s*\\*=/.test(body)),- // and it must READ what was there, not only its brightness: an earlier- // patch's hue jitter is what keeps a crown from flattening to one colour- readsBaseHue: /uSeaKeep/.test(body),-}));-""", _LIBS)- assert out["writes"] >= 1- assert out["allBlend"], "a season tint must blend, not assign"- assert out["readsBaseHue"], (- "the turn must keep a share of the hue an earlier patch left here")---def test_season_and_kind_are_uniforms_so_a_scene_shares_one_program():- """Four seasons on three kinds is twelve materials in one scene. If- either branched the SOURCE that is twelve programs, and the first material- to compile a cache key would decide the source for all of them."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const a = compiled({ season: 0.0, kind: 'leaf' });-const b = compiled({ season: 0.75, kind: 'leaf' });-const c = compiled({ season: 0.5, kind: 'grass' });-console.log(JSON.stringify({- seasonSharesSource: a.fs === b.fs,- kindSharesSource: a.fs === c.fs,- oneKey: a.key === b.key && a.key === c.key,-}));-""", _LIBS)- assert out["seasonSharesSource"], "season must be a uniform"- assert out["kindSharesSource"], "kind must be a uniform"- assert out["oneKey"]---def test_a_shader_built_crown_still_turns_unevenly():- """LAW 1. canopy.js ships `position` as a zeroed attribute, so the model- cell is one value for a whole draw call. The grain must fall back to the- world field there — and an InstancedMesh, which shares one geometry, must- decorrelate on the instance, or a stand of leaves picks one pigment and- only its DATE varies."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const c = compiled({ kind: 'leaf' });-const grain = c.fs.slice(c.fs.indexOf('vec3 astraSeasonGrain()'));-console.log(JSON.stringify({- // the flag is measured off the MODEL attribute, in the vertex stage- flagsDegenerate: /vAstraSeaD\\s*=[^;]*dot\\(\\s*position\\s*,\\s*position/- .test(c.vs),- // and it has to reach the field weight, not merely be declared- fallsBack: /vAstraSeaD/.test(grain.slice(0, grain.indexOf('return'))),- perInstance: /vAstraSeaI/.test(grain.slice(0, grain.indexOf('return'))),-}));-""", _LIBS)- assert out["flagsDegenerate"], (- "the vertex stage must flag an asset with no model position")- assert out["fallsBack"], (- "a crown whose leaves have no model position must fall back to the "- "world field, or its whole turn is one colour")- assert out["perInstance"], (- "an InstancedMesh shares one geometry: the pigment must decorrelate "- "on the instance")---def test_nothing_wraps_the_smooth_world_field():- """LAW 2. For grass and ground the grain is a continuous field, and a- `fract` on anything derived from it draws contour rings across the whole- terrain. Only the hash cells (already discontinuous) and the date's own- ring position may wrap."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const c = compiled({ kind: 'ground' });-const body = c.fs.slice(c.fs.indexOf('vec3 seG = astraSeasonGrain();'));-const tail = body.slice(0, body.indexOf('diffuseColor.rgb = mix'));-console.log(JSON.stringify({- wraps: (tail.match(/fract\\s*\\(/g) || []).length,- tail,-}));-""", _LIBS)- assert out["wraps"] == 0, (- "the twist and value randoms must be continuous combinations of the "- f"grain, not wrapped: {out['tail']}")---def test_every_anchor_is_graded_for_this_pipeline():- """LAW 3. A channel at zero has nothing for the sky to fill, and two- autumn anchors a few degrees apart are one wash however they are picked."""- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const hueOf = (c) => { const o = {}; c.getHSL(o); return o.h * 360; };-const rows = {};-for (const kind of ['leaf', 'grass', 'ground']) {- const u = compiled({ kind }).u;- const anchors = ['uSeaSpring', 'uSeaSummer', 'uSeaGold', 'uSeaRed',- 'uSeaWinter'].map((n) => u[n].value);- rows[kind] = {- // working-space (linear) channels: the albedo the shader multiplies- minChannel: Math.min(...anchors.map((c) => Math.min(c.r, c.g, c.b))),- maxChannel: Math.max(...anchors.map((c) => Math.max(c.r, c.g, c.b))),- autumnGap: Math.abs(hueOf(u.uSeaGold.value) - hueOf(u.uSeaRed.value)),- twist: u.uSeaTwist.value,- keep: u.uSeaKeep.value,- };-}-console.log(JSON.stringify(rows));-""", _LIBS)- for kind, row in out.items():- assert row["minChannel"] >= 0.012, (- f"{kind}: an anchor with a channel at zero takes nothing from the "- f"sky in shade ({row['minChannel']:.4f})")- assert row["maxChannel"] <= 0.8, f"{kind}: albedo over 0.8"- assert row["autumnGap"] >= 15, (- f"{kind}: gold and red are {row['autumnGap']:.1f} deg apart — one "- "wash, not a pair")- assert row["twist"] > 0 and row["keep"] > 0, (- f"{kind}: the hue variance knobs must not be switched off")---def test_the_sun_is_warm_low_and_neutral_at_noon():- """Colour temperature is the cue that says what hour it is. A low sun is- warm and its fill turns blue; noon is neutral."""- out = measure("""-import { dayCycle } from './lib/season.js';-const at = (hour) => {- const d = dayCycle(null, { hour, latitude: 40 });- return { el: d.elevation, keyEl: d.keyElevation,- warmth: d.sunColor.r - d.sunColor.b,- fillCool: d.ambientColor.b - d.ambientColor.r,- night: d.night, intensity: d.intensity, fill: d.fill,- kelvin: d.kelvin, mood: d.mood };-};-console.log(JSON.stringify({- dawn: at(6.5), morning: at(9), noon: at(12), dusk: at(17.5),- late: at(18.6), night: at(20),-}));-""", _LIBS)- assert out["noon"]["el"] > out["dawn"]["el"], "noon must be highest"- assert out["noon"]["el"] > out["dusk"]["el"]- assert out["dawn"]["warmth"] > out["noon"]["warmth"], (- "a low sun must be warmer than a high one")- assert out["dusk"]["warmth"] > out["noon"]["warmth"]- assert out["dawn"]["fillCool"] > 0, "low-sun shadows go blue"- assert out["night"]["night"] is True- assert out["night"]["intensity"] < out["noon"]["intensity"]- # The sun goes DOWN at night; the key is lifted so a night scene still- # has somewhere to light from, and it says so by its name.- assert out["night"]["el"] < 0, "the sun must set"- assert out["night"]["keyEl"] > 0, "the moon key stays above the horizon"- assert out["dusk"]["mood"] == "golden" and out["noon"]["mood"] == "day"---def test_the_pose_is_levelled_for_this_renderer():- """LAW 4. sunRig clamps a day key under 4.5 and a night fill under 0.8- UP, so a pose graded for a post chain at exposure 1.1 arrives as one flat- key across the whole working day and a night three times too dark."""- out = measure("""-import { dayCycle } from './lib/season.js';-const at = (hour) => {- const d = dayCycle(null, { hour, latitude: 40 });- return { intensity: d.intensity, fill: d.fill, el: d.elevation };-};-const day = [8, 9, 10, 11, 12, 13, 14, 15, 16].map(at);-console.log(JSON.stringify({- dayMin: Math.min(...day.map((d) => d.intensity)),- dayMax: Math.max(...day.map((d) => d.intensity)),- fillMin: Math.min(...day.map((d) => d.fill)),- fillMax: Math.max(...day.map((d) => d.fill)),- night: at(23), setting: at(18.75),-}));-""", _LIBS)- # environment.js's own day rig is 5.4 over a 4.5 floor: the working day- # has to live ABOVE the floor or every hour of it renders identically.- assert out["dayMin"] >= 4.5, (- f"the day key falls under sunRig's floor ({out['dayMin']:.2f}) — "- "every hour clamped to the same light")- assert out["dayMax"] <= 6.0, "and never blows past the golden rig"- assert out["fillMin"] >= 1.0 and out["fillMax"] <= 1.45, (- "the fill tracks environment.js's 1.1 (golden) .. 1.4 (day)")- # night is a MOON rig, measured at 2.2 / 1.0 on this renderer- assert out["night"]["intensity"] >= 2.0- assert out["night"]["fill"] >= 0.9- # and the sun really does go out in its last degrees- assert out["setting"]["intensity"] < out["dayMin"]---def test_the_day_cycle_does_not_mutate_what_it_was_handed():- """It returns a description a composer applies. A helper that reaches- into a rig it was given makes the pose impossible to re-derive, and two- calls at two hours would fight."""- out = measure("""-import * as THREE from 'three';-import { dayCycle } from './lib/season.js';-const rig = { sunDir: new THREE.Vector3(0, 1, 0), intensity: 1,- marker: 'untouched' };-const before = JSON.stringify(rig);-const a = dayCycle(rig, { hour: 7 });-const b = dayCycle(rig, { hour: 17 });-console.log(JSON.stringify({- rigUnchanged: JSON.stringify(rig) === before,- independent: a.elevation !== b.elevation || a.azimuth !== b.azimuth,- bothFinite: [a.elevation, b.elevation, a.fogDensity, b.fogDensity,- a.intensity, b.intensity].every(Number.isFinite),- // fog stays in the sky's own hue family — it IS the horizon colour- fogIsHorizon: a.fogColor.getHex() === a.horizon.getHex(),- freshColours: a.fogColor !== a.horizon,-}));-""", _LIBS)- assert out["rigUnchanged"], "dayCycle must not mutate its argument"- assert out["independent"] and out["bothFinite"]- assert out["fogIsHorizon"] and out["freshColours"]---def test_one_seed_turns_the_same_canopy_every_time():- out = measure("""-import * as THREE from 'three';-import { patchSeasonTint } from './lib/season.js';-""" + _COMPILE + """-const seedOf = (seed) => compiled({ seed }).u.uSeaSeed.value;-console.log(JSON.stringify({- same: seedOf(4).x === seedOf(4).x && seedOf(4).y === seedOf(4).y,- differs: seedOf(4).x !== seedOf(9).x,-}));-""", _LIBS)- assert out["same"] and out["differs"]---def test_the_tint_compiles_over_the_libraries_it_lands_on():- """A season tint goes on foliage that already carries leaf transmission,- wind and surface breakup — on an InstancedMesh, which is how a stand of- trees is drawn, and on a canopy.js crown, which is the asset whose model- position the fallback exists for."""- code, out = compile_scene("""-import * as THREE from 'three';-import { patchSeasonTint, dayCycle } from './lib/season.js';-import { patchLeafSSS, patchWind } from './lib/foliage_shade.js';-import { patchMicroBreakup } from './lib/surface_wear.js';-import { makeCanopy } from './lib/canopy.js';-export function createScene() {- const scene = new THREE.Scene();- const pose = dayCycle(null, { hour: 16 });- const sun = new THREE.DirectionalLight(pose.sunColor, pose.intensity);- sun.position.copy(pose.sunDir).multiplyScalar(60);- scene.add(sun);- scene.add(new THREE.HemisphereLight(0xbfd4ee, 0x6a5a44, pose.fill));- const leaf = new THREE.MeshStandardMaterial({ color: 0x4a6b2a });- patchLeafSSS(leaf, {});- patchWind(leaf, { height: 4 });- patchMicroBreakup(leaf, {});- patchSeasonTint(leaf, { season: 0.5, kind: 'leaf' });- scene.add(new THREE.Mesh(new THREE.PlaneGeometry(1, 1), leaf));- scene.add(new THREE.InstancedMesh(- new THREE.ConeGeometry(1, 3, 8), leaf, 4));- const crown = makeCanopy({ position: [0, 4, 0], radius: 2.5, leaves: 200 });- patchSeasonTint(crown.children[0].material,- { season: 0.5, kind: 'leaf', seed: 3 });- scene.add(crown);- const ground = new THREE.MeshStandardMaterial({ color: 0x6b5d3c });- patchSeasonTint(ground, { season: 0.5, kind: 'ground' });- const mat = new THREE.Mesh(new THREE.PlaneGeometry(20, 20, 8, 8), ground);- mat.rotation.x = -Math.PI / 2;- scene.add(mat);- return { scene, update() {},- cameras: [{ name: 'wood', position: [9, 5, 11],- lookAt: [0, 2, 0], fov: 45 }] };-}-""", ("shader.js", "season.js", "foliage_shade.js", "surface_wear.js",- "canopy.js", "grass.js", "noise.js"))- assert code == 0, out- assert "WARN" not in out, outdiff --git a/harness/tests/scene_runtime/lib/test_urban.py b/harness/tests/scene_runtime/lib/test_urban.pyindex baa9df44..93b74c22 100644--- a/harness/tests/scene_runtime/lib/test_urban.py+++ b/harness/tests/scene_runtime/lib/test_urban.py@@ -166,7 +166,7 @@ console.log(JSON.stringify({def test_the_facade_spends_no_second_render_target():- """The scene has ONE render-target budget and mirror.js or+ """The scene has ONE render-target budget and an ocean orwetground.js has usually already spent it. A curtain wall thatquietly allocates a second one costs a frame nobody authorised, sothe fresnel sky has to be computed, not rendered."""@@ -179,7 +179,7 @@ def test_the_facade_spends_no_second_render_target():"new Reflector", "CubeCamera"):assert banned not in code, (f"urban.js reaches for {banned}; the scene's one RTT is "- "already spent by mirror.js or wetground.js")+ "already spent by an ocean or wetground.js")def test_every_glow_is_kept_out_of_the_occlusion_pass():diff --git a/harness/tests/scene_runtime/lib/test_waterfall.py b/harness/tests/scene_runtime/lib/test_waterfall.pydeleted file mode 100644index 3bbdcff6..00000000--- a/harness/tests/scene_runtime/lib/test_waterfall.py+++ /dev/null@@ -1,352 +0,0 @@-"""A waterfall has to read as one from angles nobody framed for it.--Every model attempt at this brief built a flat plane, which is a line-edge-on; the reference build that convinced was the one with a swept-closed section, a projectile path, and threads that accelerate. Those-four properties are the reference's, ported 2026-09-01 from-scene_multifile_graphics (tests/test_waterfall_lib.py), and they are held-here as they stood.--THE PORT'S OWN LAWS — each one a frame rendered on our host under-fx/out/waterfall/, looked at, and measured against the same frame with-the reference module in place:--1. A FALL IS NOT A WHITE CURTAIN. Every pixel of the sheet was mixed- toward one near-white value: measured on the close camera, mean- saturation 0.099 with 24.2% of the sheet's pixels above 0.85- luminance. Everything in the shader now rides one AERATION ramp —- coherent green-blue glass at the lip, torn spray by the foot — which- takes that to 0.118 saturation and 0.14% near-white, with the lip- reading as water rather than as frosted glass.--2. THE LIGHT IS THE SCENE'S. All three materials are unlit, so every- photon in them is a decision, and the reference's were daylight- constants. Measured on this harness's night rig, the old sheet came- back at luminance 0.344 over a frame whose mean was 0.168 — a sheet- of white plastic hanging in the dark. It reads the key light, the- hemisphere fill and the fog at the first render (0.174 over 0.144- now), and `keepOutOfDepthPasses` has already claimed `onBeforeRender`- there, so the adoption CHAINS onto that guard rather than replacing- it.--3. THE PLUNGE POOL IS WATER, NOT MILK. The disc mixed 85% of its noise- straight to foam over its whole radius — a lid of grey milk on the- dirt, with the deep colour never appearing at all. Foam now belongs- to the boil and travels outward as streaks in (angle, radius - time).-"""--from __future__ import annotations--from tests.scene_runtime.lib._probe import compile_scene, measure # noqa: F401--_LIBS = ("shader.js", "waterfall.js")--# A scene the way `sunRig` builds one: a key directional light, a-# hemisphere fill and fog. `adoptSceneLight` runs off `onBeforeRender`,-# which a probe can call directly — no GPU needed to prove what it read.-# The guard `keepOutOfDepthPasses` installed runs FIRST in that chain and-# touches the geometry, so the call carries the real geometry and-# material three would hand it.-_LIT_SCENE = """-function litScene(THREE, opts) {- const o = opts || {};- const scene = new THREE.Scene();- const key = new THREE.DirectionalLight(o.sunHex || 0xfff0d8,- o.sunI === undefined ? 5.4 : o.sunI);- // Direction is position -> target, so a light at +y+x shines DOWN and- // the adopted uSun must point back up at it.- key.position.set(30, 40, -10);- scene.add(key);- const hemi = new THREE.HemisphereLight(o.skyHex || 0x9db8e8, 0x8a7f6a,- o.fillI === undefined ? 1.4 : o.fillI);- scene.add(hemi);- scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);- return scene;-}-const adopt = (g, scene) => {- const m = g.getObjectByName('Sheet');- m.onBeforeRender(null, scene, null, m.geometry, m.material);- return m.material.uniforms;-};-const rgb = (c) => [+c.r.toFixed(4), +c.g.toFixed(4), +c.b.toFixed(4)];-const lum = (c) => +(0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b).toFixed(4);-"""---def test_the_sheet_is_a_body_not_a_plane():- """A flat sheet vanishes edge-on: the section must have real depth,- and it must follow a parabola rather than a straight drop."""- out = measure("""-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({ height: 8, width: 3.2 });-const sheet = g.getObjectByName('Sheet');-const p = sheet.geometry.attributes.position.array;-let minX = 1e9, maxX = -1e9, minY = 1e9, maxY = -1e9, minZ = 1e9, maxZ = -1e9;-// The mid-height row tells a parabola from a ramp: half the drop is-// reached well before half the throw.-let zAtHalfDrop = 0, bestDy = 1e9;-for (let i = 0; i < p.length; i += 3) {- minX = Math.min(minX, p[i]); maxX = Math.max(maxX, p[i]);- minY = Math.min(minY, p[i + 1]); maxY = Math.max(maxY, p[i + 1]);- minZ = Math.min(minZ, p[i + 2]); maxZ = Math.max(maxZ, p[i + 2]);- const dy = Math.abs(p[i + 1] - 4.0); // nearest sample to half drop- if (dy < bestDy) { bestDy = dy; zAtHalfDrop = p[i + 2]; }-}-console.log(JSON.stringify({- width: +(maxX - minX).toFixed(2),- drop: +(maxY - minY).toFixed(2),- depth: +(maxZ - minZ).toFixed(2),- throwTotal: +maxZ.toFixed(2),- zAtHalfDrop: +zAtHalfDrop.toFixed(2),- names: g.children.map((c) => c.name).sort(),- hasTick: typeof g.userData.tick === 'function',-}));-""", _LIBS)- assert out["drop"] == 8.0 and 3.0 <= out["width"] <= 3.3- # Depth is the whole point: a plane would measure ~0 here.- assert out["depth"] > 1.2, out- # Free fall: half the height is gone by ~70% of the way down, so the- # sheet is still well short of the landing point there.- assert out["zAtHalfDrop"] < out["throwTotal"] * 0.75, out- assert out["names"] == ["Mist", "PlungePool", "Sheet"]- assert out["hasTick"]---def test_the_mist_keeps_position_at_the_origin():- """GTAOPass redraws with an override material that ignores custom- vertex shaders, so a billboard that keeps its quad in `position`- burns a black rectangle at the world origin."""- out = measure("""-import { makeWaterfall } from './lib/waterfall.js';-const mist = makeWaterfall({ mist: 40 }).getObjectByName('Mist');-const pos = Array.from(mist.geometry.attributes.position.array);-console.log(JSON.stringify({- posAllZero: pos.every((v) => v === 0),- hasCorner: !!mist.geometry.attributes.aCorner,- instances: mist.geometry.instanceCount,- seeded: mist.geometry.attributes.iSeed.count,-}));-""", _LIBS)- assert out["posAllZero"] and out["hasCorner"]- assert out["instances"] == 40 and out["seeded"] == 40---def test_two_waterfalls_with_one_seed_are_identical():- """Determinism is the contract for every shipped factory: a re-run- that reshuffles the mist is a re-run nobody can compare against."""- out = measure("""-import { makeWaterfall } from './lib/waterfall.js';-const seedOf = (s) => Array.from(- makeWaterfall({ seed: s, mist: 24 })- .getObjectByName('Mist').geometry.attributes.iSeed.array);-const a = seedOf(5), b = seedOf(5), c = seedOf(9);-console.log(JSON.stringify({- same: JSON.stringify(a) === JSON.stringify(b),- differs: JSON.stringify(a) !== JSON.stringify(c),-}));-""", _LIBS)- assert out["same"] and out["differs"]---def test_tick_advances_every_material_in_the_group():- out = measure("""-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({ mist: 12 });-g.userData.tick(2.5);-const times = [];-g.traverse((o) => {- for (const m of [].concat(o.material || [])) {- if (m && m.uniforms && m.uniforms.uTime) times.push(m.uniforms.uTime.value);- }-});-console.log(JSON.stringify({ times }));-""", _LIBS)- assert out["times"] and all(v == 2.5 for v in out["times"])---def test_the_sheet_normal_is_world_space_like_everything_it_meets():- """three's `normalMatrix` is the inverse transpose of the modelVIEW- matrix, so it yields a VIEW-space normal. Both consumers here —- astraFresnel-style rim work and astraFacing for the silhouette fade —- are handed `cameraPosition - vW`, which is world space. Mixing the- two keys the rim and the fade to where the camera is POINTING rather- than to how the sheet is turned, so they swim as the camera orbits a- stationary waterfall."""- out = measure(r"""-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({ height: 6, width: 3, seed: 2 });-const mats = [];-g.traverse((o) => { if (o.material && o.material.vertexShader) mats.push(o.material); });-const bad = mats.filter((m) =>- /normalMatrix\s*\*\s*normal/.test(m.vertexShader)- && /cameraPosition/.test(m.fragmentShader));-console.log(JSON.stringify({- materials: mats.length,- mixedSpaces: bad.length,- worldNormals: mats.filter((m) =>- /mat3\(modelMatrix\)\s*\*\s*normal/.test(m.vertexShader)).length,-}));-""", _LIBS)- assert out["materials"] >= 1- assert out["mixedSpaces"] == 0, (- "a view-space normal is being dotted with a world-space view "- "vector")- assert out["worldNormals"] >= 1---def test_the_light_is_the_scene_s_and_one_bundle_feeds_all_three():- """LAW 2. The sheet, the pool and the mist must agree about where- the sun is and what colour it is — three unlit materials with three- private sets of daylight constants are three separate objects- standing in the same place — so they share ONE uniform bundle, and- one adoption off the sheet updates every one of them."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({ mist: 8 });-const before = rgb(g.getObjectByName('Sheet').material.uniforms.uSunCol.value);-const u = adopt(g, litScene(THREE, { sunHex: 0xff9060 }));-const pool = g.getObjectByName('PlungePool').material.uniforms;-const mist = g.getObjectByName('Mist').material.uniforms;-console.log(JSON.stringify({- before,- sun: [+u.uSun.value.x.toFixed(3), +u.uSun.value.y.toFixed(3),- +u.uSun.value.z.toFixed(3)],- sunCol: rgb(u.uSunCol.value),- // One bundle: the pool's and the mist's uniforms are the SAME objects.- poolShares: pool.uSunCol === u.uSunCol && pool.uSun === u.uSun,- mistShares: mist.uSunCol === u.uSunCol && mist.uAmb === u.uAmb,- // ... and every material still has its OWN uTime, or one tick would- // be three writes to one number.- ownTime: u.uTime !== pool.uTime && pool.uTime !== mist.uTime,-}));-""", _LIBS)- # The key is up and to the +x/-z side; the adopted vector points at it.- assert out["sun"][1] > 0.7 and out["sun"][0] > 0.4 and out["sun"][2] < 0- # A warm key really arrives: red climbs away from green and blue.- assert out["sunCol"][0] > out["sunCol"][2] * 2.5, out- assert out["sunCol"] != out["before"]- assert out["poolShares"] and out["mistShares"] and out["ownTime"], out---def test_a_caller_who_pins_the_light_keeps_it():- """Adoption is a default, not a policy: a scene that hands the fall- its own key must not have it taken away at the first render."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({- mist: 0, sunDir: new THREE.Vector3(0, 1, 0), sunColor: 0x00ff00,- sky: 0xff0000, ambient: 0x0000ff,-});-const u = adopt(g, litScene(THREE));-console.log(JSON.stringify({- sun: [+u.uSun.value.x.toFixed(3), +u.uSun.value.y.toFixed(3)],- sunCol: rgb(u.uSunCol.value),- sky: rgb(u.uSky.value),- amb: rgb(u.uAmb.value),-}));-""", _LIBS)- assert out["sun"] == [0.0, 1.0]- assert out["sunCol"][1] > 0.9 and out["sunCol"][0] < 0.01- assert out["sky"][0] > 0.9 and out["amb"][2] > 0.9---def test_a_moonlit_fall_is_not_a_daylight_one():- """LAW 2, the half a render caught: what is adopted is the key's- strength RELATIVE to daylight, so the night rig's 2.2 moon arrives- as ~0.41 of the 5.4 sun instead of as the same white sheet."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeWaterfall } from './lib/waterfall.js';-const day = adopt(makeWaterfall({ mist: 0 }), litScene(THREE));-const dayL = lum(day.uSunCol.value), dayA = lum(day.uAmb.value);-const night = adopt(makeWaterfall({ mist: 0 }), litScene(THREE, {- sunHex: 0xb5c7e8, sunI: 2.2, skyHex: 0x3f5378, fillI: 1.0 }));-console.log(JSON.stringify({- dayKey: dayL, nightKey: lum(night.uSunCol.value),- dayAmb: dayA, nightAmb: lum(night.uAmb.value),-}));-""", _LIBS)- assert out["nightKey"] < out["dayKey"] * 0.5, out- assert out["nightAmb"] < out["dayAmb"] * 0.5, out- # Dark, but never off: an unlit material at zero is a black hole.- assert out["nightKey"] > 0.02 and out["nightAmb"] > 0.005, out---def test_adopting_the_light_does_not_disarm_the_override_guard():- """`keepOutOfDepthPasses` guards the sheet by owning- `onBeforeRender`, and `adoptSceneLight` wants the same hook: the- adoption CHAINS. Replacing it would put a double-sided transparent- shell back into the ambient-occlusion pass as a solid wall — 50/255- of darkening on ground it never touched, which is the measurement- that put the guard there in the first place."""- out = measure(_LIT_SCENE + """-import * as THREE from 'three';-import { makeWaterfall } from './lib/waterfall.js';-const g = makeWaterfall({ mist: 4 });-const scene = litScene(THREE);-const sheet = g.getObjectByName('Sheet');-const own = sheet.material;-const override = new THREE.MeshDepthMaterial();-// three's own call shape, once with the mesh's material and once with-// the override an AO or shadow pass substitutes.-sheet.onBeforeRender(null, scene, null, sheet.geometry, own);-const drawnNormally = sheet.geometry.drawRange.count;-sheet.onBeforeRender(null, scene, null, sheet.geometry, override);-const drawnInOverride = sheet.geometry.drawRange.count;-sheet.onAfterRender(null, scene, null, sheet.geometry);-console.log(JSON.stringify({- drawnNormally: drawnNormally === Infinity ? -1 : drawnNormally,- drawnInOverride,- restored: sheet.geometry.drawRange.count === Infinity,- casts: sheet.castShadow,- adopted: +sheet.material.uniforms.uSun.value.y.toFixed(3),-}));-""", _LIBS)- assert out["drawnNormally"] == -1 # Infinity: drawn in full- assert out["drawnInOverride"] == 0 # and skipped by the AO pass- assert out["restored"] and not out["casts"]- assert out["adopted"] > 0.7 # the chain still adopted---_SCENE = """-import * as THREE from 'three';-import { tickShaders } from './lib/shader.js';-import { makeWaterfall } from './lib/waterfall.js';--export async function createScene() {- const scene = new THREE.Scene();- // Fogged, because the mist is one custom shader on the RAW route and- // the fog chunk is exactly what a hand-written shader forgets.- scene.fog = new THREE.FogExp2(0xcfd8e6, 0.0035);- const key = new THREE.DirectionalLight(0xfff0d8, 5.4);- key.position.set(30, 40, -10);- scene.add(key);- scene.add(new THREE.HemisphereLight(0x9db8e8, 0x8a7f6a, 1.4));- const fall = makeWaterfall({ height: 8, width: 3.2, seed: 3, mist: 40 });- scene.add(fall);- // A camera, because the host reports a scene with none as not booted- // and never reaches the compile stage at all.- return {- scene,- cameras: [{ name: 'a', position: [9, 4, 12], lookAt: [0, 3, 0],- fov: 45 }],- update(t) { tickShaders(scene, t); fall.userData.tick(t); },- };-}-"""---def test_the_whole_waterfall_compiles_on_our_gpu():- """Three custom shaders, one of them on the raw route with its own- billboard projection — the depth, fog and tone-map chunks are- hand-carried there, and only the GPU can say whether that was done- right. The raw route also gets no GLSL_UTIL, which is why the mist's- value noise is written out inside it."""- code, out = compile_scene(_SCENE, _LIBS)- assert code == 0, out- assert "every program compiled" in out- # Sheet, pool and mist: three, or one of them silently never built.- assert '"custom_materials":3' in out.replace(" ", ""), out- assert "WARN" not in out, outdiff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.pyindex b6c1b89c..61290d43 100644--- a/harness/tests/scene_runtime/test_skeleton.py+++ b/harness/tests/scene_runtime/test_skeleton.py@@ -79,7 +79,7 @@ def test_both_skeleton_paths_ship_the_effect_library(tmp_path):from codeverse.languages.scene_threejs import lib_filesnames = {p.name for p in lib_files()}- assert len(names) >= 50 and "grass.js" in names and "shader.js" in names+ assert len(names) >= 40 and "grass.js" in names and "shader.js" in namesfor label, plan in (("example", None), ("plan", make_plan())):ws = Workspace(tmp_path / label)@@ -146,7 +146,7 @@ def test_the_effects_catalog_reaches_the_scene_prompts_and_only_those():def test_every_call_the_catalog_advertises_is_a_real_export():- """The catalog is the agent's only index of 52 modules. One stale name and a+ """The catalog is the agent's only index of 44 modules. One stale name and asession writes an import that cannot resolve — and the reference catalog thiswas ported from already carried five (`makeFigure`, `makeCreature`, `place`,`instanceAll`, `hash` are none of them exports here)."""