Skip to content

Official Codebase of 3DCodeVerse

Python

scene: the effect library — 52 harness-owned modules ship in every scene workspace (D51)

gaoypeng5f0544189cae
diff --git a/harness/codeverse/agents/cli_common.py b/harness/codeverse/agents/cli_common.py
index fd9cfd0e..213baffb 100644
--- a/harness/codeverse/agents/cli_common.py
+++ b/harness/codeverse/agents/cli_common.py
@@ -22,7 +22,7 @@ from typing import Any
from pydantic import BaseModel
from codeverse.contracts.agent import AgentJob, AgentResult, FileChange
-from codeverse.contracts.common import Usage
+from codeverse.contracts.common import Usage, is_harness_owned
from codeverse.models.pricing import estimate_cost
from codeverse.proc import ManagedProcess, append_jsonl_line, read_jsonl_lenient, scrub_secrets
from codeverse.workspace import Workspace
@@ -457,7 +457,7 @@ def _enforce_scope(s: Session) -> dict[str, str]:
continue
if f.path in HARNESS_OWNED_FILES: # was a silent skip: the tamper survived AND went unreported
why = "harness control file: never agent-writable"
- elif f.path in frozen:
+ elif is_harness_owned(f.path, frozen):
why = "harness-owned: call its functions, never rewrite it"
elif roots and not any(f.path == r or f.path.startswith(r + "/") for r in roots):
why = f"outside write_roots {sorted(roots)}"
diff --git a/harness/codeverse/agents/materialize.py b/harness/codeverse/agents/materialize.py
index bb97b21a..5630320a 100644
--- a/harness/codeverse/agents/materialize.py
+++ b/harness/codeverse/agents/materialize.py
@@ -123,7 +123,8 @@ def _body(agent_kind: str, contract_md: str, cookbook_note: str, spatial_tools:
"1. You may create or edit files ONLY under `src/` and `public/`. Never modify `artifacts/`, "
"`trajectories/`, `.git/`, `.gemini/`, `.3dcv/`, or this file — they are harness-owned.\n"
"2. Write RAW code in the language named by the contract below. Never import from `codeverse` or "
- "any helper SDK; do not install packages; do not use the network; do not write "
+ "any helper SDK (harness-owned modules the contract ships INSIDE your src/ are the one "
+ "exception — call them, never rewrite them); do not install packages; do not use the network; do not write "
"camera / render / export / file-output code unless the contract explicitly asks for it — "
"the harness owns export and rendering.\n"
"3. Do not run `git`; the harness snapshots your work before and after the session.\n"
diff --git a/harness/codeverse/contracts/common.py b/harness/codeverse/contracts/common.py
index 652726c9..88a66e3e 100644
--- a/harness/codeverse/contracts/common.py
+++ b/harness/codeverse/contracts/common.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from collections.abc import Collection
from enum import StrEnum
from typing import Annotated
@@ -78,10 +79,23 @@ ENTRY_FILE: dict[Language, str] = {
#: Measured 2026-08-26 (bench/out/seed_v1, aurora brief, gemini-3.7-flash api-agent): recipes
#: seeded into the agent's own ``src/common.glsl`` were gone by the end of the run — it rewrote
#: the file with its own helpers — so a seeded file has to be one the agent cannot rewrite.
+#: An entry ending in ``/`` is a DIRECTORY prefix: every file under it is owned. That is
+#: how the 52-module effect library is named without listing 52 paths — and the list is
+#: the library's contents, so an entry per file would go stale the day one is added.
HARNESS_OWNED_SRC: dict[Language, tuple[str, ...]] = {
Language.GLSL_SHADER: ("src/recipes.glsl",),
+ # the effect library (D51): the agent imports and calls it, never rewrites it.
+ Language.SCENE_THREEJS: ("src/lib/",),
}
+
+def is_harness_owned(rel: str, owned: Collection[str]) -> bool:
+ """Is ``rel`` a harness-owned source file, given a language's ``HARNESS_OWNED_SRC``?
+
+ Exact match, or under a directory entry (one ending in ``/``).
+ """
+ return any(rel == o or (o.endswith("/") and rel.startswith(o)) for o in owned)
+
#: human label per language (galleries, captions, reports)
LANGUAGE_LABEL: dict[Language, str] = {
Language.BLENDER: "Blender Python",
diff --git a/harness/codeverse/languages/scene_threejs/__init__.py b/harness/codeverse/languages/scene_threejs/__init__.py
index cb38c4ea..8b3474e1 100644
--- a/harness/codeverse/languages/scene_threejs/__init__.py
+++ b/harness/codeverse/languages/scene_threejs/__init__.py
@@ -54,6 +54,21 @@ def _js_files(ws: Workspace) -> list[Path]:
return sorted(p for p in ws.src.rglob("*.js") if "node_modules" not in p.parts) + sorted(ws.src.rglob("*.mjs"))
+def _is_lib(path: Path, ws: Workspace) -> bool:
+ """Is this one of the harness's own effect modules (``src/lib/*.js``)?
+
+ They ship into every workspace (D51) and are verified by the harness's own
+ suite — ``tests/scene_runtime/lib/`` — not by the workspace gate, whose job
+ is to police the code the AGENT writes. Linting them as agent code was
+ three hard ERRORs (signage.js's node-only font fallback imports
+ ``node:module`` / ``node:fs/promises`` / ``node:url``, which the browser
+ half never touches) plus twelve "large file" WARNs telling the agent to
+ split files it does not own. Syntax is still checked below: a library file
+ the agent broke must still fail loudly.
+ """
+ return path.parent == ws.src / "lib"
+
+
def _node_check(path: Path, rel: str) -> GateFinding | None:
p = node_check_syntax(path, get_settings().binaries.node or "node")
if p is None:
@@ -105,6 +120,8 @@ def lint(ws: Workspace) -> GateReport:
if syntax:
findings.append(syntax)
continue
+ if _is_lib(path, ws):
+ continue
findings.extend(_check_imports(rel, text, ws, path))
for pat, sev, msg, hint in _PATTERNS:
m = pat.search(text)
@@ -144,6 +161,16 @@ def lint(ws: Workspace) -> GateReport:
STARTER_DIR = Path(__file__).resolve().parent / "starter" / "src"
#: pattern files copied verbatim in plan mode (shown as reusable examples)
PATTERN_FILES = ("shaders/sky.js", "shaders/water.js", "assets/pine_tree.js", "assets/windmill.js")
+#: the harness-owned effect library (``src/lib/*.js``), shipped into EVERY workspace.
+#: Plan mode copied only PATTERN_FILES, so a planned run got the effects catalog in its
+#: prompt and no ``src/lib/`` to import from — every ``from './lib/grass.js'`` a 2026-09-01
+#: agent wrote would have been a build error. Both skeleton paths write it now.
+LIB_DIR = STARTER_DIR / "lib"
+
+
+def lib_files() -> list[Path]:
+ """The effect-library modules shipped into a workspace, sorted."""
+ return sorted(LIB_DIR.glob("*.js"))
def _write(path: Path, text: str, written: list[Path]) -> None:
@@ -152,6 +179,11 @@ def _write(path: Path, text: str, written: list[Path]) -> None:
written.append(path)
+def _write_lib(ws: Workspace, written: list[Path]) -> None:
+ for src in lib_files():
+ _write(ws.src / "lib" / src.name, src.read_text(), written)
+
+
def write_example(ws: Workspace) -> list[Path]:
"""Copy the full example scene into ws.src (overwrites).
@@ -318,6 +350,7 @@ def write_skeleton(ws: Workspace, plan: Plan | None = None) -> list[Path]:
written: list[Path] = []
for rel in PATTERN_FILES:
_write(ws.src / rel, (STARTER_DIR / rel).read_text(), written)
+ _write_lib(ws, written)
_write(ws.src / "env.js", _env_for_plan(plan), written)
assets = {to_snake(a.name): a for a in plan.assets}
for a in plan.assets:
@@ -649,6 +682,8 @@ class SceneThreeJsRuntime(RuntimeDocs):
# census.json is only rewritten `if census:` below, so it MUST be wiped here
ws.stage_artifacts("census.json", "scene_probe.json", "shader_preflight.json", "build.json").invalidate()
probe, shaders, census = _probe_and_preflight(ws, timeout_s=tmo)
+ if census and probe.passed:
+ _ablation_into(ws, census)
if census:
(ws.artifacts / "census.json").write_text(json.dumps(census, indent=1))
gates_dir = ws.artifacts / "gates"
@@ -678,6 +713,27 @@ class SceneThreeJsRuntime(RuntimeDocs):
return res
+def _ablation_into(ws: Workspace, census: dict[str, Any]) -> None:
+ """Opt-in (``CV3D_ABLATION``): measure how much of the frame the scene's custom
+ shaders actually paint and put it in the census, so the scene gates and the
+ judge context read "the effect contributes N%" instead of "N custom materials
+ compiled". A second browser boot with its own renders, hence a switch and not
+ a default; instrumentation never breaks a build, so every failure is swallowed
+ into a census note. Details: ``spatial/ablation.py``."""
+ from codeverse.config import env_flag
+
+ if not env_flag("CV3D_ABLATION", False):
+ return
+ from codeverse.spatial.ablation import CENSUS_FIELD, ablate_scene
+
+ try:
+ report = ablate_scene(ws, frames=False)
+ except Exception as e: # noqa: BLE001 — an instrument must never fail a build
+ census[CENSUS_FIELD] = {"error": f"{type(e).__name__}: {e}"[:300]}
+ return
+ census[CENSUS_FIELD] = report.census_field()
+
+
def _probe_and_preflight(ws: Workspace, *, timeout_s: float) -> tuple[GateReport, GateReport, dict]:
"""One ``probe_scene.mjs --compile`` run → (scene_probe, shader_preflight, census).
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/accumulation.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/accumulation.js
new file mode 100644
index 00000000..41c0e007
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/accumulation.js
@@ -0,0 +1,512 @@
+/**
+ * Accumulation: what LIES on a scene, from one rule on every surface.
+ *
+ * A scene reads as WEATHER when the same stuff is on everything at
+ * once — snow on the roof, the sill, the branch and the rock; sand
+ * banked against the windward side of every wall. One white-topped
+ * material is a prop, twenty materials sharing one deposit rule is a
+ * storm, so both patches shade from world position and world normal
+ * only: no UV, no per-object setup, and two objects sharing a scale
+ * share one weather.
+ *
+ * Both go through `patchStandard`, so lighting, shadows, fog and the
+ * depth chunks survive, and both CHAIN with `surface_wear`,
+ * `terrain_shade`, `waterside` and `aging` on one material.
+ *
+ * THE CONSTRAINT IS THAT NEITHER HAS THICKNESS. `fragmentBody` edits
+ * albedo and nothing else; a vertex displacement would tear every
+ * hard-edged BoxGeometry open at its rim, because the top face's
+ * vertices carry a different normal from the side's and would walk
+ * away from them. So a layer sells its depth by what it COVERS (steep
+ * faces lose it, concave lees keep it), by a torn edge instead of a
+ * ruled one, and by the shade it drops on the material just outside
+ * that edge. Gloss is per MATERIAL, not per pixel, so each patch
+ * composes ONE factor through `composeRoughness`, weighted by how much
+ * of the surface it took over.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, waterside, surface_wear and aging name them,
+// so a material wearing several libraries declares ONE pair; the vertex
+// locals are ac* because those four own astraWp, wsP, wrP and agP.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// Both patches read these, so they are declared once, in the base.
+// astraAcc*, not a neighbour's spelling: patchStandard THROWS when two
+// chained patches give one function name two different bodies.
+const ACC_HEAD = [
+ 'vec3 astraAccAxes(vec3 n) {',
+ ' vec3 w = abs(n * n * n);',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+ // Three world-plane projections blended by the normal: a deposit
+ // must break up the same way on a wall, a roof and a boulder.
+ 'float astraAccNoise(vec3 p, vec3 w) {',
+ ' return astraNoise2(p.yz + 23.1) * w.x',
+ ' + astraNoise2(p.zx + 57.7) * w.y',
+ ' + astraNoise2(p.xy + 91.3) * w.z;',
+ '}',
+ // Curvature in 1/m: how far the normal turns per metre of surface
+ // under one pixel. NEGATIVE is the concave lee that holds what a
+ // convex edge sheds. Zero across a hard, unwelded edge.
+ 'float astraAccCurv(vec3 n, vec3 p) {',
+ ' vec3 dx = dFdx(p), dy = dFdy(p);',
+ ' float d = dot(dx, dx) + dot(dy, dy);',
+ ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',
+ '}',
+].join('\n');
+
+// One base for both. `transformed` is still object-space after
+// <begin_vertex>, so the instance transform is folded in by hand or
+// every scattered copy takes its weather from the world origin.
+const BASE = {
+ name: 'acc:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 acP = vec4(transformed, 1.0);',
+ ' vec3 acN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' acP = instanceMatrix * acP;',
+ ' acN = mat3(instanceMatrix) * acN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * acP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(acN, 0.0)).xyz);',
+ ].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, ACC_HEAD].join('\n'),
+};
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed
+ * for every material sharing the cache key. The constants differ from
+ * surface_wear's and aging's, or one seed would drift this library's
+ * snow along that library's blotches.
+ */
+function seedOffset(seed, salt) {
+ return new THREE.Vector3(
+ hash11(seed + salt + 1.61), hash11(seed + salt + 8.09),
+ hash11(seed + salt + 13.77)).multiplyScalar(56);
+}
+
+/**
+ * Read `up`-style options as a unit vector, never as NaN.
+ *
+ * A degenerate vector would divide by zero in the shader and paint the
+ * object black, so a zero-length one falls back to world up.
+ */
+function upVector(value) {
+ const v = new THREE.Vector3(0, 1, 0);
+ if (value) v.fromArray(value.toArray ? value.toArray() : value);
+ if (!(v.lengthSq() > 1e-9)) v.set(0, 1, 0);
+ return v.normalize();
+}
+
+/**
+ * Read `wind` as a direction it blows TOWARD, length 0..1 = strength.
+ *
+ * Length rather than a second option: zero wind must mean an even fall
+ * with no drift axis at all, and normalizing a zero vector is NaN.
+ */
+function windVector(value, fallback) {
+ const v = new THREE.Vector3();
+ if (value) v.fromArray(value.toArray ? value.toArray() : value);
+ else if (fallback) v.fromArray(fallback);
+ if (v.lengthSq() > 1) v.normalize();
+ return v;
+}
+
+/**
+ * Move the material's gloss toward the cover's, never past it.
+ *
+ * Roughness is per MATERIAL here, so a cover can only say how much of
+ * the surface is no longer the material: `blend` 0 leaves it alone, 1
+ * hands the whole material to the cover's own roughness.
+ */
+function towardRoughness(material, target, blend) {
+ const store = material.userData.astraRoughness;
+ const base = store ? store.base : material.roughness;
+ if (!(base > 0)) return 1;
+ return 1 + (target / base - 1) * unit(blend);
+}
+
+/**
+ * Lay snow on everything at once, by how each surface is turned.
+ *
+ * Snow is the deposit that most changes a scene, because it lands on
+ * every upward face in it from one rule: a roof with a white cap over
+ * a bare sill, a bare branch and a bare rock is a prop in a snow
+ * scene, and the fix is not more painting but the SAME patch on every
+ * material. What makes it snow rather than white paint is where it
+ * stops — and it stops in four ways.
+ *
+ * DEPOSIT is the cosine against `up` (the scene's own gravity, not
+ * world Y — a tilted asset or a listing hull snows on the faces that
+ * really point up), thinning as a face steepens and reaching NOTHING
+ * past about 58 degrees, the angle snow slides off at. That gate is
+ * MULTIPLICATIVE, so no amount of noise can put snow on a wall.
+ * SHELTER is the surface's own signed curvature: a convex edge sheds
+ * what a concave lee keeps, and how small a feature the fall can bury
+ * goes with how deep it lies. Curvature reads ZERO across a hard,
+ * unwelded edge (`BoxGeometry`'s corners, anything flat-shaded), so
+ * there the cosine carries it alone. WIND scours the face it meets and
+ * leaves the lee packed. And the EDGE is a threshold on a two-octave
+ * world field, torn by its own screen gradient, with a soft shade laid
+ * on the material just outside it — the only thickness a patch that
+ * cannot displace geometry has.
+ *
+ * `melt` gives the material back from the bottom up: the thaw line
+ * climbs from the plane through the world origin, which is where an
+ * asset's foot rests, so a wall's footing goes bare while its coping
+ * stays white. Passed `{ amount, at, radius }` it also eats a hole
+ * around one warm world point — a flue, a lamp, a vent.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` snows every mesh
+ * wearing it, so clone it first (and clone BEFORE patching).
+ * @param {object} [opts] `depth` metres of lying snow, which sets how
+ * far down a pitch it holds and how opaque it is (default 0.05; 0.01
+ * is a dusting, 0.15 buries); `color` THREE.Color or hex (default a
+ * cold white at 0.78 linear — snow is the brightest albedo in a scene
+ * and still has to sit UNDER the tone curve's shoulder, or its own
+ * shading clips to one flat card); `up` THREE.Vector3 or [x, y, z], the scene's up
+ * (default +Y); `wind` THREE.Vector3 or [x, y, z] it blows TOWARD,
+ * its LENGTH 0..1 the strength (default none, an even fall);
+ * `melt` 0..1 how high the thaw has climbed, or
+ * `{ amount, at, radius }` to melt around a warm point as well
+ * (default 0); `seed` moves the drifts (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uSnowMelt` can thaw over a
+ * shot and `uSnowDepth` can deepen through a storm.
+ */
+export function patchSnow(material, opts = {}) {
+ const depth = opts.depth === undefined ? 0.05 : Math.max(0, opts.depth);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const melt = opts.melt;
+ const meltAmt = unit(
+ typeof melt === 'number' ? melt : (melt && melt.amount) || 0);
+ const at = (melt && melt.at) || null;
+ const warm = new THREE.Vector3();
+ if (at) warm.fromArray(at.toArray ? at.toArray() : at);
+ const warmR = at
+ ? Math.max(1e-3, melt.radius === undefined ? 0.9 : melt.radius) : 0;
+ // Snow is a diffuse cover with a faint sheen, and it takes the
+ // material's gloss over only as far as it takes the surface over.
+ composeRoughness(material, 'acc:snow',
+ towardRoughness(material, 0.86,
+ 0.65 * unit(depth / 0.05)
+ * (1 - meltAmt)));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'acc:snow',
+ uniforms: {
+ uSnowDepth: { value: depth },
+ uSnowColor: { value: toColor(opts.color, 0xc9d2dd) },
+ uSnowUp: { value: upVector(opts.up) },
+ uSnowWind: { value: windVector(opts.wind, null) },
+ uSnowMelt: { value: meltAmt },
+ uSnowWarm: { value: new THREE.Vector4(warm.x, warm.y, warm.z, warmR) },
+ uSnowSeed: { value: seedOffset(seed, 0.7) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uSnowDepth;',
+ 'uniform vec3 uSnowColor;',
+ 'uniform vec3 uSnowUp;',
+ 'uniform vec3 uSnowWind;',
+ 'uniform float uSnowMelt;',
+ 'uniform vec4 uSnowWarm;',
+ 'uniform vec3 uSnowSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 snN = normalize(vAstraWorldN);',
+ ' vec3 snUp = normalize(uSnowUp);',
+ // Depth in metres decides how much this fall can bury and how
+ // little of the material is left showing through it.
+ ' float snCov = clamp(uSnowDepth / 0.06, 0.0, 1.0);',
+ ' vec3 snW = astraAccAxes(snN);',
+ ' vec3 snP = vAstraWorld * mix(2.6, 1.3, snCov) + uSnowSeed;',
+ ' float snG = astraAccNoise(snP, snW) * 0.62',
+ ' + astraAccNoise(snP * 4.3, snW) * 0.38;',
+ // Wind combs a drift OUT along itself: the same field with its
+ // wind axis compressed makes every feature four times as long.
+ ' float snWl = clamp(length(uSnowWind), 0.0, 1.0);',
+ ' vec3 snWv = uSnowWind / max(length(uSnowWind), 1e-4);',
+ ' vec3 snQ = vAstraWorld - snWv * dot(vAstraWorld, snWv) * 0.74;',
+ ' snG = mix(snG, snG * 0.45',
+ ' + astraAccNoise(snQ * 2.6 + uSnowSeed, snW) * 0.55, snWl);',
+ // How far the surface faces up, gone by ~58 degrees — the angle
+ // snow slides off — and thinner on everything steeper than flat.
+ ' float snC = dot(snN, snUp);',
+ ' float snLay = smoothstep(0.52, 0.80, snC)',
+ ' * mix(0.55, 1.0, clamp(snC, 0.0, 1.0));',
+ // A convex edge sheds what a concave lee holds, and a deeper fall
+ // buries a bigger feature before it starts to shed.
+ ' float snCv = astraAccCurv(snN, vAstraWorld);',
+ ' float snR = 1.0 / max(uSnowDepth * 6.0, 0.05);',
+ ' float snHold = 1.0 - 0.70 * smoothstep(snR * 0.6, snR * 3.0, snCv)',
+ ' + 0.60 * smoothstep(snR * 0.4, snR * 2.2, -snCv);',
+ // Wind scours the face it meets; its LENGTH is the strength, so
+ // no wind is an even fall rather than a normalize() of zero.
+ ' float snScour = 1.0 - 0.45 * snWl',
+ ' * smoothstep(-0.10, 0.90, -dot(snN, snWv));',
+ // MULTIPLICATIVE, so a steep face keeps nothing whatever the
+ // field says: noise may tear an edge, never move a wall's.
+ ' float snD = snLay * snHold * snScour * (0.55 + 0.90 * snG);',
+ // The thaw climbs from the plane through the origin, where an
+ // asset's foot rests, and its line is ragged from the same field.
+ ' float snH = dot(vAstraWorld, snUp) + (snG - 0.5) * 0.8;',
+ ' float snLine = mix(-0.8, 5.0, uSnowMelt);',
+ ' float snThaw = 1.0 - smoothstep(snLine - 0.7, snLine + 0.5, snH);',
+ ' float snWr = max(uSnowWarm.w, 1e-3);',
+ ' float snWarm = (1.0 - smoothstep(snWr * 0.35, snWr,',
+ ' length(vAstraWorld - uSnowWarm.xyz)))',
+ ' * step(1e-4, uSnowWarm.w);',
+ ' snD -= snThaw * 1.10 + snWarm * 1.10;',
+ // One threshold, antialiased by its own screen gradient: a hard
+ // line is paint, and a torn one is something that landed.
+ ' float snT = mix(0.92, 0.18, snCov);',
+ ' float snAA = clamp(fwidth(snD), 0.0, 0.35);',
+ ' float snK = smoothstep(snT - 0.05 - snAA, snT + 0.12 + snAA, snD);',
+ // A SECOND, finer field, for the tone alone — kept out of snD so
+ // the edge is untouched. The deposit's own field is most of a
+ // metre across, and a metre of one value at arm's length is paint.
+ // It fades out once a pixel spans it, or the grain aliases into
+ // shimmer at the far end of a shot.
+ ' float snFad = 1.0 - smoothstep(0.04, 0.10,',
+ ' length(fwidth(vAstraWorld)));',
+ ' float snF = astraAccNoise(snP * 6.0 + 17.3, snW);',
+ ' float snTn = clamp(mix(snG, snG * 0.66 + snF * 0.34, snFad),',
+ ' 0.0, 1.0);',
+ // The tone rides both fields, over a swing that has to live BELOW
+ // the tone curve's shoulder: at exposure 1.0 with no post chain,
+ // 0.85 linear and 0.56 linear come out of ACES as the same white,
+ // so a near-white cover shaded across the top of the curve renders
+ // as one flat card however much field is under it.
+ ' vec3 snCol = mix(uSnowColor * 0.46, uSnowColor * 1.04,',
+ ' smoothstep(0.16, 0.86, snTn));',
+ // Deep pack goes BLUE and a scoured lane goes warm: a drift is lit
+ // by the sky through its own scattering, while thin snow hands
+ // some of the substrate back. The concave lee counts extra,
+ // because a hollow is the bluest snow in any photograph.
+ ' float snPack = clamp(smoothstep(0.30, 1.20, snD)',
+ ' + clamp(snHold - 1.0, 0.0, 1.0) * 0.6,',
+ ' 0.0, 1.0);',
+ ' snCol *= mix(vec3(1.05, 1.01, 0.96), vec3(0.90, 0.96, 1.10),',
+ ' snPack);',
+ // Snow is the most coloured surface in any scene — it reflects
+ // whatever lights it — so it takes the swing too, but gently:
+ // past a narrow band it stops reading as snow. TWO scales, because
+ // one field the width of a yard is still one flat tint on a roof.
+ ' snCol = astraHueBreak(snCol, vAstraWorld.xz, 0.22, 0.14);',
+ ' snCol = astraHueBreak(snCol, vAstraWorld.xz + 31.7, 1.45, 0.07);',
+ // A third of a code value of screen dither: a near-white ramp
+ // across a roof is the one place 8-bit banding is unmissable, and
+ // there is no post chain here to dither it for us.
+ ' snCol += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ // The shade just OUTSIDE the edge is the only thickness a patch
+ // that cannot displace geometry has. The band is a FRACTION of the
+ // threshold and never a fixed offset below it: past a dusting snT
+ // drops under 0.55, a fixed 0.55 offset puts ZERO deposit inside
+ // the ramp, and every bare wall and soffit in the scene picks up a
+ // shade it has no snow to justify (measured: a 21% darkening on
+ // every vertical face, with the melt hole printed through it).
+ ' float snLip = (1.0 - snK) * smoothstep(snT * 0.40, snT - 0.02,',
+ ' snD);',
+ ' diffuseColor.rgb *= 1.0 - 0.30 * snLip;',
+ // Thin snow is TRANSLUCENT — the substrate comes through it — so
+ // the drifts read as deep and the scoured lanes as shallow.
+ ' float snThin = mix(0.38, 1.0, smoothstep(0.55, 1.30, snD));',
+ ' float snAmt = clamp(snK * snThin * mix(0.55, 1.0, snCov)',
+ ' * smoothstep(0.0, 0.004, uSnowDepth), 0.0, 1.0);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, snCol, snAmt);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Bank sand against everything the wind runs into.
+ *
+ * Sand is not dust: dust is a film on what faces up, and sand is a
+ * DRIFT — it has a windward side, a lee, a wedge profile that is
+ * deepest at the foot of whatever stopped it, and ripples. A scene
+ * reads as desert when every wall in it is banked on the same side,
+ * which is one wind vector shared by every material.
+ *
+ * THE DRIFT IS A WEDGE. Deposit is banked on the face that meets the
+ * wind and tapers to a thin tail in the lee, and it thins with height
+ * above the plane through the world origin — so it climbs the foot of
+ * a wall and lets its head go clear, which is the profile that says
+ * drift rather than wash. `amount` raises the whole bank: how high it
+ * climbs, how much it fills, how far the ripples space out.
+ *
+ * IT FILLS THE CONCAVITIES FIRST. The surface's own signed curvature
+ * adds where it is concave and subtracts where it is convex, so at a
+ * low `amount` sand shows only in the inside corners, along the joints
+ * and in the hollows of a rock — the way a floor sands up before its
+ * middle does. Curvature reads ZERO across a hard, unwelded edge, so
+ * there the wedge carries it alone.
+ *
+ * RIPPLES RUN ACROSS THE WIND. Their phase advances ALONG the wind
+ * axis, which puts every crest square to the flow the way aeolian
+ * ripples lie; they wander on the same field so they are not ruled
+ * lines, they light the crest and shade the trough, they hold a little
+ * more sand than the troughs do, and they are dropped once a pixel
+ * spans one — past that they are not ripples, they are static.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` sands every mesh
+ * wearing it, so clone it first (and clone BEFORE patching).
+ * @param {object} [opts] `amount` how much has drifted, 0..1 (default
+ * 0.45; 0.1 is sand in the corners, 0.9 is a buried wall);
+ * `color` THREE.Color or hex (default a warm ochre at 0.42 linear, the
+ * luminance family a lit ground sits in — a paler one renders as cream
+ * under a physical sun and stops reading as sand at all); `wind`
+ * THREE.Vector3 or [x, y, z] it blows TOWARD, its LENGTH 0..1 the
+ * strength (default [1, 0, 0]); `up` THREE.Vector3 or [x, y, z], the
+ * scene's up (default +Y); `seed` moves the drifts (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uSandWind` can swing with a
+ * storm and `uSandAmt` can bury a scene over a shot.
+ */
+export function patchSand(material, opts = {}) {
+ const amount = opts.amount === undefined ? 0.45 : unit(opts.amount);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Sand is the mattest thing in any scene it lands in.
+ composeRoughness(material, 'acc:sand',
+ towardRoughness(material, 0.94, 0.70 * amount));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'acc:sand',
+ uniforms: {
+ uSandAmt: { value: amount },
+ uSandColor: { value: toColor(opts.color, 0xb08a55) },
+ uSandWind: { value: windVector(opts.wind, [1, 0, 0]) },
+ uSandUp: { value: upVector(opts.up) },
+ uSandSeed: { value: seedOffset(seed, 3.9) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uSandAmt;',
+ 'uniform vec3 uSandColor;',
+ 'uniform vec3 uSandWind;',
+ 'uniform vec3 uSandUp;',
+ 'uniform vec3 uSandSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 sdN = normalize(vAstraWorldN);',
+ ' vec3 sdUp = normalize(uSandUp);',
+ ' float sdWl = clamp(length(uSandWind), 0.0, 1.0);',
+ ' vec3 sdWv = uSandWind / max(length(uSandWind), 1e-4);',
+ ' vec3 sdW = astraAccAxes(sdN);',
+ ' vec3 sdP = vAstraWorld * 1.4 + uSandSeed;',
+ ' float sdG = astraAccNoise(sdP, sdW) * 0.62',
+ ' + astraAccNoise(sdP * 3.9, sdW) * 0.38;',
+ // The wedge: deepest at the foot of whatever stopped it, gone by
+ // the height this much sand can climb.
+ ' float sdTop = mix(0.35, 2.4, uSandAmt);',
+ ' float sdRise = 1.0 - smoothstep(0.0, sdTop,',
+ ' max(dot(vAstraWorld, sdUp), 0.0));',
+ // Banked on the face that meets the wind, a thin tail in the lee;
+ // with no wind at all there is no windward side to bank on.
+ ' float sdFace = -dot(sdN, sdWv);',
+ ' float sdBank = mix(0.45, mix(0.18, 1.0,',
+ ' smoothstep(-0.55, 0.75, sdFace)), sdWl);',
+ ' float sdLie = smoothstep(-0.10, 0.55, dot(sdN, sdUp));',
+ // Nothing banks against a soffit: a face turned under holds no
+ // more sand than it holds water.
+ ' sdBank *= smoothstep(-0.55, -0.05, dot(sdN, sdUp));',
+ // Concave first: a corner sands up long before the flat beside it
+ // does, and a convex edge is swept clean. The shed window starts
+ // WELL past the fill's, because sand does not scour a stone the
+ // way it scours a rib: at the old 0.5/2.5 window every cobble in a
+ // drift came out bare and black while the sand ran on around it,
+ // which is a deflation pavement and not the yard we asked for.
+ ' float sdCv = astraAccCurv(sdN, vAstraWorld);',
+ ' float sdR = 1.0 / max(uSandAmt * 0.6 + 0.05, 0.05);',
+ ' float sdFill = smoothstep(sdR * 0.35, sdR * 2.0, -sdCv);',
+ ' float sdShed = smoothstep(sdR * 0.9, sdR * 3.2, sdCv);',
+ // The wedge gates EVERY term, tops included: wind carries sand
+ // along the ground, so a roof four metres up gets none of it.
+ ' float sdLay = clamp((max(sdLie * 0.90, sdBank)',
+ ' + sdFill * 0.55) * sdRise',
+ ' - sdShed * 0.42, 0.0, 1.6);',
+ // Crests square to the flow: the phase runs ALONG the wind axis,
+ // wandering on the field so they are not ruled lines. The skew
+ // steepens the lee face of each crest the way a ripple's is.
+ ' float sdLam = mix(0.12, 0.45, uSandAmt);',
+ ' float sdPh = dot(vAstraWorld, sdWv) / sdLam + (sdG - 0.5) * 1.4;',
+ ' sdPh = sdPh * 6.2831853;',
+ // Gone once a pixel spans a ripple: past that it is not a ripple,
+ // it is static, which is the one way this reads as an effect.
+ ' float sdFade = 1.0 - smoothstep(0.16, 0.50,',
+ ' length(fwidth(vAstraWorld)) / sdLam);',
+ ' float sdRip = sin(sdPh + 0.55 * sin(sdPh)) * sdFade * sdWl',
+ ' * mix(0.25, 1.0, sdLie);',
+ // The crests hold a little more than the troughs, so the ripple
+ // is in the COVERAGE and not only in the tone.
+ ' float sdD = sdLay * (0.55 + 0.90 * sdG) + sdRip * 0.14;',
+ ' float sdT = mix(1.10, 0.20, uSandAmt);',
+ ' float sdAA = clamp(fwidth(sdD), 0.0, 0.35);',
+ ' float sdK = smoothstep(sdT - 0.05 - sdAA, sdT + 0.14 + sdAA, sdD);',
+ // A finer field for the TONE only, faded once a pixel spans it:
+ // dune sand is graded, and a decimetre of one value is paint.
+ ' float sdFad = 1.0 - smoothstep(0.04, 0.10,',
+ ' length(fwidth(vAstraWorld)));',
+ ' float sdF = astraAccNoise(sdP * 7.5 + 41.9, sdW);',
+ ' float sdTn = clamp(mix(sdG, sdG * 0.66 + sdF * 0.34, sdFad),',
+ ' 0.0, 1.0);',
+ ' vec3 sdCol = mix(uSandColor * 0.68, uSandColor * 1.10,',
+ ' smoothstep(0.22, 0.84, sdTn));',
+ // The crest is sun-bleached and warm, the trough holds the sky: a
+ // ripple that is one brightness is a stripe painted on flat sand.
+ ' sdCol *= vec3(1.0) + sdRip * vec3(0.20, 0.15, 0.06);',
+ // Sand is a mineral mix, not a paint chip: quartz, iron and shell
+ // put warm and cool metres apart, and the palette probe named a
+ // whole dune field "one flat hue per surface". Wider than stone
+ // because a dune has nothing else in it to carry variety, and at
+ // TWO scales because the metre-wide one alone is a flat tint on
+ // anything smaller than the dune it was written for.
+ ' sdCol = astraHueBreak(sdCol, vAstraWorld.xz, 0.28, 0.36);',
+ ' sdCol = astraHueBreak(sdCol, vAstraWorld.xz + 12.4, 1.70, 0.13);',
+ ' sdCol += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ // A FRACTION of the threshold, never a fixed offset below it — see
+ // snLip: past `amount` 0.5 sdT drops under 0.55 and a fixed offset
+ // shades every wall the drift never reached.
+ ' float sdLip = (1.0 - sdK) * smoothstep(sdT * 0.40, sdT - 0.02,',
+ ' sdD);',
+ ' diffuseColor.rgb *= 1.0 - 0.22 * sdLip;',
+ ' float sdAmt = clamp(sdK * mix(0.70, 1.0, uSandAmt)',
+ ' * smoothstep(0.0, 0.05, uSandAmt), 0.0, 1.0);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, sdCol, sdAmt);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/aging.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/aging.js
new file mode 100644
index 00000000..d10555b3
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/aging.js
@@ -0,0 +1,514 @@
+/**
+ * Aging: the three marks that say a surface has STOOD somewhere.
+ *
+ * `surface_wear` breaks up the flat colour and takes the finish off the
+ * edges; these three add the part only weather writes — what ran DOWN
+ * the face, what corroded where water sat, and what settled on top. All
+ * three go through `patchStandard`, so lighting, shadows, fog and the
+ * depth chunks survive; all three shade from world position and world
+ * normal, so none needs a UV, gravity stays world Y whatever the
+ * surface is doing, and two objects sharing a scale share one weather.
+ *
+ * The constraint that shapes all of them: a fragment sees its own
+ * position, its own normal and its own screen derivatives, and nothing
+ * else — it cannot look UP the surface to find the ledge the water
+ * poured over. So the vertical structure rides fields that are
+ * STRETCHED along world Y (drips) or CONSTANT along it (rust), which is
+ * what makes a stain continue below the rim that made it; and
+ * `patchDripStains(m, { from })` is the one way to pin the source to an
+ * exact sill.
+ *
+ * Gloss is per MATERIAL, not per pixel — `<color_fragment>` runs before
+ * `<roughnessmap_fragment>` — so each patch composes one roughening
+ * factor through `composeRoughness`: dirt, rust and dust are all matte.
+ *
+ * COLOUR: no effect here is one tone. Weather is a mixture — the dirt
+ * that ran down is not the salt it leached out of the wall, the pit in
+ * a corrosion patch is not the ochre bloom at its edge, and a drift of
+ * dust is warmer than the veil between drifts. So each patch carries a
+ * PAIR (drips, dust) or a TRIPLE (rust) built off its one colour
+ * option, hue-broken across the field by `astraHueBreak`, and the
+ * lighter member of each pair is derived from the SURFACE's own albedo
+ * rather than named here — a leached halo belongs to whatever it is
+ * leaching out of, and nothing in this file may hardcode a light.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, waterside and surface_wear name them, so a
+// material wearing several libraries declares ONE pair; the vertex
+// locals are ag* because those three own astraWp, wsP and wrP.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// All three patches read these, so they are declared once, in the base.
+// Names are age-prefixed rather than shared with surface_wear's: a
+// neighbour's helper is only there when that neighbour was applied.
+const AGE_HEAD = [
+ 'vec3 astraAgeAxes(vec3 n) {',
+ ' vec3 w = abs(n * n * n);',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+ // The vertical-streak field: three world-plane projections blended by
+ // the normal, world Y compressed by `lift` in the two upright ones so
+ // a feature is taller than wide on ANY face. lift 1.0 = blotches.
+ 'float astraAgeStreak(vec3 p, vec3 w, float lift) {',
+ ' return astraNoise2(vec2(p.z, p.y * lift) + 17.3) * w.x',
+ ' + astraNoise2(p.xz + 41.9) * w.y',
+ ' + astraNoise2(vec2(p.x, p.y * lift) + 73.1) * w.z;',
+ '}',
+ // Curvature in 1/m: how far the normal turns per metre of surface
+ // under one pixel. Positive is convex (swept clean), negative the
+ // concave lee that holds. Zero across a hard, unwelded edge.
+ 'float astraAgeCurv(vec3 n, vec3 p) {',
+ ' vec3 dx = dFdx(p), dy = dFdy(p);',
+ ' float d = dot(dx, dx) + dot(dy, dy);',
+ ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',
+ '}',
+].join('\n');
+
+// One base for all three. `transformed` is still object-space after
+// <begin_vertex>, so the instance transform is folded in by hand or
+// every scattered copy weathers from the world origin.
+const BASE = {
+ name: 'aging:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 agP = vec4(transformed, 1.0);',
+ ' vec3 agN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' agP = instanceMatrix * agP;',
+ ' agN = mat3(instanceMatrix) * agN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * agP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(agN, 0.0)).xyz);',
+ ].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, AGE_HEAD].join('\n'),
+};
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed
+ * for every material that shares the cache key. The constants differ
+ * from surface_wear's, or one seed would land this library's stains on
+ * that one's blotches.
+ */
+function seedOffset(seed, salt) {
+ return new THREE.Vector3(
+ hash11(seed + salt + 0.29), hash11(seed + salt + 5.13),
+ hash11(seed + salt + 9.47)).multiplyScalar(48);
+}
+
+/**
+ * A roughening factor one patch cannot push past fully rough.
+ *
+ * Every effect here is matte, so each raises roughness; roughness only
+ * means anything up to 1, and the material may start near it.
+ *
+ * The `add` each patch passes used to be token — a fully rusted steel
+ * tank moved from 0.45 to 0.50 and went on mirroring the sky, which
+ * washed the oxide off the frame at every distance. A crust of oxide,
+ * dust or dried grime is one of the matte-est things there is, so these
+ * now buy real roughness: the cap keeps a surface that already starts
+ * rough from moving at all.
+ */
+function matteFactor(material, add) {
+ const store = material.userData.astraRoughness;
+ const base = store ? store.base : material.roughness;
+ return base > 0 ? Math.min(1 + add, 1 / base) : 1;
+}
+
+/**
+ * The vertical streaks that run down from every ledge, sill and joint.
+ *
+ * Rain does not wash a facade evenly: it collects on the horizontals,
+ * pours over their lips, and carries the dirt off them down the face in
+ * runs — so an exterior with clean verticals under dirty ledges reads
+ * as a model of a building rather than a building. This lays those runs
+ * over the albedo, and it is the single strongest "this has stood
+ * outside" cue there is.
+ *
+ * DOWN IS WORLD Y — the field is projected on the world planes and
+ * stretched ~11x along Y, so a wall at any angle, a pipe and a tank all
+ * streak vertically with no UV to author and no per-object setup. Three
+ * thresholds cut it into a pale leached rim, the body of the run and a
+ * narrow dark core, so the runs come out wide, hairline or absent; and
+ * the field is sampled a second time 4 * `scale` HIGHER and faded in,
+ * which drags every feature downward and tapers its tail — that
+ * asymmetry is what reads as flow rather than as stripes.
+ *
+ * The rim is the surface's OWN albedo lifted, not a colour chosen here:
+ * rain leaches a wall before it dirties it, and a pale edge beside a
+ * dark core is what makes a run legible at any distance — with the
+ * grime alone the whole face just dims (measured on the showcase wall:
+ * the run signal, the high-pass of the column-mean luminance, went
+ * 0.0111 -> 0.0126 and its peak-to-peak 0.049 -> 0.061 when the rim
+ * was split out of the wash).
+ *
+ * A fragment cannot see the surface above it, so `from` is the only way
+ * to say where the water came over: given, the runs start just under
+ * that world Y (each a little lower than its neighbour) and die out at
+ * their own length; left out, they take their tops from the field
+ * itself and read as general staining down the whole face. Faces that
+ * shed nothing — level tops, level soffits — are left alone.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` streaks every mesh
+ * wearing it, so clone it first if that is not what you want.
+ * @param {object} [opts] `strength` how far a run goes toward `color`,
+ * 0..1 (default 0.35); `color` THREE.Color or hex, the washed-down
+ * dirt, hue-broken per run so no two are the same brown (default a
+ * sooty grey-brown); `scale` metres between runs
+ * (default 0.6; their length scales with it, ~2 to 7 m); `from` world
+ * Y the runs start below — a ledge top, a sill, a joint (default:
+ * none, staining down the whole face); `seed` moves them (default 1).
+ * @returns {THREE.Material} The same material. Its uniforms stay live
+ * on `material.userData.uniforms`, so `uDripFrom` can follow a sill.
+ */
+export function patchDripStains(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.35 : opts.strength;
+ const scale = opts.scale === undefined ? 0.6 : opts.scale;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const from = opts.from;
+ const gated = Number.isFinite(from);
+ composeRoughness(material, 'aging:drip',
+ matteFactor(material, 0.22 * unit(strength)));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'aging:drip',
+ uniforms: {
+ uDripAmt: { value: unit(strength) },
+ // A grime that is DARKER than the wall, not a hole in it: the old
+ // 0x4a4139 lands at 0.074/0.058/0.041 linear and the hue break
+ // takes the low side of that to 0.04, which reads as a shadow
+ // rather than as soot. This sits at 0.098/0.072/0.051.
+ uDripColor: { value: toColor(opts.color, 0x584c40) },
+ uDripScale: { value: Math.max(1e-3, scale) },
+ uDripFrom: { value: gated ? from : 0 },
+ uDripGate: { value: gated ? 1 : 0 },
+ uDripSeed: { value: seedOffset(seed, 0) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uDripAmt;',
+ 'uniform vec3 uDripColor;',
+ 'uniform float uDripScale;',
+ 'uniform float uDripFrom;',
+ 'uniform float uDripGate;',
+ 'uniform vec3 uDripSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 drN = normalize(vAstraWorldN);',
+ ' vec3 drP = vAstraWorld / uDripScale + uDripSeed;',
+ // Water runs only where it cannot sit: a level top sheds nothing
+ // down its own surface, and neither does a level soffit.
+ ' float drFlow = 1.0 - smoothstep(0.30, 0.92, abs(drN.y));',
+ ' vec3 drW = astraAgeAxes(drN);',
+ ' float drA = astraAgeStreak(drP, drW, 0.09);',
+ // The same field 4 * scale HIGHER, faded in: every feature is
+ // dragged down from where it started and tapers as it goes.
+ ' float drB = astraAgeStreak(drP + vec3(0.0, 4.0, 0.0), drW, 0.09);',
+ // A finer field, stretched even harder, ADDED before the
+ // threshold rather than multiplied after: it tears the edge of
+ // every run into fibres that run WITH it.
+ ' float drC = astraAgeStreak(drP * 3.3, drW, 0.045);',
+ ' float drF = max(drA, drB * 0.80) + (drC - 0.5) * 0.28;',
+ // Two thresholds on one field: a broad faint wash with a narrow
+ // dark core inside it, which is a run rather than a stripe. The
+ // widths vary because the peaks the thresholds cut do.
+ //
+ // fwidth here is a PIXEL guard, not a softener. A wall seen at a
+ // grazing angle carries a screen gradient many times the width of
+ // either threshold band, so the old 0.5 cap let it swallow both
+ // and every run came out an airbrushed smudge with no edge at all
+ // (measured on the showcase wall: the runs had no local contrast
+ // to speak of). Capped near one band's width it antialiases and
+ // stops there.
+ ' float drAA = clamp(fwidth(drF), 0.0, 0.045);',
+ // THREE cuts, not two. The outer rim and the body used to be one
+ // band, so the pale leach and the dark grime landed on the same
+ // pixels and cancelled — the run lost contrast instead of gaining
+ // it (wall lum_std 0.0468 -> 0.0415 on the first attempt). Split
+ // them and the rim frames the body instead of bleaching it.
+ ' float drWash = smoothstep(0.50 - drAA, 0.60 + drAA, drF);',
+ ' float drBody = smoothstep(0.60 - drAA, 0.70 + drAA, drF);',
+ ' float drCore = smoothstep(0.715 - drAA, 0.775 + drAA, drF);',
+ ' float drRim = drWash * (1.0 - drBody);',
+ // The sill: full just under it, nothing above it, each run
+ // starting a little lower and dying at its own length.
+ ' float drL = mix(3.0, 12.0, drA) * uDripScale;',
+ ' float drH = uDripFrom - vAstraWorld.y - drB * uDripScale;',
+ ' float drS = smoothstep(0.0, uDripScale * 0.5, drH)',
+ ' * (1.0 - smoothstep(drL * 0.4, drL, drH));',
+ ' float drG = mix(1.0, drS, uDripGate) * drFlow * uDripAmt;',
+ // What the rain LEACHED, before what it carried: the run's pale
+ // halo is the surface's own colour lifted, so it belongs to
+ // whatever it is running on — concrete, render, rusting steel —
+ // instead of being a grey chosen here. It sits BESIDE the core,
+ // never under it, which is the light-then-dark pairing that makes
+ // a run read as a run at any distance.
+ ' vec3 drSalt = diffuseColor.rgb * 1.34 + 0.030;',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, drSalt,',
+ ' clamp(drRim * 0.85 * drG, 0.0, 1.0));',
+ // ...and the dirt itself, hue-broken along the wall: two runs off
+ // one sill are never the same brown, and one flat tone is the
+ // tell that a texture was painted rather than deposited.
+ ' vec3 drDirt = astraHueBreak(uDripColor, drP.xz * 0.7 + drP.y,',
+ ' 0.35, 0.55) * (0.70 + 0.60 * drA);',
+ ' float drAmt = clamp((0.42 * drBody + 0.58 * drCore) * drG,',
+ ' 0.0, 1.0);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, drDirt, drAmt);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Corrode where water SITS and RUNS, and bleed it downward.
+ *
+ * Rust sprayed evenly over a tank is a red tank; rust reads as rust
+ * because it starts where water cannot leave — the upward faces, the
+ * lee of a rim, the inside of a corner — and then bleeds down the face
+ * below in the same patches that fed it. Both halves are here: a
+ * pooling term from the world normal and the surface's own signed
+ * curvature, and a running term on the faces that shed.
+ *
+ * THE BLEED IS THE FIELD'S DOING — the corrosion map is read from world
+ * XZ only, so a whole vertical column of surface shares one value, and
+ * a patch that eats the rim of a tank keeps eating straight down the
+ * side under it. That is the one way a fragment, which cannot see the
+ * surface above it, can know what drained onto it. A second field, its
+ * vertical period in METRES rather than in patches and dragged 2 m
+ * downward, ends the trail — without it a coarse `scale` paints one
+ * column floor to ceiling — and THREE tones ride that field rather than
+ * one brightness ramp: a near-black pitted crust in its lee, the oxide
+ * through the body, and an ochre bloom where the crust is thinnest.
+ * That grading is what stops a small subject — a 2.6 m tank, a pipe —
+ * from reading as a single dark bruise.
+ *
+ * Curvature reads ZERO across a hard, unwelded edge (`BoxGeometry`'s
+ * corners, anything flat-shaded), so the lee term needs bevelled or
+ * smooth-shaded geometry; the pooling and bleeding terms work on
+ * anything. And rust is a dielectric CRUST: per-pixel metalness is as
+ * unreachable as per-pixel roughness from this hook, so on a shiny
+ * `metalness: 1` tank the oxide tints the metal's own reflection and
+ * comes out pink — give a rusting surface a low metalness yourself.
+ * What this CAN do is take the whole material matte, and at full
+ * strength it does (roughness x1.6, capped at fully rough): a corroded
+ * tank that goes on mirroring the sky washes the oxide out of the frame
+ * at every distance.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material rusts every mesh wearing it.
+ * @param {object} [opts] `strength` how far the worst of it goes toward
+ * `color`, 0..1 (default 0.4); `color` THREE.Color or hex (default an
+ * iron oxide); `scale` metres across a corrosion patch (default 1.2,
+ * which also sets the corner radius the lee term looks for); `seed`
+ * moves the patches (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`.
+ */
+export function patchRust(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.4 : opts.strength;
+ const scale = opts.scale === undefined ? 1.2 : opts.scale;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ composeRoughness(material, 'aging:rust',
+ matteFactor(material, 0.60 * unit(strength)));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'aging:rust',
+ uniforms: {
+ uRustAmt: { value: unit(strength) },
+ // An iron oxide with a blue channel. 0x70320f is 0.157/0.034/0.005
+ // linear — the blue is BLACK, so the mid tone had nowhere to go
+ // but a bruise, and the pit tone under it went to zero. A real
+ // goethite/hematite crust sits near 0.25/0.09/0.035.
+ uRustColor: { value: toColor(opts.color, 0x87542f) },
+ uRustScale: { value: Math.max(1e-3, scale) },
+ uRustSeed: { value: seedOffset(seed, 2.3) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uRustAmt;',
+ 'uniform vec3 uRustColor;',
+ 'uniform float uRustScale;',
+ 'uniform vec3 uRustSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 rsN = normalize(vAstraWorldN);',
+ ' vec3 rsP = vAstraWorld / uRustScale + uRustSeed;',
+ // Y-INDEPENDENT on purpose: one column of surface, one value, so
+ // what corrodes a rim goes on corroding the face beneath it.
+ ' float rsF = astraFbm2(rsP.xz, 3);',
+ // The bleed's own texture, its vertical period in METRES rather
+ // than in patches: how far a stain trails is a physical distance,
+ // so a coarse map must not paint one column floor to ceiling.
+ ' vec3 rsQ = vec3(rsP.x, vAstraWorld.y * 0.25, rsP.z) * 1.6;',
+ ' vec3 rsA = astraAgeAxes(rsN);',
+ ' float rsG = astraAgeStreak(rsQ, rsA, 1.0);',
+ // The same field 2 m higher, faded in: the stain trails DOWN off
+ // whatever fed it and dies a couple of metres on.
+ ' float rsH = astraAgeStreak(rsQ + vec3(0.0, 0.8, 0.0), rsA, 1.0);',
+ ' float rsB = max(rsG, rsH * 0.82);',
+ // Where water SITS: on what faces up, and in the concave lee a
+ // shape shelters from the rain that would rinse it.
+ ' float rsC = astraAgeCurv(rsN, vAstraWorld);',
+ ' float rsR = 1.0 / uRustScale;',
+ ' float rsLee = smoothstep(rsR * 0.5, rsR * 2.0, -rsC);',
+ ' float rsSit = clamp(smoothstep(-0.05, 0.55, rsN.y)',
+ ' + rsLee * 0.8, 0.0, 1.0);',
+ // Where it RUNS: the faces that shed keep the patch that drained
+ // onto them, textured — not gated — by the streak field.
+ ' float rsDown = 1.0 - smoothstep(0.30, 0.90, abs(rsN.y));',
+ ' float rsRun = rsDown',
+ ' * (0.12 + 0.88 * smoothstep(0.40, 0.62, rsB));',
+ // The patch edge is torn by the finer field, or corrosion has a
+ // soft airbrushed boundary no oxide ever had.
+ ' float rsK = smoothstep(0.46, 0.62, rsF + (rsB - 0.5) * 0.30)',
+ ' * clamp(rsSit + rsRun, 0.0, 1.0);',
+ ' float rsAmt = clamp(rsK * uRustAmt, 0.0, 1.0);',
+ // THREE tones, not one brightness ramp. Corrosion is a stack: a
+ // near-black pitted crust where it has eaten in, the oxide itself
+ // across the body of the patch, and a thin ochre bloom at the
+ // leading edge where it is still only a stain. A single colour
+ // scaled 0.45..1.05 gives the last of those none of its hue and
+ // reads as a dark bruise on anything cool-coloured.
+ ' vec3 rsBase = astraHueBreak(uRustColor, rsP.xz, 0.8, 0.40);',
+ ' vec3 rsPit = rsBase * vec3(0.38, 0.32, 0.30);',
+ ' vec3 rsGlow = min(rsBase * vec3(1.30, 1.95, 1.70), vec3(0.82));',
+ // The three tones ride the STREAK field, so the whole patch is
+ // graded across rather than one flat oxide with a rim: pits in
+ // its lee, the oxide through the body, ochre where the crust is
+ // thin and freshly wet. Confining the bloom to the boundary (a
+ // first attempt) left the patch reading as one dark bruise on
+ // anything as small as a 2.6 m tank.
+ ' vec3 rsCol = mix(rsPit, rsBase, smoothstep(0.16, 0.50, rsB));',
+ ' rsCol = mix(rsCol, rsGlow, smoothstep(0.50, 0.78, rsB) * 0.60',
+ ' + clamp(rsK * (1.0 - rsK) * 4.0, 0.0, 1.0) * 0.30);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, rsCol, rsAmt);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Settle dust on what faces up, thickest where it is flat and sheltered.
+ *
+ * An interior or a long-idle exterior loses its contrast from the top
+ * down: every upward face gets the same pale film, which is why a
+ * spotless top surface reads as new. This is the cheapest of the three
+ * — one cosine against the up axis, broken by a blotch field so it is a
+ * settling rather than a wash — and the one that most changes how OLD a
+ * room looks.
+ *
+ * The film is two tones at ONE value: the coarse grit that fell out
+ * first sits warm in the drifts, the fine powder the sky keeps lighting
+ * sits cool in the veil between them, both split by the same field that
+ * sets the coverage. Equal value keeps the surface lightening evenly
+ * while the hue moves under it (measured on the showcase slab: hue
+ * spread 0.066 -> 0.080 at unchanged mean luminance) — a single grey
+ * mixed over everything is a coat of paint, not a settling.
+ *
+ * `up` is a uniform vector, not world Y: dust settles along whatever
+ * gravity the scene is telling, so a tilted asset, a capsized hull or a
+ * deck under a listing ship dusts on the faces that actually point up.
+ *
+ * SHELTER is the surface's own signed curvature: a convex edge is swept
+ * by every passing hand and by the rain, a concave corner keeps what
+ * lands in it. Curvature reads ZERO across a hard unwelded edge, so on
+ * `BoxGeometry` the shelter term simply does nothing and the cosine
+ * carries it.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material dusts every mesh wearing it.
+ * @param {object} [opts] `strength` how far the film goes toward
+ * `color` on a flat top, 0..1 (default 0.3); `color` THREE.Color or
+ * hex (default a pale grey); `up` THREE.Vector3 or [x, y, z], the
+ * world up (default +Y); `seed` moves the blotches (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uDustUp` can follow a tilt.
+ */
+export function patchDust(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.3 : opts.strength;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const up = new THREE.Vector3(0, 1, 0);
+ if (opts.up) up.fromArray(opts.up.toArray ? opts.up.toArray() : opts.up);
+ if (!(up.lengthSq() > 1e-9)) up.set(0, 1, 0);
+ composeRoughness(material, 'aging:dust',
+ matteFactor(material, 0.55 * unit(strength)));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'aging:dust',
+ uniforms: {
+ uDustAmt: { value: unit(strength) },
+ uDustColor: { value: toColor(opts.color, 0xb8b2a6) },
+ uDustUp: { value: up.normalize() },
+ uDustSeed: { value: seedOffset(seed, 4.7) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uDustAmt;',
+ 'uniform vec3 uDustColor;',
+ 'uniform vec3 uDustUp;',
+ 'uniform vec3 uDustSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 duN = normalize(vAstraWorldN);',
+ // Settling is a cosine against the scene's own up, not world Y.
+ ' float duLay = smoothstep(0.02, 0.70,',
+ ' dot(duN, normalize(uDustUp)));',
+ // Swept off what sticks out, held in what is sheltered.
+ ' float duC = astraAgeCurv(duN, vAstraWorld);',
+ ' float duHold = 1.0 - 0.85 * smoothstep(3.0, 10.0, duC)',
+ ' + 0.35 * smoothstep(2.0, 8.0, -duC);',
+ // Drifts at ~2 m with a grain inside them, or the film is a wash
+ // of paint rather than something that landed.
+ ' vec3 duP = vAstraWorld * 0.55 + uDustSeed;',
+ ' vec3 duW = astraAgeAxes(duN);',
+ ' float duB = astraAgeStreak(duP, duW, 1.0) * 0.65',
+ ' + astraAgeStreak(duP * 3.7, duW, 1.0) * 0.35;',
+ ' float duK = clamp(duLay * duHold',
+ ' * mix(0.30, 1.0, smoothstep(0.28, 0.78, duB)),',
+ ' 0.0, 1.0);',
+ // A settled film is not one grey. The drifts are the coarse warm
+ // grit that fell out first; the veil between them is the fine
+ // pale powder the sky keeps lighting. Splitting them by the same
+ // field that sets the coverage costs nothing and is the whole
+ // difference between dust and a coat of paint — the two tones sit
+ // at the same VALUE, so the film still lightens evenly.
+ ' vec3 duCol = astraHueBreak(uDustColor, duP.xz, 0.5, 0.35);',
+ // Rec.709-matched on purpose (0.962 against 0.967): a warm/cool
+ // pair that also differs in VALUE reads as a stain, not a film.
+ ' duCol = mix(duCol * vec3(0.92, 0.96, 1.10),',
+ ' duCol * vec3(1.12, 0.94, 0.78),',
+ ' smoothstep(0.22, 0.80, duB));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, duCol,',
+ ' duK * uDustAmt);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/atmosphere.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/atmosphere.js
new file mode 100644
index 00000000..8547f1b5
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/atmosphere.js
@@ -0,0 +1,591 @@
+/**
+ * Atmosphere: the two distance cues correct geometry cannot supply.
+ *
+ * A fog BANK is geometry — things wade in it, which `scene.fog` can
+ * never do (it is a function of camera distance, so it veils a figure's
+ * head exactly as much as its boots). Aerial perspective is the COLOUR
+ * half of distance: FogExp2 dims but never shifts hue, and without the
+ * shift a correctly built scene still reads as a tabletop model.
+ */
+
+import * as THREE from 'three';
+import { mulberry32 } from './noise.js';
+import { makeShaderMaterial, patchStandard, tickShaders } from './shader.js';
+
+// Sheets are packed toward the ground (h ~ f^PACK): an evenly spaced
+// stack spends most of its geometry in the thin top half where there
+// is almost nothing to draw. BASE_H keeps the first sheet off the soil.
+//
+// LAYERS is the QUANTISATION of the height integral, and it shows: a
+// sheet's plane crosses anything vertical standing in the bank along a
+// horizontal line, and across that line the count of sheets in front
+// changes by one. At 12 sheets a crate in the bank wore six hard
+// contour bands (measured on this renderer: six steps over its front
+// face, the largest 7/255). Twenty sheets halve the step, and the
+// noise floor + dither in the fragment stage break what is left.
+const LAYERS = 20;
+const PACK = 1.6;
+const BASE_H = 0.03;
+// Metres of the bank's thickest air that `density` is quoted over, so
+// the dial means one physical thing at any `extent`, `height` or
+// LAYERS. Written into the GLSL below as 1/REF_M.
+const REF_M = 10;
+// environment.js MOODS.day.horizon — the fallback for a bank built with
+// no scene to read. Not a light colour anyone should be relying on:
+// pass `scene` (or `color`) and the bank takes the scene's own.
+const DAY_HORIZON = 0xdbe3ea;
+// Henyey-Greenstein asymmetry. Water droplets scatter hard forward, so
+// a bank you look THROUGH toward the sun is a light source and the same
+// bank with the sun behind you is a grey wall. HG_NORM normalises the
+// broadside value to 1 so `uSunAmt` alone sets the strength.
+const HG_G = 0.55;
+const HG_G2 = HG_G * HG_G;
+const HG_NORM = ((1 - HG_G2) / Math.pow(1 + HG_G2, 1.5)).toFixed(6);
+// Radiance the key light leaves in a metre of the bank's thickest air,
+// per unit of three's directional intensity. Tuned on this renderer
+// against the moon rig (2.2) and the day rig (5.4).
+const BEAM_K = 0.022;
+
+const LUMA = 'vec3(0.2126, 0.7152, 0.0722)';
+/** One horizon read per baked environment, not per patched material. */
+const AIR_CACHE = new WeakMap();
+
+/** Luminance of a linear-space THREE.Color. */
+function lumOf(c) {
+ return Math.max(1e-4, 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b);
+}
+
+/** `c`'s chromaticity at unit luminance — hue without brightness. */
+function chroma(c) {
+ return c.clone().multiplyScalar(1 / lumOf(c));
+}
+
+/**
+ * The radiance of the air itself, read off the baked environment.
+ *
+ * In-scattered light IS the colour of fog, and the scene already
+ * carries it: `sunRig` bakes the same graded sky the dome draws into a
+ * linear half-float equirect. The band from the horizon to 25 degrees
+ * up is what a ground-level ray flies through, so its radiance is the
+ * bank's colour and the far field's airlight — in every mood, with no
+ * constant of mine anywhere near it. Measured off this bake: day
+ * (0.436, 0.764, 1.082), a real sky blue rather than the near-white
+ * `scene.fog` carries; night (0.026, 0.036, 0.073), seven times the
+ * night mood's fog colour, which is set to swallow the far field and
+ * is far too dark to be air.
+ *
+ * The middle two quartiles, not the mean: at a low sun the bake's HDR
+ * sun disc (radiance 5) sits inside this band and doubles a mean
+ * (golden reads 0.505 flat, 0.262 trimmed).
+ *
+ * @param {THREE.Scene} [scene]
+ * @returns {THREE.Color|null} null unless `scene.environment` is a
+ * linear equirect DataTexture (a PMREM cube, an LDR texture or no
+ * environment at all falls back to the fog colour).
+ */
+function horizonRadiance(scene) {
+ const tex = scene && scene.environment;
+ const img = tex && tex.image;
+ const data = img && img.data;
+ if (!data || tex.mapping !== THREE.EquirectangularReflectionMapping) {
+ return null;
+ }
+ // Per BAKE, not per call: `patchAerialPerspective` is called once per
+ // material and every one of them would otherwise re-read a quarter of
+ // the equirect. The cached colour is never handed out — callers of
+ // `readScene` mutate what they get.
+ if (AIR_CACHE.has(tex)) {
+ const hit = AIR_CACHE.get(tex);
+ return hit ? hit.clone() : null;
+ }
+ const half = tex.type === THREE.HalfFloatType;
+ const w = img.width | 0;
+ const h = img.height | 0;
+ const stride = w && h ? data.length / (w * h) : 0;
+ if ((!half && tex.type !== THREE.FloatType)
+ || w < 4 || h < 4 || (stride !== 3 && stride !== 4)) {
+ AIR_CACHE.set(tex, null);
+ return null;
+ }
+ const f = half ? THREE.DataUtils.fromHalfFloat : (v) => v;
+ // three samples an equirect at v = 0.5 + asin(dir.y) / PI and a
+ // DataTexture never flips Y, so v 0.500 is the horizon and 0.639 is
+ // 25 degrees up.
+ const y1 = Math.min(h, Math.round(0.639 * h));
+ const px = [];
+ for (let y = Math.round(0.5 * h); y < y1; y++) {
+ for (let x = 0; x < w; x += 2) {
+ const i = (y * w + x) * stride;
+ const c = [f(data[i]), f(data[i + 1]), f(data[i + 2])];
+ px.push([0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2], c]);
+ }
+ }
+ if (px.length < 8) {
+ AIR_CACHE.set(tex, null);
+ return null;
+ }
+ px.sort((a, b) => a[0] - b[0]);
+ const slice = px.slice(Math.floor(px.length * 0.25),
+ Math.ceil(px.length * 0.75));
+ const acc = new THREE.Color(0, 0, 0);
+ for (const [, c] of slice) { acc.r += c[0]; acc.g += c[1]; acc.b += c[2]; }
+ acc.multiplyScalar(1 / slice.length);
+ AIR_CACHE.set(tex, acc);
+ return acc.clone();
+}
+
+/**
+ * Air is never darker than the light standing in it.
+ *
+ * `scene.fog.color` is doing TWO jobs and they part company at night:
+ * it also has to swallow the far field, so a night mood sets it near
+ * black (0x0b0f1a — luminance 0.005 linear) while the air in front of
+ * you is still carrying whatever the sky and the moon put into it. Used
+ * raw, the far field crushes to a black-blue silhouette (measured: a
+ * ridge 70 m out fell to (9, 23, 50) against a (26, 36, 64) sky).
+ * Below `floor` the colour is pulled toward `ref`'s hue and lifted to
+ * it: dark, but lit, and blue rather than nothing.
+ *
+ * @param {THREE.Color} color Mutated and returned.
+ * @param {THREE.Color|null} ref The hue to fall back toward (the air's
+ * own radiance, else the fill light).
+ * @param {number} floor Luminance floor, linear.
+ */
+function inScatterFloor(color, ref, floor) {
+ if (!ref || !(floor > 0) || lumOf(color) >= floor) return color;
+ color.lerp(ref, 0.6);
+ return color.multiplyScalar(floor / lumOf(color));
+}
+
+/**
+ * What the scene says about its own air and its own light.
+ *
+ * Atmosphere is the one effect that may not carry colours of its own:
+ * a bank at a baked-in daylight white is a slab of milk in a night
+ * scene (measured here: the ground under it read (69,66,64) against a
+ * (26,36,64) sky — the brightest thing in the frame). So the colour of
+ * the air comes from `scene.environment`, the fall-backs from
+ * `scene.fog`, the warm half from the scene's own key light and the
+ * cool half from its fill.
+ *
+ * @param {THREE.Scene} [scene]
+ * @returns {{air: THREE.Color|null, fog: THREE.Color|null,
+ * dir: THREE.Vector3|null, sun: THREE.Color|null, key: number,
+ * amb: THREE.Color|null, ambLum: number, fogDensity: number}}
+ */
+function readScene(scene) {
+ const out = { air: null, fog: null, dir: null, sun: null, key: 0,
+ amb: null, ambLum: 0, fogDensity: 0 };
+ if (!scene || typeof scene.traverse !== 'function') return out;
+ out.air = horizonRadiance(scene);
+ if (scene.fog && scene.fog.color) {
+ out.fog = scene.fog.color.clone();
+ out.fogDensity = scene.fog.density || 0;
+ }
+ let best = null;
+ let fill = null;
+ scene.traverse((o) => {
+ if (o.isDirectionalLight) {
+ if (!best || o.intensity > best.intensity) best = o;
+ } else if (o.isHemisphereLight || o.isAmbientLight) {
+ if (!fill || o.intensity > fill.intensity) fill = o;
+ }
+ });
+ if (best) {
+ // sunRig aims its light at the origin, so the position IS the
+ // vector to the light — and at night that is the MOON, which is
+ // what a bank actually scatters. An authored `sunDir` from a set
+ // sun would point under the ground.
+ out.dir = best.position.clone();
+ if (out.dir.lengthSq() < 1e-8) out.dir = null;
+ else out.dir.normalize();
+ out.sun = best.color.clone();
+ out.key = best.intensity;
+ }
+ if (fill) {
+ out.amb = fill.color.clone();
+ out.ambLum = lumOf(fill.color) * fill.intensity;
+ }
+ return out;
+}
+
+const FOG_VERT = [
+ ' vPos = transformed;',
+ // The slope of the view ray decides how much air a sheet stands for,
+ // and the profile is in WORLD metres of height, so the ray must be
+ // measured in world space too.
+ ' vWorld = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' vH = aH;',
+ ' vDH = aDH;',
+].join('\n');
+
+const FOG_HEAD = [
+ 'uniform vec3 uColor;',
+ 'uniform vec3 uSunTint;',
+ 'uniform vec3 uAmbTint;',
+ 'uniform vec3 uBeam;',
+ 'uniform vec3 uSunDir;',
+ 'uniform float uSunAmt;',
+ 'uniform float uDensity;',
+ 'uniform float uTop;',
+ 'uniform float uScale;',
+ 'uniform float uFreq;',
+ 'uniform float uRadius;',
+ 'uniform vec2 uOffset;',
+].join('\n');
+
+const FOG_FRAG = [
+ // Density falls with HEIGHT in metres and is forced to exactly zero
+ // at uTop; a bank that merely gets thin has a visible lid.
+ ' float prof = exp(-vH / uScale)',
+ ' * (1.0 - smoothstep(uTop * 0.45, uTop, vH));',
+ // Feather the rim INSIDE the geometry, or a transparent sheet draws
+ // its own rectangle across the frame.
+ ' float edge = 1.0 - smoothstep(0.60, 1.0,',
+ ' length(vPos.xz) / uRadius);',
+ // METRES OF AIR this sheet stands for: its own slab crossed at the
+ // view ray's slope, never more than the ray has flown. Ignore the
+ // slope and the ground at your feet is charged the whole column.
+ ' vec3 ray = vWorld - cameraPosition;',
+ ' float dist = length(ray);',
+ ' float climb = max(abs(ray.y) / dist, 1e-3);',
+ ' float air = min(vDH / climb, dist) * prof * edge;',
+ // Extinction per metre at the foot of the bank, from the dial.
+ ` float sigma = -log(1.0 - min(uDensity, 0.995)) / ${REF_M}.0;`,
+ ' if (sigma * air < 0.0015) discard;',
+ // Offset the noise domain by height: without it every sheet wears the
+ // same blotches and the stack reads as one printed slab.
+ ' vec2 p = vPos.xz * uFreq + uOffset + vec2(vH * 0.31, vH * -0.22);',
+ ' p += vec2(uTime * 0.015, uTime * -0.009);',
+ ' float n = smoothstep(0.20, 0.80, astraFbm2(p, 4));',
+ // Eaten by noise at the top; at the ground it keeps its MEAN (n runs
+ // 0..1 about 0.5) but not its uniformity. A flat 1.0 down there was
+ // the sheet stack's tell: every sheet drew one constant alpha, so
+ // each sheet's plane printed a hard contour line across anything
+ // standing in the bank. Patchy air makes the same line a ragged edge,
+ // and real fog at the soil is patchy anyway.
+ ' float low = 0.55 + 0.90 * n;',
+ ' float breakup = mix(low, n, smoothstep(0.10, 0.85, vH / uTop));',
+ // Beer-Lambert on that air, so the stack telescopes into ONE integral
+ // however many sheets a ray meets: opacity 1 - exp(-sum of the taus).
+ ' float a = 1.0 - exp(-sigma * air * breakup * (0.85 + 0.30 * n));',
+ // A screen-space dither of half the remaining quantisation step: the
+ // eye integrates the noise and stops finding the contour. Gated by
+ // `a` so the thin outer wisps are not dusted with speckle.
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.02',
+ ' * smoothstep(0.0, 0.12, a);',
+ ' if (a < 0.002) discard;',
+ // COLOUR. Fog is not a paint value, it is the light in the air, and
+ // it has to move: warm and bright looking through it toward the key
+ // light, cool and flat looking away, brighter at the top of the bank
+ // where the sky reaches than in the shadowed soil at the bottom.
+ // uColor is the base (the scene's own fog tint); uSunTint/uAmbTint
+ // are its two chromaticities at unit luminance, so these mixes move
+ // HUE and the two literal gains own every change of brightness.
+ ` float baseL = dot(uColor, ${LUMA});`,
+ ' vec3 shadeC = mix(uColor, uAmbTint * baseL, 0.35) * 0.76;',
+ ' vec3 litC = mix(uColor, uSunTint * baseL, 0.55) * 1.18;',
+ ' vec3 V = ray / dist;',
+ ' float ct = clamp(dot(V, uSunDir), -1.0, 1.0);',
+ ` float hgD = 1.0 + ${HG_G2.toFixed(6)} - ${(2 * HG_G).toFixed(6)} * ct;`,
+ ` float phase = clamp(((1.0 - ${HG_G2.toFixed(6)})`,
+ ` / (hgD * sqrt(hgD))) / ${HG_NORM}, 0.75, 2.6);`,
+ ' float sunMix = clamp(0.45 + uSunAmt * (phase - 1.0) * 0.35, 0.0, 1.0);',
+ // The BEAM is added, not mixed: the sky already in `uColor` outruns
+ // the moon twenty to one by day and only two to one at night, so a
+ // multiplier tuned for one is invisible in the other. This term is
+ // the key light's own radiance in the air, so a moonlit bank glows
+ // (measured: 32/255, under the soil it covered, before this) while
+ // the same code adds a modest warm haze at noon.
+ ' vec3 tint = mix(shadeC, litC, sunMix) + uBeam * phase;',
+ // The bank is lit from above and shadows itself downward, so the top
+ // is the bright surface. Without it twenty sheets of one colour are
+ // still one flat value.
+ ' tint *= mix(0.88, 1.25, smoothstep(0.0, 0.75, vH / uTop));',
+ // Patch-to-patch hue spread on the SAME field the density uses, so
+ // the warm and cool blooms sit where the thick and thin air is.
+ ' tint = astraHueBreak(tint, p, 0.55, 0.30);',
+ ' gl_FragColor = vec4(tint, clamp(a, 0.0, 1.0));',
+].join('\n');
+
+/**
+ * Stacked sheets: y follows the terrain, `aH` is height above it,
+ * `aDH` the metres of column that sheet is the sample of.
+ */
+function fogSheets(extent, top, heightAt) {
+ // Flat ground needs no tessellation at all — every variation lives in
+ // the fragment stage, so the whole bank is then LAYERS quads.
+ const seg = heightAt
+ ? Math.max(8, Math.min(64, Math.round(extent / 1.5))) : 1;
+ const row = seg + 1;
+ const half = extent * 0.5;
+ const pos = [];
+ const hs = [];
+ const dhs = [];
+ const idx = [];
+ const at = (l) => BASE_H
+ + (top - BASE_H) * Math.pow(l / (LAYERS - 1), PACK);
+ for (let l = 0; l < LAYERS; l++) {
+ const h = at(l);
+ // Half way down to the sheet below, half way up to the one above,
+ // so the stack partitions the column [0, top] exactly once and no
+ // metre of air is either counted twice or missed.
+ const dh = (l < LAYERS - 1 ? (h + at(l + 1)) * 0.5 : top)
+ - (l > 0 ? (at(l - 1) + h) * 0.5 : 0);
+ const base = l * row * row;
+ for (let j = 0; j < row; j++) {
+ const z = -half + (extent * j) / seg;
+ for (let i = 0; i < row; i++) {
+ const x = -half + (extent * i) / seg;
+ pos.push(x, (heightAt ? heightAt(x, z) : 0) + h, z);
+ hs.push(h);
+ dhs.push(dh);
+ }
+ }
+ for (let j = 0; j < seg; j++) {
+ for (let i = 0; i < seg; i++) {
+ const a = base + j * row + i;
+ idx.push(a, a + row, a + 1, a + 1, a + row, a + row + 1);
+ }
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geo.setAttribute('aH', new THREE.Float32BufferAttribute(hs, 1));
+ geo.setAttribute('aDH', new THREE.Float32BufferAttribute(dhs, 1));
+ geo.setIndex(idx);
+ return geo;
+}
+
+/**
+ * A ground-hugging fog bank as real geometry — things WADE in it.
+ *
+ * Density is a function of height above the ground, not of camera
+ * distance: milk in the first metre, gone by `height`, so boots vanish
+ * while heads stay clear. What a ray then COLLECTS is the air it flies
+ * through, so the band is a thing you see across — faint at your feet,
+ * where you look steeply down through a metre of it, and solid down the
+ * valley, where the same metre lies along the sightline for a hundred.
+ * Every sheet is one colour, which makes the over-blend order
+ * independent, so the whole stack is one draw call with no sorting to
+ * get wrong.
+ *
+ * PASS THE SCENE. The bank's colour is in-scattered light, never a
+ * paint value: `scene` gives it the scene's own fog tint, its key
+ * light's warmth on the sun side and its fill's cool in the shade, so
+ * one call reads right at noon and at midnight. Without it the bank
+ * falls back to a daylight horizon and a night scene gets a slab of
+ * milk.
+ *
+ * @param {object} [opts]
+ * `scene` THREE.Scene to read (fog colour + the strongest
+ * DirectionalLight + the fill) — strongly recommended;
+ * `extent` metres square (default 60); `height` metres at which the
+ * bank is gone (default 4; `top` is the old name and still works);
+ * `density` how thick the air is — the opacity of a 10 m horizontal
+ * look through the bank's foot (default 0.75), so it means the same
+ * thing at any extent, height or sheet count; `color` THREE.Color
+ * overriding the base tint (default: the radiance of the scene's own
+ * air, read off `scene.environment`, then `scene.fog.color`, then the
+ * day mood horizon); `sunDir` Vector3 or [x, y, z] TOWARD the key
+ * light, overriding the one read from the scene; `sunAmount` how
+ * strongly the air scatters that light, 0..1 against a full sun (the
+ * day rig's 5.4 is 1.0, the moon's 2.2 is 0.44; default from the
+ * light itself); `heightAt` (x, z) => y to follow terrain —
+ * omit it and the bank is flat and costs 20 quads; `seed` noise
+ * offset.
+ * @returns {THREE.Group} Named `HeightFog`, with `userData.tick(t)`
+ * driving the drift. Move the group to move the bank: the soft rim
+ * is inscribed in `extent`, so it never shows a boundary of its own.
+ * Retune later through `uniforms.uColor` / `uDensity` / `uSunAmt`.
+ */
+export function makeHeightFog(opts = {}) {
+ const extent = opts.extent ?? 60;
+ // Every other lib in here names this `height` (watermist, rain,
+ // grass...), and a silently ignored `height` gave the default 4 m
+ // bank to callers who asked for a 1.6 m one.
+ const top = Math.max(0.2, opts.height ?? opts.top ?? 4);
+ const density = opts.density ?? 0.75;
+ const heightAt = opts.heightAt || null;
+ const env = readScene(opts.scene);
+ // The bank is a VOLUME of lit air standing in front of the camera,
+ // so its colour is the radiance of the air, not the far-field tint
+ // `scene.fog` carries. Moonlit mist is BRIGHTER than the ground it
+ // lies on — the ground returns a fraction of the moon, the air
+ // scatters it whole — and at the raw night fog colour this rendered
+ // UNDER the soil it covered (28/255 over 45/255) and read as a stain.
+ const color = opts.color !== undefined ? new THREE.Color(opts.color)
+ : (env.air ? env.air.clone()
+ : inScatterFloor(env.fog || new THREE.Color(DAY_HORIZON),
+ env.amb, 0.55 * env.ambLum));
+ const sunDir = opts.sunDir
+ ? (Array.isArray(opts.sunDir)
+ ? new THREE.Vector3().fromArray(opts.sunDir)
+ : new THREE.Vector3().copy(opts.sunDir)).normalize()
+ : (env.dir || new THREE.Vector3(0, 1, 0));
+ // `sunAmount` is quoted against a full sun (three's physical units:
+ // the day rig runs 5.4, the moon 2.2), so one dial drives both the
+ // hue mix and the beam.
+ const keyI = opts.sunAmount === undefined ? env.key : opts.sunAmount * 5;
+ const sunAmt = Math.min(1, Math.max(0, keyI / 5));
+ const beam = (env.sun ? env.sun.clone() : new THREE.Color(0xffffff))
+ .multiplyScalar(Math.max(0, keyI) * BEAM_K);
+ const rand = mulberry32(opts.seed ?? 1);
+ const mat = makeShaderMaterial({
+ name: 'HeightFog',
+ uniforms: {
+ uColor: { value: color },
+ uSunTint: { value: chroma(env.sun || color) },
+ uAmbTint: { value: chroma(env.amb || color) },
+ uBeam: { value: beam },
+ uSunDir: { value: sunDir },
+ uSunAmt: { value: sunAmt },
+ uDensity: { value: density },
+ uTop: { value: top },
+ // ~1/4 of the bank is the e-fold, so the first metre carries most
+ // of the extinction at the default height of 4 m.
+ uScale: { value: top * 0.28 },
+ uFreq: { value: 3 / extent },
+ uRadius: { value: extent * 0.5 },
+ uOffset: {
+ value: new THREE.Vector2(rand() * 128, rand() * 128),
+ },
+ },
+ varyings: 'varying vec3 vPos;\nvarying vec3 vWorld;\n'
+ + 'varying float vH;\nvarying float vDH;',
+ vertexHead: 'attribute float aH;\nattribute float aDH;',
+ vertexMain: FOG_VERT,
+ fragmentHead: FOG_HEAD,
+ fragmentMain: FOG_FRAG,
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+ const mesh = new THREE.Mesh(fogSheets(extent, top, heightAt), mat);
+ mesh.name = 'HeightFogBank';
+ // Drawn with an OVERRIDE material — GTAOPass's depth+normal buffer —
+ // a dozen sheets read as a dozen solid floors occluding each other:
+ // 50/255 of darkening on ground the fog was not even touching.
+ mesh.onBeforeRender = (r, s, cam, geo, m) => {
+ geo.setDrawRange(0, m === mat ? Infinity : 0);
+ };
+ mesh.onAfterRender = (r, s, cam, geo) => {
+ geo.setDrawRange(0, Infinity);
+ };
+ const group = new THREE.Group();
+ group.name = 'HeightFog';
+ group.add(mesh);
+ group.userData.tick = (t) => tickShaders(group, t);
+ return group;
+}
+
+const AERIAL_VERT = [
+ // three's own fog measures view-space Z (`vFogDepth = -mvPosition.z`),
+ // so this uses the same ruler and the two cues stay locked. Instances
+ // are transformed here because <begin_vertex> runs before that.
+ ' vec4 aerialP = vec4(transformed, 1.0);',
+ '#ifdef USE_INSTANCING',
+ ' aerialP = instanceMatrix * aerialP;',
+ '#endif',
+ ' vAerialDepth = -(modelViewMatrix * aerialP).z;',
+].join('\n');
+
+const AERIAL_FRAG = [
+ // Chromaticity from the sky, brightness mostly the fragment's own:
+ // the dimming is FogExp2's job and fighting it double-counts.
+ ` float aerialL = dot(diffuseColor.rgb, ${LUMA});`,
+ ' float aerialT = uAerialK * smoothstep(uAerialStart, uAerialEnd,',
+ ' vAerialDepth);',
+ // AIRLIGHT, the part pure luminance preservation cannot reach. Air
+ // does not only tint what is behind it, it glows: the far field
+ // loses contrast from BOTH ends, darks lifting toward the sky and
+ // lights settling toward it. Preserving luminance exactly left a
+ // shadowed ridge 70 m out as black as one at arm's length — the
+ // silhouette that reads as a hole in the frame rather than distance.
+ // `uAerialLum` is the sky's own luminance, so at night (a dark sky)
+ // this correctly nearly vanishes. ONE-SIDED on purpose: airlight is
+ // light ADDED on the way to the eye. Letting it pull the other way
+ // dimmed every far surface brighter than the sky, which is the
+ // extinction half — three's fog owns that, and doing it twice is how
+ // a hazy distance turns into a dark one.
+ ' float aerialB = aerialL',
+ ' + uAerialLift * max(0.0, uAerialLum - aerialL);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb,',
+ ' clamp(uAerialSky * aerialB, 0.0, 1.0), aerialT);',
+].join('\n');
+
+const AERIAL_HEAD = [
+ 'varying float vAerialDepth;',
+ 'uniform vec3 uAerialSky;',
+ 'uniform float uAerialStart;',
+ 'uniform float uAerialEnd;',
+ 'uniform float uAerialK;',
+ 'uniform float uAerialLum;',
+ 'uniform float uAerialLift;',
+].join('\n');
+
+/**
+ * Desaturate a built-in material toward the sky with distance.
+ *
+ * FogExp2 dims the far field but never moves its hue, and a saturated
+ * far hill under correct fog is what still reads as a painted tabletop.
+ * This tints the ALBEDO (at `<color_fragment>`, so lighting, shadows
+ * and the fog chunk all still run on top) toward the sky's
+ * chromaticity at the fragment's own brightness — it composes with the
+ * scene's fog instead of competing with it.
+ *
+ * @param {THREE.Material} material Any built-in material (the patch
+ * needs three's `<color_fragment>`); patched in place.
+ * @param {object} [opts] `scene` THREE.Scene to read — the shift then
+ * targets the scene's OWN fog colour and finishes at one e-fold of
+ * its density, so the two cues cannot disagree about where far is;
+ * `skyColor` THREE.Color override (default the day mood horizon,
+ * matching `worldShell`); `start`/`end` metres over which the shift
+ * ramps in (default 40/600 — `end` is one e-fold of the day fog
+ * density, so the shift completes as fog takes over); `strength`
+ * maximum shift (default 0.8; 1.0 is pure sky); `lift` how much of
+ * the sky's own brightness the far field takes on — airlight
+ * (default 0.35; 0 is the pure hue shift, 1 flattens the far field
+ * to the sky).
+ * @returns {THREE.Material} The same material. Apply it LAST: every
+ * `patchStandard` owns `onBeforeCompile`, so a second patch on the
+ * same material replaces this one. Tune later through
+ * `material.userData.uniforms.uAerialK.value`.
+ */
+export function patchAerialPerspective(material, opts = {}) {
+ const env = readScene(opts.scene);
+ // The TARGET stays the scene's own fog colour — the whole point is
+ // that the hue shift and three's fog agree about what far looks like
+ // — but it is floored by the radiance of the air, so a night mood's
+ // deliberately black fog cannot take the far field to black with it.
+ const sky = opts.skyColor !== undefined ? new THREE.Color(opts.skyColor)
+ : inScatterFloor(env.fog || env.air || new THREE.Color(DAY_HORIZON),
+ env.air || env.amb,
+ env.air ? 0.5 * lumOf(env.air) : 0.2 * env.ambLum);
+ const start = opts.start ?? 40;
+ // One e-fold of the scene's own fog, exactly as the 600 m default is
+ // one e-fold of the day mood's 0.0018.
+ const efold = env.fogDensity > 0 ? 1 / env.fogDensity : 600;
+ const end = Math.max(start + 1, opts.end ?? efold);
+ // Pre-divided by its own luminance, so `uAerialSky * L` lands back on
+ // the fragment's brightness and the shader stays two instructions.
+ const lum = lumOf(sky);
+ return patchStandard(material, {
+ // One name on purpose: the GLSL is identical for every material, so
+ // they SHOULD share a program. The uniforms stay per material.
+ name: 'aerialPerspective',
+ uniforms: {
+ uAerialSky: { value: sky.clone().multiplyScalar(1 / lum) },
+ uAerialStart: { value: start },
+ uAerialEnd: { value: end },
+ uAerialK: { value: opts.strength ?? 0.8 },
+ uAerialLum: { value: lum },
+ uAerialLift: { value: opts.lift ?? 0.35 },
+ },
+ vertexHead: 'varying float vAerialDepth;',
+ vertexBody: AERIAL_VERT,
+ fragmentHead: AERIAL_HEAD,
+ fragmentBody: AERIAL_FRAG,
+ util: false,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js
new file mode 100644
index 00000000..fa7a813d
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/building.js
@@ -0,0 +1,965 @@
+/**
+ * A facade with real openings, instead of a textured box. The fix is
+ * depth, not a texture: spandrel bands and mullions with GAPS onto a
+ * dark recessed shell, a glazed ground floor, plinth and projecting
+ * cornice — real geometry that holds in silhouette and casts shadow.
+ * Cheap by design: one merged mesh per material, ~800-1,500 triangles
+ * for an eight-storey block.
+ */
+
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import * as MAT from './materials.js';
+
+/** Metres of wall per texture tile. One number for the whole module, so
+ * a mullion, a spandrel and a cornice share one masonry scale. */
+const UV_TILE = 2.6;
+
+/**
+ * A box as geometry, positioned by its centre, with its UVs scaled to a
+ * CONSTANT texel density.
+ *
+ * three gives every box face a full 0..1 UV whatever that face measures,
+ * so one merged facade stretched a single brick tile across a 14 m wall
+ * and squeezed the same tile onto a 0.34 m mullion — which is why the
+ * piers read as vertical woodgrain stripes next to a flat wall. Scaling
+ * u,v by the face's own metres fixes it for every part at once (the
+ * library's noise maps are all RepeatWrapping, so uv > 1 tiles).
+ */
+function bx(w, h, d, x, y, z) {
+ const g = new THREE.BoxGeometry(w, h, d);
+ const uv = g.attributes.uv;
+ // BoxGeometry lays its 24 vertices out px, nx, py, ny, pz, nz.
+ const dims = [[d, h], [d, h], [w, d], [w, d], [w, h], [w, h]];
+ for (let f = 0; f < 6; f++) {
+ const su = dims[f][0] / UV_TILE, sv = dims[f][1] / UV_TILE;
+ for (let i = f * 4; i < f * 4 + 4; i++) {
+ uv.setXY(i, uv.getX(i) * su, uv.getY(i) * sv);
+ }
+ }
+ uv.needsUpdate = true;
+ g.translate(x, y, z);
+ return g;
+}
+
+/**
+ * The warm interior-glow card behind a lit window — one definition so
+ * `block()`, `cottage()` and `casement()` glow alike. At dusk, lit
+ * windows are the strongest habitation cue.
+ *
+ * Emissive stays in the 1.1-2.6 band: bloom-friendly, and a lit pane
+ * that peaks at 20 is a white hole with no colour left in it.
+ */
+function litMat(o = {}) {
+ return MAT.plaster({
+ color: o.color === undefined ? 0xffdca8 : o.color,
+ roughness: 1,
+ hueBreak: 0.02,
+ extra: { emissive: new THREE.Color(
+ o.emissive === undefined ? 0xffca7a : o.emissive),
+ emissiveIntensity: o.intensity === undefined
+ ? 1.5 : o.intensity } });
+}
+
+/**
+ * A LIT FACADE IS NOT ONE COLOUR. Every window on one emissive material
+ * turns a night block into a single glowing slab; real windows split by
+ * room — tungsten living rooms, warm-white bedrooms, the odd cool
+ * kitchen or stairwell — and that split IS the night read. Three
+ * buckets keep it to three merged meshes per building.
+ */
+const LIT_CLASSES = [
+ { color: 0xffd9ad, emissive: 0xffb765, intensity: 1.9 }, // tungsten
+ { color: 0xffe6c4, emissive: 0xffd39a, intensity: 1.25 }, // warm white
+ { color: 0xdfe9ff, emissive: 0xbcd4ff, intensity: 1.55 }, // cool room
+];
+
+/**
+ * Wall/trim albedos are held under 0.8 sRGB. Plaster and travertine
+ * ship near 0.92, which under exposure 1.0 with no post chain lands a
+ * whole facade at the top of the range — a white card that no shadow
+ * can shape and no cornice can read against.
+ */
+const STYLES = {
+ // Stock brick, not pillarbox: 0x9c4a35 under ACES at exposure 1.0
+ // came out a saturated candy red across a whole facade. Lower
+ // contrast too — a merged box gives every face a full 0..1 UV, so a
+ // slim mullion stretches the noise into stripes.
+ brick: { wall: () => MAT.brick({ color: 0x8d5341, contrast: 0.3 }),
+ floorH: 3.2, bayW: 3.4,
+ trim: () => MAT.travertine({ color: 0xc3b79e }),
+ glassColor: 0x37454f },
+ masonry: { wall: () => MAT.plaster({ color: 0xc9bcaa }), floorH: 3.4,
+ bayW: 3.8, trim: () => MAT.travertine({ color: 0xcbbfa8 }),
+ glassColor: 0x3c4b58 },
+ stone: { wall: () => MAT.granite(), floorH: 3.6, bayW: 4.0,
+ trim: () => MAT.travertine({ color: 0xc7bca6 }),
+ glassColor: 0x374651 },
+ glass: { wall: () => MAT.brushedSteel(), floorH: 3.9, bayW: 5.0,
+ trim: () => MAT.brushedSteel(), glassColor: 0x46606f },
+};
+
+/**
+ * Glazing. A dielectric with a fresnel ramp, tinted per style, and a
+ * lifted `envMapIntensity` so the panes mirror the sky instead of
+ * reading as black rectangles punched in the wall.
+ */
+function glazing(color, k = 0) {
+ // Two batches per facade. Real glazing is never one value — blinds,
+ // curtains, a room behind one pane and none behind the next — and a
+ // grid of identical panes is the "flat glass tower" verdict.
+ const c = new THREE.Color(color);
+ if (k) c.offsetHSL(0.02, -0.05, 0.05);
+ return MAT.glass({ color: c.getHex(), opacity: k ? 0.55 : 0.66,
+ extra: { envMapIntensity: 2.2, roughness: k ? 0.14 : 0.08 } });
+}
+
+/**
+ * The shell seen through every opening. NOT black: a room's back wall
+ * still catches sky through the window, and 0x14161a rendered as a
+ * hole. This is dark enough to read as depth and light enough that the
+ * environment shapes it.
+ */
+function revealMat() {
+ return MAT.plaster({ color: 0x24262c, roughness: 1, hueBreak: 0.05 });
+}
+
+/**
+ * Build a block with modelled openings, a plinth and a cornice.
+ *
+ * @param {object} opts
+ * `w` width, `d` depth, `h` height in metres; `style` one of
+ * `brick | masonry | stone | glass` (default `masonry`); `rand` a
+ * seeded PRNG (REQUIRED for variation -- no `Math.random`);
+ * `color` overrides the wall colour; `ground` `'storefront'` (default,
+ * a taller glazed base) or `'plain'`; `lit` 0..1 fraction of windows
+ * that glow, for night scenes (default 0); `name`.
+ * @returns {THREE.Group} Resting on y=0, centred on x/z, facing -Z,
+ * 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.
+ */
+export function block(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const w = opts.w || 14;
+ const d = opts.d || 12;
+ const h = opts.h || 22;
+ const st = STYLES[opts.style] || STYLES.masonry;
+
+ // A DISTRICT OF ONE COLOUR reads as one stamped asset however varied
+ // the massing is. `tint` clones the cached material into nine hue +
+ // lightness buckets, so a hundred blocks cost nine materials.
+ let wallMat = st.wall();
+ if (opts.color !== undefined) {
+ wallMat = wallMat.clone();
+ wallMat.userData = {};
+ wallMat.color = new THREE.Color(opts.color);
+ } else {
+ // Half of `tint`'s range: its full swing is +-25% lightness, which
+ // walks brick from stock to candy. A street wants a batch spread,
+ // not four different bricks.
+ wallMat = MAT.tint(wallMat, 0.5 + (rand() - 0.5) * 0.6);
+ }
+ const trimMat = st.trim();
+ const glassMats = [glazing(st.glassColor, 0), glazing(st.glassColor, 1)];
+ const darkMat = revealMat();
+
+ // A storefront base is taller than the floors above it, which is most
+ // of what makes a street read as a street rather than a stack.
+ const baseH = opts.ground === 'plain' ? 0
+ : Math.min(h * 0.28, st.floorH * 1.45);
+ const upperH = h - baseH;
+ const floors = Math.max(1, Math.round(upperH / st.floorH));
+ const fh = upperH / floors;
+ const bays = Math.max(1, Math.round(w / st.bayW));
+ const baysD = Math.max(1, Math.round(d / st.bayW));
+
+ const wall = []; // spandrels + mullions + plinth
+ const trim = []; // cornice, sills, string courses
+ const glassBins = [[], []]; // panes, set back inside the openings
+ const glass = glassBins[0]; // the storefront runs on one batch
+ const dark = []; // the recess shell seen through the openings
+ const litBins = LIT_CLASSES.map(() => []); // lit panes, by room class
+
+ // The shell that gives every opening a dark interior behind it. It is
+ // inset, so what you see through a window is depth, not the sky.
+ const inset = 0.42;
+ dark.push(bx(w - inset * 2, h, d - inset * 2, 0, h / 2, 0));
+
+ const plinth = Math.min(0.6, h * 0.03);
+ wall.push(bx(w + 0.22, plinth, d + 0.22, 0, plinth / 2, 0));
+
+ // Ground floor: wide glazing between slim piers.
+ if (baseH > 0) {
+ const pierW = Math.max(0.45, w * 0.035);
+ for (const [len, along, faceZ] of
+ [[w, 'x', d / 2], [w, 'x', -d / 2], [d, 'z', w / 2], [d, 'z', -w / 2]]) {
+ const n = Math.max(2, Math.round(len / (st.bayW * 1.6)));
+ for (let i = 0; i <= n; i++) {
+ const t = -len / 2 + (len / n) * i;
+ const g = along === 'x'
+ ? bx(pierW, baseH, 0.5, t, plinth + baseH / 2, faceZ)
+ : bx(0.5, baseH, pierW, faceZ, plinth + baseH / 2, t);
+ wall.push(g);
+ }
+ const gp = along === 'x'
+ ? bx(len - pierW, baseH * 0.86, 0.12, 0,
+ plinth + baseH / 2, faceZ - Math.sign(faceZ) * 0.3)
+ : bx(0.12, baseH * 0.86, len - pierW,
+ faceZ - Math.sign(faceZ) * 0.3, plinth + baseH / 2, 0);
+ glass.push(gp);
+ }
+ trim.push(bx(w + 0.5, 0.28, d + 0.5, 0, plinth + baseH + 0.14, 0));
+ }
+
+ // Upper floors, each face built as spandrel bands + mullions with the
+ // gaps between them left OPEN onto the dark shell.
+ const y0 = plinth + baseH;
+ const spandrel = fh * 0.34; // solid band under each window
+ const openH = fh - spandrel;
+ for (let f = 0; f < floors; f++) {
+ const yb = y0 + f * fh;
+ for (const [len, along, faceOff, n] of
+ [[w, 'x', d / 2, bays], [w, 'x', -d / 2, bays],
+ [d, 'z', w / 2, baysD], [d, 'z', -w / 2, baysD]]) {
+ const s = Math.sign(faceOff);
+ // Spandrel band across the whole face.
+ wall.push(along === 'x'
+ ? bx(len, spandrel, 0.5, 0, yb + spandrel / 2, faceOff)
+ : bx(0.5, spandrel, len, faceOff, yb + spandrel / 2, 0));
+ // Mullions between bays.
+ const mw = Math.max(0.34, len / n * 0.22);
+ for (let i = 0; i <= n; i++) {
+ const t = -len / 2 + (len / n) * i;
+ wall.push(along === 'x'
+ ? bx(mw, openH, 0.5, t, yb + spandrel + openH / 2, faceOff)
+ : bx(0.5, openH, mw, faceOff, yb + spandrel + openH / 2, t));
+ }
+ // A pane per bay, set back 0.22 m so the reveal reads as depth.
+ for (let i = 0; i < n; i++) {
+ const t = -len / 2 + (len / n) * (i + 0.5);
+ const pw = len / n - mw;
+ const lit = opts.lit && rand() < opts.lit;
+ const geo = along === 'x'
+ ? bx(pw, openH * 0.95, 0.1, t, yb + spandrel + openH / 2,
+ faceOff - s * 0.22)
+ : bx(0.1, openH * 0.95, pw, faceOff - s * 0.22,
+ yb + spandrel + openH / 2, t);
+ // A lit pane is its OWN card, never the shell: pushing it onto
+ // `dark` and then making the whole shell emissive lit every
+ // window in the building from one 22 m glowing box, so `lit:
+ // 0.4` still came out as a solid lantern.
+ if (lit) litBins[Math.floor(rand() * LIT_CLASSES.length)
+ % LIT_CLASSES.length].push(geo);
+ else glassBins[rand() < 0.72 ? 0 : 1].push(geo);
+ }
+ // A sill ledge under the openings — the "missing trim" complaint.
+ trim.push(along === 'x'
+ ? bx(len, 0.13, 0.72, 0, yb + spandrel + 0.06, faceOff)
+ : bx(0.72, 0.13, len, faceOff, yb + spandrel + 0.06, 0));
+ }
+ }
+
+ // Cornice + parapet: a flat top edge reads as an untouched box. The
+ // cornice must clear the projecting corner mullions, not just the
+ // wall plane, or the roofline still comes out flush.
+ trim.push(bx(w + 1.3, 0.42, d + 1.3, 0, h + 0.21, 0));
+ wall.push(bx(w + 0.5, 0.75, d + 0.5, 0, h + 0.42 + 0.375, 0));
+
+ const root = new THREE.Group();
+ root.name = opts.name || 'Block';
+ const parts = [[wall, wallMat, 'Walls'],
+ [trim, trimMat, 'Trim'],
+ [glassBins[0], glassMats[0], 'Glazing'],
+ [glassBins[1], glassMats[1], 'Glazing2'],
+ [dark, darkMat, 'Reveals']];
+ litBins.forEach((geos, i) => parts.push(
+ [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));
+ for (const [geos, mat, nm] of parts) {
+ if (!geos.length) continue;
+ const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);
+ if (!merged) continue;
+ const m = new THREE.Mesh(merged, mat);
+ m.name = nm;
+ // The shell and the lit cards live inside the openings; casting
+ // from them only stipples the reveal they are meant to fill.
+ m.castShadow = nm !== 'Reveals' && !nm.startsWith('LitRooms');
+ m.receiveShadow = true;
+ root.add(m);
+ }
+ root.userData.forward = '-Z';
+ root.userData.floors = floors + (baseH > 0 ? 1 : 0);
+ return root;
+}
+
+/**
+ * A casement window assembly, because a flush quad is not a window.
+ * The good form in one call: a frame standing proud of the wall, the
+ * pane recessed >= 0.1 m behind it, a mullion cross, a projecting
+ * sill, optional louvered shutters hinged open ~55 degrees, and a
+ * `lit` path that swaps the backing for the warm card `block()` uses.
+ *
+ * @param {object} opts
+ * `w`, `h` opening metres (default 1.1 x 1.4); `frameColor`;
+ * `shutters` boolean, paired louvered panels hinged open ~55 deg
+ * (default false); `shutterColor`; `lit` true or a 0..1 chance the
+ * window glows warm (default 0); `interior` true builds the ROOM
+ * side of the window instead (see below); `view` `'day' | 'night'`
+ * for the interior daylight card; `rand` seeded PRNG; `name`.
+ * @returns {THREE.Group} Centred on the opening, mount plane at z = 0,
+ * facing -Z (the outside), with `userData.forward`. Position it at
+ * the window's centre ON the wall face; the frame and sill project
+ * outward (-Z), the pane and backing sit inside the wall (+Z).
+ * With `interior: true` the group instead faces +Z (the room).
+ */
+export function casement(opts = {}) {
+ if (opts.interior) return interiorCasement(opts);
+ const rand = opts.rand || (() => 0.5);
+ const w = opts.w || 1.1;
+ const h = opts.h || 1.4;
+ const lit = opts.lit === true || (opts.lit ? rand() < opts.lit : false);
+ const t = Math.max(0.06, w * 0.06); // frame border width
+ const proud = 0.06; // frame front, beyond the wall
+ const deep = 0.16; // frame depth, into the wall
+ const zc = -proud + deep / 2;
+
+ // Joinery paint, held under 0.8 albedo: 0xf4efe6 is a 0.96 white that
+ // clips against a plaster wall instead of sitting on it.
+ const frameMat = MAT.paintedWood({ color: opts.frameColor === undefined
+ ? 0xcbc4b6 : opts.frameColor });
+ const glassMat = glazing(0x3c4b58);
+
+ // Frame: four borders around the opening, plus the mullion cross that
+ // splits the glazing into four lights — the depth cue a decal lacks.
+ const frame = [
+ bx(w + 2 * t, t, deep, 0, h / 2 + t / 2, zc),
+ bx(w + 2 * t, t, deep, 0, -h / 2 - t / 2, zc),
+ bx(t, h, deep, -w / 2 - t / 2, 0, zc),
+ bx(t, h, deep, w / 2 + t / 2, 0, zc),
+ bx(0.05, h, 0.05, 0, 0, 0.05),
+ bx(w, 0.05, 0.05, 0, 0, 0.05),
+ ];
+ // The pane sits DEEP in the reveal: >= 0.1 m behind the frame front,
+ // which is what makes the opening read as depth in raking light.
+ const pane = bx(w, h, 0.02, 0, 0, proud + 0.02);
+ // Behind the pane, an interior card: warm-lit when `lit`, dark
+ // otherwise, so what you see through the glass is never the sky.
+ const backing = bx(w, h, 0.02, 0, 0, proud + 0.07);
+ // The sill projects past even the proud frame and sheds the rain.
+ const sill = bx(w + 2 * t + 0.16, 0.07, 0.24, 0, -h / 2 - t - 0.035,
+ -0.04);
+
+ const root = new THREE.Group();
+ root.name = opts.name || 'Casement';
+ for (const [geos, mat, nm] of [
+ [frame, frameMat, 'Frame'],
+ [[sill], frameMat, 'Sill'],
+ [[pane], glassMat, 'Pane'],
+ // One window is one room: it draws a WARM class (tungsten or warm
+ // white), never the cool one — a lone blue window reads as a fault.
+ [[backing], lit ? litMat(LIT_CLASSES[rand() < 0.5 ? 0 : 1])
+ : revealMat(), 'Backing']]) {
+ const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);
+ const m = new THREE.Mesh(merged, mat);
+ m.name = nm;
+ m.castShadow = nm !== 'Backing';
+ m.receiveShadow = true;
+ root.add(m);
+ }
+
+ // Shutters: a stile-and-rail border with tilted louver slats, hinged
+ // at the jamb and swung ~55 degrees out from the wall plane — the
+ // form the best audited harbour scene hand-built at 58 degrees.
+ if (opts.shutters) {
+ const open = (55 / 180) * Math.PI;
+ const sw = w * 0.52, sh = h + t;
+ const st = 0.07, th = 0.03;
+ const smat = MAT.paintedWood({ color: opts.shutterColor === undefined
+ ? 0x44584c : opts.shutterColor });
+ for (const sgn of [-1, 1]) {
+ // Built extending from the hinge (x = 0) toward the window
+ // centre, i.e. along -sgn — the CLOSED orientation — then the
+ // open swing is baked in as a rotation about the hinge.
+ const cx = -sgn * sw / 2;
+ const gs = [
+ bx(sw, st, th, cx, sh / 2 - st / 2, 0),
+ bx(sw, st, th, cx, -sh / 2 + st / 2, 0),
+ bx(st, sh, th, -sgn * st / 2, 0, 0),
+ bx(st, sh, th, -sgn * (sw - st / 2), 0, 0),
+ ];
+ const slats = 5;
+ const span = sh - 2 * st;
+ for (let i = 0; i < slats; i++) {
+ const g = new THREE.BoxGeometry(sw - 2 * st, 0.09, 0.02);
+ g.rotateX(0.6);
+ g.translate(cx, -span / 2 + (span / slats) * (i + 0.5), 0);
+ gs.push(g);
+ }
+ const merged = mergeGeometries(gs, false);
+ // -sgn * open swings the free edge toward -Z: outward, off the
+ // wall, never through it.
+ merged.applyMatrix4(new THREE.Matrix4().makeRotationY(-sgn * open));
+ merged.translate(sgn * (w / 2 + t), 0, -proud - th);
+ const m = new THREE.Mesh(merged, smat);
+ m.name = sgn < 0 ? 'ShutterL' : 'ShutterR';
+ m.castShadow = true;
+ m.receiveShadow = true;
+ root.add(m);
+ }
+ }
+ root.userData.forward = '-Z';
+ return root;
+}
+
+/**
+ * The room side of a window (interior windows ship as black holes —
+ * the brightest surface a room has reading as its darkest). The film-
+ * set trick: frame + sill reveal on the room side, a pane, and a
+ * bright emissive daylight card OUTSIDE the pane, oversized so an
+ * oblique camera never sees its edge; `view: 'night'` swaps the card.
+ * Reached via `casement({ interior: true })`; not exported.
+ *
+ * @param {object} opts
+ * `w`, `h` opening metres (default 1.1 x 1.4); `frameColor`;
+ * `view` `'day'` (default) or `'night'`; `name`.
+ * @returns {THREE.Group} Centred on the opening, wall plane at z = 0,
+ * facing +Z (the room), with `userData.forward`. The frame stands
+ * proud into the room and the sill stool projects past it; the pane
+ * sits inside the wall (-Z) and the daylight card outside the pane.
+ */
+function interiorCasement(opts) {
+ const w = opts.w || 1.1;
+ const h = opts.h || 1.4;
+ const t = Math.max(0.06, w * 0.06); // frame border width
+ const proud = 0.06; // frame front, into the room
+ const deep = 0.16; // frame depth, into the wall
+ const zc = proud - deep / 2;
+
+ const frameMat = MAT.paintedWood({ color: opts.frameColor === undefined
+ ? 0xf4efe6 : opts.frameColor });
+ // Light tint, low opacity: the card behind must shine THROUGH.
+ const glassMat = MAT.glass({ color: 0xcfe0ee, opacity: 0.3 });
+
+ // Frame borders plus the mullion cross, all on the room side of the
+ // pane -- the reveal depth that separates a window from a decal.
+ const frame = [
+ bx(w + 2 * t, t, deep, 0, h / 2 + t / 2, zc),
+ bx(w + 2 * t, t, deep, 0, -h / 2 - t / 2, zc),
+ bx(t, h, deep, -w / 2 - t / 2, 0, zc),
+ bx(t, h, deep, w / 2 + t / 2, 0, zc),
+ bx(0.05, h, 0.05, 0, 0, -0.05),
+ bx(w, 0.05, 0.05, 0, 0, -0.05),
+ ];
+ const pane = bx(w, h, 0.02, 0, 0, -(proud + 0.02));
+ // The daylight card: OUTSIDE the pane (lower Z) and oversized, so an
+ // oblique interior camera still sees sky, never the card's edge.
+ const card = bx(w + 0.5, h + 0.5, 0.02, 0, 0, -(proud + 0.09));
+ const cardMat = opts.view === 'night'
+ ? litMat({ color: 0x0d1830, emissive: 0x0d1830, intensity: 0.4 })
+ : litMat({ color: 0xdfeaff, emissive: 0xdfeaff, intensity: 2.2 });
+ // The stool projects past the proud frame INTO the room.
+ const sill = bx(w + 2 * t + 0.12, 0.05, 0.24, 0, -h / 2 - 0.025, 0.04);
+
+ const root = new THREE.Group();
+ root.name = opts.name || 'Casement';
+ for (const [geo, mat, nm] of [
+ [mergeGeometries(frame, false), frameMat, 'Frame'],
+ [sill, frameMat, 'Sill'],
+ [pane, glassMat, 'Pane'],
+ [card, cardMat, 'Daylight']]) {
+ const m = new THREE.Mesh(geo, mat);
+ m.name = nm;
+ m.castShadow = nm === 'Frame' || nm === 'Sill';
+ m.receiveShadow = nm !== 'Daylight';
+ root.add(m);
+ }
+ root.userData.forward = '+Z';
+ return root;
+}
+
+/**
+ * A cottage window, built ON a solid wall: a frame ring standing proud
+ * of the wall face, the pane just outside that face behind the ring, a
+ * mullion cross and a projecting sill.
+ *
+ * The pane CANNOT sit inside the wall the way `casement()`'s does —
+ * a cottage wall is one solid box with no opening cut in it, so a pane
+ * behind the face is simply buried (it was, and every cottage window
+ * shipped as an opaque slab). The depth comes from the proud frame and
+ * the sill shadow instead.
+ *
+ * @param {number} x centre, {number} y centre, {number} z the wall face
+ * @param {number} s +1 or -1, which way the face looks
+ * @param {number} ww opening width, {number} wh opening height
+ * @param {Array} trim geometry sink for frame, cross and sill
+ * @returns {THREE.BufferGeometry} the pane, for `glass` or a lit bin
+ */
+function cottageWindow(x, y, z, s, ww, wh, trim) {
+ const t = 0.1; // frame bar
+ const fz = z + s * 0.09; // ring centre: proud of the wall
+ trim.push(
+ bx(ww + 2 * t, t, 0.17, x, y + wh / 2 + t / 2, fz),
+ bx(ww + 2 * t, t, 0.17, x, y - wh / 2 - t / 2, fz),
+ bx(t, wh, 0.17, x - ww / 2 - t / 2, y, fz),
+ bx(t, wh, 0.17, x + ww / 2 + t / 2, y, fz),
+ bx(0.045, wh, 0.05, x, y, z + s * 0.06),
+ bx(ww, 0.045, 0.05, x, y, z + s * 0.06),
+ // The sill projects past even the ring, and its shadow is what
+ // sells the opening in raking light.
+ bx(ww + 2 * t + 0.16, 0.06, 0.22, x, y - wh / 2 - t - 0.03,
+ z + s * 0.1));
+ return bx(ww, wh, 0.05, x, y, z + s * 0.025);
+}
+
+/**
+ * The same window on a face that does NOT look along Z: built at the
+ * origin looking -Z, then moved by `M`.
+ * @returns {THREE.BufferGeometry} the pane
+ */
+function placedWindow(ww, wh, trim, M) {
+ const local = [];
+ const pane = cottageWindow(0, 0, 0, -1, ww, wh, local);
+ for (const g of local) trim.push(g.applyMatrix4(M));
+ return pane.applyMatrix4(M);
+}
+
+/**
+ * A pitched-roof village building: cottage, shop, inn, centre. The
+ * roof IS the silhouette — pitch, overhanging eaves, ridge, chimney;
+ * a village of flat-topped boxes reads as a housing estate.
+ *
+ * @param {object} opts
+ * `w`, `d` footprint metres, `h` wall height to the eaves (default 3),
+ * `roof` `gable | hip` (default gable), `pitch` roof height as a
+ * multiple of half-width (default 0.85), `roofColor`, `wallColor`,
+ * `trimColor` (joinery: frames, sills, door surround), `doorColor`,
+ * `chimney` boolean (default true), `dormers` count along the -X
+ * slope (the ridge runs front-to-back, so the gables — door, main
+ * windows — face +-Z and the slopes face +-X) (default 0),
+ * `lit` true or a 0..1 fraction of
+ * windows that glow warm for dusk/night (default 0), `rand` seeded
+ * PRNG, `name`.
+ * @returns {THREE.Group} Resting on y=0, centred on x/z, facing -Z.
+ * Meshes: `Walls`, `Roof`, `Trim` (joinery), `Glazing`, `Door` and,
+ * when `lit`, `LitRooms*`.
+ */
+export function cottage(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const w = opts.w || 7;
+ const d = opts.d || 6;
+ const h = opts.h || 3;
+ const pitch = (opts.pitch === undefined ? 0.85 : opts.pitch) * w / 2;
+ const eave = Math.max(0.28, w * 0.06); // overhang: reads as a roof
+
+ // Limewash, not a white card: 0xf2ece0 is 0.95 albedo, which under
+ // exposure 1.0 leaves a cottage the brightest thing in a daylit
+ // frame — brighter than the sky it stands against.
+ const wallMat = MAT.tint(MAT.plaster({ color: opts.wallColor === undefined
+ ? 0xcdc2ae : opts.wallColor }), opts.wallColor === undefined
+ ? 0.5 + (rand() - 0.5) * 0.6 : 0.5);
+ // Tile is fired clay, and a roof of it is never ONE red: the seeded
+ // variant walks the hue and lightness a kiln does.
+ const roofMat = MAT.terracotta({ color: opts.roofColor === undefined
+ ? 0xa8492f : opts.roofColor, repeat: 3, hueBreak: 0.18,
+ variant: opts.roofColor === undefined ? rand() : 0.5, spread: 0.1 });
+ const trimMat = MAT.paintedWood({ color: opts.trimColor === undefined
+ ? 0x6b4a33 : opts.trimColor });
+ const doorMat = MAT.paintedWood({ color: opts.doorColor === undefined
+ ? 0x3f5148 : opts.doorColor });
+ const glassMat = glazing(0x3c4b58);
+ // The lit path block() has and cottage() measurably lacked: at dusk
+ // every audited failing scene had zero window glow.
+ const litP = opts.lit === true ? 1 : (opts.lit || 0);
+
+ const walls = [], roof = [], trim = [], glass = [], door = [], stack = [];
+ const litBins = LIT_CLASSES.map(() => []);
+ walls.push(bx(w, h, d, 0, h / 2, 0));
+
+ // Windows: a frame ring proud of the wall with the pane behind it —
+ // NOT a solid slab, which is what a filled frame box reads as.
+ const bays = Math.max(1, Math.round(w / 2.6));
+ const ww = Math.min(1.1, w / bays * 0.5), wh = Math.min(1.3, h * 0.45);
+ for (let i = 0; i < bays; i++) {
+ const x = -w / 2 + (w / bays) * (i + 0.5);
+ for (const z of [d / 2, -d / 2]) {
+ const s = Math.sign(z);
+ const pane = cottageWindow(x, h * 0.55, z, s, ww, wh, trim);
+ // A cottage lights room by room, so its warm classes only.
+ if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);
+ else glass.push(pane);
+ }
+ }
+ // The EAVES walls (+-X) had no openings at all: whichever way a
+ // cottage was turned, one long blank elevation faced the camera.
+ const sideBays = Math.max(1, Math.round(d / 2.8));
+ for (let i = 0; i < sideBays; i++) {
+ const z = -d / 2 + (d / sideBays) * (i + 0.5);
+ for (const sx of [-1, 1]) {
+ // -Z rotated by -sx*90 deg looks along +-X: the sign matters, the
+ // wrong one buries the frame in the wall it should stand on.
+ const M = new THREE.Matrix4().makeRotationY(-sx * Math.PI / 2)
+ .setPosition(sx * w / 2, h * 0.55, z);
+ const pane = placedWindow(ww, wh, trim, M);
+ if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);
+ else glass.push(pane);
+ }
+ }
+ // Door on the front face: a surround standing proud, a leaf recessed
+ // inside it, a threshold step. A flush slab reads as painted-on.
+ const dz = -d / 2;
+ trim.push(
+ bx(1.32, 0.14, 0.18, 0, 2.31, dz - 0.09),
+ bx(0.14, 2.24, 0.18, -0.66, 1.19, dz - 0.09),
+ bx(0.14, 2.24, 0.18, 0.66, 1.19, dz - 0.09),
+ bx(1.5, 0.1, 0.5, 0, 0.05, dz - 0.16));
+ door.push(bx(1.16, 2.18, 0.09, 0, 1.11, dz - 0.045),
+ bx(0.1, 0.1, 0.06, 0.42, 1.05, dz - 0.12));
+
+ // ROOF. A gable is two slabs meeting at a ridge plus two end walls;
+ // a hip slopes on all four sides.
+ const rw = w + eave * 2, rd = d + eave * 2;
+ if (opts.roof === 'hip') {
+ const g = new THREE.CylinderGeometry(0.001, Math.SQRT1_2, pitch, 4);
+ g.rotateY(Math.PI / 4);
+ g.scale(rw / Math.SQRT2 * Math.SQRT2, 1, rd / Math.SQRT2 * Math.SQRT2);
+ g.translate(0, h + pitch / 2, 0);
+ roof.push(g);
+ } else {
+ const slope = Math.hypot(pitch, rw / 2);
+ for (const s of [-1, 1]) {
+ const g = new THREE.BoxGeometry(slope, 0.16, rd);
+ g.translate(0, 0, 0);
+ // NEGATIVE s: the slab's +X end must fall AWAY from the ridge,
+ // else the roof comes out as a V — invisible in a bbox, so a
+ // test measures where the roof's high point actually is.
+ const m = new THREE.Matrix4().makeRotationZ(
+ -s * Math.atan2(pitch, rw / 2));
+ g.applyMatrix4(m);
+ g.translate(s * rw / 4, h + pitch / 2, 0);
+ roof.push(g);
+ }
+ // A ridge cap along the join: the one line every tiled roof has,
+ // and its absence is why two slabs read as folded cardboard.
+ roof.push(bx(0.36, 0.15, rd + 0.06, 0, h + pitch - 0.06, 0));
+ // Gable end walls: a 3-sided cylinder is a prism along its OWN
+ // axis — rotateX lays it down to face the viewer (rotateY just
+ // spins it in place). A unit 3-gon spans 1.732 x 1.5 with base at
+ // y = -0.5, so scale to (w, pitch) and lift the base to the eaves.
+ //
+ // The SIGN of that rotateX decides which way up the triangle is,
+ // and it was positive: three's first radial vertex sits at +Z, so
+ // +90 deg sends the apex to y = -1 and leaves a FLAT edge at +0.5.
+ // Measured (rotateX(+PI/2) spans y -1..+0.5, rotateX(-PI/2) spans
+ // -0.5..+1): every gable shipped upside down, its two top corners
+ // sticking out through the roof slopes as white wings, and the
+ // triangle a bbox test sees is identical either way.
+ for (const s of [-1, 1]) {
+ const g = new THREE.CylinderGeometry(1, 1, 0.2, 3);
+ g.rotateX(-Math.PI / 2);
+ g.scale(w / 1.7320508, pitch / 1.5, 1);
+ g.translate(0, h + pitch / 3, s * (d / 2 - 0.08));
+ walls.push(g);
+ }
+ }
+ if (opts.chimney !== false) {
+ const cx = w * (0.18 + rand() * 0.16);
+ // A stack is masonry, not limewash: merged into `walls` it came out
+ // the same white as the cottage and vanished against it.
+ stack.push(bx(0.7, pitch + 1.1, 0.7, cx, h + (pitch + 1.1) / 2 - 0.2,
+ d * 0.16));
+ roof.push(bx(0.92, 0.2, 0.92, cx, h + pitch + 0.85, d * 0.16));
+ }
+ // DORMERS RIDE A SLOPE. The ridge runs front-to-back (along Z), so
+ // the slopes face +-X and the gables face +-Z; a dormer spread along
+ // X at one Z, as this was, is a box buried INSIDE the roof mass —
+ // it rendered as nothing at all. They march along the ridge instead,
+ // set on the -X slope, each protruding through the tiles it sits in.
+ const nd = opts.dormers || 0;
+ for (let i = 0; i < nd; i++) {
+ const z = -d / 2 + (d / (nd + 1)) * (i + 1);
+ const y = h + pitch * 0.42;
+ const xs = -(rw / 2) * (1 - 0.42); // the slope surface, at y
+ walls.push(bx(1.3, 1.1, 1.3, xs - 0.3, y, z));
+ // Its own little cap, or the dormer is a box growing out of tiles.
+ roof.push(bx(1.6, 0.13, 1.6, xs - 0.3, y + 0.58, z));
+ // Built facing -Z, then swung to face -X onto the slope it opens on.
+ const pane = placedWindow(0.72, 0.62, trim,
+ new THREE.Matrix4().makeRotationY(Math.PI / 2)
+ .setPosition(xs - 0.95, y, z));
+ if (litP && rand() < litP) litBins[rand() < 0.6 ? 0 : 1].push(pane);
+ else glass.push(pane);
+ }
+
+ const root = new THREE.Group();
+ root.name = opts.name || 'Cottage';
+ // Joinery is NOT roof tile. The frames, sills and door surround used
+ // to be merged into the Roof mesh and came out terracotta: red
+ // rectangles pasted on a white wall, which is what the flat-facade
+ // complaint actually looked like on a cottage.
+ const parts = [[walls, wallMat, 'Walls'],
+ [roof, roofMat, 'Roof'],
+ [stack, MAT.brick({ color: 0x8f5843, variant: rand() }),
+ 'Chimney'],
+ [trim, trimMat, 'Trim'],
+ [door, doorMat, 'Door'],
+ [glass, glassMat, 'Glazing']];
+ litBins.forEach((geos, i) => parts.push(
+ [geos, litMat(LIT_CLASSES[i]), i ? 'LitRooms' + (i + 1) : 'LitRooms']));
+ for (const [geos, mat, nm] of parts) {
+ if (!geos.length) continue;
+ const merged = geos.length === 1 ? geos[0] : mergeGeometries(geos, false);
+ if (!merged) continue;
+ const m = new THREE.Mesh(merged, mat);
+ m.name = nm;
+ m.castShadow = !nm.startsWith('LitRooms');
+ m.receiveShadow = true;
+ root.add(m);
+ }
+ root.userData.forward = '-Z';
+ root.userData.ridgeY = h + pitch;
+ return root;
+}
+
+/**
+ * A setback tower: the Manhattan silhouette, in tiers. Towers STEP IN
+ * as they rise; each tier is a `block()`, so every tier keeps real
+ * openings.
+ *
+ * @param {object} opts
+ * `w`, `d`, `h` overall metres; `tiers` (default 3); `style` passed
+ * to `block()`; `taper` fraction each tier narrows by (default 0.22);
+ * `crown` boolean spire/mast on top (default true); `rand`, `lit`.
+ * @returns {THREE.Group}
+ */
+export function tower(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const tiers = Math.max(1, opts.tiers || 3);
+ const taper = opts.taper === undefined ? 0.22 : opts.taper;
+ let w = opts.w || 22, d = opts.d || 20;
+ const h = opts.h || 90;
+ const root = new THREE.Group();
+ root.name = opts.name || 'Tower';
+ let y = 0;
+ for (let i = 0; i < tiers; i++) {
+ // Lower tiers are taller: a stack of equal slabs reads as a layer
+ // cake, and the real setback ratio is roughly halving.
+ const share = (tiers - i) / ((tiers * (tiers + 1)) / 2);
+ const th = h * share;
+ const t = block({ w, d, h: th, style: opts.style, rand,
+ lit: opts.lit, ground: i === 0 ? 'storefront' : 'plain' });
+ t.position.y = y;
+ t.name = 'Tier' + (i + 1);
+ root.add(t);
+ y += th;
+ w *= 1 - taper; d *= 1 - taper;
+ }
+ if (opts.crown !== false) {
+ const mast = new THREE.Mesh(
+ new THREE.CylinderGeometry(w * 0.03, w * 0.09, h * 0.09, 8),
+ MAT.brushedSteel());
+ mast.position.y = y + h * 0.045;
+ mast.castShadow = true;
+ mast.name = 'Crown';
+ root.add(mast);
+ }
+ root.userData.forward = '-Z';
+ void rand;
+ return root;
+}
+
+/**
+ * Scatter roof furniture on a flat-topped block: water tanks, plant.
+ * A bare flat roof is the most visible emptiness in an aerial city
+ * shot after the ground plane itself.
+ *
+ * @param {THREE.Object3D} host Block to add onto (roof assumed at its
+ * bbox top).
+ * @param {object} opts `rand` (REQUIRED), `tanks` count (default 1),
+ * `units` HVAC boxes (default 3), `mast` boolean.
+ * @returns {THREE.Object3D} host
+ */
+export function roofClutter(host, opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ host.updateMatrixWorld(true);
+ const b = new THREE.Box3().setFromObject(host);
+ const y = b.max.y;
+ const w = (b.max.x - b.min.x) * 0.7, d = (b.max.z - b.min.z) * 0.7;
+ const g = new THREE.Group();
+ g.name = 'RoofClutter';
+ const wood = MAT.weatheredWood();
+ const steel = MAT.brushedSteel({ color: 0x8d949b });
+ for (let i = 0; i < (opts.tanks === undefined ? 1 : opts.tanks); i++) {
+ const r = Math.min(1.7, w * 0.16);
+ const tank = new THREE.Mesh(
+ new THREE.CylinderGeometry(r, r * 1.04, r * 2.1, 12), wood);
+ const cone = new THREE.Mesh(new THREE.ConeGeometry(r * 1.12, r * 0.7, 12),
+ wood);
+ const legs = new THREE.Group();
+ for (let k = 0; k < 4; k++) {
+ const a = (k / 4) * Math.PI * 2 + 0.4;
+ const l = new THREE.Mesh(
+ new THREE.CylinderGeometry(r * 0.07, r * 0.07, r * 1.5, 6), steel);
+ l.position.set(Math.cos(a) * r * 0.72, r * 0.75, Math.sin(a) * r * 0.72);
+ legs.add(l);
+ }
+ const t = new THREE.Group();
+ tank.position.y = r * 1.5 + r * 1.05;
+ cone.position.y = r * 1.5 + r * 2.1 + r * 0.35;
+ t.add(legs, tank, cone);
+ t.position.set((rand() - 0.5) * w, y, (rand() - 0.5) * d);
+ g.add(t);
+ }
+ for (let i = 0; i < (opts.units === undefined ? 3 : opts.units); i++) {
+ // Its OWN height sets where it sits. A fixed 0.45 lift buried any
+ // unit over 0.9 m tall in the roof it stands on (measured: 0.09 m
+ // under, on a box the sampler can make 1.2 m).
+ const uh = 0.7 + rand() * 0.5;
+ const u = new THREE.Mesh(
+ new THREE.BoxGeometry(1.1 + rand(), uh, 0.9 + rand()),
+ // Plant is replaced piecemeal over decades: three identical grey
+ // boxes on one axis read as a copy, so each takes its own paint
+ // bucket and its own yaw.
+ MAT.tint(steel, rand()));
+ u.position.set((rand() - 0.5) * w, y + uh / 2, (rand() - 0.5) * d);
+ u.rotation.y = (rand() - 0.5) * 0.9;
+ g.add(u);
+ }
+ g.traverse((o) => { if (o.isMesh) { o.castShadow = true;
+ o.receiveShadow = true; } });
+ host.add(g);
+ return host;
+}
+
+/**
+ * Block spans and road gaps along one district axis, centred on 0.
+ *
+ * Every 4th gap widens to `avenue` when `avenue` is non-zero — the
+ * Manhattan rhythm of narrow cross-streets against wide avenues.
+ */
+function citySpans(total, cell, street, avenue) {
+ const cells = [];
+ const roads = [];
+ let x = 0;
+ let i = 0;
+ while (x + cell <= total + 1e-6) {
+ cells.push([x, x + cell]);
+ const gw = avenue && (i + 1) % 4 === 0 ? avenue : street;
+ if (x + cell + gw + cell <= total + 1e-6) {
+ roads.push({ center: x + cell + gw / 2, width: gw });
+ }
+ x += cell + gw;
+ i += 1;
+ }
+ const off = cells.length ? -cells[cells.length - 1][1] / 2 : 0;
+ return {
+ cells: cells.map(([a, b]) => [a + off, b + off]),
+ roads: roads.map((r) => ({ center: r.center + off, width: r.width })),
+ };
+}
+
+/** Split one block into 2-6 lots: full-width strips, or two columns. */
+function cityLots(rand, bw, bd) {
+ const r = rand();
+ const n = r < 0.4 ? 2 : r < 0.7 ? 3 : r < 0.85 ? 4 : r < 0.95 ? 5 : 6;
+ const cols = n <= 3 ? [n] : [Math.floor(n / 2), Math.ceil(n / 2)];
+ const lots = [];
+ const cw = bw / cols.length;
+ for (let c = 0; c < cols.length; c++) {
+ for (let k = 0; k < cols[c]; k++) {
+ lots.push({ x: c * cw, z: (bd / cols[c]) * k, w: cw, d: bd / cols[c] });
+ }
+ }
+ return lots;
+}
+
+/**
+ * Fill a district rectangle with believable city fabric in ONE call —
+ * density is a LAYOUT, not an asset, so this function IS the layout:
+ * streets/avenues are real gaps, each block subdivides into 2-6 lots,
+ * every built lot gets a `block()` (or a `tower()` where the skyline
+ * says tall) with seeded variety, and heights follow `skyline(x, z)`
+ * so the district reads as one coherent skyline, not uniform stamps.
+ *
+ * @param {object} opts
+ * `rand` seeded PRNG (REQUIRED); `width`, `depth` district metres
+ * (default 600 x 600); `blockW`, `blockD` block metres (default
+ * 55 x 90); `streetW` street gap (default 14); `avenueW` every 4th
+ * north-south street widens to this (default 24); `density` 0..1
+ * fraction of lots built (default 0.85 — the rest stay empty, like
+ * parking lots); `skyline` `(x, z) => heightScale` (default 1);
+ * `styles` array of `block()` styles to draw from; `lit` passed to
+ * every building for dusk/night; `name`.
+ * @returns {{group: THREE.Group, buildings: number,
+ * footprintFrac: number}} `group` rests on y=0, centred on x/z.
+ * `buildings` is the built count and `footprintFrac` the built lot
+ * area over district area, so callers and tests can MEASURE
+ * fullness. `group.userData.streets` lists road centrelines
+ * (`alongZ: [{x, width}]`, `alongX: [{z, width}]`) for road
+ * surfaces and traffic routes.
+ */
+export function cityFabric(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const width = opts.width || 600;
+ const depth = opts.depth || 600;
+ const blockW = opts.blockW || 55;
+ const blockD = opts.blockD || 90;
+ const streetW = opts.streetW || 14;
+ const avenueW = opts.avenueW || 24;
+ const density = opts.density === undefined ? 0.85 : opts.density;
+ const skyline = opts.skyline || (() => 1);
+ const styles = opts.styles || ['masonry', 'brick', 'stone', 'glass'];
+
+ const gx = citySpans(width, blockW, streetW, avenueW);
+ const gz = citySpans(depth, blockD, streetW, 0);
+
+ const group = new THREE.Group();
+ group.name = opts.name || 'CityFabric';
+ group.userData.streets = {
+ alongZ: gx.roads.map((r) => ({ x: r.center, width: r.width })),
+ alongX: gz.roads.map((r) => ({ z: r.center, width: r.width })),
+ };
+
+ let buildings = 0;
+ let builtArea = 0;
+ for (let ci = 0; ci < gx.cells.length; ci++) {
+ const [x0] = gx.cells[ci];
+ // Which side of this block column fronts an avenue, if either.
+ const aveEast = (ci + 1) % 4 === 0 && ci + 1 < gx.cells.length;
+ const aveWest = ci > 0 && ci % 4 === 0;
+ for (let ri = 0; ri < gz.cells.length; ri++) {
+ const [z0] = gz.cells[ri];
+ for (const lot of cityLots(rand, blockW, blockD)) {
+ if (rand() >= density) continue; // an empty lot, not a hole
+ // Sidewalk + light-well inset keeps every wall (and the
+ // cornice that projects past it) strictly inside the block.
+ const inset = 1.6 + rand() * 1.4;
+ const lw = lot.w - inset;
+ const ld = lot.d - inset;
+ const cx = x0 + lot.x + lot.w / 2;
+ const cz = z0 + lot.z + lot.d / 2;
+ const scale = Math.max(0, skyline(cx, cz));
+ let h = (14 + rand() * 26) * scale * (0.7 + rand() * 0.6);
+ if (rand() < 0.07) h *= 2.4; // the odd outlier high-rise
+ h = Math.max(8, h);
+ const onAvenue = (aveEast && lot.x + lot.w > blockW - 0.5)
+ || (aveWest && lot.x < 0.5);
+ const rot = onAvenue && rand() < 0.5;
+ const style = h > 60 && rand() < 0.5 ? 'glass'
+ : styles[Math.floor(rand() * styles.length) % styles.length];
+ const b = h > 60
+ ? tower({ w: rot ? ld : lw, d: rot ? lw : ld, h, style, rand,
+ lit: opts.lit, tiers: h > 130 ? 4 : 3 })
+ : block({ w: rot ? ld : lw, d: rot ? lw : ld, h, style, rand,
+ lit: opts.lit });
+ if (rot) b.rotation.y = aveEast ? -Math.PI / 2 : Math.PI / 2;
+ b.position.set(cx, 0, cz);
+ group.add(b);
+ buildings += 1;
+ builtArea += lw * ld;
+ }
+ }
+ }
+ return { group, buildings, footprintFrac: builtArea / (width * depth) };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/canopy.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/canopy.js
new file mode 100644
index 00000000..df4694df
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/canopy.js
@@ -0,0 +1,495 @@
+/**
+ * Canopy: a crown that reads as LEAVES rather than as a green solid.
+ *
+ * The failure this replaces is not a lack of effort. A builder given a
+ * crown reaches for a displaced Icosahedron, and a good one stacks 32
+ * of them with four octaves of noise — the measured autumn avenue did
+ * exactly that. It still reads as painted rock, because every one of
+ * those blobs is a CLOSED CONTINUOUS SURFACE: no gap for the sky to
+ * come through, one normal field over the whole mass, and one albedo.
+ * Silhouette is what tells an eye "leaves", and a convex hull has none.
+ *
+ * So a crown here is a few thousand separate ovate cards, each with its
+ * own outward facing, its own tilt and its own hue. Three consequences
+ * follow, and they are the point:
+ * - the edge breaks up, because the edge IS leaves;
+ * - light passes BETWEEN them, so the crown has depth instead of a
+ * lit side and a dark side;
+ * - the colour is mixed by the eye, not by the material. Neighbouring
+ * leaves sit up to `hue` radians apart, which is what a broken-colour
+ * painter does and what a single MeshStandardMaterial cannot do
+ * however carefully its one colour is chosen.
+ *
+ * Every crown you pass is ONE draw call together — `position` stays at
+ * zero and each leaf is built in the vertex shader from its instance
+ * attributes, the same construction `makeGrass` uses for blades. A
+ * woodland of 40 trees is one mesh, not 40, and not the 158k separate
+ * meshes the avenue shipped.
+ */
+
+import * as THREE from 'three';
+import { fbm3, mulberry32 } from './noise.js';
+import { patchStandard, shadowLike, tickShaders } from './shader.js';
+import { patchLeafSSS } from './foliage_shade.js';
+import { windOf } from './grass.js';
+
+const LOCAL_DIR = [
+ 'vec3 leafLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+/**
+ * Build the leaf mass for one or more crowns.
+ *
+ * Deterministic in `seed`: same seed, same leaves. Drive it from your
+ * `tick()` — `canopy.userData.tick(t)` — or nothing moves.
+ *
+ * @param {object} [opts]
+ * `crowns` array of `{position: [x, y, z], radius, height?, seed?}`,
+ * or `{position, size: [x, y, z]}` for a mass that is not a ball —
+ * a hedge is `size: [0.9, 1.4, 20]`
+ * in the group's local space — one entry per tree, all sharing the
+ * single draw call; a lone crown may instead be given as `position`
+ * + `radius`. `radius` metres of the crown's half-width (default 3),
+ * `height` its half-height (default `radius * 0.85`, so a crown is
+ * slightly squat). `leaves` cards per crown — by default it is
+ * derived from each mass's own surface area, which is the only way
+ * one number suits both a hedge and an oak;
+ * `maxLeaves` hard cap over ALL crowns (default 160000 — spread by
+ * thinning every crown alike, never by dropping the last tree).
+ * `size` leaf-spray length in metres (default `0.12 *` the mean crown
+ * radius, so coverage holds at any tree size — set it small only for
+ * a crown a camera stands under). `color` the albedo of
+ * a leaf in full sun, `underColor` one deep inside the crown
+ * (default a darker, cooler form of `color`). `hue` radians of
+ * leaf-to-leaf hue spread (default 0.30 — this is the broken colour;
+ * 0 gives back the flat mass). `shell` 0..1 how strongly leaves
+ * crowd the outer surface (default 0.72; real crowns are hollow).
+ * `droop` how far a tip falls (default 0.35 of leaf length).
+ * `backlit` the transmission through a leaf, as `patchLeafSSS` takes
+ * it (`{sunDir, tint, strength}`) — on by default, because the rim
+ * of a crown against the sky is lit through and not lit on; `false`
+ * turns it off, and a `sunDir` below the horizon fades it out for
+ * you (the glow is added to the ALBEDO, so nothing else would).
+ * `wind` as `makeGrass` takes it. `shadows` cast leaf
+ * shadows via a
+ * displaced depth pass (default false — the cost that made grass
+ * default the same way). `seed` PRNG seed (default 7). `name` group
+ * name.
+ * @returns {THREE.Group} Named `Canopy`, holding one `Leaves` mesh,
+ * with `userData.tick(t)`.
+ */
+export function makeCanopy(opts = {}) {
+ const crowns = crownList(opts);
+ // A leaf card stands for what the camera can RESOLVE, which at any
+ // useful distance is a spray, not one leaf. Sized off the mass's
+ // THINNEST axis, because that is what sets the scale of the foliage
+ // on it: a 34 m hedge sized off its length grew half-metre leaves.
+ const thin = crowns.reduce(
+ (a, c) => a + Math.min(c.rx, c.ry, c.rz), 0) / crowns.length;
+ const size = opts.size === undefined
+ ? Math.max(0.05, Math.min(0.4, thin * 0.12))
+ : opts.size;
+ const seed = opts.seed === undefined ? 7 : opts.seed;
+ const shell = clamp01(opts.shell === undefined ? 0.72 : opts.shell);
+ const droop = opts.droop === undefined ? 0.35 : opts.droop;
+ const hue = opts.hue === undefined ? 0.3 : opts.hue;
+ // Albedos, not screen colours: a scene sun runs at 5-6, so a hex that
+ // already looks like sunlit foliage tone-maps to pale felt.
+ const lit = new THREE.Color(
+ opts.color === undefined ? 0x4d6b28 : opts.color);
+ const under = new THREE.Color(
+ opts.underColor === undefined ? shadeOf(lit) : opts.underColor);
+ const wind = windOf(opts.wind);
+
+ const g = new THREE.Group();
+ g.name = opts.name || 'Canopy';
+ const field = leafField(crowns, opts, shell, size, seed);
+ g.add(leafMesh(field, size, droop, hue, lit, under, wind,
+ opts.shadows === true,
+ opts.backlit === false ? null : (opts.backlit || {})));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/** Clamp to -1..1: the hue offset is scaled by `hue` downstream. */
+function clampSigned(v) {
+ return Math.max(-1, Math.min(1, v));
+}
+
+/** Clamp to 0..1 without importing MathUtils for three calls. */
+function clamp01(v) {
+ return Math.max(0, Math.min(1, v));
+}
+
+/**
+ * A leaf in shadow is darker, cooler AND more saturated — never merely
+ * darker. The old form desaturated it (`s * 0.9`), which is what a
+ * lightening does, not a shading: mixed against the lit colour across a
+ * crown it pulled the whole mass toward grey-green felt. A shade leaf is
+ * physically the more chlorophyll-dense one, so its chroma goes UP as
+ * its value comes down.
+ */
+function shadeOf(c) {
+ const hsl = {};
+ c.getHSL(hsl);
+ return new THREE.Color().setHSL(
+ hsl.h + 0.045, Math.min(1, hsl.s * 1.15), hsl.l * 0.3);
+}
+
+/**
+ * How much SUN there is to come through a leaf, from the sun's own
+ * direction. `patchLeafSSS` adds its transmission to the ALBEDO, before
+ * any light is applied, so it does not go out when the sun does: on the
+ * night pass of the showcase — sun at -20 deg, ground and sky correctly
+ * dark — every crown stayed a bright yellow-green and read as daylight
+ * foliage pasted onto a night frame. The ramp holds FULL strength for
+ * any sun at or above the horizon, because a low sun is exactly when a
+ * backlit crown glows most, and closes over the five degrees below it.
+ */
+function sunUp(dir) {
+ if (!dir || dir.y === undefined) return 1;
+ return clamp01((dir.y + 0.09) / 0.09);
+}
+
+/** Read `crowns`, or the single-crown spelling, into one list. */
+function crownList(opts) {
+ const raw = Array.isArray(opts.crowns) && opts.crowns.length
+ ? opts.crowns
+ : [{ position: opts.position, radius: opts.radius }];
+ return raw.map((c, i) => {
+ const r = c.radius === undefined ? 3 : c.radius;
+ const p = c.position || [0, r, 0];
+ // Per-axis half-extents, because not every leaf mass is a ball. A
+ // hedge is a long low one, and the first builder offered this
+ // library wrote its own Icosahedra rather than fake a hedgerow out
+ // of spheres — its comment said "non-spherical" in as many words.
+ const sz = Array.isArray(c.size) ? c.size : null;
+ return {
+ x: p[0], y: p[1], z: p[2],
+ rx: sz ? sz[0] : r,
+ ry: sz ? sz[1] : (c.height === undefined ? r * 0.85 : c.height),
+ rz: sz ? sz[2] : r,
+ seed: c.seed === undefined ? i * 131 + 5 : c.seed,
+ };
+ });
+}
+
+/** Knud Thomsen's approximation; exact enough to set a leaf count. */
+function ellipsoidArea(c) {
+ const p = 1.6;
+ const a = Math.pow(c.rx, p), b = Math.pow(c.ry, p), d = Math.pow(c.rz, p);
+ return 4 * Math.PI * Math.pow((a * b + a * d + b * d) / 3, 1 / p);
+}
+
+/**
+ * Place every leaf of every crown.
+ *
+ * Leaves crowd the outer shell because that is where a real crown puts
+ * them and because interior leaves are invisible work: `shell` biases
+ * the sampled radius, it does not hollow the crown out, so a camera
+ * looking up through the branches still finds leaves overhead.
+ */
+function leafField(crowns, opts, shell, size, seed) {
+ const cap = opts.maxLeaves === undefined ? 160000 : opts.maxLeaves;
+ // Count follows AREA, so coverage — about 1.8 masses-worth of leaf,
+ // dense enough to read yet open enough to pass sky — holds for a
+ // hedge and for an oak alike. One fixed count cannot: the same 3100
+ // cards that clothe a crown leave a 34 m hedgerow bald.
+ const leafArea = Math.max(1e-4, size * size * 0.5);
+ const counts = crowns.map((c) => opts.leaves !== undefined
+ ? opts.leaves
+ : Math.max(120, Math.round(1.8 * ellipsoidArea(c) / leafArea)));
+ let total = counts.reduce((a, b) => a + b, 0);
+ if (total > cap) {
+ // Thin every mass alike; dropping the last one leaves a gap a
+ // viewer reads as a missing tree.
+ const f = cap / total;
+ for (let i = 0; i < counts.length; i++) {
+ counts[i] = Math.max(1, Math.floor(counts[i] * f));
+ }
+ total = counts.reduce((a, b) => a + b, 0);
+ }
+ const n = total;
+ const pos = new Float32Array(n * 3);
+ const axis = new Float32Array(n * 3);
+ const vary = new Float32Array(n * 4);
+ const box = new THREE.Box3();
+ let k = 0;
+ for (let ci = 0; ci < crowns.length; ci++) {
+ const c = crowns[ci];
+ const per = counts[ci];
+ const rand = mulberry32(seed + c.seed);
+ for (let i = 0; i < per; i++, k++) {
+ // Direction first, radius second: sampling a box and rejecting
+ // would thin the poles of every crown alike and read as a seam.
+ const u = rand() * 2 - 1;
+ const phi = rand() * Math.PI * 2;
+ const s = Math.sqrt(Math.max(0, 1 - u * u));
+ const dx = s * Math.cos(phi), dy = u, dz = s * Math.sin(phi);
+ const t = Math.pow(rand(), 1 - shell * 0.85);
+ // A crown is boughs, not a ball: without this the silhouette is
+ // a perfect sphere and no amount of leaf detail reads as a tree.
+ // fbm3 is SIGNED about zero — unlike GLSL's astraFbm2, which
+ // runs 0..0.75 about 0.375. Recentring it here is how the crown
+ // ends up shrunk to one side.
+ //
+ // ONE low frequency, deliberately. A second, finer octave on the
+ // radius was tried and rendered worse: it scatters leaves ALONG
+ // the ray instead of moving the shell, so the crown loses the
+ // dense outer skin that makes it read as mass and thins to a
+ // haze. Boughs are big; the fine detail is the leaf card itself.
+ const lump = 1 + 0.42 * fbm3(dx * 1.15, dy * 1.15, dz * 1.15,
+ { seed: c.seed + 3, octaves: 2 });
+ const px = c.x + dx * c.rx * t * lump;
+ const py = c.y + dy * c.ry * t * lump;
+ const pz = c.z + dz * c.rz * t * lump;
+ pos[k * 3] = px; pos[k * 3 + 1] = py; pos[k * 3 + 2] = pz;
+ // The outward normal of an ELLIPSOID, not of the unit sphere the
+ // direction was drawn on: on a long hedge those differ by most
+ // of a right angle, and the lighting follows the wrong shape.
+ const nx = dx / c.rx, ny = dy / c.ry, nz = dz / c.rz;
+ const nl = Math.hypot(nx, ny, nz) || 1;
+ axis[k * 3] = nx / nl;
+ axis[k * 3 + 1] = ny / nl;
+ axis[k * 3 + 2] = nz / nl;
+ vary[k * 4] = 0.62 + rand() * 0.76; // size
+ // Hue in two scales. Per-leaf alone averages back to one green
+ // at any distance — a canopy Monet paints turns warm in whole
+ // passages and cool in others, and that is the scale that
+ // survives being seen from across the street.
+ vary[k * 4 + 1] = clampSigned(
+ (rand() * 2 - 1) * 0.45
+ + fbm3(px * 0.42, py * 0.42, pz * 0.42,
+ { seed: c.seed + 61, octaves: 2 }) * 1.5);
+ vary[k * 4 + 2] = rand() * Math.PI * 2; // twist / phase
+ // Depth into the crown, plus a lift for the leaves the sky sees:
+ // a canopy is lit from ABOVE, not evenly over its shell.
+ vary[k * 4 + 3] = clamp01(t * (0.72 + 0.28 * (dy * 0.5 + 0.5)));
+ box.expandByPoint(new THREE.Vector3(px, py, pz));
+ }
+ }
+ return { n, pos, axis, vary, box };
+}
+
+/** The one instanced mesh every crown shares. */
+function leafMesh(field, size, droop, hue, lit, under, wind, shadows,
+ backlit) {
+ // Segmented along its length: the ovate profile is zero at BOTH
+ // ends, so a single quad's four corners all collapse to zero width
+ // and the crown draws nothing at all.
+ const base = new THREE.PlaneGeometry(1, 1, 1, 3);
+ const geom = new THREE.InstancedBufferGeometry();
+ geom.index = base.index;
+ geom.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(base.attributes.position.count * 3), 3));
+ geom.setAttribute('aCorner', base.attributes.position);
+ geom.setAttribute('uv', base.attributes.uv);
+ geom.setAttribute('normal', base.attributes.normal);
+ geom.instanceCount = field.n;
+ const inst = (name, arr, sz) => geom.setAttribute(
+ name, new THREE.InstancedBufferAttribute(new Float32Array(arr), sz));
+ inst('iPos', field.pos, 3);
+ inst('iAxis', field.axis, 3);
+ inst('iVar', field.vary, 4);
+ // position is zero, so the derived bounds would be a point at the
+ // origin: state the crowns' real box, and never cull on it.
+ geom.boundingBox = field.box.clone().expandByScalar(size);
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(
+ new THREE.Sphere());
+
+ // 0.78 measured against 0.70 and 0.82 on our pipeline and kept: a
+ // leaf IS waxy, but with no post chain the dielectric lobe reflects a
+ // bright sky straight into the crown's crest, and 0.70 traded 0.02 of
+ // measured foliage saturation for that gloss. 0.78 keeps the sheen at
+ // grazing angles without chalking the top of the tree.
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.78, metalness: 0,
+ side: THREE.FrontSide, name: 'CanopyLeaf',
+ });
+ patchStandard(mat, {
+ name: 'canopy:leaf',
+ uniforms: {
+ uLeafLit: { value: lit.clone() },
+ uLeafUnder: { value: under.clone() },
+ uLeafSize: { value: size },
+ uLeafDroop: { value: droop },
+ uLeafHue: { value: hue },
+ uLeafWind: { value: wind.dir.clone() },
+ uLeafAmp: { value: wind.amp },
+ uLeafSpeed: { value: wind.speed },
+ },
+ vertexHead: LEAF_HEAD,
+ vertexBody: LEAF_VERTEX,
+ fragmentHead: [
+ 'uniform vec3 uLeafLit;',
+ 'uniform vec3 uLeafUnder;',
+ 'varying vec3 vLeaf;',
+ 'varying vec2 vLeafB;',
+ ].join('\n'),
+ fragmentBody: LEAF_FRAGMENT,
+ });
+
+ // A crown without the backlit glow is a black rim against the sky:
+ // the underside leaves take no sun and no bounce, and only light
+ // coming THROUGH them says foliage rather than soot.
+ if (backlit) {
+ // 0.62 was too much on OUR pipeline: the transmission lands on the
+ // ALBEDO (it is added before lighting), so at 0.62 the sun-side
+ // leaves ran past 1.0 albedo and tone-mapped to pale mint. 0.44
+ // keeps the whole crown inside the 0.02-0.8 albedo band and leaves
+ // the glow to read as glow rather than as a wash.
+ const amt = backlit.strength === undefined ? 0.44 : backlit.strength;
+ patchLeafSSS(mat, { sunDir: backlit.sunDir, tint: backlit.tint,
+ strength: amt * sunUp(backlit.sunDir) });
+ }
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Leaves';
+ mesh.frustumCulled = false;
+ mesh.receiveShadow = true;
+ // Without the displaced depth pass a shadow pass draws only the
+ // degenerate zero-position quads, so casting stays off by default.
+ mesh.castShadow = false;
+ if (shadows) {
+ shadowLike(mesh, 'canopy:leafDepth', LEAF_HEAD, LEAF_VERTEX);
+ }
+ return mesh;
+}
+
+const LEAF_HEAD = [
+ 'uniform float uTime;',
+ 'uniform float uLeafSize;',
+ 'uniform float uLeafDroop;',
+ 'uniform float uLeafHue;',
+ 'uniform vec2 uLeafWind;',
+ 'uniform float uLeafAmp;',
+ 'uniform float uLeafSpeed;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iPos;',
+ 'attribute vec3 iAxis;',
+ 'attribute vec4 iVar;',
+ 'varying vec3 vLeaf;',
+ // Per-leaf constants the FRAGMENT grade needs and the geometry does
+ // not: x a decorrelated lightness draw, y how far the leaf's own
+ // facing looks at the sky. Both are constant over a card, so they
+ // ride a varying rather than being recomputed per pixel.
+ 'varying vec2 vLeafB;',
+ LOCAL_DIR,
+].join('\n');
+
+const LEAF_VERTEX = [
+ ' vec3 lfN = normalize(iAxis);',
+ // Any stable tangent will do, but the naive cross with +Y collapses
+ // for the leaves at the crown's top and bottom.
+ ' vec3 lfRef = abs(lfN.y) > 0.9 ? vec3(1.0, 0.0, 0.0)',
+ ' : vec3(0.0, 1.0, 0.0);',
+ ' vec3 lfT = normalize(cross(lfRef, lfN));',
+ ' vec3 lfB = cross(lfN, lfT);',
+ ' float lfTw = iVar.z;',
+ ' vec3 lfE1 = lfT * cos(lfTw) + lfB * sin(lfTw);',
+ ' vec3 lfE2 = -lfT * sin(lfTw) + lfB * cos(lfTw);',
+ // Ovate: widest past the middle, drawn to a point at the tip. This
+ // profile IS the silhouette, and the silhouette is the whole reason
+ // for the card.
+ ' float lfV = aCorner.y + 0.5;',
+ ' float lfProf = sin(3.14159 * pow(lfV, 0.72));',
+ ' float lfS = iVar.x * uLeafSize;',
+ ' vec2 lfC = vec2(aCorner.x * lfProf, aCorner.y);',
+ ' vec3 lfP = iPos + lfE1 * (lfC.x * lfS) + lfE2 * (lfC.y * lfS);',
+ ' lfP.y -= uLeafDroop * lfS * lfV * lfV;',
+ // Gusts are streaks running downwind, as in the grass: the same wind
+ // has to move a meadow and the trees over it alike.
+ ' vec3 lfW3 = leafLocalDir(vec3(uLeafWind.x, 0.0, uLeafWind.y));',
+ ' vec2 lfW = normalize(lfW3.xz + vec2(1e-5, 0.0));',
+ ' float lfG = astraFbm2(vec2(',
+ ' dot(iPos.xz, lfW) * 0.05 - uTime * uLeafSpeed * 0.5,',
+ ' dot(iPos.xz, vec2(-lfW.y, lfW.x)) * 0.2), 2);',
+ ' float lfT2 = uTime * uLeafSpeed;',
+ // Outer leaves move most: the trunk end of a bough barely travels.
+ ' float lfSway = uLeafAmp * (0.2 + 1.1 * lfG) * iVar.w',
+ ' * (0.6 + 0.4 * sin(lfT2 * 1.7 + iVar.z));',
+ ' lfP.xz += lfW * lfSway * 0.45;',
+ // Flutter is the leaf turning on its own stem, which is what catches
+ // the light — a card that only translates reads as dead foliage.
+ ' float lfFl = uLeafAmp * (0.35 + 0.65 * lfG)',
+ ' * sin(lfT2 * 3.1 + iVar.z * 2.3);',
+ ' lfP += lfN * (lfFl * lfC.y * lfS * 0.9);',
+ ' transformed = lfP;',
+ ' vLeaf = vec3(iVar.w, iVar.y * uLeafHue, lfV);',
+ // Decorrelated from hue, size and twist alike, so no two neighbours
+ // agree on VALUE either. Hue spread on its own still averages to one
+ // even green at a distance; a crown's real dazzle is that some leaves
+ // catch and some do not.
+ ' float lfJit = fract(sin(iVar.z * 91.7 + dot(iPos.xz, vec2(12.9898,',
+ ' 78.233))) * 43758.5453);',
+ ' vLeafB = vec2(lfJit, lfN.y * 0.5 + 0.5);',
+ '#ifndef FLAT_SHADED',
+ // Outward from the crown, not the card's own facing: this is what
+ // makes a crown light like a volume instead of a heap of flat chips.
+ // Leaves turn toward the light, and a canopy's light is the SKY, so
+ // the outward normal is bent upward — but only PART of the way. At
+ // the old fixed +1.15 every normal in the crown fell within ~40 deg
+ // of straight up, so with a 38 deg sun every leaf took the same
+ // near-full diffuse and the mass lost its form: measured, the two
+ // crowns rendered as flat pale discs with no lit side. The bend is
+ // now weak on the shell, where the outward normal IS the crown's
+ // shape, and strong in the interior, where nothing but sky reaches
+ // and a leaf lit only by its own facing goes to soot.
+ ' float lfSky = 0.34 + 0.44 * (1.0 - iVar.w);',
+ ' vNormal = normalize(normalMatrix',
+ ' * normalize(lfN + vec3(0.0, lfSky, 0.0)',
+ ' + lfE1 * (lfFl * 0.5)));',
+ '#endif',
+].join('\n');
+
+const LEAF_FRAGMENT = [
+ // Depth runs 0.26..0.89 over a crown (measured), so a straight mix
+ // never reached either end and the interior colour was decoration
+ // that never showed. Widen it to the range the field actually
+ // occupies and the crown gets an inside.
+ ' vec3 lfC = mix(uLeafUnder, uLeafLit,',
+ ' smoothstep(0.18, 0.88, vLeaf.x));',
+ // The hue spread between neighbours is the broken colour; without it
+ // the mass returns to one flat green however many cards it holds.
+ ' lfC = astraHueShift(lfC, vLeaf.y);',
+ // Sun leaves and shade leaves are not one leaf at two brightnesses:
+ // the ones the sky sees are thinner and yellower, the ones facing the
+ // ground keep their chlorophyll and read cool. This is a real
+ // botanical split and it is what gives a crown its warm crest.
+ ' lfC *= mix(vec3(0.92, 1.0, 1.06), vec3(1.12, 1.04, 0.82),',
+ ' vLeafB.y * vLeafB.y);',
+ // Value spread leaf to leaf, +-20%: the broken-colour painter varies
+ // the tone as much as the hue.
+ ' lfC *= 0.80 + 0.40 * vLeafB.x;',
+ // The crown's own occlusion. A shadow map sized for a whole scene has
+ // texels far larger than a leaf, so it can shade the crown's broad
+ // underside but never the metre of leaf a ray crosses on its way in —
+ // and without that the inside of a tree is as bright as its rim,
+ // which is the single clearest tell of fake foliage. Depth is the
+ // only occlusion signal there is here, and it is a good one.
+ ' lfC *= 0.55 + 0.45 * smoothstep(0.05, 0.85, vLeaf.x);',
+ // Sky occlusion, the other half of the same story: a leaf on the
+ // underside of a crown sees a hand's width of sky and a great deal of
+ // leaf, and it is this — not the sun — that draws the dark belly
+ // under a tree and the bright crest over it. Without it a crown lit
+ // by a bright environment has the same value top and bottom, which is
+ // why the first render read as a flat pale disc.
+ ' lfC *= 0.62 + 0.38 * vLeafB.y;',
+ // A leaf is thin: the light behind it comes through near the tip,
+ // where there is least of it — and it comes through WARM, because
+ // what survives a leaf is the red end. Adding the leaf's own colour
+ // back (the old form) only raised its value and paled the crown.
+ ' lfC += uLeafLit * vec3(1.5, 1.15, 0.5) * 0.19',
+ ' * smoothstep(0.45, 1.0, vLeaf.z) * vLeaf.x;',
+ // Albedo, not a screen colour: hold the whole crown inside the band a
+ // physical dielectric occupies, so no leaf can blow out under a sun
+ // running at 5-6 and none goes to a black chip in shade. The floor is
+ // TINTED — a flat grey floor is how a deep crown loses its colour
+ // exactly where the two occlusions have made it most saturated.
+ ' vec3 lfFloor = max(uLeafUnder * 0.25, vec3(0.012));',
+ ' diffuseColor.rgb = clamp(lfC, lfFloor, vec3(0.8));',
+].join('\n');
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/caustics.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/caustics.js
new file mode 100644
index 00000000..fbedecdc
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/caustics.js
@@ -0,0 +1,319 @@
+/**
+ * Caustics: the net of light a water surface throws on what is under it.
+ *
+ * The one cue that says a floor is UNDERWATER rather than merely blue,
+ * and it belongs to the lit surface, not to the water — a pool floor,
+ * harbour steps, a boulder, a swimmer. It is a `patchStandard`, so the
+ * material keeps its lighting, shadows, fog and depth chunks and can
+ * chain with the waterline (`waterside.js`), the rock projection
+ * (`terrain_shade.js`) and the wear (`surface_wear.js`) it will
+ * normally be wearing already.
+ */
+
+import * as THREE from 'three';
+import { patchStandard } from './shader.js';
+
+// Named as terrain_shade and waterside name them, so a submerged bank
+// wearing a splat, a waterline and this declares ONE pair.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// `transformed` is still object-space after <begin_vertex>, so an
+// instanced boulder takes the origin's depth unless this is folded in.
+const CAU_VERTEX = [
+ ' vec4 cauWp = vec4(transformed, 1.0);',
+ ' vec3 cauWn = normal;',
+ '#ifdef USE_INSTANCING',
+ ' cauWp = instanceMatrix * cauWp;',
+ ' cauWn = mat3(instanceMatrix) * cauWn;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * cauWp).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(cauWn, 0.0)).xyz);',
+].join('\n');
+
+const CAU_HEAD = [
+ 'uniform float uCauLevel;',
+ 'uniform vec3 uCauSun;',
+ 'uniform vec2 uCauSlide;',
+ 'uniform float uCauScale;',
+ 'uniform float uCauAmt;',
+ 'uniform float uCauSpeed;',
+ 'uniform vec3 uCauColor;',
+ 'uniform float uCauFade;',
+ 'uniform vec3 uCauAbs;',
+ // xyz = a LOCAL source over the water, w = 1 / its reach. w = 0 (the
+ // default) is the sun: parallel light, no falloff, no branch.
+ 'uniform vec4 uCauSrc;',
+ 'uniform vec2 uCauSeed;',
+ // A crease, not a blob: folded about its own mid-line, noise leaves a
+ // ridge along every contour, and the power narrows that ridge to a
+ // filament. The second octave kinks it; one alone draws smooth worms.
+ 'float astraCauWeb(vec2 p) {',
+ // fbm2 over two octaves tops out at 0.75, so 2.667 centres the fold.
+ ' float d = abs(astraFbm2(p, 2) * 2.667 - 1.0);',
+ ' return pow(1.0 - d, 16.0);',
+ '}',
+].join('\n');
+
+const CAU_BODY = [
+ ' float cauD = max(uCauLevel - vAstraWorld.y, 0.0);',
+ // Shade from where this fragment's light ENTERED the water: the net
+ // belongs to the surface overhead, so a riser takes a stretched
+ // slice of the floor's net instead of a pattern of its own.
+ ' vec2 cauP = (vAstraWorld.xz + uCauSlide * cauD) / uCauScale',
+ ' + uCauSeed;',
+ ' float cauAa = max(fwidth(cauP.x), fwidth(cauP.y));',
+ ' float cauT = uTime * uCauSpeed;',
+ // Water does not slide past itself: warping the sample point is what
+ // makes the net writhe where a scrolled one would crawl.
+ ' vec2 cauW = vec2(astraNoise2(cauP * 0.35 + cauT * 0.07),',
+ ' astraNoise2(cauP * 0.35 - cauT * 0.06 + 7.3));',
+ ' cauP += (cauW - 0.5) * 0.40;',
+ // And a second, finer, faster warp: without it the filaments are
+ // clean arcs, which is the one thing water never draws.
+ ' cauP += (vec2(astraNoise2(cauP * 2.2 + cauT * 0.30),',
+ ' astraNoise2(cauP * 2.2 - cauT * 0.27 + 3.7)) - 0.5)',
+ ' * 0.10;',
+ // Two wave trains crossing near a right angle. Each is sampled in
+ // its OWN frame, stretched across its travel, because a train's
+ // crests — and so its filaments — run across the way it runs.
+ ' vec2 cauU = vec2(0.86, 0.51);',
+ ' vec2 cauV = vec2(-0.51, 0.86);',
+ ' float cauA = astraCauWeb(vec2(dot(cauP, cauU) + cauT,',
+ ' dot(cauP, cauV) * 0.80));',
+ ' float cauB = astraCauWeb(vec2(dot(cauP, cauV) * 1.43 - cauT * 0.83,',
+ ' dot(cauP, cauU) * 1.14 + 3.1));',
+ // Their sum is the net; their product flares the crossings into the
+ // bright nodes, which travel at neither train's speed. That
+ // interference is the caustic — one field of it is a smear. The two
+ // halves are kept APART because they are not the same light: a node
+ // is where every wavelength converged, a filament is one fold's
+ // edge, and they are coloured differently below.
+ ' float cauFil = (cauA + cauB) * 0.5;',
+ ' float cauNode = cauA * cauB;',
+ ' float cauNet = cauFil + 4.0 * cauNode;',
+ // A third, slow, broad cell: open water is not uniformly lit, and
+ // this is where the swell has bunched the light.
+ ' float cauC = astraNoise2(cauP * 0.30',
+ ' + vec2(0.20, -0.14) * (cauT * 0.21) + 11.7);',
+ ' float cauSwell = 0.35 + 1.30 * cauC;',
+ ' cauNet *= cauSwell;',
+ // Once a pixel spans a cell the net can only alias into sparkle —
+ // but fading it to BLACK draws a line across the floor where the
+ // water stops being lit. It fades to the field's own mean instead,
+ // keeping the swell, so distance goes smooth and stays lit.
+ ' cauNet = mix(cauNet, 0.30 * cauSwell,',
+ ' smoothstep(0.25, 0.9, cauAa));',
+ // Two folds plus their product run to 5, and the swell carries that
+ // to 8: 8 x strength is far outside anything a tone map holds, so
+ // the brightest nodes came out of ACES as the same flat white as the
+ // ones a third as bright — the net lost its own structure at the top
+ // and took the floor's material with it. This rolls the peaks toward
+ // 5.5 instead, which lands a node near 3.5 units of radiance: inside
+ // the tone map's shoulder, and inside a bloom threshold's range.
+ ' cauNet = cauNet / (1.0 + 0.18 * cauNet);',
+ // Light needs a run to converge: nothing at the line, a focus a
+ // fraction of a depth down. The column it loses light IN is the
+ // tint below — extinction is per channel, not one number.
+ ' float cauK = smoothstep(0.0, uCauFade * 0.3, cauD);',
+ ' cauK *= 0.12 + 0.88 * max(dot(normalize(vAstraWorldN), uCauSun),',
+ ' 0.0);',
+ // A long shallow shelf is one smooth ramp of this term over hundreds
+ // of pixels, which is exactly where 8-bit output bands.
+ ' cauK *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.05;',
+ // A lamp over a pool at night lights a POOL of net, not a reservoir:
+ // inverse-square in units of its reach, and identically 1.0 for the
+ // sun, whose w is zero.
+ ' float cauR = length(vAstraWorld.xz - uCauSrc.xz) * uCauSrc.w;',
+ ' cauK /= 1.0 + cauR * cauR;',
+ // WATER DRINKS RED FIRST. The scalar fade this replaces dimmed the
+ // net evenly and left a deep floor lit the same colour as a shin-
+ // deep one; a per-channel Beer-Lambert is what makes shallow water
+ // warm and a depth go green-blue — the whole reason a pool
+ // photographs. uCauAbs is luminance-neutral, so the net still dims
+ // over exactly the `depthFade` metres asked for: only the hue splits.
+ ' vec3 cauTint = uCauColor * exp(-cauD * uCauAbs);',
+ // Dispersion: a lone filament is a fold seen edge-on and keeps the
+ // cool end, a crossing is achromatic and runs warm-white.
+ ' float cauNf = cauNode / (cauNode + cauFil * 0.5 + 1e-4);',
+ ' cauTint *= mix(vec3(0.84, 0.98, 1.10), vec3(1.08, 1.00, 0.92),',
+ ' cauNf);',
+ // And broken colour over metres, so no two bays of one pool are the
+ // same green — a single flat tint is the tell of a painted pattern.
+ ' cauTint = astraHueBreak(cauTint, cauP, 0.25, 0.22);',
+ // Caustics are LIGHT, so they land on the emissive term; tinted by
+ // the albedo, because what the eye sees is that light reflected.
+ ' totalEmissiveRadiance += cauTint * diffuseColor.rgb',
+ ' * (cauNet * cauK * uCauAmt);',
+].join('\n');
+
+/** 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);
+}
+
+/**
+ * Metres a sunbeam slides sideways per metre of depth, REFRACTED.
+ *
+ * Water bends the ray toward the vertical (n = 1.333), so the air
+ * tangent overshoots — at a low sun by more than a third, which would
+ * shear the net right off the wall it is supposed to be climbing.
+ */
+function refractSlide(sun) {
+ const sinAir = Math.min(Math.hypot(sun.x, sun.z), 1);
+ const sinWater = Math.min(sinAir / 1.333, 0.999);
+ const tanWater = sinWater / Math.sqrt(1 - sinWater * sinWater);
+ return new THREE.Vector2(sun.x, sun.z).normalize()
+ .multiplyScalar(tanWater);
+}
+
+/**
+ * Per-channel extinction of the beam through the water column.
+ *
+ * Water is not a grey filter: red is gone in a couple of metres where
+ * blue crosses tens, which is why every photograph of a pool ramps warm
+ * at the step and green-blue at the drain. Red runs 0.62 of the
+ * caller's `depthFade` and blue 1.45 — pulled IN from the ~20:1 clear
+ * water really has, because the true ratio takes the net monochrome
+ * cyan inside three metres and a pool is not an ocean trench.
+ *
+ * NORMALISED to luminance, so this is a pure hue split and not a
+ * dimmer: mid-grey still decays over exactly the metres the caller
+ * asked for, and `depthFade` keeps meaning what it meant before there
+ * was a colour here at all. (Weighting by Rec.709 rather than thirds
+ * matters — green carries 71% of the luminance and is the channel in
+ * the middle, so an unweighted normalisation would darken the net by a
+ * tenth at every depth.)
+ */
+function absorption(fade) {
+ const w = new THREE.Vector3(1 / 0.62, 1 / 1.00, 1 / 1.45);
+ const lum = 0.2126 * w.x + 0.7152 * w.y + 0.0722 * w.z;
+ return w.divideScalar(lum * Math.max(1e-3, fade));
+}
+
+/**
+ * A local source over the water, packed as (x, y, z, 1 / reach).
+ *
+ * The sun is parallel light and covers a bay as evenly as a puddle, so
+ * it is the default and its `w` is 0 — which makes the falloff term in
+ * the shader exactly 1.0 with no branch. A LAMP is the opposite: a
+ * night pool is a pool, and one bulb lighting a whole reservoir's floor
+ * is the tell that the net is a texture. `reach` is where the net is
+ * down to half.
+ */
+function sourceReach(source, reach) {
+ if (!source) return new THREE.Vector4(0, 0, 0, 0);
+ const r = Math.max(1e-3, reach === undefined ? 8 : reach);
+ return new THREE.Vector4(source.x, source.y, source.z, 1 / r);
+}
+
+/**
+ * A seed becomes a far-apart lattice offset, not a one-cell shift.
+ *
+ * Seeds 7 and 8 offsetting by 1 would TRANSLATE the net by one cell,
+ * which is the same pool twice.
+ */
+function seedOffset(seed) {
+ const s = Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973;
+ return new THREE.Vector2(((s * 16807) % 9973) * 0.103,
+ ((s * 48271) % 9973) * 0.071);
+}
+
+/**
+ * Throw a moving net of caustic light on what is under the water.
+ *
+ * Applied to the material of the surface being LIT, never to the
+ * water. Nothing above `level` is touched at all; below it the net
+ * fades IN over the first fraction of a depth — light needs a run to
+ * converge — and out again with the water column, which is what
+ * separates a lit pool from a floor with a pattern painted on it.
+ *
+ * Two things earn the look. The pattern is sampled where the sunbeam
+ * ENTERED the water: this fragment's world XZ slid toward the sun by
+ * its own depth, refracted. So the net belongs to the surface overhead
+ * and a step riser takes a stretched slice of the same net rather than
+ * a pattern of its own. And it is ridged interference — two wave
+ * trains crossing, plus a slow third that bunches the light — so the
+ * bright nodes travel at neither train's speed, where one fbm at any
+ * speed reads as dirt sliding over the floor.
+ *
+ * The third is the COLOUR. The light reaching a fragment has crossed
+ * its own depth of water, and water drinks red long before blue, so the
+ * tint is a per-channel Beer-Lambert rather than one fade: warm at the
+ * step, green-blue at the drain, all from one `depthFade` (measured on
+ * a two-slab rig, blue/red 1.17 -> 1.41 at 2.4 m against 0.95 -> 0.92
+ * at 0.4 m). Over that, the crossings run warm-white — every wavelength
+ * converged there — against cooler filaments, and a slow broken-colour
+ * field keeps two bays of one pool from being the same green. And the
+ * whole net is rolled off before it is scaled, so a bright node lands
+ * near 3.5 units of radiance rather than the 30 that came out of the
+ * tone map as flat white with the floor's material inside it.
+ *
+ * It lifts `totalEmissiveRadiance`, tinted by `diffuseColor`, and does
+ * NOT change albedo: caustics are light, and albedo alone would cap
+ * them at the light the surface already gets, so a shaded corner or a
+ * soffit would take none. That needs a LIT material — MeshStandard /
+ * MeshPhysical, not Basic, which has no emissive term at all. Drive it
+ * with `tickShaders(scene, t)`; an un-advanced uTime is a frozen net.
+ *
+ * @param {THREE.Material} material A built-in lit material, patched in
+ * place.
+ * @param {object} [opts] `level` world Y of the water surface (default
+ * 0); `sunDir` THREE.Vector3 TOWARD the sun — the same one the key
+ * light uses (default 0.45, 0.75, 0.35); `scale` metres across one
+ * cell of the net (default 0.6); `strength` how hard the net
+ * burns — a node peaks near 3 x this (default 4); `speed` how fast
+ * the water runs (default 0.35); `color` THREE.Color or hex of the
+ * light ABOVE the surface, before the water tints it (default a
+ * warm daylight white); `depthFade` metres of water the net survives
+ * in luminance — red keeps 0.62 of that and blue 1.45, which is the
+ * ramp from a warm step to a green-blue drain (default 3); `seed`
+ * moves the lattice, so two pools are not one pool twice (default 1);
+ * `source` a THREE.Vector3 world position when the light over the
+ * water is a LAMP rather than the sun, with `reach` the metres at
+ * which its net is half gone (default 8) — omit both for sunlight.
+ * @returns {THREE.Material} The same material, its uniforms live on
+ * `material.userData.uniforms` so `uCauLevel` can follow a tide.
+ */
+export function patchCaustics(material, opts = {}) {
+ const level = opts.level === undefined ? 0 : opts.level;
+ const scale = opts.scale === undefined ? 0.6 : opts.scale;
+ const strength = opts.strength === undefined ? 4 : opts.strength;
+ const speed = opts.speed === undefined ? 0.35 : opts.speed;
+ const fade = opts.depthFade === undefined ? 3 : opts.depthFade;
+ const sun = (opts.sunDir ? opts.sunDir.clone()
+ : new THREE.Vector3(0.45, 0.75, 0.35)).normalize();
+ const slide = refractSlide(sun);
+ // The one silent failure here: no emissive term means either a raw
+ // ShaderMaterial (no hook at all) or a Basic (no such variable).
+ if (material && material.emissive === undefined) {
+ console.warn(
+ 'patchCaustics: ' + (material.name || material.type) + ' has no '
+ + 'emissive term — caustics are LIGHT and land on '
+ + 'totalEmissiveRadiance, which a MeshBasicMaterial and a raw '
+ + 'ShaderMaterial do not have. Patch a lit material instead.');
+ }
+ return patchStandard(material, {
+ name: 'caustics:net',
+ uniforms: {
+ uCauLevel: { value: level },
+ uCauSun: { value: sun },
+ uCauSlide: { value: slide },
+ uCauScale: { value: Math.max(1e-3, scale) },
+ uCauAmt: { value: Math.max(0, strength) },
+ uCauSpeed: { value: speed },
+ uCauColor: { value: toColor(opts.color, 0xfff2e2) },
+ uCauFade: { value: Math.max(1e-3, fade) },
+ uCauAbs: { value: absorption(fade) },
+ uCauSrc: { value: sourceReach(opts.source, opts.reach) },
+ uCauSeed: { value: seedOffset(opts.seed) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: CAU_VERTEX,
+ fragmentHead: [WORLD_VARYINGS, CAU_HEAD].join('\n'),
+ fragmentBody: CAU_BODY,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js
new file mode 100644
index 00000000..ba9edc33
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/celestial.js
@@ -0,0 +1,824 @@
+/**
+ * The sky above the scene, and the air that bends what is behind it.
+ *
+ * Two different jobs share this file because both live OUTSIDE the
+ * lit world and both are additive-or-nothing:
+ *
+ * A SHIMMER IS NOT A THING YOU CAN SEE. Heat haze has no colour, no
+ * silhouette and no shape — it is the image behind it, moved. So this
+ * 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`
+ * 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`.
+ *
+ * A NIGHT SKY IS THE DARK FRAME ADDED LIGHT SURVIVES. Stars and
+ * aurora both ADD light, which is right only while the frame behind
+ * them is dark — godrays.js measured 12.8% of a pale frame blown past
+ * 0.97 by exactly this. So both take the same `ambient` escape it has.
+ * The DEFAULT is the night build, because a star field belongs to
+ * exactly one frame and that frame is dark; `ambient: 0.9` still buys
+ * the blend that cannot clip, and it is still measurably harmless over
+ * a daylight sky (blown_frac 0.0000 on this renderer).
+ *
+ * Nothing here is tone-map-exempt except the shimmer, so all of it is
+ * graded for ACES at exposure 1.0 with no post chain: added light that
+ * reaches alpha 1 comes back out of the curve WHITE, so the aurora
+ * saturates toward a ceiling below 1 and the band's gain is spent on
+ * structure rather than on level.
+ *
+ * Neither sky field writes depth, casts a shadow or takes part in fog:
+ * a star is at infinity and `FogExp2` at the night density erases
+ * anything past ~400 m, which is why `worldShell()`'s own dome runs
+ * `fog: false` too.
+ */
+
+import * as THREE from 'three';
+
+import {
+ instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,
+ tickShaders } from './shader.js';
+
+// Backdrop paint order among TRANSPARENT meshes. three renders every
+// opaque object before any transparent one whatever renderOrder says,
+// so these only sort the sky against itself; depth testing is what
+// keeps the scene in front of it.
+const ORDER_MILKYWAY = -1.75;
+const ORDER_STARS = -1.70;
+const ORDER_AURORA = -1.60;
+const ORDER_SHIMMER = 20;
+
+const _SIZE = new THREE.Vector2();
+
+/** 16807 LCG: same seed, same sky, on every machine. */
+function prng(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);
+}
+
+/**
+ * Copy the frame drawn so far into a texture the shimmer can sample.
+ *
+ * `renderer.copyFramebufferToTexture` cannot do this job: measured on
+ * ANGLE/D3D12, `copyTexSubImage2D` is INVALID_OPERATION out of the
+ * MULTISAMPLED buffer every renderer here draws into (the composer
+ * runs 4x MSAA, the canvas `antialias: true`), and again into an sRGB
+ * destination. A resolve BLIT survives both, on one condition: the
+ * destination's internal format must equal the source's exactly — so
+ * the type is taken from the bound target (HalfFloat under the post
+ * chain, byte straight to canvas) and the colour space left off, or
+ * 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.
+ */
+function frameGrabber(mat) {
+ let tex = null;
+ let fbo = null;
+ let warned = false;
+ return (renderer) => {
+ const gl = renderer.getContext();
+ if (typeof gl.blitFramebuffer !== 'function') {
+ if (!warned) {
+ warned = true;
+ console.warn(
+ 'makeHeatShimmer: no WebGL2 blitFramebuffer — the ' +
+ 'card cannot read the frame and draws nothing.');
+ }
+ return;
+ }
+ renderer.getDrawingBufferSize(_SIZE);
+ const w = _SIZE.x, h = _SIZE.y;
+ const rt = renderer.getRenderTarget();
+ const type = rt ? rt.texture.type : THREE.UnsignedByteType;
+ if (!tex || tex.image.width !== w || tex.image.height !== h
+ || tex.type !== type) {
+ if (tex) tex.dispose();
+ if (fbo) { gl.deleteFramebuffer(fbo); fbo = null; }
+ tex = new THREE.FramebufferTexture(w, h);
+ tex.type = type;
+ tex.colorSpace = THREE.NoColorSpace;
+ tex.minFilter = THREE.LinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ mat.uniforms.uScene.value = tex;
+ }
+ renderer.initTexture(tex);
+ const handle = renderer.properties.get(tex).__webglTexture;
+ if (!handle) return;
+ if (!fbo) fbo = gl.createFramebuffer();
+ const prev = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, fbo);
+ gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, gl.COLOR_ATTACHMENT0,
+ gl.TEXTURE_2D, handle, 0);
+ gl.blitFramebuffer(0, 0, w, h, 0, 0, w, h,
+ gl.COLOR_BUFFER_BIT, gl.NEAREST);
+ // Restored to exactly what was bound, so three's own state
+ // cache is still telling the truth afterwards.
+ gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, prev);
+ mat.uniforms.uResolution.value.set(w, h);
+ // Straight to canvas the frame is already sRGB-encoded and
+ // <colorspace_fragment> is about to encode it again; into a
+ // render target it is linear and that chunk is identity.
+ mat.uniforms.uEncoded.value =
+ (!rt && renderer.outputColorSpace === THREE.SRGBColorSpace)
+ ? 1 : 0;
+ };
+}
+
+/**
+ * Air over a fire, an exhaust or a summer road: the backdrop, moved.
+ *
+ * Draws NOTHING of its own. The fragment's only colour source is a
+ * copy of the frame taken the instant before this card is drawn,
+ * sampled at coordinates pushed around by a rising noise field — so
+ * there is no shape to see, only a wobble in whatever stands behind.
+ * Verified over a striped backdrop: a stripe edge travels about 6 px
+ * in a 560 px frame at the default strength.
+ *
+ * WHAT IT CANNOT DO, because the copy carries colour and no depth:
+ * (1) an object standing IN FRONT of the card can be smeared into it,
+ * since the sample has no way to reject a nearer pixel — keep the card
+ * behind the things it belongs to; (2) it cannot displace anything
+ * drawn AFTER it (a later transparent pass, bloom, the AO blend);
+ * (3) it costs one full-frame copy per shimmer per view, so use one
+ * card per heat source, not a field of them.
+ *
+ * @param {object} [opts]
+ * `width` / `height` card size in metres (default 2.4 x 3.2); the
+ * card billboards about its own centre and rests on y = 0, so put
+ * the group AT the fire; `strength` peak displacement as a fraction
+ * of FRAME HEIGHT (default 0.012 — refraction is an angle, so the
+ * screen shift of a distant plume is the same as a near one);
+ * `speed` how fast the cells rise (default 1); `cells` how many
+ * convection cells span the card's height (default 3.4 — fewer is
+ * an engine's slow roll, more is a fire's boil); `seed` PRNG seed
+ * (default 5).
+ * @returns {THREE.Group} Named `HeatShimmer`, resting on y = 0, with
+ * `userData.tick(t)`. No `ambient` escape and none needed: a
+ * material whose output IS the backdrop cannot brighten a frame it
+ * never adds to.
+ */
+export function makeHeatShimmer(opts = {}) {
+ const width = opts.width === undefined ? 2.4 : opts.width;
+ const height = opts.height === undefined ? 3.2 : opts.height;
+ const strength = opts.strength === undefined ? 0.012 : opts.strength;
+ const speed = opts.speed === undefined ? 1 : opts.speed;
+ // Cell SIZE is set by the air, not by the card: scaling the count
+ // with the card keeps a metre-wide cell on a 3 m plume and on a
+ // 30 m one, where a fixed count would give the big card boulders.
+ const cells = opts.cells === undefined
+ ? Math.max(2.5, height / 0.95) : opts.cells;
+ const rnd = prng(opts.seed === undefined ? 5 : opts.seed);
+
+ // The billboard sweeps a sphere about the card's centre, which is
+ // half a card up: a stated radius, never instancedQuad's 10 km
+ // default, or a rig that frames on it frames 10 km of empty air.
+ const reach = height * 0.5 + Math.hypot(width, height) * 0.5;
+ const geom = instancedQuad(1, width, height, reach);
+ const mat = shimmerMaterial(
+ strength, speed, cells, width / height, height, rnd() * 97);
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'HeatShimmer';
+ // Last of the transparents, so the copy holds everything the
+ // shimmer is supposed to bend.
+ mesh.renderOrder = ORDER_SHIMMER;
+
+ const g = new THREE.Group();
+ g.name = 'HeatShimmer';
+ g.add(mesh);
+ keepOutOfDepthPasses(g);
+ // keepOutOfDepthPasses OWNS onBeforeRender (it blanks the draw
+ // range under an override material), so the grab wraps its guard
+ // instead of replacing it — and only fires for our own material,
+ // never inside the AO or shadow pass.
+ const guard = mesh.onBeforeRender;
+ const grab = frameGrabber(mat);
+ mesh.onBeforeRender = (r, s, cam, geo, m) => {
+ guard(r, s, cam, geo, m);
+ if (m === mat) grab(r);
+ };
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/** Resample the grabbed frame; emit no colour that is not in it. */
+function shimmerMaterial(strength, speed, cells, aspect, height, phase) {
+ return makeShaderMaterial({
+ name: 'HeatShimmer',
+ uniforms: {
+ uScene: { value: null },
+ uResolution: { value: new THREE.Vector2(1, 1) },
+ uEncoded: { value: 0 },
+ uStrength: { value: strength },
+ uSpeed: { value: speed },
+ uCells: { value: cells },
+ uAspect: { value: aspect },
+ uPhase: { value: phase },
+ uCentre: { value: new THREE.Vector3(0, height * 0.5, 0) },
+ },
+ varyings: 'varying vec2 vUv;',
+ vertexHead: 'attribute vec3 aCorner; uniform vec3 uCentre;',
+ vertexMain: [
+ ' vUv = uv;',
+ // Rows of the model-view rotation are the LOCAL directions
+ // that map to screen x and y, so the card faces the camera
+ // whatever the group is turned to.
+ ' mat3 mv3 = mat3(modelViewMatrix);',
+ ' vec3 rt = vec3(mv3[0][0], mv3[1][0], mv3[2][0]);',
+ ' vec3 up = vec3(mv3[0][1], mv3[1][1], mv3[2][1]);',
+ ' transformed = uCentre + rt * aCorner.x + up * aCorner.y;',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform sampler2D uScene;',
+ 'uniform vec2 uResolution;',
+ 'uniform float uStrength; uniform float uSpeed;',
+ 'uniform float uCells; uniform float uAspect;',
+ 'uniform float uPhase; uniform float uEncoded;',
+ // The exact sRGB EOTF, because this has to be the precise
+ // inverse of the encode three is about to re-apply.
+ 'vec3 astraCelDecode(vec3 c) {',
+ ' return mix(pow((c + 0.055) / 1.055, vec3(2.4)),',
+ ' c / 12.92, step(c, vec3(0.04045)));',
+ '}',
+ ].join('\n'),
+ fragmentMain: [
+ ' vec2 uv = gl_FragCoord.xy / uResolution;',
+ ' float t = uTime * uSpeed;',
+ ' vec2 q = vec2(vUv.x * uCells * uAspect, vUv.y * uCells);',
+ // Cells RISE, so the field scrolls down through them, and
+ // the two axes read different noise or the whole card
+ // slides sideways as one sheet.
+ ' float nx = astraFbm2(q + vec2(uPhase, -t), 3);',
+ ' float ny = astraFbm2(q + vec2(uPhase + 31.7, -t * 1.27),',
+ ' 3);',
+ // astraFbm2 lands in 0..0.875 about a mean of 0.4375 and
+ // its octaves almost never align, so the raw signal swings
+ // by about a tenth: centred and stretched, or uStrength
+ // means a twelfth of what it says.
+ ' vec2 n = clamp((vec2(nx, ny) - 0.4375) * 4.0,',
+ ' vec2(-1.0), vec2(1.0));',
+ // Hot air spreads and slows as it climbs, so the wobble
+ // grows up the plume rather than being uniform.
+ ' vec2 push = n * uStrength * (0.30 + 0.95 * vUv.y);',
+ // uStrength is a fraction of frame HEIGHT; x has to be
+ // divided by the aspect or the wobble is anisotropic.
+ ' push.x *= uResolution.y / uResolution.x;',
+ ' vec3 behind = texture2D(uScene, uv + push).rgb;',
+ ' behind = mix(behind, astraCelDecode(behind), uEncoded);',
+ // The envelope: a plume, not a rectangle. A hard edge here
+ // is the one way this effect becomes a visible shape.
+ ' float wan = (astraFbm2(vec2(uPhase, vUv.y * 1.7 - t * 0.5),',
+ ' 2) - 0.5) * 0.34;',
+ ' float u = abs(vUv.x - 0.5 + wan) * 2.0;',
+ ' float body = 0.45 + 0.85 * astraFbm2(q * 0.75',
+ ' + vec2(uPhase, -t * 0.7), 3);',
+ ' float a = (1.0 - smoothstep(0.30, 1.0, u))',
+ ' * smoothstep(0.0, 0.12, vUv.y)',
+ ' * (1.0 - smoothstep(0.40, 1.0, vUv.y)) * body;',
+ ' a = clamp(a * 1.9, 0.0, 1.0);',
+ ' if (a < 0.004) discard;',
+ ' gl_FragColor = vec4(behind, a);',
+ ].join('\n'),
+ // additive:true buys the ALPHA fade into fog — the ordinary
+ // fog chunk would mix the resampled pixel toward the fog
+ // colour, which paints haze the frame already has. The blend
+ // stays NORMAL: this replaces pixels, it does not add light.
+ additive: true,
+ blending: THREE.NormalBlending,
+ // Tone mapping already happened to the pixels being resampled;
+ // running it again is the one way this shader could change a
+ // colour instead of moving it.
+ toneMapped: false,
+ depthWrite: false,
+ transparent: true,
+ side: THREE.DoubleSide,
+ });
+}
+
+/**
+ * A night sky: mostly faint stars, a Milky Way, and a slow twinkle.
+ *
+ * Brightness is drawn from the real one — the number of stars brighter
+ * than magnitude m grows as 10^(0.6 m), so half of any field sits past
+ * magnitude 5.5 and under 1% of it is what anyone would call bright.
+ * A field of equal dots is the giveaway that it was not.
+ *
+ * Sits OUTSIDE the world and never occludes it: no depth write, no
+ * shadow, and every star fades out below ~6 degrees of elevation the
+ * way real extinction takes them, so a horizon ridge is never speckled.
+ * Its meshes are named `StarField` / `MilkyWayStars` on purpose — the
+ * scene renderer keys its content-fit and occluder filters on `star` /
+ * `sky` in a mesh name, and a 2 km sphere that misses those filters
+ * becomes the content bbox and pushes every camera out of the scene.
+ *
+ * Combine with a dome, never instead of one: `worldShell({mood:
+ * 'night'})` (lib/environment.js) draws the gradient this sits in
+ * front of, and `makeSky()` (lib/sky.js) is a DAYLIGHT dome — its
+ * Preetham shader has no night. Both leave `scene.background` null and
+ * neither writes depth, so the stars paint over either one.
+ *
+ * @param {object} [opts]
+ * `count` stars (default 1400); `radius` metres to the star sphere
+ * (default 2000 — inside `worldShell`'s 4 km dome and the camera's
+ * far plane, outside any content); `magnitude` overall brightness
+ * gain (default 1); `twinkle` scintillation depth 0..1 (default
+ * 0.35, over periods of 4-9 s); `milkyWay` the band of unresolved
+ * light, which also pulls part of the field into it (default true);
+ * `seed` PRNG seed (default 3); `ambient` how bright the frame
+ * behind is, 0 a real night to 1 daylight (default 0.2). Added
+ * light cannot see what it adds to, so from 0.35 up the field
+ * switches from ADDING to a plain blend that cannot clip; pass
+ * `ambient: 0.9` when the sky behind is genuinely bright.
+ * @returns {THREE.Group} Named `Stars`, centred on the camera's world
+ * — put it at the origin — with `userData.tick(t)`.
+ */
+export function makeStars(opts = {}) {
+ const count = Math.max(1, Math.round(
+ opts.count === undefined ? 1400 : opts.count));
+ const radius = opts.radius === undefined ? 2000 : opts.radius;
+ const gain = opts.magnitude === undefined ? 1 : opts.magnitude;
+ const twinkle = Math.min(Math.max(
+ opts.twinkle === undefined ? 0.35 : opts.twinkle, 0), 1);
+ const seed = opts.seed === undefined ? 3 : opts.seed;
+ // 0.2, not the 0.85 this shipped with. A star field belongs to ONE
+ // frame — a night one — and at 0.85 the safe blend put the whole
+ // sky inside a single 8-bit bucket on this renderer (modal_frac
+ // 0.95, sky luminance flat at 0.19): the catalog promised stars and
+ // the frame had none. The bright build is still one argument away.
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.2 : opts.ambient, 0), 1);
+ const bright = ambient >= 0.35;
+ const rnd = prng(seed);
+ // Galactic pole: the band is a great circle, so one vector fixes
+ // where it crosses the sky.
+ const pole = new THREE.Vector3(0.34, 0.83, -0.44).normalize();
+
+ const g = new THREE.Group();
+ g.name = 'Stars';
+ if (opts.milkyWay !== false) g.add(milkyWayMesh(radius, pole, bright));
+ g.add(starMesh(count, radius, gain, twinkle, rnd, pole, bright,
+ opts.milkyWay !== false));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/**
+ * Relative flux for one star, drawn from the magnitude distribution.
+ *
+ * Inverse-samples N(<= m) ~ 10^(0.6 m) over magnitude 0..6 and returns
+ * the linear flux 10^(-0.4 m) — 1 for the brightest star in the field,
+ * 0.004 for the faintest, median about 0.006. That skew IS the sky.
+ */
+function starFlux(u) {
+ const top = Math.pow(10, 0.6 * 6);
+ const m = Math.log(1 + u * (top - 1)) / Math.LN10 / 0.6;
+ return Math.pow(10, -0.4 * m);
+}
+
+/** The stars themselves: GTAO-safe billboards, one per instance. */
+function starMesh(count, radius, gain, twinkle, rnd, pole, bright,
+ banded) {
+ const geom = instancedQuad(count, 1, 1, radius * 1.02);
+ const dir = new Float32Array(count * 3);
+ const star = new Float32Array(count * 4);
+ const v = new THREE.Vector3();
+ for (let i = 0; i < count; i++) {
+ // Upper hemisphere only: a star under the horizon is a star
+ // behind the ground, and the shader fades the last few degrees.
+ v.set(rnd() * 2 - 1, rnd(), rnd() * 2 - 1);
+ if (v.lengthSq() < 1e-6) v.set(0, 1, 0);
+ v.normalize();
+ // Part of the field belongs to the band: flattening a share of
+ // it toward the galactic plane is what makes the Milky Way
+ // read as stars rather than as painted haze.
+ if (banded && rnd() < 0.42) {
+ v.addScaledVector(pole, -v.dot(pole) * (0.55 + 0.4 * rnd()));
+ v.normalize();
+ }
+ dir[i * 3] = v.x; dir[i * 3 + 1] = v.y; dir[i * 3 + 2] = v.z;
+ star[i * 4] = starFlux(rnd());
+ star[i * 4 + 1] = rnd();
+ // 4-9 s periods: the eye reads anything faster as fireflies.
+ star[i * 4 + 2] = 0.7 + 0.85 * rnd();
+ star[i * 4 + 3] = rnd();
+ }
+ geom.setAttribute('aDir', new THREE.InstancedBufferAttribute(dir, 3));
+ geom.setAttribute('aStar', new THREE.InstancedBufferAttribute(star, 4));
+ const mesh = new THREE.Mesh(
+ geom, starMaterial(radius, gain, twinkle, bright));
+ mesh.name = 'StarField';
+ mesh.renderOrder = ORDER_STARS;
+ return mesh;
+}
+
+function starMaterial(radius, gain, twinkle, bright) {
+ return makeShaderMaterial({
+ name: 'StarField',
+ uniforms: {
+ // ~2 px across at 560 px and fov 55 for the faintest star,
+ // ~5 px for the brightest: a point source, not a disc.
+ uSize: { value: radius * 0.0042 },
+ uRadius: { value: radius },
+ uTwinkle: { value: twinkle },
+ uGain: { value: gain * (bright ? 0.55 : 1.0) },
+ },
+ varyings: 'varying vec2 vUv; varying float vGain;'
+ + ' varying vec3 vTint;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec3 aDir;'
+ + ' attribute vec4 aStar; uniform float uSize;'
+ + ' uniform float uRadius; uniform float uTwinkle;',
+ vertexMain: [
+ ' vUv = uv;',
+ ' float f = aStar.x;',
+ ' float tw = 1.0 + uTwinkle * sin(uTime * aStar.z',
+ ' + aStar.y * 6.2831853);',
+ // Extinction: the last few degrees of sky eat a star, which
+ // is also what keeps the field off a horizon silhouette.
+ ' vGain = pow(f, 0.38) * tw * smoothstep(0.0, 0.11, aDir.y);',
+ // Spectral class, biased the way a real field is: warm K/M
+ // stars are the minority, so the sample is pushed toward
+ // the blue-white end rather than split down the middle.
+ ' vec3 hot = mix(vec3(1.0, 0.74, 0.52), vec3(0.70, 0.81, 1.0),',
+ ' pow(aStar.w, 0.7));',
+ // At threshold the eye has no colour at all: only the
+ // bright ones may show their class, or a faint field turns
+ // into scattered red and blue confetti.
+ ' vTint = mix(vec3(0.93, 0.95, 1.0), hot,',
+ ' 0.22 + 0.78 * pow(f, 0.30));',
+ ' mat3 mv3 = mat3(modelViewMatrix);',
+ ' vec3 rt = vec3(mv3[0][0], mv3[1][0], mv3[2][0]);',
+ ' vec3 up = vec3(mv3[0][1], mv3[1][1], mv3[2][1]);',
+ ' float s = uSize * (0.55 + 0.85 * pow(f, 0.25));',
+ ' transformed = aDir * uRadius',
+ ' + (rt * aCorner.x + up * aCorner.y) * s;',
+ ].join('\n'),
+ fragmentHead: 'uniform float uGain;',
+ fragmentMain: [
+ ' float d = length(vUv - 0.5) * 2.0;',
+ ' if (d > 1.0) discard;',
+ // A tight core in a faint halo. A flat disc is the look
+ // that reads as confetti.
+ ' float a = (pow(1.0 - d, 4.0) + 0.20 * pow(1.0 - d, 1.4))',
+ ' * vGain * uGain;',
+ // A halo this soft steps in 8-bit: one sub-LSB of noise per
+ // pixel costs nothing and buys the rings back as grain.
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ ' if (a < 0.004) discard;',
+ ' gl_FragColor = vec4(vTint, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ // 3dcv: no-fog — a star is at infinity, and FogExp2 at the
+ // night density erases anything past ~400 m. worldShell's own
+ // dome opts out the same way.
+ fog: false,
+ blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,
+ transparent: true,
+ depthWrite: false,
+ });
+}
+
+/** The band: unresolved light, dust lanes, and a bulge to aim at. */
+function milkyWayMesh(radius, pole, bright) {
+ const geom = new THREE.SphereGeometry(radius * 1.01, 48, 24);
+ // Two axes across the band give the noise a seamless 2D coordinate
+ // — an atan around the pole would print a meridian down the sky.
+ const a = new THREE.Vector3(0, 1, 0).cross(pole).normalize();
+ const b = new THREE.Vector3().crossVectors(pole, a).normalize();
+ const core = a.clone().multiplyScalar(0.72)
+ .addScaledVector(b, 0.55).addScaledVector(pole, 0.06).normalize();
+ const mat = makeShaderMaterial({
+ name: 'MilkyWay',
+ uniforms: {
+ uPole: { value: pole.clone() },
+ uAxisA: { value: a },
+ uAxisB: { value: b },
+ uCore: { value: core },
+ // TWO colours, because the band has two: the bulge is seen
+ // through the whole disc of dust and comes out reddened,
+ // while the outer arms are the blue-white of the young
+ // stars in them. One flat tint is what made this render as
+ // a grey cloud (sky hue sigma 0.0025 over the band).
+ uArm: { value: new THREE.Color(0x9fbcf8) },
+ uHub: { value: new THREE.Color(0xffd79a) },
+ // Higher than the 0.42 this shipped with, because the alpha
+ // it multiplies is no longer a plateau: deep dust lanes,
+ // the rift and a real extinction ramp take most of the band
+ // to nearly nothing, and the gain has to buy the star
+ // clouds back or the whole band disappears with the wash.
+ uGain: { value: bright ? 0.24 : 0.62 },
+ },
+ varyings: 'varying vec3 vDir;',
+ vertexMain: ' vDir = normalize(position);',
+ fragmentHead: 'uniform vec3 uPole; uniform vec3 uAxisA;'
+ + ' uniform vec3 uAxisB; uniform vec3 uCore;'
+ + ' uniform vec3 uArm; uniform vec3 uHub;'
+ + ' uniform float uGain;',
+ fragmentMain: [
+ ' vec3 d = normalize(vDir);',
+ ' float s = dot(d, uPole);',
+ ' float band = exp(-(s * s) / 0.032);',
+ // 7.0, not 3.2: at the coarse scale one lobe of the noise
+ // spanned tens of degrees and the band arrived as a bank of
+ // grey FOG. The band is unresolved STARS — its texture has
+ // to be finer than the shape it fills.
+ ' vec2 p = vec2(dot(d, uAxisA), dot(d, uAxisB)) * 7.0;',
+ ' float n = astraFbm2(p + vec2(s * 6.0, 0.0), 4);',
+ // Dark lanes are dust in front of the band, so they CUT it
+ // rather than tinting it; a smooth gaussian is a smear.
+ ' float lanes = smoothstep(0.26, 0.72, n);',
+ // A second field finer again: star clouds INSIDE the arms.
+ // One scale of noise is a smear at any contrast.
+ ' float fine = astraFbm2(p * 2.9 + vec2(11.0, s * 4.0), 3);',
+ ' lanes *= 0.34 + 1.05 * fine;',
+ // The Great Rift: dust lying IN the plane, so it splits the
+ // band down its own spine instead of dimming it evenly.
+ // Without it the brightest pixel is the exact centre line,
+ // which is the one place the real band is darkest.
+ ' float spine = abs(s + (astraNoise2(p * 0.35) - 0.5) * 0.05);',
+ ' float rift = smoothstep(0.05, 0.17, spine);',
+ ' float bulge = exp(-pow(1.0 - dot(d, uCore), 2.0) / 0.09);',
+ ' float a = band * (0.10 + 1.15 * lanes)',
+ ' * (0.55 + 1.15 * bulge) * mix(0.30, 1.0, rift) * uGain',
+ // Extinction is a LONG ramp. Ending it at 0.12 put the
+ // whole fade inside the sky a level camera actually frames,
+ // and drew a straight horizontal edge across the band.
+ ' * smoothstep(-0.03, 0.26, d.y);',
+ // Warm hub, cool arms, and the star clouds carry the mix so
+ // the band has warm and cold patches instead of one tint.
+ ' vec3 c = mix(uArm, uHub,',
+ ' clamp(bulge * 0.8 + (fine - 0.42) * 1.1, 0.0, 1.0));',
+ // Sub-LSB dither: a veil this smooth bands into visible
+ // contour rings on an 8-bit frame.
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',
+ ' if (a < 0.003) discard;',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ // 3dcv: no-fog — see StarField.
+ fog: false,
+ side: THREE.BackSide,
+ blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,
+ transparent: true,
+ depthWrite: false,
+ });
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'MilkyWayStars';
+ mesh.renderOrder = ORDER_MILKYWAY;
+ return mesh;
+}
+
+/**
+ * The vertical emission profile of one curtain, bottom edge to top.
+ *
+ * An aurora is brightest at its LOWER BORDER, where the electrons
+ * finally stop, and fades up the column — a curtain lit evenly, or
+ * lit at the top, is the tell. Baked per vertex so the profile is
+ * data the CPU owns rather than a constant buried in GLSL.
+ */
+function auroraGlow(v) {
+ const rim = 0.35 + 0.65 * Math.exp(-v * 16);
+ const k = 1 - Math.min(1, Math.max(0, (v - 0.72) / 0.28));
+ return rim * Math.exp(-v * 2.3) * k * k * (3 - 2 * k);
+}
+
+/**
+ * Curtains of light: vertical rays, folding, brightest along the foot.
+ *
+ * Built as ribbons, not sheets of one brightness: each carries a baked
+ * `aGlow` profile that falls from its bottom edge upward, the rays run
+ * across it as antialiased strokes, and the folds brighten where they
+ * turn edge-on because a sheet's chord through the eye grows there —
+ * that edge-on flare is what makes an aurora read as a hanging curtain
+ * instead of a painted band.
+ *
+ * The mesh is named `AuroraSkyCurtains`: the scene renderer excludes
+ * sky envelopes from its content fit by the token `sky` in a mesh
+ * name, and a 1.4 km curtain that misses it becomes the content bbox.
+ *
+ * @param {object} [opts]
+ * `radius` metres from the origin to the curtain band (default 1400
+ * — inside `makeStars`'s 2 km sphere); `height` metres of curtain
+ * (default 400); the foot hangs at `radius * 0.30`, so translate the
+ * group in Y to raise or lower the display; `color` the main
+ * emission (default 0x54ffa8, the 557.7 nm oxygen green — the rim
+ * reddens and the top goes violet on their own); `activity` 0..1
+ * (default 0.5) driving how many curtains there are, how hard they
+ * fold and how fast they drift; `seed` PRNG seed (default 9);
+ * `ambient` how bright the frame behind is, 0 a real night to 1
+ * daylight (default 0.2) — see `makeStars`; pass `ambient: 0.9` when
+ * the sky behind is genuinely bright.
+ *
+ * The curtains are laid one per equal slice of the compass, jittered
+ * inside it, so a display always crosses whatever the camera is looking
+ * at — n independent draws leave holes a hundred degrees wide.
+ * @returns {THREE.Group} Named `Aurora`, with `userData.tick(t)`.
+ */
+export function makeAurora(opts = {}) {
+ const radius = opts.radius === undefined ? 1400 : opts.radius;
+ const height = opts.height === undefined ? 400 : opts.height;
+ const activity = Math.min(Math.max(
+ opts.activity === undefined ? 0.5 : opts.activity, 0), 1);
+ const seed = opts.seed === undefined ? 9 : opts.seed;
+ // 0.2 for the same reason as `makeStars`: an aurora is a night
+ // effect, and the daylight-safe blend rendered nothing here.
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.2 : opts.ambient, 0), 1);
+ const bright = ambient >= 0.35;
+ const color = opts.color
+ ? new THREE.Color(opts.color) : new THREE.Color(0x54ffa8);
+ const rnd = prng(seed);
+ const n = 3 + Math.round(activity * 4);
+ const base = radius * 0.30;
+ const swing = radius * (0.02 + 0.10 * activity);
+
+ const geom = curtainGeometry(n, rnd, radius, base, height, activity);
+ // The vertex stage folds the ribbon after the sphere is computed,
+ // so the stated one has to allow for the whole swing or the band
+ // is culled the moment a fold carries it past the edge.
+ geom.boundingSphere.radius += swing;
+ const mesh = new THREE.Mesh(
+ geom, auroraMaterial(color, activity, swing, bright));
+ mesh.name = 'AuroraSkyCurtains';
+ mesh.renderOrder = ORDER_AURORA;
+
+ const g = new THREE.Group();
+ g.name = 'Aurora';
+ g.add(mesh);
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/** All curtains in one ribbon geometry, tagged by `aCurtain`. */
+function curtainGeometry(n, rnd, radius, base, height, activity) {
+ const nu = 72, nv = 20;
+ const pos = [], uv = [], glow = [], tag = [], idx = [];
+ for (let c = 0; c < n; c++) {
+ // STRATIFIED, not random: n independent draws clump, and a
+ // measured one (seed 11, n = 5) left a 100-degree hole that a
+ // camera looking into it saw an empty sky through. The real
+ // auroral oval is an ARC across the whole sky, so one curtain
+ // per equal slice — jittered inside it — is both truer and the
+ // only version that cannot miss the frame entirely.
+ const slice = (Math.PI * 2) / n;
+ const a0 = (c + rnd()) * slice;
+ // A curtain covers PART of its slice. The span was an absolute
+ // arc, so five of them at this activity ran shoulder to
+ // shoulder all the way round and the display rendered as one
+ // unbroken wall of bars. Measured against the slice it always
+ // leaves sky between the curtains, which is the difference
+ // between a display and a fence.
+ const span = slice * (0.34 + 0.30 * rnd()) * (0.75 + 0.5 * activity);
+ const bow = (0.08 + 0.22 * rnd()) * radius;
+ const ph = rnd() * Math.PI * 2;
+ const first = pos.length / 3;
+ for (let j = 0; j <= nv; j++) {
+ // v packed toward the foot: the bright rim is a tenth of
+ // the column and an even ladder smears it into a gradient.
+ const v = Math.pow(j / nv, 1.7);
+ const y = base + height * v;
+ const gl = auroraGlow(v);
+ for (let i = 0; i <= nu; i++) {
+ const u = i / nu;
+ const a = a0 + (u - 0.5) * span;
+ // Two beats of bow: one arc is a fence, two make the
+ // hairpin folds a curtain actually hangs in.
+ const r = radius
+ + bow * Math.sin(u * 6.2831853 * 1.5 + ph)
+ + bow * 0.45 * Math.sin(u * 6.2831853 * 3.7 + ph * 2.1);
+ pos.push(Math.cos(a) * r, y, Math.sin(a) * r);
+ uv.push(u, v);
+ glow.push(gl);
+ tag.push((c + 0.5) / n, radius * span);
+ }
+ }
+ for (let j = 0; j < nv; j++) {
+ for (let i = 0; i < nu; i++) {
+ const p = first + j * (nu + 1) + i;
+ idx.push(p, p + nu + 1, p + 1,
+ p + 1, p + nu + 1, p + nu + 2);
+ }
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setAttribute('aGlow', new THREE.Float32BufferAttribute(glow, 1));
+ g.setAttribute('aCurtain', new THREE.Float32BufferAttribute(tag, 2));
+ g.setIndex(idx);
+ g.computeVertexNormals();
+ g.computeBoundingSphere();
+ return g;
+}
+
+function auroraMaterial(color, activity, swing, bright) {
+ const tint = bright ? color.clone().lerp(new THREE.Color(0xffffff),
+ 0.45) : color.clone();
+ return makeShaderMaterial({
+ name: 'Aurora',
+ uniforms: {
+ uColor: { value: tint },
+ uRim: { value: new THREE.Color(0xff5f9e) },
+ // Green -> TEAL -> violet, in two stops. Mixing 557.7 nm
+ // green straight to violet passes through grey at the
+ // halfway point, and a grey band up the middle of a curtain
+ // is exactly the wash this was showing.
+ uMid: { value: new THREE.Color(0x3ce6b0) },
+ uTop: { value: new THREE.Color(0xa855e8) },
+ uSwing: { value: swing },
+ uDrift: { value: 0.03 + 0.09 * activity },
+ uRays: { value: 26 + 34 * activity },
+ uGain: { value: bright ? 0.30 : 0.85 },
+ // The ceiling matters more than the gain. ACES desaturates
+ // as it rolls off, so a curtain allowed to reach alpha 1
+ // arrives WHITE — measured: 2.1% of the frame clipped past
+ // 0.97 and the green gone. Held here, the same curtain
+ // stays inside the part of the curve that keeps its hue.
+ uPeak: { value: bright ? 0.26 : 0.50 },
+ },
+ varyings: 'varying vec2 vUv; varying float vGlow;'
+ + ' varying vec3 vN; varying vec3 vW; varying float vTag;',
+ vertexHead: [
+ 'attribute float aGlow;',
+ 'attribute vec2 aCurtain;',
+ 'uniform float uSwing; uniform float uDrift;',
+ // One fold field, sampled twice so the shading normal can
+ // follow the fold instead of the flat ribbon it left.
+ 'float astraCelFold(float u, float tag) {',
+ ' return (astraFbm2(vec2(u * 2.6 + tag * 17.0,',
+ ' uTime * uDrift), 3) - 0.5) * uSwing;',
+ '}',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv;',
+ ' vGlow = aGlow;',
+ ' vTag = aCurtain.x;',
+ ' vec3 nrm = normalize(normal);',
+ ' float f0 = astraCelFold(uv.x, aCurtain.x);',
+ ' float f1 = astraCelFold(uv.x + 0.02, aCurtain.x);',
+ ' transformed += nrm * f0;',
+ ' vec3 tg = normalize(cross(vec3(0.0, 1.0, 0.0), nrm));',
+ ' float slope = (f1 - f0) / max(0.02 * aCurtain.y, 1e-3);',
+ ' vN = normalize(mat3(modelMatrix)',
+ ' * normalize(nrm - tg * slope));',
+ ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uRim;'
+ + ' uniform vec3 uMid; uniform vec3 uTop; uniform float uRays;'
+ + ' uniform float uDrift; uniform float uGain;'
+ + ' uniform float uPeak;',
+ fragmentMain: [
+ ' float v = vUv.y;',
+ ' float x = vUv.x * uRays + vTag * 23.0 + uTime * uDrift;',
+ // Rays are strokes, not a sine: astraStroke antialiases by
+ // its own gradient and dissolves once a filament is finer
+ // than a pixel, which is what stops the shimmer crawling.
+ // The floor is 0.10, not 0.30: at 0.30 the gaps between
+ // filaments never went dark and the foot of the curtain
+ // rendered as one solid wall of light.
+ // Each filament its own width, or the curtain is a printed
+ // barcode: real rays run from a hairline to a hand's
+ // breadth inside one display.
+ ' float w = 0.085 + 0.115 * astraHash11(floor(x) * 0.37 + 2.0);',
+ ' float ray = 0.10 + 1.05 * astraStroke(x, w);',
+ ' ray *= 0.45 + 0.85 * astraNoise2(vec2(floor(x) * 0.71,',
+ ' uTime * 0.06 + vTag * 5.0));',
+ ' vec3 eye = normalize(cameraPosition - vW);',
+ // A sheet is thin: the eye cuts a LONGER chord through it
+ // edge-on, so a fold turning away flares instead of
+ // vanishing. Clamped, or the silhouette divides by zero.
+ ' float chord = 1.0 / max(astraFacing(vN, eye), 0.46);',
+ ' float ends = smoothstep(0.0, 0.10, vUv.x)',
+ ' * (1.0 - smoothstep(0.90, 1.0, vUv.x));',
+ ' float a = vGlow * ray * chord * ends * uGain;',
+ // Saturating toward uPeak rather than toward 1: same slope
+ // where the curtain is faint, a hard hue-preserving ceiling
+ // where a fold turns edge-on.
+ ' a = uPeak * (1.0 - exp(-a * 2.1));',
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',
+ ' if (a < 0.003) discard;',
+ // The green body owns most of the column. Ramping to the
+ // cool stop from v = 0.05 turned the whole LOWER half —
+ // the half a level camera ever frames — teal, and 557.7 nm
+ // green is the one colour that says aurora.
+ ' vec3 c = mix(uColor, uMid, smoothstep(0.22, 0.68, v));',
+ ' c = mix(c, uTop, smoothstep(0.62, 0.98, v));',
+ // The lower border is where the electrons stop and the
+ // nitrogen answers in magenta — the one warm note in the
+ // whole display, and the thing that dates a fake aurora.
+ ' c = mix(c, uRim, (1.0 - smoothstep(0.0, 0.075, v)) * 0.72);',
+ // No two curtains in one display are the same green. One
+ // hash per curtain, so the tint is stable in time and the
+ // band never reads as a single printed colour.
+ ' float hj = astraHash11(vTag * 13.7 + 4.0);',
+ ' c *= mix(vec3(1.14, 0.98, 0.76), vec3(0.76, 1.0, 1.20), hj);',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ // 3dcv: no-fog — the curtain hangs a kilometre out, past
+ // every scene fog density this engine sets.
+ fog: false,
+ side: THREE.DoubleSide,
+ blending: bright ? THREE.NormalBlending : THREE.AdditiveBlending,
+ transparent: true,
+ depthWrite: false,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/cloth.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/cloth.js
new file mode 100644
index 00000000..6185591d
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/cloth.js
@@ -0,0 +1,1028 @@
+/**
+ * Cloth and crop: the three things in a scene that show the wind
+ * INSTEAD OF being shown by it.
+ *
+ * Each of the three fails the same way when it is written as "a sine
+ * over the surface", and each fails differently:
+ *
+ * `makeFlag` — the wave has to TRAVEL from the mast to the fly and
+ * GROW as it goes. Amplitude is pinned to zero along the attachment
+ * and largest at the free edge, so the eye reads a sheet held at one
+ * end. A sine over the whole sheet is a rippling billboard: it has
+ * no attachment, so it reads as a screen playing a video of cloth.
+ *
+ * `makeBanner` — a cloth hung along its TOP edge does not flap, it
+ * SWINGS, at the pendulum rate its own drop sets (sqrt(g/drop), so a
+ * long curtain is slower than a short one), and it gathers into fold
+ * lines that run DOWN from the hanging edge. Flap it like a flag and
+ * a heavy curtain reads as a sheet of paper.
+ *
+ * `makeWheatField` — the subject is the WAVE crossing the field, not
+ * the stalk. The gust field is shared by every stalk and travels
+ * downwind at a stated m/s, so neighbours move together with the lag
+ * between them; per-stalk motion is a tenth of it, the texture that
+ * makes the wave visible. Give every stalk its own phase — as grass
+ * does, correctly, at grass's scale — and a hectare of wheat boils
+ * instead of rippling.
+ *
+ * Which sibling do you want?
+ * `grass.js` — ankle-high ground cover, clumped, per-blade phase; the
+ * ground itself needs covering.
+ * `smalllife.js` makeReeds — waterline stand, rooted on a bed, the
+ * bend BREAKING at the surface.
+ * `flowers.js` — colour above the grass, nodding heads.
+ * here — a crop: chest-high, sown in DRILL ROWS, one shared wave.
+ *
+ * All three take grass.js's `wind` (its `windOf` is imported, never
+ * re-read), so one scene's meadow, its wheat and its flags move as one
+ * wind. All three are deterministic in `seed`, and all three need
+ * driving from your `tick()` — `obj.userData.tick(t)` — or the wind
+ * never blows.
+ */
+
+import * as THREE from 'three';
+
+import { windOf } from './grass.js';
+import { mulberry32 } from './noise.js';
+import { patchStandard, shadowLike, tickShaders } from './shader.js';
+
+const _TAU = Math.PI * 2;
+const _G = 9.81;
+// Rows up a stalk, and where its ear starts. The ear is a fifth of the
+// stalk and takes nearly half the rows, because that is where the bend
+// turns hardest; fatter or longer and the crop reads as pennants.
+const _STALK_ROWS = 7;
+const _STEM_ROWS = 4;
+const _EAR_AT = 0.8;
+// Tileable modes of the gust field. Integer frequencies only: the
+// field scrolls downwind forever, so a seam would cross the crop.
+const _WAVE_MODES = [
+ [1, 0], [0, 1], [1, 1], [1, -1], [2, 1], [1, 2],
+ [2, -1], [2, 2], [3, 1], [1, 3], [3, 2], [2, 3],
+];
+
+/** Clamp to 0..1 without importing MathUtils for a handful of calls. */
+function clamp01(v) {
+ return Math.max(0, Math.min(1, v));
+}
+
+/**
+ * Rotations about Y that send local +X (or +Z) to a world XZ heading.
+ *
+ * Both sheets are authored with the wind along one local axis and
+ * turned by this, so their GLSL never has to carry a wind vector: the
+ * flag flies along its own +X, the banner swings along its own +Z.
+ */
+function yawToX(dir) {
+ return Math.atan2(-dir.y, dir.x);
+}
+
+function yawToZ(dir) {
+ return Math.atan2(dir.x, dir.y);
+}
+
+/**
+ * A flag on a mast, whose wave travels out to the fly and grows.
+ *
+ * Buys the cue that says "held at one edge": the amplitude envelope is
+ * a per-vertex attribute pinned to 0 along the hoist and rising to 1
+ * at the fly, and the phase runs `k*u - rate*t`, so crests LEAVE the
+ * mast. Chord length is conserved as the sheet ripples (the fly is
+ * pulled back by the integral of its own slope), or a flapping flag
+ * grows visibly longer than its own cloth.
+ *
+ * The constraint: the mast rests on y = 0 and the sheet hangs from its
+ * top, so the group can be dropped straight onto ground; and the
+ * stated bounding sphere covers the sheet's full excursion, because
+ * the wave lives in the vertex shader and three culls on the sphere.
+ *
+ * @param {object} [opts]
+ * `width` chord of the sheet in metres, mast to fly (default 1.6);
+ * `height` hoist height of the sheet (default 1.0); `mast` mast
+ * height in metres (default 6, 0 for no mast at all — a flag already
+ * hung on someone else's pole); `wind` grass.js's option, a strength
+ * multiplier or `{dir, strength, speed}` with `dir` the direction it
+ * BLOWS TOWARD over world XZ — the flag flies that way; `color`
+ * cloth albedo (default a flag red); `seed` PRNG seed (default 11);
+ * `name` group name.
+ * @returns {THREE.Group} Named `Flag`, resting on y = 0, holding
+ * `Mast` and a `FlagSheet` whose ripple is one patched material,
+ * with `userData.tick(t)` driving it.
+ */
+export function makeFlag(opts = {}) {
+ const width = opts.width === undefined ? 1.6 : opts.width;
+ const height = opts.height === undefined ? 1.0 : opts.height;
+ const mast = opts.mast === undefined ? 6 : opts.mast;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const wind = windOf(opts.wind);
+ const rand = mulberry32(seed);
+ // Albedo, not a screen colour: a scene sun runs at 5-6, so a hex
+ // that already looks like sunlit bunting tone-maps to pale card.
+ // A dye, and a dye has a blue channel: at 0x8e2b28 the green and the
+ // blue sit at 0.024 and 0.021 in linear, so every part of the sheet
+ // the sun misses tone-maps to a black-red hole. This reads the same
+ // red in the light and still has cloth in it in the shade.
+ const color = new THREE.Color(
+ opts.color === undefined ? 0x9b3630 : opts.color);
+
+ const g = new THREE.Group();
+ g.name = opts.name || 'Flag';
+ const rad = Math.max(0.018, Math.min(0.05, height * 0.045));
+ if (mast > 0) g.add(mastPole(mast, rad));
+ const fly = new THREE.Group();
+ fly.name = 'FlagFly';
+ fly.position.y = Math.max(mast, height + 0.05);
+ fly.rotation.y = yawToX(wind.dir);
+ fly.add(flagSheet(width, height, rad, color, wind, rand));
+ g.add(fly);
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/** The pole, tapered and capped so it is not a bare cylinder. */
+function mastPole(mast, rad) {
+ const geom = new THREE.CylinderGeometry(rad * 0.72, rad, mast, 10, 1);
+ geom.translate(0, mast / 2, 0);
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xb8b3a6, roughness: 0.45, metalness: 0.65, name: 'FlagMast',
+ });
+ const pole = new THREE.Mesh(geom, mat);
+ pole.name = 'Mast';
+ pole.castShadow = true;
+ pole.receiveShadow = true;
+ const cap = new THREE.Mesh(
+ new THREE.SphereGeometry(rad * 1.7, 10, 8), mat);
+ cap.name = 'MastFinial';
+ cap.position.y = mast;
+ cap.castShadow = true;
+ pole.add(cap);
+ return pole;
+}
+
+/**
+ * The sheet: one plane whose envelope is CPU data, not GLSL.
+ *
+ * `aFlag` carries (u along the chord, the amplitude envelope, its
+ * derivative for the normal, the integral of its square for the chord
+ * shortening). Keeping the envelope on the CPU is what lets a test
+ * read "pinned at the mast, free at the fly" as a number instead of
+ * trusting a claim about a shader.
+ */
+function flagSheet(width, height, rad, color, wind, rand) {
+ const segX = Math.max(24, Math.min(96, Math.round(width * 40)));
+ const segY = Math.max(8, Math.min(48, Math.round(height * 20)));
+ const geom = new THREE.PlaneGeometry(width, height, segX, segY);
+ geom.translate(width / 2 + rad, -height / 2, 0);
+ const pos = geom.attributes.position;
+ const env = new Float32Array(pos.count * 4);
+ for (let i = 0; i < pos.count; i++) {
+ const u = clamp01((pos.getX(i) - rad) / Math.max(width, 1e-6));
+ // u^1.6, not u: a linear envelope reads as a sheet hinged at the
+ // mast, and the growth toward the fly is the whole cue.
+ env[i * 4] = u;
+ env[i * 4 + 1] = Math.pow(u, 1.6);
+ env[i * 4 + 2] = 1.6 * Math.pow(u, 0.6);
+ env[i * 4 + 3] = Math.pow(u, 4.2) / 4.2;
+ }
+ geom.setAttribute('aFlag', new THREE.BufferAttribute(env, 4));
+
+ const waves = Math.max(0.9, Math.min(3, 1.15 * width / Math.max(
+ height, 1e-3)));
+ const k = _TAU * waves;
+ const amp = width * 0.22 * wind.amp;
+ const rate = 11 * wind.speed;
+ // A slack flag hangs; a taut one flies. Both are the same cloth, so
+ // the droop is what `strength` buys back.
+ const sag = height * 0.30 / (1 + 4.4 * wind.amp);
+ const shrink = amp * amp * k * k / (4 * Math.max(width, 1e-6));
+ const mat = new THREE.MeshStandardMaterial({
+ color, roughness: 0.86, metalness: 0, side: THREE.DoubleSide,
+ name: 'FlagCloth',
+ });
+ const head = [
+ 'uniform float uFlagAmp;',
+ 'uniform float uFlagK;',
+ 'uniform float uFlagRate;',
+ 'uniform float uFlagTilt;',
+ 'uniform float uFlagSag;',
+ 'uniform float uFlagShrink;',
+ 'uniform float uFlagMaxShrink;',
+ 'uniform float uFlagWidth;',
+ 'uniform float uFlagPhase;',
+ 'attribute vec4 aFlag;',
+ 'varying vec4 vFlag;',
+ ].join('\n');
+ patchStandard(mat, {
+ name: 'cloth:flag',
+ uniforms: {
+ uFlagAmp: { value: amp },
+ uFlagK: { value: k },
+ uFlagRate: { value: rate },
+ uFlagTilt: { value: 0.9 / Math.max(height, 1e-3) },
+ uFlagSag: { value: sag },
+ uFlagShrink: { value: shrink },
+ uFlagMaxShrink: { value: width * 0.25 },
+ uFlagWidth: { value: width },
+ uFlagPhase: { value: rand() * _TAU },
+ // Threads per SHEET, at 300 to the metre and 0.06 wide — thin
+ // enough that astraStroke drops them once a pixel spans one,
+ // which is every distance but a hand's breadth away.
+ uFlagWeave: { value: new THREE.Vector2(width, height)
+ .multiplyScalar(300) },
+ // Cloth is fuzzy, so a sheet turning away from the eye catches
+ // the sky along its own curve instead of ending in an ink edge.
+ // The facing term is computed per vertex, where the wave's
+ // normal already is; the fragment only spends it.
+ uFlagSheen: { value: 0.85 },
+ // Years on a pole: a flag fades from the FLY inward, because the
+ // hoist spends its life rolled around the rope.
+ uFlagFade: { value: 0.42 },
+ // Radians of dye swing across the sheet, warm to cool. Dyed
+ // cloth is never one value, and one value is what reads plastic.
+ uFlagDye: { value: 0.6 },
+ },
+ vertexHead: head,
+ vertexBody: FLAG_MOVE + '\n' + FLAG_NORMAL,
+ fragmentHead: [
+ 'uniform vec2 uFlagWeave;',
+ 'uniform float uFlagSheen;',
+ 'uniform float uFlagFade;',
+ 'uniform float uFlagDye;',
+ 'varying vec4 vFlag;',
+ ].join('\n'),
+ fragmentBody: FLAG_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'FlagSheet';
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ shadowLike(mesh, 'cloth:flagDepth', head, FLAG_MOVE);
+ // The wave lives in the vertex shader, so the derived bounds are the
+ // FLAT sheet's and three would cull the flag on a box it leaves.
+ const reach = amp * 1.42;
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(rad - 0.02, -height - sag, -reach),
+ new THREE.Vector3(rad + width + 0.02, 0.02, reach));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(
+ new THREE.Sphere());
+ return mesh;
+}
+
+const FLAG_MOVE = [
+ ' float flU = aFlag.x;',
+ // The phase runs k*u - rate*t, so a crest LEAVES the mast; the tilt
+ // term keeps the crest off the vertical, as a real fly is.
+ ' float flPh = uFlagK * flU - uFlagRate * uTime + uFlagPhase',
+ ' + uFlagTilt * transformed.y;',
+ ' float flS = sin(flPh) + 0.42 * sin(1.7 * flPh + 1.3);',
+ ' float flD = cos(flPh) + 0.714 * cos(1.7 * flPh + 1.3);',
+ ' float flZ = uFlagAmp * aFlag.y * flS;',
+ // Cloth does not stretch: a rippled chord has to give back the
+ // length its own slope spends, or the fly grows as the wind rises.
+ ' float flBack = min(uFlagShrink * aFlag.w, uFlagMaxShrink);',
+ ' transformed.x -= flBack;',
+ ' transformed.y -= uFlagSag * aFlag.y;',
+ ' transformed.z += flZ;',
+ // .w is the facing term the sheen spends; the depth pass is
+ // FLAT_SHADED and never fills it, so it starts at "square on".
+ ' vFlag = vec4(flU, uv.y, flS, 1.0);',
+].join('\n');
+
+const FLAG_NORMAL = [
+ '#ifndef FLAT_SHADED',
+ ' float flZx = uFlagAmp * (aFlag.z * flS + aFlag.y * flD * uFlagK)',
+ ' / max(uFlagWidth, 1e-4);',
+ ' float flZy = uFlagAmp * aFlag.y * flD * uFlagTilt;',
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' vec3(-flZx, -flZy, 1.0)));',
+ // Both in VIEW space, so a scaled or rotated flag needs no basis of
+ // its own: 1 square on to the eye, 0 edge-on.
+ ' vec4 flMv = modelViewMatrix * vec4(transformed, 1.0);',
+ ' vFlag.w = astraFacing(vNormal, -flMv.xyz);',
+ '#endif',
+].join('\n');
+
+const FLAG_FRAGMENT = [
+ // Dyed cloth is never one hex. A slow warm/cool break across the
+ // SHEET's own coordinates — so it travels with the cloth rather than
+ // swimming through it — is the difference between bunting and a
+ // painted panel, and it costs one fbm.
+ ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb,',
+ ' vec2(vFlag.x * 2.6, vFlag.y * 1.7), 1.0, uFlagDye);',
+ // Warp and weft, not a wash — and gone before either can alias.
+ ' float flW = astraStroke(vFlag.y * uFlagWeave.y, 0.06)',
+ ' + astraStroke(vFlag.x * uFlagWeave.x, 0.06);',
+ ' diffuseColor.rgb *= 0.94 + 0.10 * flW;',
+ // The hoist is doubled cloth over a rope, so it is darker and
+ // slightly duller than the field of the flag.
+ ' diffuseColor.rgb *= 1.0 - 0.30 * (1.0 - smoothstep(0.0, 0.045,',
+ ' vFlag.x));',
+ // And the FLY is the end that has flown: sun and weather take the
+ // dye out of it, which lightens and desaturates rather than fading
+ // to grey. Without this a flag is uniformly new, and nothing in a
+ // scene is uniformly new.
+ ' float flOld = uFlagFade * smoothstep(0.30, 1.0, vFlag.x);',
+ ' float flLum = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb,',
+ ' mix(diffuseColor.rgb, vec3(flLum), 0.5) * 1.30, flOld);',
+ // Crests catch the sky and troughs hold shade: this is what makes
+ // the travelling wave read in flat light as well as in sun. The
+ // swing carries HUE too — a crest is turned to a blue sky and a
+ // trough sees only the warm bounce off the cloth beside it.
+ ' float flC = clamp(vFlag.z * 0.5 + 0.5, 0.0, 1.0);',
+ ' diffuseColor.rgb *= 0.84 + 0.26 * flC;',
+ ' diffuseColor.rgb = astraHueShift(diffuseColor.rgb,',
+ ' (flC - 0.5) * 0.17);',
+ // Cloth fuzz: the pile stands off the weave, so a sheet turning away
+ // lights along its own curve instead of ending in an ink edge. This
+ // is the cue that separates cloth from sheet metal in one frame.
+ ' float flGrz = 1.0 - clamp(vFlag.w, 0.0, 1.0);',
+ ' diffuseColor.rgb *= 1.0 + uFlagSheen * flGrz * flGrz * flGrz;',
+].join('\n');
+
+/**
+ * A cloth banner or curtain hung along its top edge.
+ *
+ * Buys the cue that says "hung, and heavy": the whole sheet swings as
+ * a PENDULUM about its top edge at sqrt(g / drop) rad/s — a 4 m
+ * curtain is visibly slower than a 1 m one — and it gathers into fold
+ * lines that run straight DOWN from the hanging edge, pinched at the
+ * rod and opening toward the hem. Nothing flaps: a hung cloth that
+ * flaps like a flag reads as paper.
+ *
+ * The constraint: the fold profile is a function of x ALONE, held in a
+ * per-vertex attribute, so the folds cannot drift into diagonal
+ * ripples; and the swing is a rigid rotation about the top edge, so
+ * the cloth swings without growing.
+ *
+ * @param {object} [opts]
+ * `width` metres across (default 2); `drop` metres from the hanging
+ * edge to the hem (default 3); `hang` height of the hanging edge
+ * above the group origin (default `drop`, which puts the hem on
+ * y = 0); `wind` grass.js's option — the banner leans and swings
+ * ALONG `dir`; `color` cloth albedo (default a banner crimson);
+ * `seed` PRNG seed (default 11); `rod` draw the rail it hangs from
+ * (default true); `folds` how many fold lines across the width
+ * (default 5); `name` group name.
+ * @returns {THREE.Group} Named `Banner`, holding `BannerCloth` and
+ * (unless declined) `BannerRod`, with `userData.tick(t)` driving the
+ * swing.
+ */
+export function makeBanner(opts = {}) {
+ const width = opts.width === undefined ? 2 : opts.width;
+ const drop = opts.drop === undefined ? 3 : opts.drop;
+ const hang = opts.hang === undefined ? drop : opts.hang;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const folds = Math.max(1, Math.round(
+ opts.folds === undefined ? 5 : opts.folds));
+ const wind = windOf(opts.wind);
+ const rand = mulberry32(seed);
+ // A curtain is the biggest flat area this library ships, and it
+ // usually hangs in its own shade: 0x7a2733 puts its green and blue
+ // at 0.019 and 0.032 linear, which is a black hole with a red rim.
+ // Same crimson, with cloth still in it where the sun is not.
+ const color = new THREE.Color(
+ opts.color === undefined ? 0x963a36 : opts.color);
+
+ const g = new THREE.Group();
+ g.name = opts.name || 'Banner';
+ const swing = new THREE.Group();
+ swing.name = 'BannerHang';
+ swing.position.y = hang;
+ // Local +Z is downwind, so the pendulum swings in the ZY plane and
+ // the fold lines stay square to the rod.
+ swing.rotation.y = yawToZ(wind.dir);
+ swing.add(bannerCloth(width, drop, folds, color, wind, rand));
+ if (opts.rod !== false) swing.add(bannerRod(width, drop));
+ g.add(swing);
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/** The rail: what makes "fixed along the top edge" visible. */
+function bannerRod(width, drop) {
+ const r = Math.max(0.012, Math.min(0.045, drop * 0.012));
+ const geom = new THREE.CylinderGeometry(r, r, width * 1.08, 10, 1);
+ geom.rotateZ(Math.PI / 2);
+ const mesh = new THREE.Mesh(geom, new THREE.MeshStandardMaterial({
+ color: 0x6a5a44, roughness: 0.6, metalness: 0.3, name: 'BannerRod',
+ }));
+ mesh.name = 'BannerRod';
+ mesh.position.y = r * 0.4;
+ mesh.castShadow = true;
+ return mesh;
+}
+
+/**
+ * The cloth: folds are CPU data indexed by x, swing is one angle.
+ *
+ * `aBan` carries (depth fraction from the rod, the fold profile at
+ * this x, its slope, the width the fold gathers). Every one of them is
+ * a function of x or of y ALONE, which is exactly the claim "the folds
+ * run down" — and a test can read it off the attribute.
+ */
+function bannerCloth(width, drop, folds, color, wind, rand) {
+ const segX = Math.max(24, Math.min(120, Math.round(width * 26)));
+ const segY = Math.max(10, Math.min(60, Math.round(drop * 12)));
+ const geom = new THREE.PlaneGeometry(width, drop, segX, segY);
+ geom.translate(0, -drop / 2, 0);
+ const prof = foldProfile(folds, rand);
+ const pos = geom.attributes.position;
+ const data = new Float32Array(pos.count * 4);
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i) / Math.max(width, 1e-6) + 0.5;
+ const f = prof(x);
+ data[i * 4] = clamp01(-pos.getY(i) / Math.max(drop, 1e-6));
+ data[i * 4 + 1] = f.v;
+ data[i * 4 + 2] = f.d / Math.max(width, 1e-6);
+ data[i * 4 + 3] = f.s;
+ }
+ geom.setAttribute('aBan', new THREE.BufferAttribute(data, 4));
+
+ // A fold is deep in proportion to its OWN spacing, never to the
+ // width: at a fifth of the spacing the cloth is already gathering
+ // back a tenth of its span, and past that it is a concertina.
+ const fold = Math.min(0.16 * width / folds, drop * 0.06);
+ // The pendulum a cloth of this drop actually is. Doubling the drop
+ // slows the swing by 1.41, which is the whole "heavy" cue.
+ const rate = Math.sqrt(_G / Math.max(drop, 0.05));
+ const lean = 0.55 * wind.amp;
+ const sway = 0.18 * wind.amp + 0.02;
+ const mat = new THREE.MeshStandardMaterial({
+ color, roughness: 0.9, metalness: 0, side: THREE.DoubleSide,
+ name: 'BannerClothMat',
+ });
+ patchStandard(mat, {
+ name: 'cloth:banner',
+ uniforms: {
+ uBanDrop: { value: drop },
+ uBanFold: { value: fold },
+ uBanShrink: { value: fold * fold / Math.max(width, 1e-6) },
+ uBanShrinkMax: { value: width * 0.15 },
+ uBanRate: { value: rate },
+ uBanLean: { value: lean },
+ uBanSway: { value: sway },
+ // The hem arrives after the rod: a cloth with no lag swings as
+ // one board, which is the paper look again.
+ uBanLag: { value: 0.85 },
+ uBanPhase: { value: rand() * _TAU },
+ // Threads across the SHEET at 300 to the metre: thin enough that
+ // astraStroke drops them before they can alias into moire.
+ uBanWeave: { value: width * 300 },
+ // Same three as the flag: the fuzz that lights a turning edge,
+ // the dye that is never one value, and the dust a hem stands in.
+ uBanSheen: { value: 0.75 },
+ uBanDye: { value: 0.38 },
+ uBanDust: { value: 0.40 },
+ },
+ vertexHead: BANNER_HEAD,
+ vertexBody: BANNER_MOVE + '\n' + BANNER_NORMAL,
+ fragmentHead: [
+ 'uniform float uBanWeave;',
+ 'uniform float uBanSheen;',
+ 'uniform float uBanDye;',
+ 'uniform float uBanDust;',
+ 'varying vec4 vBan;',
+ ].join('\n'),
+ fragmentBody: BANNER_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'BannerCloth';
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ shadowLike(mesh, 'cloth:bannerDepth', BANNER_HEAD, BANNER_MOVE);
+ // The hem can only RISE as the cloth swings (y = -drop * cos), so
+ // the box's floor is the drop itself and the asset still rests where
+ // the caller hung it.
+ const reach = drop * Math.sin(Math.min(lean + sway, 1.3)) + fold + 0.02;
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-width / 2 - fold, -drop, -fold - 0.02),
+ new THREE.Vector3(width / 2 + fold, 0.02, reach));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(
+ new THREE.Sphere());
+ return mesh;
+}
+
+/**
+ * The fold profile across the width: value, slope and gathered width.
+ *
+ * All three are functions of x ALONE, which is the whole claim "the
+ * fold lines run down". Seeded sines of integer frequency, so the
+ * profile is smooth and the count of fold lines is what `folds` says;
+ * the gathered width is the slope-squared integral, in units of the
+ * NORMALISED x the shader scales back to metres.
+ */
+function foldProfile(folds, rand) {
+ const modes = [];
+ let peak = 1e-6;
+ for (let i = 0; i < 3; i++) {
+ modes.push([folds + i, rand() * _TAU, 1 / (1 + i * 1.4)]);
+ }
+ const raw = (x) => {
+ let v = 0;
+ for (const [f, p, a] of modes) v += a * Math.sin(_TAU * f * x + p);
+ return v;
+ };
+ for (let i = 0; i <= 256; i++) peak = Math.max(peak, Math.abs(raw(i / 256)));
+ const slope = (x) => {
+ let d = 0;
+ for (const [f, p, a] of modes) {
+ d += a * _TAU * f * Math.cos(_TAU * f * x + p);
+ }
+ return d / peak;
+ };
+ // One pass of the slope integral, sampled once and reused: cheaper
+ // than integrating per vertex and identical for equal x.
+ const N = 512;
+ const cum = new Float32Array(N + 1);
+ for (let i = 1; i <= N; i++) {
+ const s = slope((i - 0.5) / N);
+ cum[i] = cum[i - 1] + 0.5 * s * s / N;
+ }
+ const mid = cum[N] / 2;
+ return (x) => {
+ const t = clamp01(x) * N;
+ const i = Math.min(N - 1, Math.floor(t));
+ const f = t - i;
+ return {
+ v: raw(clamp01(x)) / peak,
+ d: slope(clamp01(x)),
+ s: cum[i] + (cum[i + 1] - cum[i]) * f - mid,
+ };
+ };
+}
+
+const BANNER_HEAD = [
+ 'uniform float uBanDrop;',
+ 'uniform float uBanFold;',
+ 'uniform float uBanShrink;',
+ 'uniform float uBanShrinkMax;',
+ 'uniform float uBanRate;',
+ 'uniform float uBanLean;',
+ 'uniform float uBanSway;',
+ 'uniform float uBanLag;',
+ 'uniform float uBanPhase;',
+ 'attribute vec4 aBan;',
+ 'varying vec4 vBan;',
+].join('\n');
+
+const BANNER_MOVE = [
+ ' float bnS = aBan.x;',
+ // Folds open downward from the rod, where the cloth is nailed flat.
+ ' float bnE = bnS * (2.0 - bnS);',
+ ' float bnFold = uBanFold * aBan.y * bnE;',
+ // ONE angle for the whole cloth, at the drop\'s own pendulum rate,
+ // with the hem arriving after the rod.
+ ' float bnA = uBanLean + uBanSway * sin(uBanRate * uTime + uBanPhase',
+ ' - uBanLag * bnS);',
+ ' float bnC = cos(bnA), bnSi = sin(bnA);',
+ ' float bnD = uBanDrop * bnS;',
+ // Cloth pulled into a fold is cloth taken out of the span, so the
+ // banner narrows as its folds deepen instead of growing.
+ ' transformed.x -= clamp(uBanShrink * aBan.w * bnE * bnE,',
+ ' -uBanShrinkMax, uBanShrinkMax);',
+ ' transformed.y = -bnD * bnC;',
+ ' transformed.z = bnD * bnSi + bnFold;',
+ ' vBan = vec4(bnS, aBan.y, uv.x, 1.0);',
+].join('\n');
+
+const BANNER_NORMAL = [
+ '#ifndef FLAT_SHADED',
+ ' float bnZx = uBanFold * aBan.z * bnE;',
+ ' float bnZd = uBanFold * aBan.y * (2.0 - 2.0 * bnS)',
+ ' / max(uBanDrop, 1e-4);',
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' vec3(-bnZx * bnC, bnSi + bnZd, bnC)));',
+ // View space, as the flag's: 1 square on to the eye, 0 edge-on.
+ ' vec4 bnMv = modelViewMatrix * vec4(transformed, 1.0);',
+ ' vBan.w = astraFacing(vNormal, -bnMv.xyz);',
+ '#endif',
+].join('\n');
+
+const BANNER_FRAGMENT = [
+ // A hung cloth is the largest flat area this library draws, so it is
+ // the one that most needs its dye broken up: a slow warm/cool field
+ // across the width and down the drop, in the cloth's own frame.
+ ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb,',
+ ' vec2(vBan.z * 2.2, vBan.x * 1.6), 1.0, uBanDye);',
+ ' float bnW = astraStroke(vBan.z * uBanWeave, 0.06);',
+ ' diffuseColor.rgb *= 0.95 + 0.09 * bnW;',
+ // A fold holds shade in its trough and the light on its ridge, and
+ // the gradient DEEPENS downward as the fold opens. Hue follows the
+ // value: a trough sees only the sky, a ridge sees the sun.
+ ' float bnF = vBan.y * smoothstep(0.0, 0.6, vBan.x);',
+ ' diffuseColor.rgb *= 1.0 + 0.26 * bnF;',
+ ' diffuseColor.rgb = astraHueShift(diffuseColor.rgb, 0.13 * bnF);',
+ // A hem stands in dust, and dust GREYS cloth. Darkening alone leaves
+ // a dark dye reading as soot; this keeps the hem lighter than the
+ // shadow it sits in and still visibly dirtier than the rod.
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.20, 0.185, 0.16),',
+ ' uBanDust * smoothstep(0.42, 1.0, vBan.x));',
+ ' diffuseColor.rgb *= 1.03 - 0.10 * vBan.x;',
+ // Cloth fuzz at the turn of a fold — the same term the flag spends,
+ // and here it is what makes the folds read at all in flat light.
+ ' float bnGrz = 1.0 - clamp(vBan.w, 0.0, 1.0);',
+ ' diffuseColor.rgb *= 1.0 + uBanSheen * bnGrz * bnGrz * bnGrz;',
+].join('\n');
+
+/**
+ * A field of tall crop whose gusts cross it as visible waves.
+ *
+ * Buys the shot a meadow cannot give: a hectare of wheat with the wind
+ * running over it in long streaks, at a stated metres per second, so
+ * the field reads as weather rather than as animated scenery. Every
+ * stalk samples ONE gust field — a seeded, seamlessly tiling texture
+ * scrolled downwind at `uWheatMps` — so neighbours move together with
+ * the travel lag between them, and per-stalk wobble is a tenth of it.
+ *
+ * The constraint: this is a CROP, not tall grass. It is sown in drill
+ * rows at `rowGap`, so the field carries lines a meadow never has; the
+ * stalk is a bare stem with a heavy EAR that bends further than the
+ * stem does; and the wave is made visible by the pale flank a laid-
+ * over ear turns to the light, not by the bend alone. For ankle-high
+ * ground cover use `grass.js`; at a waterline use `makeReeds`.
+ *
+ * @param {object} [opts]
+ * `extent` metres of the square field's side (default 30, centred on
+ * the group origin); `density` stalks per square metre (default 70;
+ * `maxStalks` caps it by widening the DRILL spacing, never by
+ * dropping a corner); `height` stalk height in metres (default 1.1);
+ * `wind` grass.js's option — `speed` scales the wave's travel, which
+ * is `waveMps` metres per second; `color` straw albedo; `earColor`
+ * the ripe head; `heightAt` (x, z) => y, the caller's ground;
+ * `seed` PRNG seed (default 11); `rowGap` drill spacing in metres
+ * (default 0.18); `waveMps` crest travel at `wind.speed` 1 (default
+ * 7, about what a crop wave really runs at); `maxStalks` hard cap
+ * (default 70000); `shadows` cast stalk shadows through a displaced
+ * depth pass (default false — the same cost call grass.js makes);
+ * `name` group name.
+ * @returns {THREE.Group} Named `Wheat`, resting on y = 0 (or on
+ * `heightAt`), holding `Stalks` — ONE draw call — with
+ * `userData.tick(t)` driving the wave.
+ */
+export function makeWheatField(opts = {}) {
+ const extent = opts.extent === undefined ? 30 : opts.extent;
+ const density = opts.density === undefined ? 70 : opts.density;
+ const height = opts.height === undefined ? 1.1 : opts.height;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const rowGap = opts.rowGap === undefined ? 0.18 : opts.rowGap;
+ const maxStalks = opts.maxStalks === undefined ? 70000 : opts.maxStalks;
+ const waveMps = opts.waveMps === undefined ? 7 : opts.waveMps;
+ const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const wind = windOf(opts.wind);
+ const straw = new THREE.Color(
+ opts.color === undefined ? 0xa8863a : opts.color);
+ const ear = new THREE.Color(
+ opts.earColor === undefined ? 0xd2ad55 : opts.earColor);
+
+ const g = new THREE.Group();
+ g.name = opts.name || 'Wheat';
+ const field = sowField(
+ extent, density, rowGap, maxStalks, height, ground, seed);
+ g.add(stalkMesh(field, extent, straw, ear, wind, waveMps, seed,
+ opts.shadows === true));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/**
+ * Sow the field in DRILL ROWS — the cue no meadow has.
+ *
+ * A crop is planted by a machine: straight rows at a fixed gap, dense
+ * along the row, bare between. Scattering it like grass.js's clumps
+ * would make this library a taller copy of that one, and would lose
+ * the lines that tell a viewer the ground was worked.
+ */
+function sowField(extent, density, rowGap, maxStalks, height, ground,
+ seed) {
+ const rand = mulberry32(seed);
+ // The drill ran at some angle to the world; the wind does not know
+ // about it, which is what keeps the wave off the rows.
+ const ang = rand() * Math.PI;
+ const ux = Math.cos(ang), uz = Math.sin(ang);
+ const want = Math.max(1, Math.round(density * extent * extent));
+ // A cap widens the DRILL spacing, so a capped field is thinner and
+ // never smaller than the extent it advertises.
+ const scale = Math.sqrt(Math.max(1, want / maxStalks));
+ const gap = rowGap * scale;
+ const step = scale / Math.max(density * rowGap, 1e-3);
+ const span = extent * 0.71 + gap;
+ const rows = Math.floor(span / Math.max(gap, 1e-3));
+ const along = Math.floor(span / Math.max(step, 1e-3));
+ const half = extent / 2;
+ const pos = [], crop = [], vary = [];
+ let n = 0, maxH = 0, low = Infinity, high = -Infinity;
+ for (let r = -rows; r <= rows && n < maxStalks; r++) {
+ for (let s = -along; s <= along && n < maxStalks; s++) {
+ const a = s * step + (rand() - 0.5) * step * 0.8;
+ const b = r * gap + (rand() - 0.5) * gap * 0.45;
+ const x = ux * a - uz * b;
+ const z = uz * a + ux * b;
+ if (x < -half || x > half || z < -half || z > half) continue;
+ const y = ground ? ground(x, z) : 0;
+ const h = height * (0.82 + 0.30 * rand());
+ pos.push(x, y, z);
+ // A taller stalk is a longer lever on the same stem, so it lays
+ // over further in the same gust.
+ crop.push(h, h * (0.0032 + 0.0016 * rand()), _EAR_AT,
+ (0.72 + 0.34 * rand()) * (0.7 + 0.5 * h / height));
+ vary.push(rand(), (rand() - 0.5) * 0.5, (rand() - 0.5) * 0.36);
+ maxH = Math.max(maxH, h);
+ low = Math.min(low, y);
+ high = Math.max(high, y + h);
+ n++;
+ }
+ }
+ return { n, pos, crop, vary, maxH,
+ low: n ? low : 0, high: n ? high : 0 };
+}
+
+/**
+ * The gust field, baked once on the CPU so both sides agree on it.
+ *
+ * grass.js builds its gusts from GLSL_UTIL's noise, which takes no
+ * seed — every grass field in every scene gusts identically, and no
+ * test can read what the shader will see. A tiling texture fixes both:
+ * it is seeded, and the exact numbers the vertex shader samples are
+ * readable from `uniforms.uWheatWave.value.image.data`.
+ *
+ * @param {number} seed PRNG seed.
+ * @param {number} [size] Texels per side (default 128).
+ * @returns {THREE.DataTexture} Repeat-wrapped, linear, no mipmaps
+ * (a vertex fetch has no derivatives to choose one with).
+ */
+function gustTexture(seed, size = 128) {
+ const rand = mulberry32(seed);
+ const modes = _WAVE_MODES.map(
+ ([p, q]) => [p, q, rand() * _TAU, 1 / Math.pow(p * p + q * q, 0.62)]);
+ const raw = new Float32Array(size * size);
+ let peak = 1e-6;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ let v = 0;
+ for (const [p, q, ph, a] of modes) {
+ v += a * Math.sin(_TAU * (p * x / size + q * y / size) + ph);
+ }
+ raw[y * size + x] = v;
+ peak = Math.max(peak, Math.abs(v));
+ }
+ }
+ const data = new Uint8Array(size * size * 4);
+ for (let i = 0; i < raw.length; i++) {
+ const v = Math.round(255 * clamp01(0.5 + 0.5 * raw[i] / peak));
+ data[i * 4] = data[i * 4 + 1] = data[i * 4 + 2] = v;
+ data[i * 4 + 3] = 255;
+ }
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.minFilter = tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = false;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+/**
+ * The stalk lattice: ONE instanced strip with `position` pinned at 0.
+ *
+ * GTAOPass redraws with an override material that ignores this vertex
+ * shader, so a real stalk left in `position` would stack every copy at
+ * the world origin and burn a black slab there.
+ */
+function stalkLattice(count) {
+ const base = new THREE.PlaneGeometry(1, 1, 1, _STALK_ROWS);
+ base.translate(0, 0.5, 0);
+ // Spend the rows where the curvature is: an evenly spaced strip
+ // draws the nodding ear with one segment and it reads as an elbow.
+ const p = base.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const a = p.getY(i) * _STALK_ROWS;
+ p.setY(i, a <= _STEM_ROWS
+ ? _EAR_AT * a / _STEM_ROWS
+ : _EAR_AT + (1 - _EAR_AT) * (a - _STEM_ROWS)
+ / (_STALK_ROWS - _STEM_ROWS));
+ }
+ const g = new THREE.InstancedBufferGeometry();
+ g.index = base.index;
+ g.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(base.attributes.position.count * 3), 3));
+ g.setAttribute('aCorner', base.attributes.position);
+ g.setAttribute('normal', base.attributes.normal);
+ g.setAttribute('uv', base.attributes.uv);
+ g.instanceCount = count;
+ return g;
+}
+
+/** One mesh, one draw call: every stalk lives in the vertex shader. */
+function stalkMesh(field, extent, straw, ear, wind, waveMps, seed,
+ shadows) {
+ const geom = stalkLattice(field.n);
+ const inst = (name, arr, size) => geom.setAttribute(
+ name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));
+ inst('iPos', field.pos, 3);
+ inst('iCrop', field.crop, 4);
+ inst('iVar', field.vary, 3);
+ // position is zero, so the derived bounds would be a point at the
+ // origin. A stalk bends along an arc of its OWN length, so its tip
+ // never leaves a circle of that radius about its root.
+ const reach = extent / 2 + field.maxH;
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-reach, field.low, -reach),
+ new THREE.Vector3(reach, field.high, reach));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(
+ new THREE.Sphere());
+
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.74, metalness: 0,
+ side: THREE.DoubleSide, name: 'WheatStalk',
+ });
+ patchStandard(mat, {
+ name: 'cloth:wheat',
+ uniforms: {
+ uWheatStraw: { value: straw.clone() },
+ uWheatEar: { value: ear.clone() },
+ uWheatWave: { value: gustTexture(seed) },
+ uWheatWind: { value: wind.dir.clone() },
+ // Metres the crest travels per second, and the metres one tile
+ // of the gust field covers ALONG and ACROSS the wind. The 3.8:1
+ // is grass.js's streak ratio, at the scale a crop wave needs.
+ uWheatMps: { value: waveMps * wind.speed },
+ uWheatTile: { value: new THREE.Vector2(1 / 46, 1 / 12) },
+ // The shared wave is what moves this field; the per-stalk terms
+ // are texture on top of it and must stay a fraction of it.
+ uWheatBase: { value: 0.10 },
+ uWheatGust: { value: 0.62 * wind.amp * 2 },
+ uWheatJitter: { value: 0.05 * wind.amp * 2 },
+ uWheatNod: { value: 0.9 },
+ uWheatRate: { value: 2.1 * wind.speed },
+ uWheatHead: { value: 3.2 },
+ uWheatDroop: { value: 1.8 },
+ uWheatSheen: { value: 0.7 },
+ // A crop does not ripen all at once: it goes first where the
+ // ground is light and last in the wet corner, so a field carries
+ // green-gold PATCHES tens of metres across with stalk-to-stalk
+ // scatter inside them. One flat straw hex over a hectare is the
+ // single loudest tell that a field was painted, not sown — and it
+ // costs one fbm of the root position to fix.
+ uWheatPatch: { value: 0.055 },
+ uWheatRipen: { value: 1 },
+ // Straw is a shiny tube: the flank turning away from the eye is
+ // where a stalk catches the sky, and it is why a crop glitters.
+ uWheatEdge: { value: 0.26 },
+ },
+ vertexHead: STALK_HEAD,
+ vertexBody: STALK_VERTEX,
+ fragmentHead: [
+ 'uniform vec3 uWheatStraw;',
+ 'uniform vec3 uWheatEar;',
+ 'uniform float uWheatSheen;',
+ 'uniform float uWheatEdge;',
+ 'varying vec4 vWheat;',
+ 'varying float vWheatTone;',
+ ].join('\n'),
+ fragmentBody: STALK_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Stalks';
+ mesh.frustumCulled = false;
+ mesh.receiveShadow = true;
+ // Without the displaced depth pass a shadow pass draws only the
+ // degenerate zero-position quads, so casting stays off by default:
+ // tens of thousands of stalks in the shadow map are a real
+ // SwiftShader cost the caller opts into.
+ mesh.castShadow = false;
+ if (shadows) {
+ shadowLike(mesh, 'cloth:stalkDepth', STALK_HEAD, STALK_VERTEX);
+ }
+ return mesh;
+}
+
+const STALK_HEAD = [
+ 'uniform sampler2D uWheatWave;',
+ 'uniform vec2 uWheatWind;',
+ 'uniform vec2 uWheatTile;',
+ 'uniform float uWheatMps;',
+ 'uniform float uWheatBase;',
+ 'uniform float uWheatGust;',
+ 'uniform float uWheatJitter;',
+ 'uniform float uWheatNod;',
+ 'uniform float uWheatRate;',
+ 'uniform float uWheatHead;',
+ 'uniform float uWheatDroop;',
+ 'uniform float uWheatPatch;',
+ 'uniform float uWheatRipen;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iPos;',
+ 'attribute vec4 iCrop;',
+ 'attribute vec3 iVar;',
+ 'varying vec4 vWheat;',
+ 'varying float vWheatTone;',
+ // A world direction as the LOCAL offset that moves this surface
+ // one metre along it, valid while the basis stays orthogonal.
+ 'vec3 clothLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+const STALK_VERTEX = [
+ ' vec3 whRoot = iPos;',
+ ' float whV = aCorner.y;',
+ ' float whH = max(iCrop.x, 1e-3);',
+ // Ripeness: a field-wide patch field plus this stalk's own scatter,
+ // read ONCE per vertex from the root, so a stalk is one tone from
+ // its foot to its ear and its neighbours are near it, not random.
+ ' float whPatch = astraFbm2(whRoot.xz * uWheatPatch, 2) - 0.375;',
+ ' vWheatTone = clamp((whPatch * 2.2 + iVar.y * 1.4) * uWheatRipen,',
+ ' -1.0, 1.0);',
+ // ONE gust field for the whole crop, scrolled downwind at a stated
+ // m/s: two stalks a metre apart see the same wave, a lag apart.
+ ' vec2 whW = uWheatWind;',
+ ' vec2 whP = vec2(dot(whRoot.xz, whW),',
+ ' dot(whRoot.xz, vec2(-whW.y, whW.x)));',
+ ' vec2 whUv = vec2((whP.x - uWheatMps * uTime) * uWheatTile.x,',
+ ' whP.y * uWheatTile.y);',
+ ' float whWave = texture2D(uWheatWave, whUv).r;',
+ ' float whGust = smoothstep(0.34, 0.98, whWave);',
+ // Per-stalk motion is texture, not the subject: a twentieth of the
+ // gust, or a hectare of wheat boils instead of rippling.
+ ' float whJit = uWheatJitter * sin(uTime * uWheatRate',
+ ' + astraStagger(iVar.x));',
+ ' float whK1 = max(iCrop.w * (uWheatBase + uWheatGust * whGust',
+ ' + whJit), 1e-3);',
+ // A ripe ear is the heavy end of a light stem: it hangs even in
+ // still air, keeps bending after the stem has stopped, and nods.
+ ' float whK2 = whK1 * uWheatHead + uWheatDroop',
+ ' + uWheatNod * (0.5 + 0.5 * whGust)',
+ ' * sin(uTime * uWheatRate * 1.6 + astraStagger(iVar.x) * 1.3);',
+ ' whK2 = max(whK2, 1e-3);',
+ ' vec2 whF = normalize(whW + vec2(-whW.y, whW.x) * iVar.z);',
+ ' float whE0 = iCrop.z;',
+ // Two circular arcs of the stalk\'s own length: a translated tip
+ // would stretch a stem that must instead lie over.
+ ' float whA1 = whK1 * min(whV, whE0);',
+ ' float whU = whH * (1.0 - cos(whA1)) / whK1;',
+ ' float whY = whH * sin(whA1) / whK1;',
+ ' float whA2 = whA1 + whK2 * max(whV - whE0, 0.0);',
+ ' whU += whH * (cos(whA1) - cos(whA2)) / whK2;',
+ ' whY += whH * (sin(whA2) - sin(whA1)) / whK2;',
+ ' vec3 whSpine = whRoot + vec3(whF.x * whU, whY, whF.y * whU);',
+ ' vec3 whTan = vec3(whF.x * sin(whA2), cos(whA2), whF.y * sin(whA2));',
+ // The ear: a spindle on the top of the stem, and the only fat part
+ // of a stalk that is otherwise 4 mm of straw.
+ ' float whE = clamp((whV - whE0) / max(1.0 - whE0, 1e-3), 0.0, 1.0);',
+ ' float whEar = whV > whE0 ? sqrt(max(sin(3.14159 * whE), 0.0)) : 0.0;',
+ ' float whWid = iCrop.y * (1.0 - 0.35 * whV) + whEar * whH * 0.011;',
+ // A stem is round, so its strip faces the eye from every angle
+ // instead of collapsing to a line like a flat blade.
+ ' vec3 whWp = (modelMatrix * vec4(whSpine, 1.0)).xyz;',
+ ' vec3 whView = normalize(clothLocalDir(cameraPosition - whWp));',
+ ' vec3 whC = cross(whTan, whView);',
+ ' float whCl = length(whC);',
+ ' vec3 whSide = whCl > 1e-4 ? whC / whCl : vec3(1.0, 0.0, 0.0);',
+ ' float whX = aCorner.x * 2.0;',
+ ' transformed = whSpine + whSide * (whX * whWid);',
+ ' vWheat = vec4(whV, whEar, whGust, whX);',
+ '#ifndef FLAT_SHADED',
+ ' vec3 whFace = normalize(cross(whSide, whTan));',
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' whFace * sqrt(max(1.0 - whX * whX, 0.04)) + whSide * whX));',
+ '#endif',
+].join('\n');
+
+const STALK_FRAGMENT = [
+ // Green where the crop is still coming, gold where it has come. The
+ // hue swing is 0.30 rad — under a fifth of that and a mixed field
+ // reads as one straw with a lighting error in it.
+ ' float whRipe = vWheatTone * 0.5 + 0.5;',
+ ' vec3 whCol = astraHueShift(uWheatStraw,',
+ ' vWheat.w * 0.04 - vWheatTone * 0.30);',
+ ' whCol *= 0.80 + 0.32 * whRipe;',
+ // Ripe from the ear DOWN, not only on the ear: from above, a crop
+ // is the colour of its heads and the hand's breadth under them.
+ ' float whGold = clamp(0.6 * smoothstep(0.5, 0.95, vWheat.x)',
+ ' + 0.6 * smoothstep(0.05, 0.5, vWheat.y), 0.0, 1.0);',
+ ' whCol = mix(whCol, astraHueShift(uWheatEar, -vWheatTone * 0.16),',
+ ' whGold * (0.62 + 0.38 * whRipe));',
+ // A crop is DEEP: the foot of a stalk sits in the shade of the row,
+ // and that gradient is most of what reads as a standing field.
+ ' whCol *= 0.34 + 0.66 * smoothstep(0.0, 0.55, vWheat.x);',
+ // Spikelets: the grain sits in ranks up the ear, and this is the
+ // texture that says wheat rather than tall grass.
+ ' whCol *= 1.0 - 0.35 * vWheat.y',
+ ' * astraStroke(vWheat.x * 220.0, 0.08);',
+ // THE WAVE, made visible: a laid-over crop turns its pale flanks to
+ // the sky, so a crest is a band of light crossing the field and a
+ // trough is a band of shade.
+ ' whCol *= 0.84 + uWheatSheen * vWheat.z * (0.6 + 0.4 * vWheat.y);',
+ // A stem is a polished tube: its turning flank is where it catches
+ // the sky, and a field of those flanks is what glitters. The strip
+ // already carries its across-width coordinate, so this is free.
+ ' float whFl = abs(vWheat.w);',
+ ' whCol *= 1.0 + uWheatEdge * whFl * whFl * whFl;',
+ ' diffuseColor.rgb *= whCol;',
+].join('\n');
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/clouds.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/clouds.js
new file mode 100644
index 00000000..f7a7bd28
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/clouds.js
@@ -0,0 +1,372 @@
+// Cloud layers: ONE InstancedMesh of billboard puffs (fbm alpha, flat
+// base, sun-tinted) + optional thin cirrus streaks. three r184's Sky
+// cloud branch grid-artifacts at any high contrast — this is the layer.
+import * as THREE from 'three';
+import { mulberry32, fbm2 } from './noise.js';
+import { makeShaderMaterial, keepOutOfDepthPasses } from './shader.js';
+
+// Cumulus/cirrus mood presets, graded for THIS renderer: ACES filmic at
+// exposure 1.0, sRGB out, NO post chain (no bloom to rescue a dim top,
+// no grade to pull a tint back). A lit cumulus top is the brightest
+// diffuse thing in a daylight frame, so `sunColor` is a near-WHITE with
+// a warm bias — the old 0xffc890 sun tint was graded against a bloom+
+// grade chain and lands as tan smoke here (measured: cloud region
+// (224,233,236) against a (232,239,242) sky, 3% contrast). `shadeColor`
+// is the sky-lit underside, never neutral grey: it is where the blue
+// comes from.
+const PRESETS = {
+ day: { sunColor: 0xfff4e6, shadeColor: 0x7e94b8, litGain: 1.55 },
+ golden: { sunColor: 0xffd0a0, shadeColor: 0x7c82ac, litGain: 1.70 },
+ // A sheet, not a field of dark clumps: wide overlapping puffs at one
+ // altitude, and the flattest lighting of the four.
+ overcast: { sunColor: 0xbcc3cc, shadeColor: 0x717b8a, litGain: 1.05,
+ count: 40, altitude: 230, spread: 45, alpha: 0.97,
+ stretch: 1.9 },
+ // Moonlit: dark but LIT — a cool silver top over a deep blue base,
+ // never the black cut-out a plain brightness scale gives.
+ night: { sunColor: 0xa8bfe0, shadeColor: 0x2c3652, litGain: 0.60,
+ alpha: 0.88 },
+};
+
+/**
+ * The vector that actually LIGHTS the deck, from the authored sun.
+ *
+ * `sunRig().sunDir` keeps reporting the authored sun after it sets (the
+ * sky needs it to paint twilight), and a light 20 deg under the ground
+ * lights nothing: passed straight in, every night cloud is lit from
+ * below through the earth. Same substitution `environment.js` makes for
+ * its own key light — the moon rises opposite the sun, 30-55 deg up,
+ * higher the deeper the sun. No argument keeps the old top-lit look.
+ */
+function lightVector(v) {
+ if (!v || !v.isVector3) return new THREE.Vector3(0, 1, 0);
+ const d = v.clone().normalize();
+ if (d.y >= -0.02) return d;
+ const el = Math.asin(-d.y); // how deep the sun is
+ const moonEl = Math.max(30, Math.min(55, 25 + el * 180 / Math.PI))
+ * Math.PI / 180;
+ const az = Math.atan2(-d.z, -d.x); // opposite azimuth
+ return new THREE.Vector3(
+ Math.cos(moonEl) * Math.cos(az), Math.sin(moonEl),
+ Math.cos(moonEl) * Math.sin(az));
+}
+
+/** Soft irregular puff alpha texture: radial falloff x fbm, flat base. */
+export function cloudTexture(seed = 7, size = 256) {
+ const data = new Uint8Array(size * size * 4);
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const nx = x / size - 0.5, ny = y / size - 0.5;
+ const r = Math.sqrt(nx * nx * 1.05 + ny * ny * 2.2) * 2;
+ // Two bands: the low one carves the cauliflower lobes, the high
+ // one frays the silhouette. One octave set alone gives the soft
+ // airbrushed blob the old texture had.
+ const n = fbm2(x / 46, y / 46, { seed, octaves: 3 }) * 0.5 + 0.5;
+ const f = fbm2(x / 13, y / 13, { seed: seed + 5, octaves: 2 }) * 0.5 + 0.5;
+ let a = Math.max(0, 1 - r) * (0.45 + 0.85 * n) - 0.18;
+ a = Math.max(0, Math.min(1, a * 1.9));
+ a = a * a * (3 - 2 * a);
+ // Erosion, strongest where the body is already thin: keeps the
+ // core solid and turns the rim into wisps.
+ a *= 1 - 0.55 * (1 - a) * (1 - f);
+ a *= Math.min(1, Math.max(0, (ny + 0.34) / 0.10));
+ const k = (y * size + x) * 4;
+ data[k] = data[k + 1] = data[k + 2] = 255;
+ data[k + 3] = Math.round(a * 255);
+ }
+ }
+ const tex = new THREE.DataTexture(data, size, size);
+ tex.needsUpdate = true;
+ tex.minFilter = THREE.LinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ return tex;
+}
+
+/**
+ * Cumulus layer as ONE instanced billboard mesh (one draw call).
+ * opts: seed, preset ('day'|'golden'|'overcast'|'night'), count, area,
+ * altitude, spread, sunDir (THREE.Vector3 toward the sun — the lit side
+ * follows it, and a sun already below the horizon becomes the moon),
+ * sunColor, shadeColor, alpha, wind (m/s along +x), rim (silver-lining
+ * strength, 0.55), haze (how far the deck may recede into scene.fog,
+ * 0.22 — the fog COLOUR is always the scene's), hueVariance (0.13).
+ * Animate cloud drift from tick(): `layer.userData.update(t)`.
+ */
+export function makeClouds(opts = {}) {
+ const p = PRESETS[opts.preset || 'day'] || PRESETS.day;
+ const seed = opts.seed ?? 7;
+ const count = opts.count ?? p.count ?? 14;
+ const area = opts.area ?? 2600;
+ const altitude = opts.altitude ?? p.altitude ?? 260;
+ const spread = opts.spread ?? p.spread ?? 120;
+ const alpha = opts.alpha ?? p.alpha ?? 0.92;
+ const wind = opts.wind ?? 3.0;
+ const stretch = opts.stretch ?? p.stretch ?? 1.0;
+ const rand = mulberry32(seed);
+ const rnd2 = mulberry32(seed + 977);
+ const puffs = [];
+ for (let c = 0; c < count; c++) {
+ const cx = (rand() - 0.5) * area;
+ const cz = (rand() - 0.5) * area - area * 0.18;
+ const cy = altitude + (rand() - 0.5) * spread;
+ const w = 130 + rand() * 240;
+ const n = 5 + Math.floor(rand() * 5);
+ const cluster = [];
+ for (let q = 0; q < n; q++) {
+ const t = (q + 0.5) / n - 0.5;
+ cluster.push({
+ x: cx + t * w * (1.5 + rand() * 0.5),
+ y: cy + (rand() - 0.35) * w * 0.22 - Math.abs(t) * w * 0.3,
+ z: cz + (rand() - 0.5) * w * 0.35,
+ s: w * (0.55 + rand() * 0.5) * (1 - Math.abs(t) * 0.75),
+ b: 0.75 + rand() * 0.25,
+ ph: rand() * Math.PI * 2,
+ h: 0,
+ });
+ }
+ // A CROWN over the middle of the row. A single line of puffs is a
+ // caterpillar, not a cumulus: the silhouette a cumulus is recognised
+ // by is a flat base under a stack of smaller lobes.
+ // Its own stream, so adding the crown did not reshuffle the deck a
+ // caller already framed a shot around.
+ const crown = 1 + Math.floor(rnd2() * 3);
+ for (let q = 0; q < crown; q++) {
+ const t = (rnd2() - 0.5) * 0.55;
+ const up = 0.30 + rnd2() * 0.34;
+ cluster.push({
+ x: cx + t * w * 1.6,
+ y: cy + w * up * 0.55,
+ z: cz + (rnd2() - 0.5) * w * 0.3,
+ s: w * (0.36 + rnd2() * 0.30),
+ b: 0.85 + rnd2() * 0.15,
+ ph: rnd2() * Math.PI * 2,
+ h: 0,
+ });
+ }
+ // Where each puff sits inside ITS OWN cluster, 0 at the base and 1
+ // at the crown. Without it every billboard carries the same top-lit
+ // gradient and a cluster reads as a bag of identical blobs instead
+ // of one mass with a shaded underside — the single biggest tell of
+ // billboard clouds.
+ const lo = Math.min(...cluster.map((q) => q.y));
+ const hi = Math.max(...cluster.map((q) => q.y));
+ for (const q of cluster) {
+ q.h = (q.y - lo) / Math.max(1e-3, hi - lo);
+ puffs.push(q);
+ }
+ }
+ const geo = new THREE.PlaneGeometry(1, 1);
+ const inst = new THREE.InstancedBufferGeometry();
+ inst.index = geo.index;
+ // `position` stays at the ORIGIN and the corner offsets ride a custom
+ // attribute: GTAOPass redraws the scene with an override material that
+ // does NOT run this vertex shader, so a real 1x1 quad here burns a
+ // hard-edged black rectangle into AO at world origin (measured).
+ inst.attributes.position = new THREE.BufferAttribute(
+ new Float32Array(geo.attributes.position.count * 3), 3);
+ inst.setAttribute('aCorner', geo.attributes.position);
+ inst.attributes.uv = geo.attributes.uv;
+ inst.instanceCount = puffs.length;
+ const off = new Float32Array(puffs.length * 3);
+ const sc = new Float32Array(puffs.length * 2);
+ const ex = new Float32Array(puffs.length * 3);
+ puffs.forEach((q, i) => {
+ off[i * 3] = q.x; off[i * 3 + 1] = q.y; off[i * 3 + 2] = q.z;
+ sc[i * 2] = q.s * stretch; sc[i * 2 + 1] = q.s * 0.62 / Math.max(1, stretch * 0.45);
+ ex[i * 3] = q.b; ex[i * 3 + 1] = q.ph; ex[i * 3 + 2] = q.h;
+ });
+ inst.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
+ inst.setAttribute('iScale', new THREE.InstancedBufferAttribute(sc, 2));
+ inst.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ex, 3));
+ // Toward the sun. `sunDir` was documented and then ignored: every puff
+ // was lit from straight up, so a low sun and a high sun painted the
+ // same cloud. Default +Y keeps that old top-lit behaviour when a
+ // caller has no rig to hand.
+ const sunDir = lightVector(opts.sunDir);
+ const mat = makeShaderMaterial({
+ name: opts.name || 'CumulusLayer',
+ transparent: true,
+ depthWrite: false,
+ // NOT three's fog. A cloud deck sits 300-1500 m out, and a scene's
+ // FogExp2 is authored for scene-scale geometry: at the density a
+ // 120 m courtyard uses (0.0035) the whole deck resolves to 100% fog
+ // colour — measured, the layer above was invisible on this host
+ // (darkest cloud pixel = the fog colour exactly). The layer opts out
+ // of the chunk and mixes its OWN bounded aerial perspective toward
+ // `fogColor` below, so it still recedes into the scene's haze and in
+ // the scene's hue, but never disappears into it.
+ fog: false,
+ uniforms: {
+ // three refreshes these itself once `mat.fog = true` (below) —
+ // the shader keeps the scene's fog COLOUR and density without
+ // taking three's fog blend.
+ ...THREE.UniformsUtils.clone(THREE.UniformsLib.fog),
+ map: { value: cloudTexture(seed + 101) },
+ uWind: { value: wind },
+ uAlpha: { value: alpha },
+ uLitGain: { value: opts.litGain ?? p.litGain },
+ uSunDir: { value: sunDir },
+ uRim: { value: opts.rim ?? 0.55 },
+ uHazeMax: { value: opts.haze ?? 0.22 },
+ uHazeScale: { value: 0.35 },
+ uHue: { value: opts.hueVariance ?? 0.13 },
+ uSunColor: {
+ value: new THREE.Color(opts.sunColor ?? p.sunColor),
+ },
+ uShade: {
+ value: new THREE.Color(opts.shadeColor ?? p.shadeColor),
+ },
+ },
+ varyings: [
+ 'varying vec2 vUv; varying vec3 vExtra;',
+ 'varying vec2 vSun; varying float vDepth; varying float vSunZ;',
+ ].join('\n'),
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff; attribute vec2 iScale; attribute vec3 iExtra;',
+ 'uniform float uWind; uniform vec3 uSunDir;',
+ ].join('\n'),
+ vertexMain: [
+ ' vExtra = iExtra;',
+ // Half the puffs wear the puff texture mirrored: one alpha map
+ // repeated at N scales is a recognisable stamp, and a free u-flip
+ // doubles the silhouettes. The base cut runs in v, so mirroring u
+ // cannot lift a cloud off its own flat bottom.
+ ' float flip = step(0.5, fract(iExtra.y * 0.1591));',
+ ' vUv = vec2(mix(uv.x, 1.0 - uv.x, flip), uv.y);',
+ ' vec3 right = vec3(viewMatrix[0][0], viewMatrix[1][0],',
+ ' viewMatrix[2][0]);',
+ ' vec3 up = vec3(viewMatrix[0][1], viewMatrix[1][1],',
+ ' viewMatrix[2][1]);',
+ ' vec3 p = iOff + vec3(uTime * uWind',
+ ' + sin(iExtra.y + uTime * 0.05) * 6.0, 0.0, 0.0);',
+ ' transformed = p + right * aCorner.x * iScale.x',
+ ' + up * aCorner.y * iScale.y;',
+ // The sun in the billboard's own 2D frame: the lit side then
+ // follows the rig instead of always being the top edge.
+ ' vec2 sp = vec2(dot(uSunDir, right), dot(uSunDir, up));',
+ ' vSun = length(sp) > 1e-3 ? normalize(sp) : vec2(0.0, 1.0);',
+ // the lit side is a world direction: mirror it with the uv or the
+ // light lands on the wrong half of every flipped puff
+ ' vSun.x *= 1.0 - 2.0 * flip;',
+ // ...and whether it is in front of or behind the deck. A cloud
+ // seen against the sun is a DARK body with a burning rim; the
+ // same cloud with the sun over the shoulder is a white one. One
+ // dot product decides which, and it is the difference between a
+ // sky that looks photographed and one that looks painted.
+ ' vec3 fwd = vec3(viewMatrix[0][2], viewMatrix[1][2],',
+ ' viewMatrix[2][2]);',
+ ' vSunZ = dot(uSunDir, fwd);',
+ ' vDepth = -(modelViewMatrix * vec4(transformed, 1.0)).z;',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform sampler2D map; uniform vec3 uSunColor; uniform vec3 uShade;',
+ 'uniform float uAlpha; uniform float uLitGain; uniform float uRim;',
+ 'uniform float uHazeMax; uniform float uHazeScale; uniform float uHue;',
+ 'uniform vec3 fogColor;',
+ 'uniform float fogDensity; uniform float fogNear; uniform float fogFar;',
+ ].join('\n'),
+ fragmentMain: [
+ ' float a = texture2D(map, vUv).a;',
+ ' if (a < 0.004) discard;',
+ // Two lighting terms: the sun's own direction across the puff,
+ // and a vertical term for the flat shaded base every cumulus has.
+ ' float face = dot(vUv - 0.5, vSun) * 2.0;',
+ ' float vert = smoothstep(-0.10, 0.62, vUv.y);',
+ ' float front = smoothstep(-0.25, 0.65, vSunZ);',
+ // one gradient for the whole cluster: the puff\'s own top plus
+ // where the puff sits in the mass (iExtra.z)
+ ' float upness = clamp(0.45 * vert + 0.62 * vExtra.z, 0.0, 1.0);',
+ ' float lit = clamp(0.34 * upness',
+ ' + 0.78 * smoothstep(-0.75, 0.55, face), 0.0, 1.0);',
+ ' lit *= vExtra.x * mix(0.22, 1.0, front);',
+ ' vec3 sunLit = uSunColor * uLitGain;',
+ // The shaded side is sky-lit, so it carries the scene's own haze
+ // colour — no hardcoded ambient, and never a black underside.
+ // Backlit, the body we see is the shadowed one: darker, bluer.
+ ' vec3 ambient = mix(uShade, fogColor, 0.22) * mix(0.52, 1.0, front)',
+ ' * mix(0.78, 1.10, vExtra.z);',
+ ' vec3 col = mix(ambient, sunLit, lit);',
+ // Silver lining: a thin edge transmits instead of reflecting — the
+ // one read that says "cloud" and not "sprite". Front-lit it is the
+ // sun-facing edge only; backlit the whole silhouette burns.
+ // A BAND just inside the silhouette, not everything below an alpha
+ // threshold: a rim that runs all the way out into the wisps turns
+ // every puff into a lit soap bubble (seen on the night render).
+ ' float thin = smoothstep(0.03, 0.26, a)',
+ ' * (1.0 - smoothstep(0.24, 0.66, a));',
+ ' float rim = thin * mix(0.40 + 0.60 * smoothstep(-0.4, 0.9, face),',
+ ' smoothstep(0.0, 0.85, face), front);',
+ ' col += sunLit * uRim * rim * mix(2.1, 1.0, front);',
+ // Hue variance: warm where the sun reaches, cool where it does
+ // not, decorrelated per puff by its phase. A cloud deck of one
+ // flat white is the giveaway of a painted sky.
+ ' col = astraHueBreak(col, vUv * 2.2 + vExtra.y * 6.3, 1.0, uHue);',
+ // Bounded aerial perspective (see the `fog: false` note above).
+ ' float hz = 0.0;',
+ '#ifdef USE_FOG',
+ '#ifdef FOG_EXP2',
+ ' float fd = fogDensity * uHazeScale * vDepth;',
+ ' hz = 1.0 - exp(-fd * fd);',
+ '#else',
+ ' hz = clamp((vDepth - fogNear) / max(fogFar - fogNear, 1e-4),',
+ ' 0.0, 1.0) * uHazeScale * 2.0;',
+ '#endif',
+ '#endif',
+ ' col = mix(col, fogColor, clamp(hz, 0.0, 1.0) * uHazeMax);',
+ // A cloud is one long smooth ramp across hundreds of pixels: at 8
+ // bits that bands. One LSB of hash noise costs nothing and kills
+ // the rings.
+ ' col += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.004;',
+ ' gl_FragColor = vec4(col, a * uAlpha);',
+ ].join('\n'),
+ });
+ // Opted out of three's fog BLEND, opted in to its fog UNIFORMS: this
+ // is what makes the renderer keep fogColor/fogDensity current.
+ mat.fog = true;
+ const mesh = new THREE.Mesh(inst, mat);
+ mesh.name = opts.name || 'CumulusLayer';
+ mesh.frustumCulled = false;
+ mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
+ return keepOutOfDepthPasses(mesh);
+}
+
+/**
+ * Thin high-altitude streaks — the same instanced billboard layer,
+ * stretched flat and thinned out.
+ * opts: seed, preset, count, area, altitude, sunDir, sunColor.
+ */
+export function makeCirrus(opts = {}) {
+ // Reuses the proven cumulus billboard shader as stretched streaks —
+ // Sprites rendered as black slabs under the post chain (measured on
+ // the manhattan run), and tilted planes went edge-on from low cams.
+ const seed = opts.seed ?? 23;
+ // Ice, not water: whiter and cooler than the cumulus of the same hour,
+ // and thin enough that the light comes THROUGH — hence the wide rim.
+ // Derived from the PRESET rather than fixed, or a night deck gets a
+ // daylight-white streak across it (measured on the night render: the
+ // cirrus band read as a light leak over a deep blue sky).
+ const p = PRESETS[opts.preset || 'day'] || PRESETS.day;
+ const white = new THREE.Color(0xffffff);
+ const ice = new THREE.Color(p.sunColor).lerp(white, 0.35);
+ const veil = new THREE.Color(p.shadeColor).lerp(white, 0.55);
+ return makeClouds({
+ // Its own name: two layers called CumulusLayer collide in the
+ // census and in the viewer's find-by-name.
+ name: 'CirrusLayer',
+ seed,
+ count: opts.count ?? 8,
+ area: opts.area ?? 3200,
+ altitude: opts.altitude ?? 520,
+ spread: 120,
+ alpha: opts.alpha ?? 0.30,
+ wind: opts.wind ?? 6.0,
+ litGain: (opts.litGain ?? p.litGain) * 0.85,
+ sunColor: opts.sunColor ?? ice.getHex(),
+ shadeColor: opts.shadeColor ?? veil.getHex(),
+ sunDir: opts.sunDir,
+ rim: opts.rim ?? 0.85,
+ hueVariance: opts.hueVariance ?? 0.08,
+ stretch: opts.stretch ?? 7.0,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.js
new file mode 100644
index 00000000..8e7cab0d
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/creature.js
@@ -0,0 +1,684 @@
+/**
+ * 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/damp.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/damp.js
new file mode 100644
index 00000000..4df09f36
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/damp.js
@@ -0,0 +1,725 @@
+/**
+ * Damp: what water leaves on ground and stone it never covers.
+ *
+ * `waterside` draws the waterline itself. These three are the metres
+ * AROUND it — the growth on the side that never dries, the darker
+ * ground that says water is close, and the polygons a bed cracks into
+ * once the water has gone. All three go through `patchStandard`, so
+ * lighting, shadows, fog and the depth chunks survive, and all three
+ * shade from world position and world normal, so none needs a UV and
+ * two objects sharing a scale share one climate.
+ *
+ * DIRECTION IS THE WHOLE EFFECT. Moss sprayed evenly is green paint;
+ * what reads as moss is that it is on ONE side of every rock, wall and
+ * trunk in the frame at once — so `north` (the world direction that
+ * stays shaded) and `up` are uniforms every material can share, and the
+ * sun-baked face is gated MULTIPLICATIVELY, where no amount of noise
+ * can put growth on it.
+ *
+ * None of them ASSIGNS a colour: each lands on a material that may
+ * already carry `patchTriplanar`, `patchSlopeSplat`, `patchMicroBreakup`
+ * or an `aging` mark, and whichever assigned last would erase the rest
+ * (measured: a splat over a triplanar did exactly that). Every one here
+ * multiplies or mixes with what it is handed.
+ *
+ * Gloss is per MATERIAL, not per pixel — `<color_fragment>` runs before
+ * `<roughnessmap_fragment>` — so each composes ONE factor through
+ * `composeRoughness`, and they pull BOTH ways: moss and dried mud are
+ * matte, damp ground and a water-filled crack are glossy.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, waterside, surface_wear, aging and
+// accumulation name them, so a material wearing several libraries
+// declares ONE pair; the vertex locals are dm* because those five own
+// astraWp, wsP, wrP, agP and acP.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// All three patches read these, so they are declared once, in the base.
+// astraDamp*, not a neighbour's spelling: patchStandard THROWS when two
+// chained patches give one function name two different bodies.
+const DAMP_HEAD = [
+ 'vec3 astraDampAxes(vec3 n) {',
+ ' vec3 w = abs(n * n * n);',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+ // Three world-plane projections blended by the normal: growth has to
+ // break up the same way on a boulder, a wall and a bridge soffit.
+ 'float astraDampNoise(vec3 p, vec3 w) {',
+ ' return astraNoise2(p.yz + 29.3) * w.x',
+ ' + astraNoise2(p.zx + 63.1) * w.y',
+ ' + astraNoise2(p.xy + 97.7) * w.z;',
+ '}',
+ // Curvature in 1/m: how far the normal turns per metre of surface
+ // under one pixel. NEGATIVE is the concave crevice that holds water.
+ // Zero across a hard, unwelded edge.
+ 'float astraDampCurv(vec3 n, vec3 p) {',
+ ' vec3 dx = dFdx(p), dy = dFdy(p);',
+ ' float d = dot(dx, dx) + dot(dy, dy);',
+ ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',
+ '}',
+ 'vec2 astraDampSite(vec2 c) {',
+ ' return c + vec2(astraHash21(c), astraHash21(c + 37.7));',
+ '}',
+ // Voronoi, measured to the nearest cell BORDER rather than by
+ // F2 - F1, which rounds every corner into a blob. Mud dries into
+ // POLYGONS with straight edges and sharp corners, and that is the
+ // whole difference between cracked mud and a dark noise.
+ 'vec2 astraDampCells(vec2 p) {',
+ ' vec2 ci = floor(p);',
+ ' vec2 cb = vec2(0.0), cr = vec2(0.0);',
+ ' float cd = 8.0;',
+ ' for (int y = -1; y <= 1; y++) {',
+ ' for (int x = -1; x <= 1; x++) {',
+ ' vec2 g = vec2(float(x), float(y));',
+ ' vec2 r = astraDampSite(ci + g) - p;',
+ ' float d = dot(r, r);',
+ ' if (d < cd) { cd = d; cb = g; cr = r; }',
+ ' }',
+ ' }',
+ ' cd = 8.0;',
+ ' for (int y = -1; y <= 1; y++) {',
+ ' for (int x = -1; x <= 1; x++) {',
+ ' vec2 g = cb + vec2(float(x), float(y));',
+ ' vec2 r = astraDampSite(ci + g) - p;',
+ ' vec2 e = r - cr;',
+ ' if (dot(e, e) > 1e-5) {',
+ ' cd = min(cd, dot(0.5 * (cr + r), normalize(e)));',
+ ' }',
+ ' }',
+ ' }',
+ ' return vec2(cd, astraHash21(ci + cb + 0.37));',
+ '}',
+].join('\n');
+
+// One base for all three. `transformed` is still object-space after
+// <begin_vertex>, so the instance transform is folded in by hand or
+// every scattered copy takes its weather from the world origin.
+const BASE = {
+ name: 'damp:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 dmP = vec4(transformed, 1.0);',
+ ' vec3 dmN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' dmP = instanceMatrix * dmP;',
+ ' dmN = mat3(instanceMatrix) * dmN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * dmP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(dmN, 0.0)).xyz);',
+ ].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, DAMP_HEAD].join('\n'),
+};
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed
+ * for every material sharing the cache key. The constants differ from
+ * surface_wear's, aging's and accumulation's, or one seed would grow
+ * this library's moss along that library's blotches.
+ */
+function seedOffset(seed, salt) {
+ return new THREE.Vector3(
+ hash11(seed + salt + 2.71), hash11(seed + salt + 6.83),
+ hash11(seed + salt + 11.29)).multiplyScalar(40);
+}
+
+/**
+ * Read an `up`-style option as a unit vector, never as NaN.
+ *
+ * A degenerate vector would divide by zero in the shader and paint the
+ * object black, so a zero-length one falls back to world up.
+ */
+function upVector(value) {
+ const v = new THREE.Vector3(0, 1, 0);
+ if (value) v.fromArray(value.toArray ? value.toArray() : value);
+ if (!(v.lengthSq() > 1e-9)) v.set(0, 1, 0);
+ return v.normalize();
+}
+
+/**
+ * Read `north` as the HORIZONTAL direction that stays shaded.
+ *
+ * A compass direction has no component along `up`: one tipped toward
+ * the sky would grow moss on every ceiling in the scene. Dropping that
+ * component leaves a north parallel to up with no direction at all, so
+ * that degenerate case takes any perpendicular instead.
+ */
+function northVector(value, up) {
+ const v = new THREE.Vector3(0, 0, -1);
+ if (value) v.fromArray(value.toArray ? value.toArray() : value);
+ if (!(v.lengthSq() > 1e-9)) v.set(0, 0, -1);
+ v.addScaledVector(up, -v.dot(up));
+ if (!(v.lengthSq() > 1e-6)) {
+ const axis = Math.abs(up.z) < 0.9
+ ? new THREE.Vector3(0, 0, 1) : new THREE.Vector3(1, 0, 0);
+ v.crossVectors(up, axis);
+ }
+ return v.normalize();
+}
+
+/**
+ * Move the material's gloss toward the cover's, never past it.
+ *
+ * Roughness is per MATERIAL here, so a cover can only say how much of
+ * the surface is no longer the material: `blend` 0 leaves it alone, 1
+ * hands the whole material to the cover's own roughness.
+ */
+function towardRoughness(material, target, blend) {
+ const base = baseRoughness(material);
+ if (!(base > 0)) return 1;
+ return 1 + (target / base - 1) * unit(blend);
+}
+
+/** The roughness the material was AUTHORED with, before any cover. */
+function baseRoughness(material) {
+ const store = material.userData.astraRoughness;
+ return store ? store.base : material.roughness;
+}
+
+/**
+ * A wet target that is glossier than the surface it lands on — never a
+ * mirror, and never rougher than what it landed on.
+ *
+ * A FIXED target is wrong in both directions, and roughness here is per
+ * MATERIAL, so whatever it does it does to the whole surface. The
+ * reference's 0.34 is a water FILM: on our renderer (a baked sky
+ * environment, ACES at exposure 1.0, no post chain) it turned a
+ * 0.95-rough bank into a sky mirror and lifted the ground from
+ * luminance 0.607 to 0.823 — BRIGHTER, when the whole point of the
+ * apron is that it is darker. Raising the fixed number instead just
+ * moves the error: 0.62 on a 0.5-rough stone would ROUGHEN it when wet.
+ *
+ * So the target is a RATIO of what the material already is, floored so
+ * a rough ground cannot be polished past wet soil, and clamped to the
+ * base so a surface already smoother than the floor is left alone.
+ */
+function wetTarget(material, floor, ratio) {
+ const base = baseRoughness(material);
+ if (!(base > 0)) return floor;
+ return Math.min(base, Math.max(floor, base * ratio));
+}
+
+/**
+ * Move one colour in HSL, wrapping the hue so a shift may cross 0.
+ *
+ * Every tone below is DERIVED, never a second option: a caller sets one
+ * `color` per patch and the family is read off it, so a scene retuning
+ * its moss cannot end up with a cushion and a crust from two different
+ * plants — and so no tone can be lost by a caller who set only one.
+ */
+function shifted(base, dh, ds, lightness) {
+ const hsl = { h: 0, s: 0, l: 0 };
+ base.getHSL(hsl);
+ return new THREE.Color().setHSL(
+ frac(hsl.h + dh), Math.min(1, hsl.s * ds), unit(lightness(hsl.l)));
+}
+
+/**
+ * The four tones of a moss cushion, and the two of a dried plate.
+ *
+ * ONE FLAT VALUE IS THE TELL. A cushion photographs as a hue RANGE, not
+ * a colour: blue-black in the depth between the clumps, the body green
+ * where it is thick, a yellow-green crown on the tips that see the sky,
+ * and — where the moss thins — crustose lichen, which is a different
+ * organism and a different colour, pale sage in its middle and ochre at
+ * its rim. Painted as one green with a brightness ramp over it (which
+ * is what this was), a metre of it reads as felt.
+ *
+ * Same for a bed that cracked: the plates did not all dry at the same
+ * hour, so the ones that went first are pale and grey and the ones that
+ * held their water are darker and warmer, and the CELL is what carries
+ * that difference — a per-plate brightness alone reads as dirt on a
+ * single chip of paint.
+ *
+ * THE SIGN OF EVERY HUE SHIFT IS THE PART THAT IS EASY TO GET WRONG
+ * (measured: the first pass had both moss shifts inverted and rendered
+ * an acid-green cushion with lavender crust). In HSL, hue RISES from
+ * yellow through yellow-green to green to blue-green — so the CROWN,
+ * which is new growth and yellower, shifts DOWN, and the depth, which
+ * is shaded and blue-green, shifts UP. Same on the bed: the plate that
+ * dried first is yellower (up from an orange-brown), the one that held
+ * its water is redder (down).
+ *
+ * And the spread is SMALL. These are two tones of one substance, not
+ * two substances: a swing wide enough to name reads as tiling.
+ */
+const lichenTone = (base) =>
+ shifted(base, 0.020, 0.42, (l) => Math.min(0.50, l * 1.40 + 0.12));
+const crustTone = (base) =>
+ shifted(base, -0.150, 0.62, (l) => Math.min(0.46, l * 1.45 + 0.10));
+const mossDeep = (base) =>
+ shifted(base, 0.045, 1.22, (l) => Math.max(0.04, l * 0.50));
+const mossCrown = (base) =>
+ shifted(base, -0.045, 0.86, (l) => Math.min(0.52, l * 1.75 + 0.05));
+const siltPale = (base) =>
+ shifted(base, 0.018, 0.72, (l) => Math.min(0.72, l * 1.00 + 0.03));
+const siltDamp = (base) =>
+ shifted(base, -0.018, 1.18, (l) => Math.max(0.04, l * 0.82));
+
+/**
+ * Grow moss and lichen on the side that never dries — and only there.
+ *
+ * Moss sprayed evenly over a rock is green paint; what reads as moss is
+ * that every rock, wall foot and trunk in the frame carries it on the
+ * SAME side, thickest low down where water lingers and in the crevices
+ * that hold it, and none at all on the face the sun bakes. Getting that
+ * direction right is the whole effect, so `north` — the world direction
+ * that stays shaded — is a uniform every material in a scene can share.
+ *
+ * FOUR TERMS DECIDE WHERE IT HOLDS. The SHADE is the cosine against
+ * `north`. Level faces hold rain whatever they face, so the cosine
+ * against `up` adds. CREVICES are the surface's own signed curvature:
+ * the concave lee keeps what a convex edge sheds — and curvature reads
+ * ZERO across a hard, unwelded edge (`BoxGeometry`'s corners, anything
+ * flat-shaded), so there the two cosines carry it alone. And it thins
+ * with height above the plane through the world origin, where an asset
+ * rests: splash, ground damp and shade all live at the foot. That foot
+ * is world-absolute, so a scene standing its ground at y = 40 gets the
+ * thin end of the fade everywhere rather than a wrong answer.
+ *
+ * THE SUN GATE IS MULTIPLICATIVE. A face turned to the sun loses the
+ * growth however generous the field is, keeping it only in the crevices
+ * that shade themselves — which is what stops this becoming an even
+ * green wash the moment `amount` is raised. Lichen rides the same gate
+ * at a finer grain and without the foot fade, because it crusts the
+ * exposed shaded stone that moss cannot hold.
+ *
+ * It MIXES over the albedo it is handed (and shades the material just
+ * outside its edge, the only thickness a patch that cannot displace
+ * geometry has), so a triplanar, a splat or a stain underneath survives
+ * everywhere the moss is thin. Gloss is per MATERIAL, not per pixel:
+ * moss is the mattest thing on any rock, so its factor goes UP.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` grows moss on every
+ * mesh wearing it, so clone it first (and clone BEFORE patching).
+ * @param {object} [opts] `amount` how much of the shaded side is taken,
+ * 0..1 (default 0.45; 0.15 is a trace in the crevices, 0.9 is a
+ * cushion); `color` THREE.Color or hex, the moss (default a deep damp
+ * green — the cushion's deep and crown tones and BOTH lichen tones
+ * are derived from it, so one option moves the whole family); `up`
+ * THREE.Vector3 or [x, y, z], the scene's up (default +Y); `north`
+ * THREE.Vector3 or
+ * [x, y, z], the world direction that stays SHADED, horizontal
+ * (default -Z); `seed` moves the growth (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uMossNorth` can swing with the
+ * sun a scene was lit for.
+ */
+export function patchMoss(material, opts = {}) {
+ const amount = opts.amount === undefined ? 0.45 : unit(opts.amount);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const up = upVector(opts.up);
+ const color = toColor(opts.color, 0x40592a);
+ // Moss is matte and it takes the gloss over only as far as it takes
+ // the surface over.
+ composeRoughness(material, 'damp:moss',
+ towardRoughness(material, 0.97, 0.70 * amount));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'damp:moss',
+ uniforms: {
+ uMossAmt: { value: amount },
+ uMossColor: { value: color },
+ uMossDeep: { value: mossDeep(color) },
+ uMossCrown: { value: mossCrown(color) },
+ uMossLichen: { value: lichenTone(color) },
+ uMossCrust: { value: crustTone(color) },
+ uMossUp: { value: up },
+ uMossNorth: { value: northVector(opts.north, up) },
+ uMossSeed: { value: seedOffset(seed, 0.4) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uMossAmt;',
+ 'uniform vec3 uMossColor;',
+ 'uniform vec3 uMossDeep;',
+ 'uniform vec3 uMossCrown;',
+ 'uniform vec3 uMossLichen;',
+ 'uniform vec3 uMossCrust;',
+ 'uniform vec3 uMossUp;',
+ 'uniform vec3 uMossNorth;',
+ 'uniform vec3 uMossSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 msN = normalize(vAstraWorldN);',
+ ' vec3 msUp = normalize(uMossUp);',
+ ' vec3 msNo = normalize(uMossNorth);',
+ // The shaded side: full on the face that looks north, gone on the
+ // one that looks at the sun. This is the whole effect.
+ ' float msFace = dot(msN, msNo);',
+ ' float msShade = smoothstep(-0.20, 0.55, msFace);',
+ ' float msLie = smoothstep(0.05, 0.70, dot(msN, msUp));',
+ // Crevices hold what an edge sheds. ~0.35 m features, the size of
+ // the hollows a cushion of moss actually fills.
+ ' float msCv = astraDampCurv(msN, vAstraWorld);',
+ ' float msLee = smoothstep(1.2, 6.0, -msCv);',
+ ' float msShed = smoothstep(1.8, 7.5, msCv);',
+ // Water lingers at the FOOT — splash, ground damp, and the shade
+ // of whatever is standing there — measured along `up` from the
+ // plane through the world origin, where an asset rests.
+ ' float msFoot = 1.0 - smoothstep(0.30, 2.60,',
+ ' dot(vAstraWorld, msUp));',
+ ' float msHold = clamp(msShade * 0.85 + msLie * 0.30',
+ ' + msLee * 0.70 - msShed * 0.55, 0.0, 1.6);',
+ ' msHold *= mix(0.30, 1.0, msFoot);',
+ // MULTIPLICATIVE, so no field can put moss on a baked face: it
+ // survives there only in the crevices that shade themselves.
+ ' float msSun = smoothstep(0.05, 0.75, -msFace)',
+ ' * (1.0 - msLee * 0.65);',
+ ' float msDry = 1.0 - clamp(msSun, 0.0, 1.0);',
+ ' msHold *= msDry;',
+ ' vec3 msW = astraDampAxes(msN);',
+ ' vec3 msP = vAstraWorld * 3.2 + uMossSeed;',
+ // Three octaves, not one: a cushion has clumps inside it and a
+ // torn edge, and one octave is an airbrush.
+ ' float msG = astraDampNoise(msP, msW) * 0.55',
+ ' + astraDampNoise(msP * 2.7, msW) * 0.28',
+ ' + astraDampNoise(msP * 7.9, msW) * 0.17;',
+ ' float msD = msHold * (0.42 + 1.10 * msG);',
+ // One threshold, torn by its own screen gradient: a clean edge is
+ // paint, and moss has none anywhere.
+ ' float msT = mix(1.05, 0.26, uMossAmt);',
+ ' float msAA = clamp(fwidth(msD), 0.0, 0.35);',
+ ' float msK = smoothstep(msT - 0.05 - msAA, msT + 0.14 + msAA, msD);',
+ // Lichen: the same direction, a finer grain, and no foot fade —
+ // it crusts the shaded stone above where moss can hold. TWO
+ // octaves, because one gives round blobs at one size, which read
+ // as mould spots rather than as a crust with a torn rim.
+ ' float msLi = astraDampNoise(msP * 7.7 + 5.3, msW) * 0.68',
+ ' + astraDampNoise(msP * 19.0 + 11.7, msW) * 0.32;',
+ ' float msLiK = smoothstep(0.52, 0.78, msLi) * msShade * msDry',
+ ' * (1.0 - msK) * max(msLie, 0.35);',
+ // The material just OUTSIDE the edge stays damp under the growth.
+ ' float msLip = (1.0 - msK)',
+ ' * smoothstep(msT - 0.55, msT - 0.02, msD);',
+ // `amount` 0 is OFF, which a threshold alone cannot say: a deep
+ // enough crevice would clear any threshold. Declared here with
+ // the rest of the MASK, so everything above this line is scalar
+ // maths a probe can lift out and evaluate against a swept normal.
+ ' float msOn = smoothstep(0.0, 0.05, uMossAmt);',
+ ' diffuseColor.rgb *= 1.0 - 0.20 * msLip;',
+ // THE CUSHION IS A HUE RANGE. Deep in the shade between the
+ // clumps, body green where it is thick, a yellow-green crown on
+ // the tips that see the sky — the field that tore the edge is the
+ // same field that says which of the three a pixel is.
+ ' vec3 msCol = mix(uMossDeep, uMossColor,',
+ ' smoothstep(0.14, 0.60, msG));',
+ ' msCol = mix(msCol, uMossCrown,',
+ ' 0.80 * smoothstep(0.58, 0.98,',
+ ' msG * (0.78 + 0.44 * msLi)));',
+ // Warm where the sun grazes it, cool where only the sky reaches —
+ // projected on the north/up plane, so a boulder and a wall break
+ // the same way and nothing needs a UV. Never on world Y.
+ ' vec2 msQ = vec2(dot(msP, msNo), dot(msP, msUp));',
+ ' msCol = astraHueBreak(msCol, msQ, 0.55, 0.20);',
+ // The crust is two colours too: pale sage where it is thick,
+ // ochre where it is thinning back to the stone.
+ ' vec3 msCr = mix(uMossCrust, uMossLichen,',
+ ' smoothstep(0.50, 0.84, msLi));',
+ // `amount` moved the THRESHOLD, so where the mask is full the
+ // growth is nearly opaque; multiplying by it again is a wash.
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, msCol,',
+ ' clamp(msK * msOn',
+ ' * mix(0.60, 1.0, uMossAmt), 0.0, 1.0));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, msCr,',
+ ' clamp(msLiK * msOn',
+ ' * mix(0.30, 0.62, uMossAmt),',
+ ' 0.0, 1.0));',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Darken and gloss the ground as it approaches water, out to `reach`.
+ *
+ * Ground within a few metres of a shoreline is visibly darker and
+ * glossier than the ground beyond it — the pores are full — and without
+ * that apron a lake sits on the land like a mirror dropped on a lawn.
+ * The edge is irregular, because the damp follows where the ground
+ * dips, never a contour.
+ *
+ * WHERE IT MEETS `patchShoreWet`. That patch owns the WATERLINE: the
+ * decimetres either side of `level`, fully wet below it and fading out
+ * over a `band` of ~0.25 m above. This owns the METRES beyond that, and
+ * the two are meant to be worn together — set `reach` to several metres
+ * and the apron hands over to the tide mark, which is darker again.
+ * They compose MULTIPLICATIVELY (both scale the albedo they are handed,
+ * neither assigns), so the overlap deepens rather than fighting; keep
+ * `strength` under `patchShoreWet`'s `darken` or the apron reads as the
+ * waterline and the real one disappears into it.
+ *
+ * REACH IS A HEIGHT, NOT A PLAN DISTANCE. A fragment sees its own
+ * position and nothing else — it cannot find where the shoreline runs —
+ * so the measure is world Y above `waterY`, exactly as
+ * `patchShallowWater` measures depth. A water surface is level by
+ * definition, so world Y is right here in a way it never is for a
+ * deposit, and it needs a bank that RISES: on ground climbing 1 m over
+ * 4 m, `reach: 1` darkens the first 4 m of it. Flat ground at the water's
+ * own level is damp all over, which is what a salt flat looks like.
+ *
+ * It MULTIPLIES the albedo it is handed and deepens its colour, so a
+ * triplanar, a splat or a wear pattern underneath comes through the
+ * apron rather than being replaced by it. Gloss is per MATERIAL, not
+ * per pixel, so the factor goes DOWN — the opposite direction from moss
+ * on the same chain.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material damps every mesh wearing it.
+ * @param {object} [opts] `waterY` world Y of the water surface (default
+ * 0); `reach` metres of HEIGHT above it the damp climbs, zero beyond
+ * (default 1.5); `strength` how dark it goes at the water's edge,
+ * 0..1 (default 0.45); `seed` moves the irregular edge (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uMoistY` can follow a tide.
+ */
+export function patchMoisture(material, opts = {}) {
+ const waterY = opts.waterY === undefined ? 0 : opts.waterY;
+ const reach = opts.reach === undefined ? 1.5 : Math.max(1e-3, opts.reach);
+ const strength = opts.strength === undefined ? 0.45 : unit(opts.strength);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Damp ground is the glossiest thing on a shore that is not water —
+ // but only a THIRD glossier than the ground it lands on, and never
+ // past wet soil: see `wetTarget` for what a fixed number did here.
+ composeRoughness(material, 'damp:moisture',
+ towardRoughness(material, wetTarget(material, 0.30, 0.68),
+ 0.45 * strength));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'damp:moisture',
+ uniforms: {
+ uMoistY: { value: waterY },
+ uMoistReach: { value: reach },
+ uMoistAmt: { value: strength },
+ uMoistSeed: { value: seedOffset(seed, 2.9) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uMoistY;',
+ 'uniform float uMoistReach;',
+ 'uniform float uMoistAmt;',
+ 'uniform vec3 uMoistSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float moH = vAstraWorld.y - uMoistY;',
+ ' float moT = clamp(moH / uMoistReach, 0.0, 1.0);',
+ // The edge wanders: a level contour is a ruled line no bank has.
+ ' float moN = astraFbm2(vAstraWorld.xz * 0.55',
+ ' + uMoistSeed.xz, 3) - 0.44;',
+ // The wander dies at BOTH ends of the ramp — the waterline is
+ // saturated whatever the noise says and `reach` is the reach — so
+ // it can only ever move the edge inside the apron.
+ ' float moW = clamp(moT + moN * 3.4 * moT * (1.0 - moT), 0.0, 1.0);',
+ // A capillary margin has an EDGE, not a gradient across the whole
+ // apron: the ramp is steep and the wander is what shapes it.
+ ' float moK = 1.0 - smoothstep(0.10, 0.80, moW);',
+ // Mottled, or the apron is a painted band; the field is centred
+ // so it cannot push the damp past the ramp either.
+ ' float moB = astraFbm2(vAstraWorld.xz * 1.9 + uMoistSeed.zx, 3);',
+ ' float moA = clamp(moK * uMoistAmt * (0.70 + 0.66 * moB),',
+ ' 0.0, 1.0);',
+ // THE CAPILLARY RIM. Water climbing a bank carries the ground's
+ // own dust with it and leaves it as a pale mineral bloom at the
+ // exact line it stops — which is the only thing that gives the
+ // apron an EDGE from twenty metres, where the darkening alone is
+ // a gradient with nothing to read. It rides the same wander, so
+ // the rim follows the damp rather than ruling its own contour,
+ // and BOTH ends are gated so nothing survives at or past `reach`.
+ ' float moR = smoothstep(0.55, 0.85, moW)',
+ ' * (1.0 - smoothstep(0.85, 1.00, moW))',
+ ' * (1.0 - smoothstep(0.80, 1.00, moT))',
+ ' * uMoistAmt * (0.55 + 0.55 * moB);',
+ // A third of a code value of screen dither: the ramp runs over
+ // metres of near-flat ground and there is no post chain here to
+ // break the steps for us. Gated by the apron's own strength, so
+ // a surface this patch does not reach is left untouched.
+ ' float moD = (astraHash21(gl_FragCoord.xy) - 0.5) * 0.008',
+ ' * max(moA, moR);',
+ // Wet ground is darker AND deeper in colour: pushing away from
+ // its own luminance is the saturation half of that. One write,
+ // folding in what it was handed — a patch that ASSIGNED here
+ // would erase the triplanar it lands on, and the bloom is that
+ // same albedo lifted and warmed rather than a colour of its own.
+ ' float moL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',
+ ' diffuseColor.rgb = clamp(',
+ ' mix(mix(vec3(moL), diffuseColor.rgb, 1.0 + 0.45 * moA)',
+ ' * (1.0 - 0.55 * moA),',
+ ' vec3(moL) * vec3(1.62, 1.54, 1.40), 0.42 * moR)',
+ ' + moD, 0.0, 1.0);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Crack a dried bed into curling polygons — cracks dark, plates pale.
+ *
+ * A lakebed, a paddy field in drought or the last puddle in a yard all
+ * dry the same way: the surface shrinks, tears into Voronoi polygons a
+ * hand's width across, and every plate curls up at its edges. A noise
+ * field cannot fake it, because what the eye reads is the STRAIGHT
+ * edges and sharp corners of the cells — so this measures the distance
+ * to the nearest cell BORDER (not F2 - F1, which rounds every corner
+ * off) and thresholds that into a crack.
+ *
+ * THE CURL IS THE SECOND HALF. A patch cannot displace geometry — a
+ * vertex displacement would tear a hard-edged bed open at its rim — so
+ * the lifted lip is a bright band just inside each crack and the crack
+ * itself is a dark line, which is exactly what a curled plate does to
+ * the light. `depth` widens the crack, darkens it and lifts the lip
+ * together, because a bed that dried harder did all three.
+ *
+ * `wet` fills the cracks with water instead of shadow: the network goes
+ * dark and cold rather than dusty, the plates keep their pale dry tops,
+ * and the material's gloss goes the other way — a drying bed is matte,
+ * a bed whose cracks still hold water is not.
+ *
+ * THE PLATES ARE READ FROM WORLD XZ, because a bed is level by
+ * definition (unlike a deposit, which needs the scene's own `up`), and
+ * the pattern thins from about 28 degrees off level and is gone by 57,
+ * where that projection would smear into stripes. The cell field is
+ * warped by a slow noise first, or every plate is the same size — and
+ * the same warp opens the cracks in one patch and leaves hairlines in
+ * the next, because a bed does not dry evenly.
+ *
+ * It MIXES over the albedo it is handed, weighted by how level the
+ * surface is, so a triplanar or a splat underneath still carries the
+ * bank while the flat of the bed cracks.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material cracks every mesh wearing it.
+ * @param {object} [opts] `scale` metres across one plate (default 0.35
+ * — 0.1 is a sun-baked crust, 1.0 a lakebed); `depth` how far the
+ * drying has gone, 0..1: crack width, darkness and curl together
+ * (default 0.5); `color` THREE.Color or hex, the dry plate (default a
+ * pale silt); `wet` 0..1 how much water is still in the cracks
+ * (default 0); `seed` moves the cells (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uMudWet` can dry over a shot.
+ */
+export function patchCrackedMud(material, opts = {}) {
+ const scale = opts.scale === undefined ? 0.35 : Math.max(1e-3, opts.scale);
+ const depth = opts.depth === undefined ? 0.5 : unit(opts.depth);
+ const wet = opts.wet === undefined ? 0 : unit(opts.wet);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const mudColor = toColor(opts.color, 0x9c8a71);
+ // Dry silt is the mattest thing in a bed and water standing in the
+ // cracks is the glossiest: ONE factor swings between the two. The dry
+ // end is absolute (silt is matte whatever it lands on); the wet end
+ // is relative, for the reason `wetTarget` gives — the cracks' gloss
+ // is charged to the whole plate, and a mirror-flat plate under a sky
+ // environment reads as a bright card, not as a bed holding water.
+ composeRoughness(material, 'damp:mud',
+ towardRoughness(
+ material,
+ 0.95 + (wetTarget(material, 0.30, 0.62) - 0.95) * wet,
+ 0.45));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'damp:mud',
+ uniforms: {
+ uMudScale: { value: scale },
+ uMudDepth: { value: depth },
+ uMudColor: { value: mudColor },
+ uMudPale: { value: siltPale(mudColor) },
+ uMudDamp: { value: siltDamp(mudColor) },
+ uMudWet: { value: wet },
+ uMudSeed: { value: seedOffset(seed, 5.1) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uMudScale;',
+ 'uniform float uMudDepth;',
+ 'uniform vec3 uMudColor;',
+ 'uniform vec3 uMudPale;',
+ 'uniform vec3 uMudDamp;',
+ 'uniform float uMudWet;',
+ 'uniform vec3 uMudSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 mdN = normalize(vAstraWorldN);',
+ // A bed is level: the cells are read from world XZ, and a face
+ // past ~45 degrees would smear that projection into stripes.
+ ' float mdLie = smoothstep(0.55, 0.88, mdN.y);',
+ ' vec2 mdP = vAstraWorld.xz / uMudScale + uMudSeed.xz;',
+ // Warped first, or every plate is the same size and the network
+ // reads as a tiling rather than as a surface that tore.
+ ' vec2 mdWp = vec2(astraFbm2(mdP * 0.31 + 7.1, 3),',
+ ' astraFbm2(mdP * 0.31 + 23.9, 3)) - 0.44;',
+ ' vec2 mdC = astraDampCells(mdP + mdWp * 1.10);',
+ // Crack width in CELLS, so one `depth` widens, darkens and lifts;
+ // water standing in a crack spreads it wider still.
+ ' float mdW = mix(0.010, 0.055, uMudDepth)',
+ ' * mix(1.0, 1.6, uMudWet)',
+ // A bed does not dry evenly: the same warp opens the cracks in
+ // one patch of it and leaves hairlines in the next.
+ ' * (1.0 + mdWp.x * 1.5);',
+ ' float mdAA = clamp(fwidth(mdC.x), 0.0, 0.25);',
+ ' float mdCrk = 1.0 - smoothstep(mdW, mdW * 2.6 + mdAA, mdC.x);',
+ // The lip: a plate curls UP at its edge, so the band just inside
+ // each crack catches the light the crack itself loses — and a
+ // soaked lip has nothing to catch it with.
+ ' float mdLip = smoothstep(mdW * 2.0, mdW * 5.5, mdC.x)',
+ ' * (1.0 - smoothstep(mdW * 6.0, mdW * 15.0, mdC.x))',
+ ' * (1.0 - 0.70 * uMudWet);',
+ // PER-PLATE TONE, AND IT IS A HUE. The plates did not all dry at
+ // the same hour: the ones that went first are pale and grey, the
+ // ones that held their water are darker and warmer, and the CELL
+ // hash is what makes them pieces rather than a pattern. A
+ // brightness ramp alone (which is what this was) reads as dirt on
+ // one flat chip of paint.
+ ' float mdG = astraFbm2(mdP * 3.3 + uMudSeed.zx, 3);',
+ ' vec3 mdPl = mix(uMudDamp, uMudPale,',
+ ' clamp(mdC.y * 1.16 - 0.08, 0.0, 1.0));',
+ ' mdPl *= (0.92 + 0.18 * mdG) * mix(1.0, 0.78, uMudWet);',
+ // Silt grain INSIDE the plate, at a finer scale than the plates:
+ // warm where the sun bakes it, cool in the film of shade a curl
+ // throws over itself.
+ ' mdPl = astraHueBreak(mdPl, mdP * 1.7, 1.0, 0.18);',
+ // A crack is a groove lit only by the sky, so its shadow is COOL
+ // — the one place on a sun-baked bed that is not warm.
+ ' vec3 mdDk = uMudColor * mix(0.34, 0.16, uMudDepth)',
+ ' * vec3(0.86, 0.95, 1.16);',
+ // Water in the crack, not shadow: far darker and cold, because a
+ // filled crack is a window into it rather than a shaded groove.
+ ' vec3 mdWc = uMudColor * 0.09 * vec3(0.75, 0.95, 1.30);',
+ ' vec3 mdCol = mix(mdPl, mix(mdDk, mdWc, uMudWet), mdCrk);',
+ // The lip catches the SUN, so it is warmer as well as brighter —
+ // a lip that only brightens reads as a highlight on plastic.
+ ' mdCol = mix(mdCol, mdCol * vec3(1.16, 1.06, 0.92),',
+ ' clamp(mdLip * 1.30, 0.0, 1.0));',
+ ' mdCol *= 1.0 + mdLip * mix(0.08, 0.30, uMudDepth);',
+ ' float mdAmt = clamp(mdLie * mix(0.55, 1.0, uMudDepth), 0.0, 1.0);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, mdCol, mdAmt);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js
new file mode 100644
index 00000000..d7a29cfa
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/dapple.js
@@ -0,0 +1,354 @@
+/**
+ * The moving light patches a canopy throws on everything under it.
+ *
+ * After aerial perspective this is the strongest single cue that a
+ * frame is OUTDOORS and under something living: a forest floor, a
+ * verandah under a vine, a street under plane trees. Without it the
+ * ground under a tree is a flat tone with a shadow blob on it.
+ *
+ * It goes on the material of the surface BEING LIT, not on the canopy,
+ * for the same reason `patchCaustics` does — the pattern belongs to the
+ * leaves overhead, which the floor knows nothing about. So the caller
+ * states where the canopy is and how dense it is.
+ *
+ * The gaps SLIDE ALONG THE SUN, not down the world axes: a gap in the
+ * canopy projects along the sun direction, so as the pattern drifts in
+ * the wind the patch on the ground travels the way the shadow of that
+ * gap would. Projecting straight down instead is the tell that turns
+ * dapple into a moving texture.
+ */
+
+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.
+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();
+
+// Half the sun's angular diameter, in radians (0.53 deg across). This is
+// the ONE number that sets how soft a sunfleck's edge is: the penumbra a
+// canopy `h` metres up throws is h * this, ~6 cm under a 7 m crown and
+// ~2 cm under a low vine. Measured against it, the edge of a 0.7 m fleck
+// is a tenth of the fleck wide — nearly hard. A smoothstep spread over
+// the noise's whole swing instead (what this file did until 2026-09-01)
+// blurs every fleck into the "cloudy" look the notes below warn about.
+const SUN_HALF_ANGLE = 0.00465;
+
+// How much the fbm field's value moves across one unit of its own domain
+// — measured over astraFbm2 at 3 octaves. Converting a distance (the
+// penumbra, a pixel footprint) into the value-space width a smoothstep
+// wants is a multiply by this and nothing more.
+const FIELD_SLOPE = 0.26;
+
+/** Warm sun through a gap; the low-sun end is what a fleck goes at dusk. */
+const FLECK_HIGH = new THREE.Color(0xffeec0);
+const FLECK_LOW = new THREE.Color(0xffc287);
+
+/**
+ * Dappled canopy light on the surface under it.
+ *
+ * The pattern is the union of two drifting fields at different scales,
+ * thresholded: leaf shadow is not a smooth wobble but a scatter of
+ * bright holes with hard-ish edges, and one octave of noise gives the
+ * cloudy blur that reads as fog on the floor instead. It lifts the
+ * light rather than the albedo — a sunfleck on a shaded floor is often
+ * the only direct light there is, and lifting albedo alone would cap it
+ * at the ambient the floor already receives, exactly the choice
+ * `windows.js` and `caustics.js` document.
+ *
+ * Three things make a fleck read as SUNLIGHT rather than as a pale
+ * texture, and all three are geometry the caller already stated:
+ * - its edge is a penumbra (`SUN_HALF_ANGLE * height`), not a fade
+ * across the noise's whole swing — and it widens again to whatever
+ * the pixel footprint is, so a floor running to the horizon greys
+ * out instead of crawling;
+ * - it is STRETCHED along the sun's ground track by 1/sin(elevation),
+ * the same way the round gap's shadow is: at a 38 deg sun a fleck is
+ * 1.6x longer than it is wide, and it is that elongation, not the
+ * brightness, that says where the sun is;
+ * - its rim is greener than its middle. Light that clipped a leaf on
+ * the way through carries the leaf's transmission, so a fleck runs
+ * warm-white in the core to yellow-green at the edge — a single flat
+ * colour is the tell of a decal.
+ *
+ * @param {THREE.Material} material Material of the LIT surface, patched
+ * in place. Needs a lit material with an `emissive` (a Standard or
+ * Physical); a Basic has none and a raw ShaderMaterial ignores this.
+ * @param {object} [opts] `sunDir` (THREE.Vector3) direction TOWARD the
+ * sun, the same vector the sun light sits on (default the day rig's);
+ * `height` metres from this surface up to the canopy (default 6) —
+ * what sets how far the pattern slides as it drifts AND how soft the
+ * flecks are, so a low vine and a high crown neither move nor blur
+ * alike; `scale` metres across one leaf gap (default 0.7); `density`
+ * 0..1 how much canopy there is (default 0.5) — 0 is open sky and
+ * lights everything, 1 is closed and lets almost nothing through;
+ * `strength` how bright a fleck goes (default 0.55); `speed` metres
+ * per second the canopy drifts (default 0.35); `color` (THREE.Color
+ * or hex) the light's own colour — the default is read off `sunDir`,
+ * warm-white overhead and orange near the horizon, so a dusk scene
+ * does not get noon flecks; `leaf` (THREE.Color or hex) what light
+ * through the leaf itself carries, the fleck's rim colour (default a
+ * yellow-green); `seed`.
+ * @returns {THREE.Material} The same material.
+ */
+export function patchDappledLight(material, opts = {}) {
+ const sun = (opts.sunDir ? opts.sunDir.clone() : DAY_SUN.clone())
+ .normalize();
+ const height = opts.height === undefined ? 6 : opts.height;
+ const scale = Math.max(0.05, opts.scale === undefined ? 0.7 : opts.scale);
+ const density = Math.min(1, Math.max(0,
+ opts.density === undefined ? 0.5 : opts.density));
+ const strength = opts.strength === undefined ? 0.55 : opts.strength;
+ const speed = opts.speed === undefined ? 0.35 : opts.speed;
+ // A fleck is a picture of THE SUN, so its colour is the sun's: the
+ // caller who set the rig low has already said the light is orange.
+ const warm = Math.min(1, Math.max(0, (sun.y - 0.05) / 0.45));
+ const color = opts.color === undefined
+ ? FLECK_LOW.clone().lerp(FLECK_HIGH, warm * warm * (3 - 2 * warm))
+ : new THREE.Color(opts.color);
+ const leaf = new THREE.Color(opts.leaf === undefined ? 0x9ec06a : opts.leaf);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+
+ if (!material.emissive) {
+ console.warn('patchDappledLight: needs a lit material (Standard or '
+ + 'Physical) — a sunfleck is light, not paint.');
+ }
+ // A canopy makes the floor under it damp and matte more often than
+ // not; a whole factor would fight a wet patch, so this is gentle.
+ composeRoughness(material, 'dapple', 1 + 0.06 * density);
+
+ // A fleck is the light that MISSED the canopy, so the albedo
+ // `patchCanopyShade` took away (its stand-in for the shadow three
+ // will not cast) must not be taken away from the fleck as well —
+ // that is what made a fleck in deep shade dimmer than one at the
+ // edge of the crown, which is backwards. The shade runs first, so
+ // its average cut is known here; give it back, capped, and only
+ // when the pair is really in use.
+ const can = material.userData.astraCanopy;
+ const comp = can
+ ? Math.min(1.7, 1 / Math.max(0.4,
+ 1 - can.depth * can.density * (0.72 + 0.28 * can.density)))
+ : 1;
+
+ return patchStandard(material, {
+ name: 'dapple',
+ uniforms: {
+ uDapSun: { value: sun },
+ uDapH: { value: height },
+ uDapScale: { value: scale },
+ uDapDens: { value: density },
+ uDapAmt: { value: strength * comp },
+ uDapSpeed: { value: speed },
+ uDapColor: { value: color },
+ uDapLeaf: { value: leaf },
+ uDapSeed: { value: seed },
+ },
+ vertexHead: 'varying vec3 vAstraDapW;\nvarying vec3 vAstraDapN;',
+ vertexBody: [
+ '#ifdef USE_INSTANCING',
+ ' vAstraDapW = (modelMatrix * instanceMatrix'
+ + ' * vec4(transformed, 1.0)).xyz;',
+ ' vAstraDapN = normalize(mat3(modelMatrix)'
+ + ' * mat3(instanceMatrix) * normal);',
+ '#else',
+ ' vAstraDapW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' vAstraDapN = normalize(mat3(modelMatrix) * normal);',
+ '#endif',
+ ].join('\n'),
+ fragmentHead: [
+ 'varying vec3 vAstraDapW;',
+ 'varying vec3 vAstraDapN;',
+ 'uniform float uTime;',
+ 'uniform vec3 uDapSun;',
+ 'uniform float uDapH;',
+ 'uniform float uDapScale;',
+ 'uniform float uDapDens;',
+ 'uniform float uDapAmt;',
+ 'uniform float uDapSpeed;',
+ 'uniform vec3 uDapColor;',
+ 'uniform vec3 uDapLeaf;',
+ 'uniform float uDapSeed;',
+ // Gaps, not clouds: fbm thresholded well above its mean leaves
+ // scattered holes with edges. Two scales union because a canopy
+ // has both leaf gaps and branch gaps — the leaf field is the
+ // common one and the branch field the rare wide hole, so its
+ // threshold sits ABOVE the other's; equal thresholds (what this
+ // did before) let the coarse field cover the floor and every
+ // fleck came out a metre-wide puddle.
+ //
+ // `w` is the edge width in VALUE space — the penumbra and the
+ // pixel, converted by the field's own slope; the branch field is
+ // 2.7x coarser, so the same distance is a smaller fraction of
+ // its swing.
+ //
+ // Returned as (gap, core): the core is the same gap eroded by
+ // one threshold step, i.e. the part of it the whole sun reaches.
+ // Taking the core off the gap VALUE instead would make the rim
+ // a couple of pixels wide once the edge is properly hard, and
+ // the leaf-green it carries would never be seen.
+ 'vec2 astraDapGaps(vec2 p, float d, float w) {',
+ ' float a = astraFbm2(p, 3);',
+ ' float b = astraFbm2(p * 0.37 + 11.3, 2);',
+ // A canopy is not evenly thin: gaps CROWD where the crown is
+ // sparse and give out under a thick one. Modulating the
+ // threshold at crown scale is what turns an even scatter —
+ // which reads as camouflage — into flecks that belong to a
+ // tree. This field drifts with the rest, so a thin patch of
+ // canopy travels over the floor as one.
+ ' float c = astraFbm2(p * 0.13 + 5.1, 2);',
+ ' float t = mix(0.28, 0.76, d) + (c - 0.375) * 0.45;',
+ ' float wb = 0.05 + w * 0.5;',
+ ' float ga = smoothstep(t - w, t + w, a);',
+ ' float gb = smoothstep(t + 0.10 - wb, t + 0.10 + wb, b);',
+ ' float ca = smoothstep(t + 0.035 - w, t + 0.035 + w, a);',
+ ' float cb = smoothstep(t + 0.145 - wb, t + 0.145 + wb, b);',
+ ' return vec2(max(ga, gb * 0.9), max(ca, cb * 0.9));',
+ '}',
+ ].join('\n'),
+ fragmentBody: [
+ // Where this fragment's sunbeam CROSSED the canopy. Sliding the
+ // sample point along the sun (not straight up) is what makes a
+ // fleck travel the way the gap's shadow would.
+ ' vec3 dpS = normalize(uDapSun);',
+ ' float dpUp = max(dpS.y, 0.15);',
+ ' vec2 dpAt = vAstraDapW.xz + dpS.xz * (uDapH / dpUp);',
+ ' vec2 dpP = dpAt / uDapScale + uDapSeed * 17.0;',
+ // The canopy drifts across the wind; the floor sees that drift
+ // magnified by how far overhead it is.
+ ' dpP += vec2(1.0, 0.35) * (uTime * uDapSpeed / uDapScale);',
+ // The gap's shadow is an ellipse: a slanted beam lands long. The
+ // sample is COMPRESSED along the sun's ground track, which is
+ // what stretches the pattern out along it in the world.
+ ' vec2 dpAx = dpS.xz;',
+ ' float dpAxL = length(dpAx);',
+ ' if (dpAxL > 1e-4) {',
+ ' dpAx /= dpAxL;',
+ ' float dpEl = clamp(1.0 / dpUp, 1.0, 3.0);',
+ ' dpP += dpAx * (dot(dpP, dpAx) * (1.0 / dpEl - 1.0));',
+ ' }',
+ // Edge = the sun's penumbra at this height, never finer than the
+ // pixel: the second term is what keeps a receding floor from
+ // boiling into noise.
+ ' float dpPen = ' + SUN_HALF_ANGLE.toFixed(5) + ' * uDapH / uDapScale;',
+ ' float dpAA = fwidth(dpP.x) + fwidth(dpP.y);',
+ ' float dpW = clamp((dpPen + dpAA) * ' + FIELD_SLOPE.toFixed(2) + ','
+ + ' 0.012, 0.40);',
+ ' vec2 dpGC = astraDapGaps(dpP, uDapDens, dpW);',
+ ' float dpG = dpGC.x;',
+ // Only what faces the sun catches a fleck, and a fleck on a
+ // surface already in full sun adds nothing anyone can see. The
+ // knee keeps a grazing face from wearing a hard lambert line.
+ ' float dpF = max(dot(normalize(vAstraDapN), dpS), 0.0);',
+ ' dpF *= smoothstep(0.0, 0.30, dpF);',
+ // Rim green, core sun, and no two flecks quite the same colour.
+ ' float dpCore = dpGC.y;',
+ ' vec3 dpTint = mix(uDapLeaf, uDapColor, dpCore);',
+ ' dpTint = astraHueBreak(dpTint, dpP, 0.23, 0.34);',
+ // The core of a fleck is the whole sun; its rim is a sliver of
+ // one. That ratio is what gives a bloom pass something to find.
+ ' float dpBeam = dpG * (1.0 + 2.2 * dpCore);',
+ ' totalEmissiveRadiance += dpTint * (uDapAmt * dpBeam * dpF'
+ + ' * diffuseColor.rgb);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * The shade a canopy casts, as a floor-level tint rather than a shadow.
+ *
+ * Three's shadow maps do not reach an instanced crown of billboards,
+ * and a forest floor lit exactly like open ground reads as a lawn with
+ * trees standing on it. This darkens and cools the surface by how much
+ * canopy is overhead, so `patchDappledLight`'s flecks have something
+ * to be flecks ON. Apply it before the dapple; both compose.
+ *
+ * `density` is COVERAGE: at 0.5 about half the floor is under crown.
+ * Until 2026-09-01 the depth of the shade was multiplied by the density
+ * as well as thresholded by it, so the default asked for half a canopy
+ * and got a 9% darkening — measured on our renderer, a 28 m floor came
+ * back with a 0.07 luminance range, i.e. a flat card. The shade is the
+ * expensive half of this file: flecks are only bright relative to it.
+ *
+ * @param {THREE.Material} material Material of the shaded surface.
+ * @param {object} [opts] `density` 0..1 (default 0.5); `scale` metres
+ * across one crown (default 6) — this is the CROWN scale, an order
+ * above the leaf-gap scale, so the two never beat together; `cool`
+ * (THREE.Color or hex) what the shade tints toward, default the green
+ * a canopy bounces down; `depth` 0..1 how dark the deepest shade goes
+ * (default 0.80 — never to black: what light a forest floor has is
+ * sky and bounce, and crushing it is the other way to lose the
+ * effect); `seed`.
+ * @returns {THREE.Material} The same material.
+ */
+export function patchCanopyShade(material, opts = {}) {
+ const density = Math.min(1, Math.max(0,
+ opts.density === undefined ? 0.5 : opts.density));
+ const scale = Math.max(0.5, opts.scale === undefined ? 6 : opts.scale);
+ const cool = new THREE.Color(
+ opts.cool === undefined ? 0x5d6b48 : opts.cool);
+ const depth = Math.min(1, Math.max(0,
+ opts.depth === undefined ? 0.80 : opts.depth));
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // What `patchDappledLight` gives back to its flecks; see there.
+ material.userData.astraCanopy = { density, depth };
+ return patchStandard(material, {
+ name: 'canopyShade',
+ uniforms: {
+ uCanDens: { value: density },
+ uCanScale: { value: scale },
+ uCanCool: { value: cool },
+ uCanDepth: { value: depth },
+ uCanSeed: { value: seed },
+ },
+ vertexHead: 'varying vec3 vAstraCanW;',
+ vertexBody: [
+ '#ifdef USE_INSTANCING',
+ ' vAstraCanW = (modelMatrix * instanceMatrix'
+ + ' * vec4(transformed, 1.0)).xyz;',
+ '#else',
+ ' vAstraCanW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ '#endif',
+ ].join('\n'),
+ fragmentHead: [
+ 'varying vec3 vAstraCanW;',
+ 'uniform float uCanDens;',
+ 'uniform float uCanScale;',
+ 'uniform vec3 uCanCool;',
+ 'uniform float uCanDepth;',
+ 'uniform float uCanSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec2 cnP = vAstraCanW.xz / uCanScale + uCanSeed * 5.0;',
+ // Crowns, and the grove they stand in: one field alone lays every
+ // tree down at the same size and the floor reads as a texture.
+ ' float cnA = astraFbm2(cnP, 3);',
+ ' float cnB = astraFbm2(cnP * 0.41 + 3.7, 2);',
+ ' float cnF = cnA * 0.72 + cnB * 0.28;',
+ // The threshold, not the amplitude, is what `density` moves: the
+ // field crosses it over about `density` of the ground.
+ ' float cnT = mix(0.72, 0.10, uCanDens);',
+ // A 28 m floor is 4 crowns across and every gradient on it is
+ // gentle enough to band on an 8-bit target; one bit of hash is
+ // cheaper than any dither texture.
+ ' float cnD = (astraHash21(gl_FragCoord.xy) - 0.5) * 0.012;',
+ ' float cnK = smoothstep(cnT, cnT + 0.30, cnF + cnD);',
+ // Deep shade is not just dark, it is GREEN — that light came
+ // through leaves — and no two patches of it are the same green.
+ ' vec3 cnTint = astraHueBreak(uCanCool, cnP, 1.7, 0.34);',
+ // Under the thickest crown the last light left is SKY, not the
+ // green bounced off the leaf above — so the deep end of the
+ // shade leans blue while its edge stays leaf-green. One flat
+ // tint over the whole range is what leaves shade reading as
+ // grey paint.
+ ' cnTint *= mix(vec3(1.0), vec3(0.84, 0.95, 1.14),',
+ ' smoothstep(0.5, 1.0, cnK));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, cnTint, cnK * 0.45);',
+ ' diffuseColor.rgb *= 1.0 - uCanDepth * cnK'
+ + ' * mix(0.72, 1.0, uCanDens);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js
new file mode 100644
index 00000000..4badaf76
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/environment.js
@@ -0,0 +1,583 @@
+/**
+ * The world beyond the scene, in one call — kills the void-background
+ * defect family. Three cheap layers far outside the playable area:
+ * a vertex-coloured gradient sky dome, a seeded ridge SILHOUETTE ring
+ * so the ground plane never meets bare sky, and fog whose colour
+ * equals the horizon tint so the far field dissolves instead of ending.
+ */
+
+import * as THREE from 'three';
+
+import { fbm2, mulberry32 } from './noise.js';
+import { patchStandard } from './shader.js';
+import { skyRadiance } from './sky.js';
+
+const MOODS = {
+ day: { zenith: 0x5d8fd6, horizon: 0xdbe3ea, ridge: 0x9fb2c4,
+ fogDensity: 0.0018 },
+ golden: { zenith: 0x3f5a9e, horizon: 0xf2c17e, ridge: 0x8c7a90,
+ fogDensity: 0.0022 },
+ night: { zenith: 0x060a18, horizon: 0x1d2a4a, ridge: 0x0c1226,
+ fogDensity: 0.0025 },
+ overcast: { zenith: 0x9aa6b2, horizon: 0xd8dde2, ridge: 0xaab4bd,
+ fogDensity: 0.003 },
+};
+
+/**
+ * Build the sky dome + horizon ridge + matched fog.
+ *
+ * @param {object} [opts]
+ * `rand` seeded PRNG (REQUIRED for the ridge silhouette);
+ * `mood` one of `day | golden | night | overcast` (default `day`);
+ * `radius` metres to the sky (default 4000 — far outside any scene);
+ * `bounds` content radius in metres (the same number `sunRig` takes)
+ * — clamps fog so the far edge of the content stays visible on
+ * km-scale worlds; `ridge` false to skip the silhouette ring (open
+ * ocean, deep space); `zenith`/`horizon`/`ridgeColor` hex overrides;
+ * `fogDensity` override (wins over the clamp).
+ * @returns {{group: THREE.Group, fog: THREE.FogExp2, radius: number}}
+ * Add `group` to the scene and assign `fog` to `scene.fog`.
+ */
+export function worldShell(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const mood = MOODS[opts.mood] || MOODS.day;
+ const radius = opts.radius || 4000;
+ const zenith = new THREE.Color(
+ opts.zenith === undefined ? mood.zenith : opts.zenith);
+ const horizon = new THREE.Color(
+ opts.horizon === undefined ? mood.horizon : opts.horizon);
+
+ const group = new THREE.Group();
+ group.name = 'WorldShell';
+
+ // SKY: gradient by vertex colour, rendered on the inside faces. A
+ // shader would be nicer; vertex colours are free and never break.
+ const sky = new THREE.SphereGeometry(radius, 32, 18);
+ const pos = sky.attributes.position;
+ const cols = new Float32Array(pos.count * 3);
+ const c = new THREE.Color();
+ for (let i = 0; i < pos.count; i++) {
+ // t: 1 at the zenith, 0 at (and below) the horizon.
+ const t = Math.max(0, pos.getY(i) / radius);
+ c.copy(horizon).lerp(zenith, Math.pow(t, 0.62));
+ cols[i * 3] = c.r; cols[i * 3 + 1] = c.g; cols[i * 3 + 2] = c.b;
+ }
+ sky.setAttribute('color', new THREE.BufferAttribute(cols, 3));
+ const skyMesh = new THREE.Mesh(sky, new THREE.MeshBasicMaterial({
+ vertexColors: true, side: THREE.BackSide, fog: false,
+ depthWrite: false,
+ }));
+ skyMesh.name = 'SkyGradient';
+ skyMesh.renderOrder = -2;
+ group.add(skyMesh);
+
+ // HORIZON RIDGE: seeded silhouette ring at 82% of the sky radius so
+ // the ground line meets hills, never void. Featureless on purpose —
+ // a backdrop, not terrain.
+ if (opts.ridge !== false) {
+ const rr = radius * 0.82;
+ const seg = 160;
+ const ridgeH = radius * 0.055;
+ const shape = [];
+ let h = 0.5;
+ for (let i = 0; i <= seg; i++) {
+ h = Math.max(0.12, Math.min(1,
+ h + (rand() - 0.5) * 0.35));
+ shape.push(h);
+ }
+ shape[seg] = shape[0]; // close the loop seamlessly
+ const geo = new THREE.BufferGeometry();
+ const verts = [];
+ for (let i = 0; i < seg; i++) {
+ const a0 = (i / seg) * Math.PI * 2;
+ const a1 = ((i + 1) / seg) * Math.PI * 2;
+ const x0 = Math.cos(a0) * rr, z0 = Math.sin(a0) * rr;
+ const x1 = Math.cos(a1) * rr, z1 = Math.sin(a1) * rr;
+ const y0 = shape[i] * ridgeH, y1 = shape[i + 1] * ridgeH;
+ // Two triangles: base ring (-ridgeH keeps the skirt below any
+ // terrain relief) up to the jagged crest.
+ verts.push(x0, -ridgeH, z0, x1, -ridgeH, z1, x0, y0, z0);
+ verts.push(x1, -ridgeH, z1, x1, y1, z1, x0, y0, z0);
+ }
+ geo.setAttribute('position',
+ new THREE.BufferAttribute(new Float32Array(verts), 3));
+ geo.computeVertexNormals();
+ const ridge = new THREE.Mesh(geo, new THREE.MeshBasicMaterial({
+ color: opts.ridgeColor === undefined ? mood.ridge : opts.ridgeColor,
+ side: THREE.DoubleSide, fog: false, depthWrite: false,
+ }));
+ ridge.name = 'HorizonRidge';
+ ridge.renderOrder = -1;
+ group.add(ridge);
+ }
+
+ // FOG matched to the horizon tint — the whole trick. Mood densities
+ // assume a ~450 m world; on km-scale scenes they dissolve the
+ // content, so `bounds` clamps rho <= 1.05 / (2*bounds) to keep the
+ // content's far edge >= 1/3 transmittance. Explicit fogDensity wins.
+ let density = mood.fogDensity;
+ if (opts.bounds) {
+ density = Math.min(density, 1.05 / Math.max(2 * opts.bounds, 150));
+ }
+ const fog = new THREE.FogExp2(
+ horizon.getHex(),
+ opts.fogDensity === undefined ? density : opts.fogDensity);
+
+ return { group, fog, radius };
+}
+
+/**
+ * The middle distance: land between the content and the horizon.
+ *
+ * `worldShell` closes the SKYLINE, but between the content's edge and
+ * its ridge the judge still sees "a diorama on a vast, empty flat
+ * plane" — measured on a scene that had a 6 km textured ground. This
+ * is that plane given relief, a field patchwork and tree clumps: an
+ * annulus that MATCHES the scene's ground at its inner seam and rises
+ * into fbm hills outward, plus one instanced layer of distant copses.
+ * Two draw calls, fogged like any land, deterministic in `seed`.
+ *
+ * @param {object} [opts]
+ * `inner` metres where the annulus starts — the content's radius
+ * (default 160); `shellRadius` the sky radius `worldShell` used
+ * (default 4000 — pass `shell.radius` when you overrode it);
+ * `outer` metres where it ends (default the shell's RIDGE line,
+ * `0.82 * shellRadius`, and clamped there: land must reach the
+ * backdrop or its edge is a visible cliff — measured, a 2 km
+ * annulus under a 3.28 km ridge left a 1.2 km pale void and the
+ * census flagged every camera with "terrain ends Nm ahead"; past
+ * the ridge it would instead paint over that silhouette);
+ * `baseY` ground level at the seam (default 0); `heightAt` (x, z) =>
+ * y, the scene's ground truth — the seam band blends from it into
+ * the relief so the joint cannot step; `relief` hill amplitude in
+ * metres at full distance (default 26); `rise` metres of gentle
+ * climb per metre of distance (default 0.004 — receding land reads
+ * flat without it); `colors` [a, b, c] hex field tones (default a
+ * muted scrub/field/dust trio); `clumps` distant-copse count
+ * (default 140, 0 disables); `clumpColor` hex (default dark
+ * grey-green); `seed` (default 7); `name` group name.
+ * @returns {THREE.Group} Named `Outskirts`; add it at the world origin
+ * the content is centred on.
+ */
+export function makeOutskirts(opts = {}) {
+ const inner = opts.inner === undefined ? 160 : opts.inner;
+ const shellRadius =
+ opts.shellRadius === undefined ? 4000 : opts.shellRadius;
+ // worldShell puts its ridge ring at 82% of the sky radius.
+ const ridgeR = shellRadius * 0.82;
+ const outer = Math.max(
+ Math.min(opts.outer === undefined ? ridgeR : opts.outer, ridgeR),
+ inner * 2);
+ const baseY = opts.baseY === undefined ? 0 : opts.baseY;
+ const heightAt =
+ typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const relief = opts.relief === undefined ? 26 : opts.relief;
+ const rise = opts.rise === undefined ? 0.004 : opts.rise;
+ const seed = opts.seed === undefined ? 7 : opts.seed;
+ const rand = mulberry32(seed);
+ const tones = (opts.colors || [0x7a7d5a, 0x8a825f, 0x6e7355])
+ .map((c) => new THREE.Color(c));
+
+ const group = new THREE.Group();
+ group.name = opts.name || 'Outskirts';
+
+ // RELIEF over a polar grid: amplitude zero at the seam, half by 1.8
+ // seam-radii — rolls must already read in the MIDDLE ground, or the
+ // annulus repeats the flat-plane defect it exists to kill. Shallow
+ // valleys allowed (-relief/4): land that only bulges reads as foam.
+ const noise = { seed, octaves: 4 };
+ // Centre the field on its own measured mean: fbm2's centre drifts by
+ // seed and region (grass.js clumpField measured the same), and an
+ // uncalibrated offset either buries the annulus or foams it.
+ let fbmMean = 0;
+ const CAL = 16;
+ for (let i = 0; i < CAL; i++) {
+ for (let j = 0; j < CAL; j++) {
+ const rr = inner + (outer - inner) * (i + 0.5) / CAL;
+ const aa = ((j + 0.5) / CAL) * Math.PI * 2;
+ fbmMean += fbm2(Math.cos(aa) * rr * 0.004,
+ Math.sin(aa) * rr * 0.004, noise);
+ }
+ }
+ fbmMean /= CAL * CAL;
+ const lift = (x, z, r) => {
+ const ramp = THREE.MathUtils.smoothstep(r, inner, inner * 1.8);
+ const h = (fbm2(x * 0.004, z * 0.004, noise) - fbmMean)
+ * relief * ramp + rise * (r - inner) * ramp;
+ const seam = heightAt
+ ? heightAt(x, z) * (1 - THREE.MathUtils.smoothstep(
+ r, inner, inner * 1.6))
+ : 0;
+ return baseY + Math.max(h, -relief * 0.25) + seam;
+ };
+
+ const RADIAL = 26;
+ const AROUND = 96;
+ const verts = [];
+ const at = (i, j) => {
+ // Radial spacing eases outward: detail near the seam, none far out.
+ const t = i / RADIAL;
+ const r = inner + (outer - inner) * t * t;
+ const a = (j / AROUND) * Math.PI * 2;
+ const x = Math.cos(a) * r;
+ const z = Math.sin(a) * r;
+ return [x, lift(x, z, r), z];
+ };
+ for (let i = 0; i < RADIAL; i++) {
+ for (let j = 0; j < AROUND; j++) {
+ const j1 = (j + 1) % AROUND;
+ verts.push(...at(i, j), ...at(i + 1, j), ...at(i, j1));
+ verts.push(...at(i + 1, j), ...at(i + 1, j1), ...at(i, j1));
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position',
+ new THREE.BufferAttribute(new Float32Array(verts), 3));
+ geo.computeVertexNormals();
+
+ // FIELDS in the fragment, not the lattice: a patchwork of worked
+ // land at km scale is what says "the world continues" — one fbm
+ // picks the field, a second lightens or tires it.
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.96, metalness: 0, name: 'OutskirtsLand',
+ });
+ patchStandard(mat, {
+ name: 'outskirts:fields',
+ uniforms: {
+ uOutA: { value: tones[0] },
+ uOutB: { value: tones[1] || tones[0] },
+ uOutC: { value: tones[2] || tones[0] },
+ },
+ vertexHead: 'varying vec2 vOutW;',
+ vertexBody:
+ ' vOutW = (modelMatrix * vec4(transformed, 1.0)).xz;',
+ fragmentHead: [
+ 'uniform vec3 uOutA;',
+ 'uniform vec3 uOutB;',
+ 'uniform vec3 uOutC;',
+ 'varying vec2 vOutW;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float ofPick = astraFbm2(vOutW * 0.0016, 3);',
+ ' vec3 ofCol = mix(uOutA, uOutB,',
+ ' smoothstep(0.35, 0.5, ofPick));',
+ ' ofCol = mix(ofCol, uOutC, smoothstep(0.58, 0.72, ofPick));',
+ ' ofCol *= 0.9 + 0.2 * astraFbm2(vOutW * 0.012 + 37.0, 2);',
+ ' diffuseColor.rgb = ofCol;',
+ ].join('\n'),
+ });
+ const land = new THREE.Mesh(geo, mat);
+ land.name = 'OutskirtsLand';
+ land.receiveShadow = false;
+ group.add(land);
+
+ // WOODS: one instanced layer of squashed dark blobs, CLUSTERED —
+ // 2-6 blobs strung along a heading make a copse or a hedgerow, and a
+ // lone pancake reads as debris. Placement is biased toward the seam
+ // (rand^1.8): that is the band a camera actually resolves, and 140
+ // singles spread over 28 km2 measured out to an empty plain.
+ const clumps = opts.clumps === undefined ? 220 : opts.clumps;
+ if (clumps > 0) {
+ const blob = new THREE.SphereGeometry(1, 6, 4);
+ blob.scale(1, 0.55, 1);
+ const cmat = new THREE.MeshStandardMaterial({
+ color: opts.clumpColor === undefined ? 0x46523c : opts.clumpColor,
+ roughness: 1, metalness: 0, name: 'OutskirtsCopse',
+ });
+ const cap = clumps * 8;
+ const copse = new THREE.InstancedMesh(blob, cmat, cap);
+ const m = new THREE.Matrix4();
+ const q = new THREE.Quaternion();
+ const s = new THREE.Vector3();
+ const p = new THREE.Vector3();
+ const tint = new THREE.Color();
+ // Woods gather in azimuth SECTORS with open field between them: an
+ // even collar of bushes read as a hedge wall around the diorama.
+ const sectors = [];
+ const nSec = 5 + Math.floor(rand() * 4);
+ for (let i = 0; i < nSec; i++) {
+ sectors.push(rand() * Math.PI * 2);
+ }
+ let n = 0;
+ for (let i = 0; i < clumps && n < cap; i++) {
+ const r = inner * 1.08
+ + (outer * 0.8 - inner * 1.08) * Math.pow(rand(), 1.8);
+ const a = sectors[Math.floor(rand() * nSec)]
+ + (rand() - 0.5) * 0.55;
+ const heading = rand() * Math.PI * 2;
+ const wood = 3 + Math.floor(rand() * 6);
+ const spread = 8 + 26 * rand();
+ for (let k = 0; k < wood && n < cap; k++) {
+ const along = (k / wood - 0.5) * spread * wood * 0.5;
+ const x = Math.cos(a) * r + Math.cos(heading) * along
+ + (rand() - 0.5) * spread;
+ const z = Math.sin(a) * r + Math.sin(heading) * along
+ + (rand() - 0.5) * spread;
+ const rr = Math.hypot(x, z);
+ if (rr < inner * 1.02) continue;
+ // Crowns, not boulders: several small lobes overlapping close
+ // to the ground read as canopy; one huge lobe reads as a rock.
+ const sc = (5 + 9 * rand()) * (0.85 + 0.6 * (rr / outer));
+ p.set(x, lift(x, z, rr) + sc * 0.55 * 0.45, z);
+ s.set(sc * (0.8 + 0.5 * rand()), sc * 0.55, sc);
+ q.setFromAxisAngle(
+ new THREE.Vector3(0, 1, 0), rand() * Math.PI);
+ copse.setMatrixAt(n, m.compose(p, q, s));
+ // instanceColor MULTIPLIES material.color: the jitter must sit
+ // around white, or the base tint is applied twice and the
+ // whole layer renders near-black (measured).
+ const f = 0.85 + 0.45 * rand();
+ tint.setRGB(f * (0.92 + 0.12 * rand()),
+ f * (0.95 + 0.10 * rand()),
+ f * (0.88 + 0.12 * rand()));
+ copse.setColorAt(n, tint);
+ n++;
+ }
+ }
+ copse.count = n;
+ copse.instanceMatrix.needsUpdate = true;
+ if (copse.instanceColor) copse.instanceColor.needsUpdate = true;
+ copse.name = 'OutskirtsCopses';
+ group.add(copse);
+ }
+ return group;
+}
+
+
+// Per-mood sun rig numbers lifted from the flagship scenes the audits
+// hold up, re-measured on THIS renderer (ACES, exposure 1.0, no post
+// chain, three's physical light units — a directional intensity I on a
+// white lambert surface is I/pi of radiance). `fillFloor` is a hard
+// readability floor: scenes below it rendered 70-90% pure black.
+// `glowCore`/`glowHalo` are LINEAR HDR radiances added to the baked
+// environment on the light vector (a half-float bake, so the sun's
+// reflection in water and chrome is a real highlight, not a clipped
+// white blob); the moon (night) is a soft cool patch.
+const RIGS = {
+ day: { sun: 0xfff0d8, intensity: 5.4, azimuth: 35, elevation: 48,
+ fillSky: 0x9db8e8, fillGround: 0x8a7f6a, fill: 1.4,
+ sunFloor: 4.5,
+ fillFloor: 1.2, glowCore: 5.0, glowHalo: 0.35, disc: true,
+ discColor: 0xfff6e0 },
+ golden: { sun: 0xffb36b, intensity: 5.6, azimuth: 35, elevation: 10,
+ fillSky: 0x9bb8ff, fillGround: 0x8a6f5a, fill: 1.1,
+ sunFloor: 4.5,
+ fillFloor: 1.0, glowCore: 5.0, glowHalo: 0.6, disc: true,
+ discColor: 0xffd9a0 },
+ // Night is a MOON rig. Measured on this renderer: the reference's
+ // moon 0.8 / fill 0.6 (graded for a post chain at exposure 1.1) put
+ // the ground at 17/255 and every wall at 4 — 30-40% of the frame
+ // under the dark threshold. 2.2 / 1.0 reads "dark but lit": ground
+ // ~45, shade ~14, sky 26-38. No sun floor: night asks stand.
+ night: { sun: 0xb5c7e8, intensity: 2.2, azimuth: 35, elevation: 45,
+ fillSky: 0x3f5378, fillGround: 0x2a2a33, fill: 1.0,
+ fillFloor: 0.8, glowCore: 1.6, glowHalo: 0.06, disc: true,
+ discColor: 0xe8eef8 },
+ overcast: { sun: 0xdfe4ea, intensity: 2.6, azimuth: 35, elevation: 55,
+ fillSky: 0xc5ccd4, fillGround: 0x6f7377, fill: 2.0,
+ sunFloor: 2.0,
+ fillFloor: 1.6, glowCore: 0.25, glowHalo: 0.3, disc: false,
+ discColor: 0xe9edf2 },
+};
+
+/**
+ * The matched sun + fill + environment + sun-disc package. Failing
+ * scenes break this package piecewise; built here, the env-map sun,
+ * the shadow sun and the visible disc agree by construction and the
+ * environment texture is never degenerate.
+ *
+ * The environment is baked from the SAME graded sky model the dome in
+ * ./sky.js draws (`skyRadiance`), as a linear half-float equirect: what
+ * a chrome ball, a puddle or a window reflects is the sky the camera
+ * sees, sun-side haze and all, and the sun in it is HDR (radiance
+ * `glowCore`) so it reads as a highlight — bloom-friendly, never a
+ * clipped white band. Overcast keeps the flat gradient bake.
+ *
+ * A SET SUN IS NIGHT: `elevation` below 0 (any mood) switches to the
+ * night rig — the key light becomes a moon opposite the sun's azimuth
+ * (elevation 30-55), the fill and env take the night mood, the disc is
+ * the moon. `sunDir` still reports the authored (below-horizon) sun so
+ * `makeSky()` paints twilight/night on it; `lightDir` is the vector the
+ * shadow light actually uses (equal to `sunDir` by day).
+ *
+ * @param {object} [opts]
+ * `mood` one of `day | golden | night | overcast` (default `day`;
+ * `night` is a moon rig); `bounds` radius in metres of the content
+ * the shadow frustum must cover (default 150); `azimuth`/`elevation`
+ * sun direction in degrees (per-mood defaults; golden sits low);
+ * `sunColor`/`intensity` sun overrides; `fill` hemisphere intensity,
+ * clamped UP to the mood's readability floor (night floor 0.55);
+ * `zenith`/`horizon` hex overrides matching `worldShell()`'s (used by
+ * the overcast/gradient bake and the below-horizon half);
+ * `radius` sky radius the disc sits inside (default 4000, matching
+ * `worldShell`); `disc` true/false forces the visible disc (default
+ * on, except overcast).
+ * @returns {{sun: THREE.DirectionalLight, fill: THREE.HemisphereLight,
+ * envTex: THREE.DataTexture, sunDisc: THREE.Mesh|null,
+ * sunDir: THREE.Vector3, lightDir: THREE.Vector3, night: boolean,
+ * moonDir: THREE.Vector3|null, mood: string}}
+ * Add `sun`, `fill` (and `sunDisc` when present) to the scene and
+ * assign `envTex` to `scene.environment`. The sun aims at the origin.
+ * `sunDir` is the normalized sun vector — for a physical atmosphere
+ * dome hand the whole rig to `makeSky(scene, { rig })` from ./sky.js,
+ * which slaves the dome to this vector and hides the flat disc (the
+ * Preetham shader draws its own sun; a night rig's moon disc stays).
+ */
+export function sunRig(opts = {}) {
+ let moodName = RIGS[opts.mood] ? opts.mood : 'day';
+ const bounds = opts.bounds || 150;
+ const radius = opts.radius || 4000;
+
+ // The one light vector everything below shares — sun position, baked
+ // env glow and visible disc can therefore never disagree.
+ const azDeg = opts.azimuth === undefined ? RIGS[moodName].azimuth : opts.azimuth;
+ const elDeg = opts.elevation === undefined ? RIGS[moodName].elevation : opts.elevation;
+ const belowHorizon = elDeg < 0;
+ if (belowHorizon) moodName = 'night';
+ const rig = RIGS[moodName];
+ const mood = MOODS[moodName];
+ const night = moodName === 'night';
+ const zenith = new THREE.Color(
+ opts.zenith === undefined ? mood.zenith : opts.zenith);
+ const horizon = new THREE.Color(
+ opts.horizon === undefined ? mood.horizon : opts.horizon);
+ const toDir = (az, el) => new THREE.Vector3(
+ Math.cos(el) * Math.cos(az), Math.sin(el), Math.cos(el) * Math.sin(az));
+ const dir = toDir(azDeg * Math.PI / 180, elDeg * Math.PI / 180);
+ // A set sun lights nothing from under the ground: the moon rises
+ // opposite it, 30-55 deg up (deeper sun, higher moon).
+ const moonDir = belowHorizon
+ ? toDir((azDeg + 180) * Math.PI / 180,
+ Math.max(30, Math.min(55, 25 - elDeg)) * Math.PI / 180)
+ : (night ? dir.clone() : null);
+ const lightDir = belowHorizon ? moonDir.clone() : dir.clone();
+
+ // SUN: shadow-casting directional, ortho frustum fitted to `bounds`.
+ // The sky dome is an UNLIT basic material at its literal hex while
+ // the world is PBR-lit, and the two were never calibrated against
+ // each other: measured over 11 delivered scenes, a midday meadow's
+ // ground sat at 0.17 of its own sky (a lit subject lands near 0.5).
+ // Requests below the floor are clamped UP, exactly as `fill` is —
+ // a scene that asks for 2.8 in daylight is asking for dusk it did
+ // not mean, and every colour in it dies with the light.
+ const sun = new THREE.DirectionalLight(
+ opts.sunColor === undefined ? rig.sun : opts.sunColor,
+ Math.max(rig.sunFloor || 0,
+ opts.intensity === undefined ? rig.intensity
+ : opts.intensity));
+ sun.name = 'SunRigSun';
+ sun.position.copy(lightDir).multiplyScalar(bounds * 2);
+ sun.castShadow = true;
+ // The map is sized to the FRUSTUM, not fixed: an ortho box of 2*bounds
+ // metres on a flat 2048 map gave every scene whatever texel it happened
+ // to get, and the library default (bounds 150) landed at 0.146 m —
+ // measured 2026-09-01, the contact shadow of a 1 m sphere came back as
+ // a 14-texel staircase on OUR PCFSoftShadowMap (no post chain to hide
+ // it). Target 0.05 m/texel, clamped to the 1024..4096 a WebGL2 context
+ // can be relied on for; the 4096 depth map is ~33 MB, one light.
+ const shadowRes = Math.max(1024, Math.min(4096,
+ 2 ** Math.ceil(Math.log2(Math.max(1, (2 * bounds) / 0.05)))));
+ sun.shadow.mapSize.set(shadowRes, shadowRes);
+ const texel = (2 * bounds) / shadowRes;
+ // Acne is cured along the NORMAL (one texel of it), not by pushing the
+ // whole depth back: a constant bias big enough for a 0.3 m texel is
+ // what detaches a shadow from the foot of the thing casting it.
+ sun.shadow.bias = -0.0001;
+ sun.shadow.normalBias = texel;
+ sun.shadow.camera.left = -bounds;
+ sun.shadow.camera.right = bounds;
+ sun.shadow.camera.top = bounds;
+ sun.shadow.camera.bottom = -bounds;
+ sun.shadow.camera.near = bounds * 0.5;
+ sun.shadow.camera.far = bounds * 3.5;
+
+ // FILL: hemisphere with a per-mood readability FLOOR. Requests below
+ // the floor are clamped UP — under-filling is the measured failure.
+ // The darkest tenth of a frame is not shade the fill reaches — it is
+ // albedo the libraries have already multiplied toward zero at contact
+ // points, and no light colour rescues a black albedo.
+ const fill = new THREE.HemisphereLight(
+ rig.fillSky, rig.fillGround,
+ Math.max(rig.fillFloor,
+ opts.fill === undefined ? rig.fill : opts.fill));
+ fill.name = 'SunRigFill';
+
+ // ENV: linear half-float equirect. 256 wide, not 64: PMREM sizes its
+ // cube at width/4, so 64 gave every metal, glass and water reflection
+ // in the corpus a 16 px source. Never 1 px on either axis — width 1
+ // emits invalid GLSL and every lit material fails.
+ const w = 256;
+ const h = 128;
+ const data = new Uint16Array(w * h * 4);
+ const groundC = new THREE.Color(rig.fillGround);
+ const glowC = new THREE.Color(rig.discColor);
+ const px = new THREE.Vector3();
+ const pc = new THREE.Color();
+ // The explicit night mood is a moon rig with its light ABOVE the
+ // horizon: the sky model must still see a set sun, or it bakes noon.
+ const skySun = night && dir.y >= 0
+ ? new THREE.Vector3(dir.x, -0.6, dir.z).normalize() : dir;
+ const skyAt = (v) => {
+ if (moodName === 'overcast') {
+ pc.copy(horizon).lerp(zenith, Math.pow(v.y, 0.62));
+ return [pc.r, pc.g, pc.b];
+ }
+ return skyRadiance(v, skySun);
+ };
+ // The ground half is the horizon radiance tinted by the ground: what a
+ // lit field bounces back up (warm by day, near-black at night).
+ const hz = skyAt(new THREE.Vector3(1, 0.001, 0));
+ const ground = [hz[0] * groundC.r * 1.6, hz[1] * groundC.g * 1.6, hz[2] * groundC.b * 1.6];
+ const half = THREE.DataUtils.toHalfFloat;
+ for (let row = 0; row < h; row++) {
+ // Row 0 is v=0, the nadir: three's equirect shader samples at
+ // v = 0.5 + asin(dir.y) / PI and a DataTexture never flips Y.
+ const lat = ((row + 0.5) / h - 0.5) * Math.PI;
+ for (let col = 0; col < w; col++) {
+ const lon = ((col + 0.5) / w - 0.5) * Math.PI * 2;
+ px.set(Math.cos(lat) * Math.cos(lon), Math.sin(lat),
+ Math.cos(lat) * Math.sin(lon));
+ let c;
+ if (px.y >= 0) {
+ c = skyAt(px);
+ } else {
+ const t = Math.min(1, -px.y * 3);
+ c = [hz[0] + (ground[0] - hz[0]) * t, hz[1] + (ground[1] - hz[1]) * t,
+ hz[2] + (ground[2] - hz[2]) * t];
+ }
+ const ang = Math.acos(Math.max(-1, Math.min(1, px.dot(lightDir))));
+ const glow = rig.glowCore * Math.exp(-(ang * ang) / 0.004) +
+ rig.glowHalo * Math.exp(-(ang * ang) / 0.245);
+ const i = (row * w + col) * 4;
+ data[i] = half(c[0] + glowC.r * glow);
+ data[i + 1] = half(c[1] + glowC.g * glow);
+ data[i + 2] = half(c[2] + glowC.b * glow);
+ data[i + 3] = half(1);
+ }
+ }
+ const envTex = new THREE.DataTexture(data, w, h, THREE.RGBAFormat, THREE.HalfFloatType);
+ envTex.mapping = THREE.EquirectangularReflectionMapping;
+ envTex.colorSpace = THREE.LinearSRGBColorSpace;
+ envTex.magFilter = THREE.LinearFilter;
+ envTex.minFilter = THREE.LinearFilter;
+ envTex.needsUpdate = true;
+
+ // SUN DISC (moon at night): on the SAME normalized light vector, at
+ // 90% of the sky radius so worldShell's horizon ridge (82%) occludes
+ // it at the skyline the way hills occlude a low sun.
+ let sunDisc = null;
+ if (opts.disc === undefined ? rig.disc : opts.disc) {
+ sunDisc = new THREE.Mesh(
+ new THREE.CircleGeometry(radius * (night ? 0.007 : 0.012), 24),
+ new THREE.MeshBasicMaterial({
+ color: rig.discColor, fog: false, depthWrite: false,
+ }));
+ sunDisc.name = night ? 'MoonDisc' : 'SunDisc';
+ sunDisc.position.copy(lightDir).multiplyScalar(radius * 0.9);
+ sunDisc.lookAt(0, 0, 0);
+ sunDisc.renderOrder = -1.5;
+ }
+
+ return { sun, fill, envTex, sunDisc, sunDir: dir.clone(), lightDir,
+ night, moonDir, mood: moodName };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/figure.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/figure.js
new file mode 100644
index 00000000..38c8340b
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/figure.js
@@ -0,0 +1,510 @@
+/**
+ * A human, with real proportions and joints that pose — the guessed
+ * arithmetic (seat heights, gait, tapers) ships as functions because
+ * prose never landed. Standard 7.5-head figure, FEET AT y=0, facing
+ * -Z, so `seat()` and `alignAlong()` from place.js work unchanged.
+ * `walk()` owns the gait contract: pass the route's `speed` and the
+ * feet match the ground covered by construction.
+ */
+
+import * as THREE from 'three';
+import * as MAT from './materials.js';
+
+/**
+ * A tapered limb segment hanging down -Y from its pivot. The taper is
+ * most of what makes a silhouette read as a person at 30 metres.
+ *
+ * @param {number} len Segment length in metres.
+ * @param {number} r0 Radius at the pivot end.
+ * @param {number} r1 Radius at the free end.
+ * @param {THREE.Material} mat
+ * @param {string} name
+ * @returns {THREE.Mesh} Positioned so its top sits at the pivot.
+ */
+function seg(len, r0, r1, mat, name) {
+ const g = new THREE.CylinderGeometry(r1, r0, len, 8, 1, false);
+ g.translate(0, -len / 2, 0);
+ const m = new THREE.Mesh(g, mat);
+ m.name = name;
+ m.castShadow = true;
+ // A ball cap at the pivot: a flat-capped cylinder opens a visible
+ // wedge at every bent knee and elbow (worst on seated crowds at
+ // close cameras). ~30 tris buys articulation at any bend angle.
+ const cap = new THREE.Mesh(new THREE.SphereGeometry(r0, 6, 5), mat);
+ cap.castShadow = true;
+ m.add(cap);
+ return m;
+}
+
+/** An empty pivot at a local point, named so poses can find it. */
+function pivot(name, x, y, z) {
+ const o = new THREE.Object3D();
+ o.name = name;
+ o.position.set(x, y, z);
+ return o;
+}
+
+// A ladder of complexions, warm through olive to deep, with the HUE
+// moving as well as the value (a crowd graded only in lightness reads
+// as one person under five lamps). Every entry stays inside the
+// non-emissive albedo window: the brightest channel here is 0xcc, and
+// the old code's real bug was handing MAT.skin `color: undefined`,
+// which `Object.assign` copied OVER the default — every face in every
+// scene rendered at albedo 1.0, i.e. a blown white ball.
+const SKIN_TONES = [0xcca07d, 0xc08e63, 0xa2764c, 0x8a6446, 0x805334,
+ 0x5b3c2a];
+
+// One shared eye material for the whole scene: low roughness so the
+// environment puts a single specular dot on each eye, which is the
+// entire difference between a face and a ball at a close camera.
+let _eyeMat = null;
+function eyeMaterial() {
+ if (!_eyeMat) {
+ // Dark, but not below the albedo floor the rest of the figure keeps:
+ // a pupil at linear 0.013 is a hole, and the specular dot is what
+ // sells an eye anyway.
+ _eyeMat = new THREE.MeshStandardMaterial(
+ { color: 0x352a20, roughness: 0.22, metalness: 0 });
+ }
+ return _eyeMat;
+}
+
+/** Never let a colour fall to a light-swallowing void (dark hair, dark
+ * shoes): floor its LINEAR lightness, keeping hue and saturation. */
+function floorValue(hex, minL) {
+ const c = new THREE.Color(hex);
+ const hsl = c.getHSL({ h: 0, s: 0, l: 0 });
+ if (hsl.l < minL) c.setHSL(hsl.h, hsl.s, minL);
+ return c;
+}
+
+/**
+ * Build an articulated human.
+ *
+ * @param {object} [opts]
+ * `height` metres (default 1.72), `build` 0.8 slight to 1.25 heavy
+ * (default 1), `fem` 0..1 slides the shoulder:hip width ratio from
+ * the measured male 1.4 to the female 1.2 biacromial:biiliac mean —
+ * two scalars that turn one generator into a mixed crowd, `rand`
+ * seeded PRNG used for the small per-person variation that keeps a
+ * crowd from looking cloned, `skin`, `top`, `bottom`, `hair` hex
+ * colours (`skin` unset picks a complexion off SKIN_TONES from the
+ * same draw that sets the material variant — so a crowd is mixed
+ * without multiplying the material cache), `face` false to drop the
+ * eyes and nose on figures that will never be seen close, `name`.
+ * @returns {THREE.Group} Feet at y=0, facing -Z, with `userData.forward`
+ * `'-Z'`, `userData.height`, and `userData.joints` naming every pivot
+ * (`waist`, `neck`, `hipL/R`, `kneeL/R`, `ankleL/R`, `shoulderL/R`,
+ * `elbowL/R`).
+ */
+export function figure(opts = {}) {
+ const rand = opts.rand || (() => 0.5);
+ const h = (opts.height || 1.72) * (0.96 + rand() * 0.08);
+ const b = opts.build || (0.9 + rand() * 0.25);
+ const fem = opts.fem === undefined ? 0 : opts.fem;
+
+ // ONE draw picks both the complexion and the material variant, so the
+ // skin cache stays at one material per variant bucket however many
+ // tones the ladder holds — a crowd costs no more textures than before.
+ const skinV = rand();
+ // Quantised to the SAME 9 buckets materials.js quantises `variant`
+ // into, so the tone is a function of the bucket and the pair stays
+ // 1:1 — a ladder of six tones still costs nine skin materials, not
+ // the thirteen two independent partitions would produce.
+ const skinQ = Math.round(skinV * 8) / 8;
+ const skinCol = opts.skin === undefined
+ ? SKIN_TONES[Math.min(SKIN_TONES.length - 1,
+ Math.floor(skinQ * SKIN_TONES.length))]
+ : opts.skin;
+ // Hue break, not just value break: real skin is pink at the knuckles
+ // and olive in the shadow, and a flat albedo is what makes a figure
+ // read as a mannequin however good the silhouette is.
+ const skin = MAT.skin({ color: skinCol, variant: skinV,
+ contrast: 0.13, hueBreak: 0.15, scale: 26, roughness: 0.58 });
+ const top = MAT.fabric({ color: opts.top === undefined ? 0x44506b
+ : opts.top, variant: rand(), contrast: 0.30, hueBreak: 0.15,
+ scale: 46 });
+ const bottom = MAT.fabric({ color: opts.bottom === undefined ? 0x2f3440
+ : opts.bottom, variant: rand(), contrast: 0.26, hueBreak: 0.12,
+ scale: 34 });
+ // Leather, not the painted-wood grain the first port put on a shoe;
+ // the value is floored off black so a shoe is a dark object in the
+ // scene's light rather than a hole in the frame.
+ // No roughness map and a high roughness on purpose: the noise
+ // roughnessMap dips to a near-mirror in places, and on the UPWARD
+ // face of a shoe that is a full sky reflection — measured as a
+ // blown white (159,152,139) toe cap on a 0x3a albedo.
+ const shoe = MAT.fabric({ color: 0x3a332c, roughness: 0.78, scale: 55,
+ contrast: 0.18, hueBreak: 0.08, bump: 0.004,
+ extra: { roughnessMap: null } });
+
+ const root = new THREE.Group();
+ root.name = opts.name || 'Figure';
+
+ const hipY = 0.53 * h;
+ const shoulderY = 0.82 * h;
+ const shoulderX = (0.115 - 0.018 * fem) * h * b;
+ const hipX = 0.052 * h;
+ const thigh = 0.25 * h;
+ const shin = 0.24 * h;
+ const upper = 0.19 * h;
+ const fore = 0.145 * h; // canon 0.146h: the wrist lands at the crotch
+
+ // Torso hangs off a waist pivot so a figure can lean or slump. A
+ // lathe, not a cylinder: the S-curve is the strongest silhouette cue
+ // and the neck ramp kills the coat-hanger read of a flat-topped torso.
+ const waist = pivot('waist', 0, hipY, 0);
+ const prof = [
+ [0.088 * (1 + 0.12 * fem) * b, 0], // hip
+ [0.070 * (1 - 0.08 * fem) * b, 0.07], // waist
+ [0.105 * (1 - 0.08 * fem) * b, 0.19], // chest
+ [0.095 * (1 - 0.10 * fem), 0.27], // shoulder
+ [0.032, 0.29], // trapezius ramp to neck
+ ];
+ const chest = new THREE.Mesh(
+ // 12 radial segments, not 10: at a close camera the 10-segment
+ // lathe threw a hard vertical facet crease down the chest, and
+ // the extra two rings cost 8 quads on the whole body.
+ new THREE.LatheGeometry(
+ prof.map((q) => new THREE.Vector2(q[0] * h, q[1] * h)), 12),
+ top);
+ chest.geometry.scale(1, 1, 0.62); // people are not cylinders in plan
+ chest.name = 'torso';
+ chest.castShadow = true;
+ waist.add(chest);
+
+ // Pelvis: below the hip line nothing existed, so a seated figure
+ // showed a see-through crotch the moment the thighs went horizontal.
+ const pelvis = new THREE.Mesh(
+ new THREE.SphereGeometry(0.095 * h * b * (1 + 0.10 * fem), 8, 6),
+ bottom);
+ pelvis.scale.set(1, 0.6, 0.62);
+ pelvis.position.y = -0.02 * h;
+ pelvis.name = 'pelvis';
+ pelvis.castShadow = true;
+ waist.add(pelvis);
+
+ const neck = pivot('neck', 0, shoulderY - hipY + 0.02 * h, 0);
+ const R = h / 15.5;
+ const head = new THREE.Mesh(
+ new THREE.SphereGeometry(R, 14, 12), skin);
+ head.geometry.scale(0.86, 1, 0.92);
+ head.position.y = R + 0.03 * h;
+ head.name = 'head';
+ head.castShadow = true;
+ neck.add(new THREE.Mesh(
+ new THREE.CylinderGeometry(0.028 * h, 0.032 * h, 0.05 * h, 8), skin));
+ neck.add(head);
+ // A face, at ~150 triangles. Without it the head is a ball, and a
+ // ball is what makes a close figure read as a shop dummy however
+ // good the gait is: the eye finds a face or it finds a mannequin.
+ // `face: false` for crowds that stay past ~15 m, where these are
+ // sub-pixel anyway.
+ if (opts.face !== false) {
+ for (const s of [-1, 1]) {
+ const eye = new THREE.Mesh(
+ new THREE.SphereGeometry(0.155 * R, 5, 4), eyeMaterial());
+ eye.name = 'eye' + (s < 0 ? 'L' : 'R');
+ // Flattened: an eye is an aperture three times wider than it is
+ // tall, and a round ball of one reads as an insect.
+ eye.scale.set(1, 0.58, 1);
+ eye.position.set(s * 0.32 * R, -0.02 * R, -0.80 * R);
+ head.add(eye);
+ }
+ // The nose is the whole profile: a head in silhouette against the
+ // sky is otherwise a circle from every angle.
+ const nose = new THREE.Mesh(
+ new THREE.SphereGeometry(0.20 * R, 5, 4), skin);
+ nose.scale.set(0.62, 1.05, 0.85);
+ nose.position.set(0, -0.18 * R, -0.90 * R);
+ head.add(nose);
+ }
+ if (opts.hair !== undefined) {
+ const hair = new THREE.Mesh(
+ // A CAP, not a helmet: 0.62pi reached below the eye line and
+ // swallowed the whole face (measured — the render showed a
+ // dark ball with a nose). 0.53pi stops at the temple, and the
+ // 0.19 rad tilt drops the rim at the back and lifts it off the
+ // brow at the front, which is what a hairline is.
+ new THREE.SphereGeometry(R * 1.06, 12, 10,
+ 0, Math.PI * 2, 0, Math.PI * 0.53),
+ // Roughness 0.62, not 0.85: hair is the one thing on a person
+ // that carries a broad specular band, and the flat 0.85 felt
+ // cap was reading as a helmet. The value floor keeps very dark
+ // hair a dark BROWN object instead of a hole in the frame.
+ MAT.fabric({ color: floorValue(opts.hair, 0.035), variant: 0.5,
+ roughness: 0.62, scale: 70, contrast: 0.35, hueBreak: 0.10,
+ bump: 0.004 }));
+ hair.position.copy(head.position);
+ hair.position.z += 0.03 * R;
+ hair.position.y -= 0.02 * R;
+ hair.rotation.x = 0.19;
+ hair.scale.set(0.90, 1.0, 0.99);
+ hair.castShadow = true;
+ neck.add(hair);
+ }
+ waist.add(neck);
+
+ const joints = { waist, neck };
+ for (const s of [-1, 1]) {
+ const tag = s < 0 ? 'L' : 'R';
+ const sh = pivot('shoulder' + tag, s * shoulderX,
+ shoulderY - hipY - 0.03 * h, 0);
+ sh.add(seg(upper, 0.042 * h * b, 0.033 * h, top, 'upperArm' + tag));
+ const el = pivot('elbow' + tag, 0, -upper, 0);
+ el.add(seg(fore, 0.033 * h, 0.024 * h, skin, 'forearm' + tag));
+ const hand = new THREE.Mesh(
+ new THREE.SphereGeometry(0.028 * h, 8, 6), skin);
+ hand.scale.set(0.8, 1.25, 0.55);
+ hand.position.y = -fore - 0.015 * h;
+ hand.name = 'hand' + tag;
+ el.add(hand);
+ sh.add(el);
+ waist.add(sh);
+ joints['shoulder' + tag] = sh;
+ joints['elbow' + tag] = el;
+
+ const hip = pivot('hip' + tag, s * hipX, 0, 0);
+ hip.add(seg(thigh, 0.062 * h * b, 0.048 * h, bottom, 'thigh' + tag));
+ const kn = pivot('knee' + tag, 0, -thigh, 0);
+ kn.add(seg(shin, 0.046 * h, 0.032 * h, bottom, 'shin' + tag));
+ // An ankle pivot: heel strike and toe-off are the only two moments
+ // the eye reads as ground contact, and a foot welded to the shin
+ // can express neither — that is the flat-footed shuffle.
+ const ak = pivot('ankle' + tag, 0, -shin, 0);
+ // A shoe, not a brick. The box was 12 triangles but presented one
+ // large FLAT horizontal facet, and a horizontal facet in an open
+ // sky is the brightest thing in the frame: measured sRGB 159 on a
+ // 0x3a albedo, i.e. a white plate stuck to a black shoe, on every
+ // figure in the render. A domed upper spreads that same light over
+ // a curve, which is what a shoe actually does — 56 triangles, and
+ // 6.4% of its area horizontal against the box's 27.2%. Rounded
+ // toe, short heel, sole clamped FLAT so the feet-at-y=0 arithmetic
+ // every placer depends on is unchanged.
+ const fg = new THREE.SphereGeometry(1, 7, 4);
+ const fp = fg.attributes.position;
+ for (let i = 0; i < fp.count; i++) {
+ const z = fp.getZ(i);
+ fp.setXYZ(i,
+ fp.getX(i) * 0.030 * h,
+ Math.max(fp.getY(i) * 0.021 * h, -0.014 * h),
+ z * (z < 0 ? 0.085 : 0.058) * h); // -Z is forward: a toe
+ }
+ fg.computeVertexNormals();
+ const foot = new THREE.Mesh(fg, shoe);
+ foot.position.set(0, -0.026 * h, -0.030 * h);
+ foot.name = 'foot' + tag;
+ foot.castShadow = true;
+ ak.add(foot);
+ kn.add(ak);
+ hip.add(kn);
+ waist.add(hip);
+ joints['hip' + tag] = hip;
+ joints['knee' + tag] = kn;
+ joints['ankle' + tag] = ak;
+ }
+
+ // Perfectly vertical limbs are the strongest mannequin tell: every
+ // figure carries its own resting offsets, and `neutral()` restores
+ // THESE, not zeros, so poses stack on a body that already stands.
+ root.userData.rest = {
+ shoulderL: [0, 0, -0.10], shoulderR: [0, 0, 0.10],
+ elbowL: [0.10, 0, 0], elbowR: [0.10, 0, 0],
+ hipL: [0, 0, -0.03], hipR: [0, 0, 0.03],
+ waist: [0, (rand() - 0.5) * 0.10, 0],
+ neck: [0, (rand() - 0.5) * 0.30, 0],
+ };
+ root.add(waist);
+ root.userData.forward = '-Z';
+ root.userData.height = h;
+ root.userData.joints = joints;
+ root.userData.hipHeight = hipY;
+ return neutral(root);
+}
+
+/** Reset every joint to this figure's resting stance (not rigid zeros). */
+function neutral(fig) {
+ const rest = fig.userData.rest || {};
+ for (const [name, j] of Object.entries(fig.userData.joints)) {
+ const r = rest[name] || [0, 0, 0];
+ j.rotation.set(r[0], r[1], r[2]);
+ }
+ fig.userData.joints.waist.position.set(0, fig.userData.hipHeight, 0);
+ return fig;
+}
+
+/**
+ * Sit a figure on something, with its pelvis ON the seat: the seat
+ * height determines the pose (thighs horizontal, shins to the floor,
+ * torso leant onto the backrest) rather than the author guessing a y.
+ *
+ * @param {THREE.Group} fig From `figure()`.
+ * @param {THREE.Object3D|number} seatTo A chair/bench/stool (its bbox top
+ * is measured) or a seat height in metres.
+ * @param {object} [opts] `lean` radians (default 0.12), `spread` radians
+ * of knee splay (default 0.06).
+ * @returns {THREE.Group} fig
+ */
+export function sit(fig, seatTo, opts = {}) {
+ // POSE WHATEVER IS ACTUALLY THE FIGURE: composers pass wrapper
+ // Groups with the figure() output nested inside. Descend to the
+ // first node with userData.joints; if there is none, say so.
+ const posed = fig && fig.userData && fig.userData.joints
+ ? fig
+ : (() => {
+ let hit = null;
+ if (fig && fig.traverse) {
+ fig.traverse((o) => {
+ if (!hit && o.userData && o.userData.joints) hit = o;
+ });
+ }
+ return hit;
+ })();
+ if (!posed) {
+ throw new Error(
+ 'sit(): "' + ((fig && fig.name) || 'this object') + '" was not '
+ + 'built by figure(), and neither is anything inside it — there '
+ + 'are no joints to pose. Build the person with figure() from '
+ + './lib/figure.js, or seat the object with seat() from '
+ + './lib/place.js instead.');
+ }
+ fig = posed;
+ const j = neutral(fig).userData.joints;
+ let seatY;
+ if (typeof seatTo === 'number') {
+ seatY = seatTo;
+ } else {
+ seatTo.updateMatrixWorld(true);
+ seatY = new THREE.Box3().setFromObject(seatTo).max.y;
+ }
+ const lean = opts.lean === undefined ? 0.12 : opts.lean;
+ const spread = opts.spread === undefined ? 0.06 : opts.spread;
+
+ // Solve the thigh angle from the seat height: on a low stool the
+ // knees ride ABOVE the hips because the shins must reach the floor.
+ // `u` lands the feet at y=0, clamped so a bar stool can't fold double.
+ const h = fig.userData.height;
+ const drop = 0.24 * h + 0.0335 * h; // shin + ankle + sole
+ const u = Math.asin(Math.max(-0.35, Math.min(0.35,
+ (drop - seatY) / (0.25 * h))));
+ j.waist.rotation.x = -lean; // back onto the backrest
+ for (const s of ['L', 'R']) {
+ const sgn = s === 'L' ? -1 : 1;
+ // `+ lean` cancels the torso's tilt, so the femur angle is set by
+ // the seat and not by how far back the person is reclining.
+ j['hip' + s].rotation.x = Math.PI / 2 + u + lean;
+ j['hip' + s].rotation.z = sgn * spread;
+ j['knee' + s].rotation.x = -(Math.PI / 2 + u); // shin vertical
+ j['shoulder' + s].rotation.x = 0.35; // forearms toward the table
+ // Positive x flexes the forearm FORWARD (measured on the rig; the
+ // old -0.8 bent every seated elbow backward, behind the chair).
+ j['elbow' + s].rotation.x = 0.8;
+ }
+ // Pelvis exactly on the seat; the legs then reach the floor on their own.
+ fig.position.y = seatY - fig.userData.hipHeight;
+ return fig;
+}
+
+/**
+ * Pose a figure mid-stride. Call per frame with the animation clock.
+ * Anti-moonwalk contract: pass `speed` — the SAME m/s the route uses —
+ * and cadence + stride are derived so stepLength x cadence === speed
+ * by construction; a time-only gait reads as "sliding sideways".
+ *
+ * @param {THREE.Group} fig From `figure()`.
+ * @param {number} t Seconds (give each walker its own `phase`, or a
+ * crowd marches in lockstep).
+ * @param {object} [opts] `speed` metres per second — pass the route's
+ * speed and the stride is sized to cover it exactly; `phase`
+ * per-person offset in stride cycles; or the manual knobs `stride`
+ * radians of hip swing (default 0.42) and `rate` strides per second
+ * (default 0.95, about 114 steps/min).
+ * @returns {THREE.Group} fig
+ */
+export function walk(fig, t, opts = {}) {
+ const j = fig.userData.joints;
+ const h = fig.userData.height;
+ const L = fig.userData.hipHeight; // hip pivot to sole: the leg
+ let a, cyc;
+ if (opts.speed !== undefined) {
+ const v = Math.max(0.05, opts.speed);
+ const wr = 0.0065 * (h / 1.72); // walk ratio, m per (step/min)
+ const cadence = Math.min(145, Math.max(70, Math.sqrt(60 * v / wr)));
+ cyc = cadence / 120; // stride cycles per second
+ // stepLen = v / (2 * cyc), so stepLen x cadence === v exactly,
+ // even where the cadence clamps; a = asin(stepLen / (2 * L)).
+ a = Math.asin(Math.min(0.98, v / (4 * cyc * L)));
+ } else {
+ a = opts.stride === undefined ? 0.42 : opts.stride;
+ cyc = opts.rate === undefined ? 0.95 : opts.rate;
+ }
+ const p = (t * cyc + (opts.phase || 0)) * Math.PI * 2;
+ const sw = Math.sin(p);
+ j.hipL.rotation.x = sw * a;
+ j.hipR.rotation.x = -sw * a;
+ // A knee bends one way only: it flexes on the backswing, never past 0.
+ j.kneeL.rotation.x = -Math.max(0, -sw) * a * 1.5;
+ j.kneeR.rotation.x = -Math.max(0, sw) * a * 1.5;
+ // Ankles: toes up on the landing leg (heel strike), toes down
+ // pushing off behind — the two moments the eye reads as contact.
+ j.ankleL.rotation.x =
+ a * (0.25 * Math.max(0, sw) - 0.6 * Math.max(0, -sw));
+ j.ankleR.rotation.x =
+ a * (0.25 * Math.max(0, -sw) - 0.6 * Math.max(0, sw));
+ // Arms counter-swing the legs, and the elbow flexes hardest when its
+ // arm is forward — a straight pumping stick reads as a mannequin.
+ j.shoulderL.rotation.x = -sw * a * 0.7;
+ j.shoulderR.rotation.x = sw * a * 0.7;
+ j.elbowL.rotation.x = 0.35 + 0.3 * Math.max(0, -sw);
+ j.elbowR.rotation.x = 0.35 + 0.3 * Math.max(0, sw);
+ j.waist.rotation.y = sw * 0.06;
+ // Pelvis dips TWICE per stride (one dip is the classic procedural
+ // limp) and sways once toward the stance foot. Both live on the
+ // waist pivot, so route() still owns fig.position.
+ j.waist.position.y = L - 0.6 * L * (1 - Math.cos(a * sw));
+ j.waist.position.x = 0.023 * (h / 1.72) * sw;
+ return fig;
+}
+
+/**
+ * Raise both forearms to hold something at chest height (a tray, a box).
+ *
+ * @param {THREE.Group} fig
+ * @param {THREE.Object3D} [held] Optional object parented between the
+ * hands, so it tracks the pose instead of floating near it.
+ * @returns {THREE.Group} fig
+ */
+export function carry(fig, held) {
+ const j = fig.userData.joints;
+ for (const s of ['L', 'R']) {
+ j['shoulder' + s].rotation.x = 0.5;
+ // +0.6 puts the hands ON the held object's rim (the old -1.3 bent
+ // the elbows backward, hands behind the body).
+ j['elbow' + s].rotation.x = 0.6;
+ j['shoulder' + s].rotation.z = (s === 'L' ? 1 : -1) * 0.12;
+ }
+ if (held) {
+ // MEASURE the hands, do not guess. The held object is parented to
+ // the WAIST pivot, which already sits at hipHeight — so the old
+ // `0.52 * h` (a figure-root height) put the tray a clear 0.85 m
+ // above the hands, i.e. balanced on top of the head. Reading the
+ // posed hands back also means the offset survives any later change
+ // to the shoulder/elbow angles above.
+ const j2 = fig.userData.joints;
+ fig.updateMatrixWorld(true);
+ const mid = new THREE.Vector3();
+ const p = new THREE.Vector3();
+ for (const s of ['L', 'R']) {
+ const hand = j2['elbow' + s].getObjectByName('hand' + s);
+ if (hand) mid.add(hand.getWorldPosition(p));
+ }
+ mid.multiplyScalar(0.5);
+ j2.waist.worldToLocal(mid);
+ const h = fig.userData.height;
+ held.position.copy(mid);
+ held.position.y += 0.035 * h; // it RESTS on the hands
+ held.position.z -= 0.020 * h; // ... just past the fingertips
+ j2.waist.add(held);
+ }
+ return fig;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/finish.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/finish.js
new file mode 100644
index 00000000..15251699
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/finish.js
@@ -0,0 +1,455 @@
+/**
+ * Two finishes a built-in material cannot reach: light coming THROUGH a
+ * thin solid, and the colour a thin film shifts with viewing angle.
+ *
+ * Both go through `patchStandard`, so lighting, shadows, fog and the
+ * depth chunks survive, both shade from world position and world normal
+ * (no UV needed), and both chain with `surface_wear`, `aging`,
+ * `terrain_shade` and `waterside` on one material.
+ *
+ * Both lift `totalEmissiveRadiance` rather than the albedo, which is the
+ * one decision that separates them from a pale repaint. The only
+ * fragment hook is `<color_fragment>`, so a patch may either tint ALBEDO
+ * — capped at the light already landing on the surface — or ADD light,
+ * the choice `windows.js` documents for a lit room. A lantern at dusk
+ * and an oil sheen on a shaded cobble are both brighter than their own
+ * front lighting, so neither can be albedo.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, waterside, surface_wear and aging name them,
+// so a material wearing several libraries declares ONE pair; the vertex
+// locals are fn* because those four own astraWp, wsP, wrP and agP.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// `transformed` is still object-space after <begin_vertex>, so the
+// instance transform is folded in by hand or every scattered copy is
+// shaded as though it stood at the world origin.
+const BASE = {
+ name: 'finish:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 fnP = vec4(transformed, 1.0);',
+ ' vec3 fnN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' fnP = instanceMatrix * fnP;',
+ ' fnN = mat3(instanceMatrix) * fnN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * fnP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(fnN, 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed for
+ * every other material that shares 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.29), hash11(seed + 5.11), hash11(seed + 9.67))
+ .multiplyScalar(48);
+}
+
+const TRANS_HEAD = [
+ 'uniform float uTrsThick;',
+ 'uniform vec3 uTrsColor;',
+ 'uniform float uTrsAmt;',
+ 'uniform float uTrsPow;',
+ 'uniform vec3 uTrsSeed;',
+ // Metres of material per e-fold. This is the ABSORPTION scale, not the
+ // millimetre free path between scatters: light random-walks far past
+ // one scatter, and wax, jade, paper and skin all absorb over cm.
+ 'const float ASTRA_TRS_MFP = 0.030;',
+ // Paper and wax scatter almost isotropically, so a share of what gets
+ // through leaves in EVERY direction. Without it a lantern's silhouette
+ // goes dark while its face glows, which reads as a lamp behind it.
+ 'const float ASTRA_TRS_ISO = 0.45;',
+ 'const float ASTRA_TRS_BEND = 0.30;',
+ // Beer-Lambert is PER CHANNEL, so the medium's hue DEEPENS along the
+ // path: a wax rim is pale gold and its shoulder is amber, one body.
+ // The exponent starts below 1 because even the thinnest crossing is
+ // already tinted (lantern paper is warm at half a millimetre), and it
+ // is capped because past ~2 mean free paths nothing gets through to
+ // colour anyway.
+ 'const float ASTRA_TRS_TINT0 = 0.55;',
+ 'const float ASTRA_TRS_TINTK = 1.30;',
+ // Bloom-friendly ceiling. A shade is a DIFFUSER: what it cannot pass
+ // it scatters back, it does not pile up. Our host tone-maps in the
+ // fragment tail with no post chain, so an uncompressed lamp against
+ // paper lands on pure white and the warmth that IS the effect is the
+ // first thing lost. The knee opens at half the ceiling, so every
+ // ordinary glow passes through untouched.
+ 'const float ASTRA_TRS_PEAK = 3.0;',
+ // Backlit means the light is on the FAR face, which is the gate; the
+ // forward lobe on top is why an eye looking into the light through the
+ // object sees the most. `n` must already face the viewer.
+ 'float astraTrsWeight(vec3 n, vec3 v, vec3 l, float p) {',
+ ' float b = max(-dot(n, l), 0.0);',
+ ' vec3 h = normalize(-l + n * ASTRA_TRS_BEND);',
+ ' return b * (ASTRA_TRS_ISO + pow(max(dot(v, h), 0.0), p));',
+ '}',
+].join('\n');
+
+const TRANS_BODY = [
+ ' vec3 trV = normalize(cameraPosition - vAstraWorld);',
+ // Turned toward the eye, so "behind" means behind from HERE: a
+ // double-sided sheet seen from its back face is still backlit.
+ ' vec3 trN = normalize(vAstraWorldN);',
+ ' trN *= sign(dot(trN, trV) + 1e-6);',
+ // The chord through a convex body is its widest crossing times how
+ // squarely it is faced, blotched by the grain wax, paper and jade
+ // all have. Metres of material this ray has to cross.
+ ' float trG = 0.55 + 0.90 * astraFbm2(',
+ ' (vAstraWorld.xz + vAstraWorld.y) * 6.0 + uTrsSeed.xy, 3);',
+ ' float trPath = uTrsThick * astraFacing(trN, trV) * trG;',
+ ' float trT = exp(-trPath / ASTRA_TRS_MFP);',
+ ' vec3 trIn = 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 trL = directionalLights[i].direction * mat3(viewMatrix);',
+ ' trIn += directionalLights[i].color',
+ ' * astraTrsWeight(trN, trV, trL, uTrsPow);',
+ ' }',
+ '#endif',
+ '#if NUM_POINT_LIGHTS > 0',
+ ' for (int i = 0; i < NUM_POINT_LIGHTS; i++) {',
+ ' vec3 trP = pointLights[i].position * mat3(viewMatrix)',
+ ' + cameraPosition;',
+ ' vec3 trD = trP - vAstraWorld;',
+ ' float trR = length(trD);',
+ ' trIn += pointLights[i].color * getDistanceAttenuation(',
+ ' trR, pointLights[i].distance, pointLights[i].decay)',
+ ' * astraTrsWeight(trN, trV, trD / max(trR, 1e-4), uTrsPow);',
+ ' }',
+ '#endif',
+ // The colour light comes out as is the colour of the path it crossed,
+ // not one flat tint: thin gives a pale wash of the medium, thick gives
+ // the medium itself, and the gradient between them is what reads as a
+ // BODY rather than a painted glow.
+ ' vec3 trTint = pow(uTrsColor, vec3(ASTRA_TRS_TINT0',
+ ' + ASTRA_TRS_TINTK * min(trPath / ASTRA_TRS_MFP, 2.0)));',
+ // trIn is the irradiance reaching the far face; what leaves this one
+ // is that spread over the hemisphere, so a lamp held against the
+ // shade blows out exactly as it does in a photograph.
+ ' vec3 trOut = trTint * (uTrsAmt * trT * 0.3183 * trIn);',
+ // ...blows out, but in COLOUR. One scalar knee on the peak channel:
+ // scaling all three by the same number moves the value and leaves the
+ // hue exactly where it was, which a per-channel clamp does not.
+ ' float trPk = max(max(trOut.r, trOut.g), trOut.b);',
+ ' trOut *= ASTRA_TRS_PEAK / (ASTRA_TRS_PEAK',
+ ' + max(trPk - 0.5 * ASTRA_TRS_PEAK, 0.0));',
+ ' totalEmissiveRadiance += trOut;',
+].join('\n');
+
+/**
+ * Light coming THROUGH a thin solid: a lantern, wax, jade, a petal.
+ *
+ * The cue is that the object glows where it is THIN and where the light
+ * is BEHIND it, and stays opaque where it is thick. Both halves are here
+ * and both are needed: a glow with no thickness term is a coat of paint,
+ * and one with no direction term is a lamp.
+ *
+ * THICKNESS is the chord through a convex body — the widest crossing
+ * times how squarely the surface is faced — so a sphere or a cylinder is
+ * exact and a flat sheet is merely harmless, its path being negligible
+ * at any angle. What survives is Beer-Lambert over that path against an
+ * absorption scale of 3 cm — the range wax, jade, paper and skin share.
+ * So 0.5 mm of lantern paper is lit everywhere, a 4 cm wax candle is
+ * dim through its core and bright around its rim, and a 30 cm block is
+ * opaque but for the last sliver of its silhouette.
+ *
+ * COLOUR runs with that path too, because absorption is per channel: a
+ * thin crossing comes out a pale wash of `color` and a long one comes
+ * out `color` itself, so one body carries a gradient of its own hue
+ * instead of a single flat tint. The result is capped by a scalar knee
+ * near radiance 3 — the same scale for all three channels, so a lamp
+ * pressed against a shade blows out in COLOUR rather than to white,
+ * which is what it does on a host that tone-maps with no post chain.
+ *
+ * DIRECTION comes from the scene's own lights — the `directionalLights`
+ * and `pointLights` three already declares — so a lamp INSIDE a shade
+ * lights it and a sun behind a leaf lights that, with no vector to pass
+ * and nothing to keep in step. Spot and area lights are not summed.
+ *
+ * It ADDS light rather than lifting albedo, because a lantern at dusk is
+ * brighter than anything falling on its front; an albedo lift would cap
+ * it at the ambient and read as pale paper.
+ *
+ * WHICH PATCH: `foliage_shade.js` `patchLeafSSS` is the thin-leaf
+ * special case — one thickness for the whole crown, a stated sun, an
+ * fbm for the leaf mass the light crossed, and an ALBEDO lift, which is
+ * right for a leaf that already sits in the light it transmits. Use this
+ * one when the thickness VARIES over the body (a candle's rim against
+ * its core), when the light is a lamp rather than the stated sun, or
+ * when the object has to out-glow its own front lighting.
+ *
+ * @param {THREE.Material} material A lit built-in material (Standard,
+ * Physical, Phong — it needs `totalEmissiveRadiance` and the light
+ * uniforms), patched in place. A shared material from `materials.js`
+ * patches every mesh wearing it, so clone it first if that is not what
+ * you want.
+ * @param {object} [opts] `thickness` metres of material the light
+ * crosses at the THICKEST point — a wall for a shell, a diameter for a
+ * solid (default 0.02); `color` THREE.Color or hex, the colour light
+ * comes out as, which is the material's own not the lamp's (default a
+ * warm parchment); `strength` how bright the transmitted light goes
+ * (default 1.0); `power` how tight the forward lobe is around the
+ * light — lower spreads the glow further off axis (default 3); `seed`
+ * moves the grain that blotches the thickness (default 1).
+ * @returns {THREE.Material} The same material, its uniforms live on
+ * `material.userData.uniforms` for a scene that dims the lamp.
+ */
+export function patchTranslucency(material, opts = {}) {
+ const thickness = opts.thickness === undefined ? 0.02 : opts.thickness;
+ const strength = opts.strength === undefined ? 1.0 : opts.strength;
+ const power = opts.power === undefined ? 3 : opts.power;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ if (!material.emissive) {
+ console.warn('patchTranslucency: needs a lit material (Standard, '
+ + 'Physical or Phong) — transmitted light is light, not paint.');
+ }
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'finish:translucency',
+ uniforms: {
+ uTrsThick: { value: Math.max(0, thickness) },
+ uTrsColor: { value: toColor(opts.color, 0xffd7a8) },
+ uTrsAmt: { value: Math.max(0, strength) },
+ uTrsPow: { value: Math.max(0.1, power) },
+ uTrsSeed: { value: seedOffset(seed) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [WORLD_VARYINGS, TRANS_HEAD].join('\n'),
+ fragmentBody: TRANS_BODY,
+ });
+}
+
+const IRID_HEAD = [
+ 'uniform float uIriAmt;',
+ 'uniform float uIriScale;',
+ 'uniform float uIriIor;',
+ 'uniform vec3 uIriSeed;',
+ // Nanometres of film: the first two interference orders, where an oil
+ // slick and a soap bubble both live. A deeper film stacks fringes
+ // until they average back to white.
+ 'const float ASTRA_IRI_D0 = 470.0;',
+ // 60, not 45: at the default index the ANGLE sweeps 0.30 of the path
+ // and the field 0.26 of it, so the field is still the smaller of the
+ // two — the law that keeps this a film and not a rainbow decal — while
+ // a FLAT film (a puddle, a wet flagstone), where the angle barely
+ // moves across the whole surface, now carries visible bands instead of
+ // one held hue.
+ 'const float ASTRA_IRI_DV = 60.0;',
+ // A film SPLITS the light it reflects; it does not make any. So what
+ // it adds is the scene's own light, hue-split around its mean: VEIL is
+ // the share left as a plain lift (a soap bubble is brighter than what
+ // is under it), the rest is a swing that shifts hue at constant level
+ // — the only way the colour survives on a puddle already reflecting a
+ // bright sky. GAIN restores the weight `strength` used to mean once
+ // the mean is taken out; REF is the light level at which the film is
+ // half strength, so a moonlit slick is a hint and a noon one is not.
+ 'const float ASTRA_IRI_VEIL = 0.35;',
+ 'const float ASTRA_IRI_GAIN = 1.5;',
+ 'const float ASTRA_IRI_REF = 1.0;',
+ // A punctual light reaches a film as a GLINT around the mirror
+ // direction plus the share the air and the ground scatter back — a
+ // real slick is rainbow at the reflected lamp and dark beside it.
+ 'const float ASTRA_IRI_HAZE = 0.10;',
+ 'const float ASTRA_IRI_LOBE = 8.0;',
+ 'vec3 astraIriFilm(float opd) {',
+ // Interference sampled at three wavelengths in nm; the half turn is
+ // the phase flip on reflection off the denser layer.
+ ' vec3 lam = vec3(612.0, 549.0, 464.0);',
+ ' vec3 c = 0.5 + 0.5 * cos(6.2831853 * opd / lam + 3.1415927);',
+ // Held at a constant mean: a film shifts HUE with angle, and a fringe
+ // that swings brightness as well reads as a stain.
+ ' c /= max((c.r + c.g + c.b) / 3.0, 0.26);',
+ // Daylight is a BAND at every wavelength, not a line, so neighbouring
+ // orders overlap and the fringes wash toward white as the order
+ // climbs. Without it the third fringe is as lurid as the first.
+ ' float ord = opd / 550.0;',
+ ' return mix(vec3(1.0), c, exp(-0.12 * ord * ord));',
+ '}',
+].join('\n');
+
+const IRID_BODY = [
+ ' vec3 irV = normalize(cameraPosition - vAstraWorld);',
+ ' vec3 irN = normalize(vAstraWorldN);',
+ ' irN *= sign(dot(irN, irV) + 1e-6);',
+ ' float irCos = clamp(dot(irN, irV), 0.0, 1.0);',
+ // Snell: the ray bends INSIDE the film, so the path it crosses
+ // shortens toward grazing. That shortening IS the colour sweep — the
+ // hue rides the angle, not the position.
+ ' float irCt = sqrt(max(1.0 - (1.0 - irCos * irCos)',
+ ' / (uIriIor * uIriIor), 0.0));',
+ ' float irD = ASTRA_IRI_D0 + ASTRA_IRI_DV * (2.0 * astraFbm2(',
+ ' (vAstraWorld.xz + vAstraWorld.y) / uIriScale',
+ ' + uIriSeed.xy, 3) - 1.0);',
+ ' float irOpd = 2.0 * uIriIor * irD * irCt;',
+ // Two-beam interference peaks at four times the single-surface
+ // Fresnel face-on and runs to total reflection at grazing: the colour
+ // is present head-on and takes the surface over at the rim.
+ ' float irR0 = (uIriIor - 1.0) / (uIriIor + 1.0);',
+ ' irR0 = 4.0 * irR0 * irR0;',
+ ' float irW = mix(irR0, 1.0, astraFresnel(irN, irV, 4.0));',
+ // The light the film has to split. The hemisphere fill IS the sky for
+ // a scene built on `sunRig`, and a film reflects the whole of it, so
+ // that one arrives as a wash. A sun or a lamp does NOT: what a mirror
+ // returns of a punctual light is a glint around the mirror direction,
+ // which is why a wet street at night is rainbow near the reflected
+ // lamp and black a metre away. Weighting them as a wash instead is
+ // what turned one lamp two metres off into a rainbow over an entire
+ // puddle (measured on the night render, before this line).
+ // Reading these rather than assuming white is what makes a slick go
+ // amber at golden hour and blue at night with nothing passed in.
+ ' vec3 irRef = reflect(-irV, irN);',
+ ' vec3 irLit = ambientLightColor;',
+ '#if NUM_HEMI_LIGHTS > 0',
+ ' for (int i = 0; i < NUM_HEMI_LIGHTS; i++) {',
+ ' vec3 irHd = hemisphereLights[i].direction * mat3(viewMatrix);',
+ ' irLit += mix(hemisphereLights[i].groundColor,',
+ ' hemisphereLights[i].skyColor,',
+ ' 0.5 + 0.5 * dot(irN, irHd));',
+ ' }',
+ '#endif',
+ '#if NUM_DIR_LIGHTS > 0',
+ ' for (int i = 0; i < NUM_DIR_LIGHTS; i++) {',
+ ' vec3 irLd = directionalLights[i].direction * mat3(viewMatrix);',
+ ' irLit += directionalLights[i].color',
+ ' * (ASTRA_IRI_HAZE + (1.0 - ASTRA_IRI_HAZE)',
+ ' * pow(max(dot(irRef, irLd), 0.0), ASTRA_IRI_LOBE));',
+ ' }',
+ '#endif',
+ '#if NUM_POINT_LIGHTS > 0',
+ ' for (int i = 0; i < NUM_POINT_LIGHTS; i++) {',
+ ' vec3 irPp = pointLights[i].position * mat3(viewMatrix)',
+ ' + cameraPosition;',
+ ' vec3 irPd = irPp - vAstraWorld;',
+ ' float irPr = length(irPd);',
+ ' irLit += pointLights[i].color * getDistanceAttenuation(',
+ ' irPr, pointLights[i].distance, pointLights[i].decay)',
+ ' * (ASTRA_IRI_HAZE + (1.0 - ASTRA_IRI_HAZE)',
+ ' * pow(max(dot(irRef, irPd / max(irPr, 1e-4)), 0.0),',
+ ' ASTRA_IRI_LOBE));',
+ ' }',
+ '#endif',
+ // Split into the scene's COLOUR and the scene's LEVEL: the tint is
+ // unit-luminance so `strength` keeps meaning what the docs say, and
+ // the level saturates rather than scaling, so a lamp two metres away
+ // does not turn one slick into a second lamp.
+ ' float irLum = dot(irLit, vec3(0.2126, 0.7152, 0.0722));',
+ ' vec3 irTint = irLit / max(irLum, 1e-4);',
+ ' float irLevel = irLum / (irLum + ASTRA_IRI_REF);',
+ ' totalEmissiveRadiance += irTint',
+ ' * ((astraIriFilm(irOpd) - (1.0 - ASTRA_IRI_VEIL))',
+ ' * (uIriAmt * irW * irLevel * ASTRA_IRI_GAIN));',
+].join('\n');
+
+/**
+ * The colour that shifts with viewing angle on a thin film.
+ *
+ * An oil slick, a soap bubble, a beetle's back, a coating on wet stone.
+ * The hue rides the FRESNEL angle, not the surface position: the ray
+ * bends inside the film, so the optical path it crosses shortens toward
+ * grazing and the fringe order slides as the camera moves. A hue that
+ * merely varies over the surface is a rainbow decal — that is the whole
+ * difference, and it is why the film thickness field is kept slow and
+ * shallow while the angle does the sweeping.
+ *
+ * It ADDS light, because a film's colour is a REFLECTION sitting on top
+ * of the surface. What it adds is the light the scene actually has —
+ * ambient plus the hemisphere fill (the sky, for anything built on
+ * `sunRig`) plus a broad share of every sun and lamp — split around its
+ * own mean rather than laid on as a white veil. So the sheen carries the
+ * scene's colour, fades with the light instead of glowing in the dark,
+ * and still reads on a wet floor that is already reflecting a bright
+ * sky, where a veil only washes out. Shadows are not readable from this
+ * hook, so a slick inside one keeps its sun share; that is the one
+ * remaining place `strength` has to be spent carefully. A scene lit ONLY
+ * by `scene.environment` declares no light uniforms for this to read (a
+ * PMREM is not reachable from `<color_fragment>`), so give it at least a
+ * dim HemisphereLight — `sunRig` always does — or the film has nothing
+ * to split and stays invisible.
+ *
+ * METALNESS is the limit. Per-pixel metalness is unreachable (there is
+ * no `composeMetalness` — `<color_fragment>` is the only hook), so this
+ * cannot do what a real coating does to metal, which is to tint how the
+ * METAL reflects. Above about 0.6 metalness the material has no diffuse
+ * left and the film reads as a flat wash over a reflection that has not
+ * changed. For a beetle's back or anodised steel, drop metalness to
+ * 0.2-0.4 and let the film carry the colour.
+ *
+ * @param {THREE.Material} material A lit built-in material (it needs
+ * `totalEmissiveRadiance`), patched in place — a shared material
+ * patches every mesh wearing it.
+ * @param {object} [opts] `strength` how strong the sheen goes at
+ * grazing, 0..1 (default 0.35 — an oil slick, not a hologram);
+ * `scale` metres per cycle of the film's own thickness swirl (default
+ * 0.35); `ior` the film's refractive index, which sets both how fast
+ * the hue sweeps with angle and how much it returns face-on (default
+ * 1.40 — oil on water; a soap film is 1.33, a beetle's chitin 1.56);
+ * `seed` moves the swirl (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`.
+ */
+export function patchIridescence(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.35 : opts.strength;
+ const scale = opts.scale === undefined ? 0.35 : opts.scale;
+ const ior = opts.ior === undefined ? 1.40 : opts.ior;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ if (!material.emissive) {
+ console.warn('patchIridescence: needs a lit material (Standard, '
+ + 'Physical or Phong) — a film reflects, it does not repaint.');
+ }
+ // A film only shows on a surface smooth enough to keep one coherent
+ // reflection; roughness is per MATERIAL, so this is the reachable
+ // half of that (see composeRoughness).
+ composeRoughness(material, 'iridescence', 1 - 0.30 * unit(strength));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'finish:iridescence',
+ uniforms: {
+ uIriAmt: { value: unit(strength) },
+ uIriScale: { value: Math.max(1e-3, scale) },
+ uIriIor: { value: Math.max(1.01, ior) },
+ uIriSeed: { value: seedOffset(seed + 0.5) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [WORLD_VARYINGS, IRID_HEAD].join('\n'),
+ fragmentBody: IRID_BODY,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/flock.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/flock.js
new file mode 100644
index 00000000..10cc6360
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/flock.js
@@ -0,0 +1,373 @@
+/**
+ * A skein of birds crossing the sky — the cheapest motion there is.
+ *
+ * A still scene with nothing moving in it reads as a model shoot, and
+ * animating a flock on the CPU means rebuilding a matrix per bird per
+ * frame, which caps the count at the point where a flock stops looking
+ * like one. So EVERY moving part lives in the vertex shader driven by
+ * uTime: the whole flock rides a closed path, each bird holds its own
+ * lag and offset off that path, and its wings beat on its own phase.
+ * Nothing is touched per frame but one float, so ten thousand birds
+ * cost what ten do, in ONE draw call.
+ *
+ * A bird at distance is two strokes. There is no bird model here: the
+ * quad is a screen-aligned billboard whose span axis is the projection
+ * of the real wing axis (so a bird flying at the camera foreshortens
+ * to a mark), and the silhouette — a V whose tips lag the root — is
+ * drawn in the fragment. Silhouette and motion carry it.
+ *
+ * COLOUR is lit, not painted. A skein is the one effect a viewer has
+ * seen ten thousand times, so the tells are cheap to spot: birds all
+ * one flat value, and a wingbeat "flash" that mixes toward WHITE on
+ * every bird at once. Both are gone. Each bird carries its own albedo
+ * (a warm/cool tilt and a value spread off `color`), the two wings
+ * ROLL opposite ways through the stroke so one catches the sun while
+ * the other is edge-on, and every bright thing on the bird — the
+ * membrane sheen, the light through the backlit primaries — arrives
+ * in `sunColor`, with `skyColor` as the ambient that keeps the shaded
+ * side off black. Pass the scene's own rig colours and the flock
+ * belongs to the frame it flies over.
+ */
+
+import * as THREE from 'three';
+
+import { mulberry32 } from './noise.js';
+import { instancedQuad, makeShaderMaterial, tickShaders, keepOutOfDepthPasses } from './shader.js';
+
+const _TAU = Math.PI * 2;
+const _MAX_PTS = 8; // the size of the shader's uPath array
+
+/** Read a Vector3, an array or an {x,y,z} into a Vector3. */
+function _toVec(p, fx = 0, fy = 0, fz = 0) {
+ 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);
+}
+
+/** Default route: a shallow ellipse over the scene, gently undulating. */
+function _defaultPath(extent, height) {
+ const pts = [];
+ for (let k = 0; k < 6; k++) {
+ const a = (k / 6) * _TAU;
+ pts.push(new THREE.Vector3(
+ Math.cos(a) * extent,
+ height * (1 + 0.12 * Math.sin(a * 2)),
+ Math.sin(a) * extent * 0.62));
+ }
+ return pts;
+}
+
+/**
+ * Build a flock travelling as a loose skein, animated in the shader.
+ *
+ * @param {object} [opts]
+ * `count` individuals (default 120) — one draw call at any count;
+ * `kind` 'bird' (default) or 'fish', which swaps the silhouette and
+ * turns the body along the travel direction; `extent` radius in
+ * metres of the default flight loop (default 60); `height` its
+ * altitude in metres (default 28); `speed` metres per second along
+ * the path (default 9); `color` the ALBEDO the plumage is varied
+ * around, not the pixel colour — it is lit here; `wingBeat` beats
+ * per second (default 3.2 birds / 1.6 fish); `sunDir` direction the
+ * KEY LIGHT comes from — pass `rig.lightDir`, not `rig.sunDir`,
+ * because at night the light is the moon and `sunDir` is under the
+ * horizon, where this turns the sun term off; `sunColor` that light's
+ * colour (pass `rig.sun.color`); `skyColor` the ambient the shaded
+ * side is lit by (pass `rig.fill.color`, or the water's tint for a
+ * school); `seed` PRNG seed (default 11); `path` 3 to 8 waypoints
+ * ([x,y,z] or Vector3) of a CLOSED loop replacing the default one;
+ * `size` wingspan in metres (default extent/20, clamped 0.35..2.4).
+ * @returns {THREE.Group} Named `Flock`, holding ONE instanced mesh,
+ * with `userData.tick(t)` advancing the only thing that changes.
+ */
+export function makeFlock(opts = {}) {
+ const count = Math.max(1, opts.count === undefined ? 120 : opts.count);
+ const kind = opts.kind === 'fish' ? 1 : 0;
+ const extent = opts.extent === undefined ? 60 : opts.extent;
+ const height = opts.height === undefined ? 28 : opts.height;
+ const speed = opts.speed === undefined ? 9 : opts.speed;
+ const beat = opts.wingBeat === undefined
+ ? (kind ? 1.6 : 3.2) : opts.wingBeat;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const size = opts.size === undefined
+ ? Math.min(2.4, Math.max(0.35, extent * 0.05)) : opts.size;
+ // An ALBEDO, so it is lit rather than drawn: 0x23262c reflects 1.5%
+ // of what lands on it, which is a hole in the sky at any exposure.
+ // A rook's back is nearer 4%, and that is what reads as a bird.
+ const color = new THREE.Color(
+ opts.color === undefined ? (kind ? 0x9fb4c2 : 0x36393f) : opts.color);
+ const sun = _toVec(opts.sunDir, 0.45, 0.78, 0.35).normalize();
+ // Defaults are a daylight rig's own two colours; a caller with a
+ // rig should hand over its sun and its sky and stop guessing.
+ const sunCol = new THREE.Color(
+ opts.sunColor === undefined ? 0xffe9cf : opts.sunColor);
+ const skyCol = new THREE.Color(
+ opts.skyColor === undefined ? 0x93b4dd : opts.skyColor);
+
+ const pts = (opts.path && opts.path.length >= 3
+ ? opts.path.map((p) => _toVec(p))
+ : _defaultPath(extent, height)).slice(0, _MAX_PTS);
+ // Uniform Catmull-Rom, closed: the same curve the shader evaluates,
+ // so `speed` is honest metres per second rather than a loop rate.
+ const curve = new THREE.CatmullRomCurve3(pts, true, 'catmullrom', 0.5);
+ const loop = Math.max(curve.getLength(), 1e-3);
+
+ const geom = instancedQuad(count, 1, 1);
+ const spread = size * 6;
+ // Strung out along the route, never wrapped onto its own tail.
+ const skein = Math.min(loop * 0.45, count * size * 2.4);
+ const rand = mulberry32(seed);
+ const off = new Float32Array(count * 3);
+ const ext = new Float32Array(count * 4);
+ let wide = 0, tall = 0;
+ for (let i = 0; i < count; i++) {
+ const t = count > 1 ? i / (count - 1) : 0;
+ const lag = t * skein + (rand() - 0.5) * (skein / count);
+ // A skein is a wavy line, not a block: the slow sinusoid is the
+ // shape, the jitter keeps it from reading as a drawn curve.
+ off[i * 3] = Math.sin(t * 5.0) * spread * 0.5
+ + (rand() - 0.5) * spread * 0.7;
+ off[i * 3 + 1] = Math.sin(t * 3.3 + 1.0) * spread * 0.22
+ + (rand() - 0.5) * spread * 0.45;
+ off[i * 3 + 2] = lag / loop;
+ ext[i * 4] = rand() * _TAU;
+ ext[i * 4 + 1] = 0.78 + rand() * 0.5;
+ ext[i * 4 + 2] = 0.85 + rand() * 0.35;
+ ext[i * 4 + 3] = size * (0.25 + rand() * 0.55);
+ wide = Math.max(wide, Math.abs(off[i * 3]) + ext[i * 4 + 3] * 1.4);
+ tall = Math.max(tall, Math.abs(off[i * 3 + 1]) + ext[i * 4 + 3]);
+ }
+ geom.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
+ geom.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 4));
+ // `position` is all zeros, so the bounds three would compute are a
+ // point at the origin: framing, culling and the census all need the
+ // volume the shader actually flies the flock through.
+ const box = new THREE.Box3().setFromPoints(curve.getPoints(64));
+ box.expandByVector(new THREE.Vector3(
+ wide + size, tall + size, wide + size));
+ geom.boundingBox = box;
+ geom.boundingSphere = box.getBoundingSphere(new THREE.Sphere());
+
+ const path = [];
+ for (let k = 0; k < _MAX_PTS; k++) {
+ path.push(pts[Math.min(k, pts.length - 1)].clone());
+ }
+ const mesh = new THREE.Mesh(geom, flockMaterial({
+ path, n: pts.length, rate: speed / loop, size: size * 0.5,
+ beat, kind, color, sun, sunCol, skyCol,
+ }));
+ mesh.name = kind ? 'FlockFish' : 'FlockBirds';
+ mesh.frustumCulled = false; // every position lives in the shader
+ mesh.renderOrder = 3;
+
+ const g = new THREE.Group();
+ g.name = 'Flock';
+ g.add(mesh);
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/** The one material: path, formation, beat and silhouette, all in GLSL. */
+function flockMaterial(o) {
+ return makeShaderMaterial({
+ name: 'Flock',
+ uniforms: {
+ uPath: { value: o.path },
+ uPathN: { value: o.n },
+ uRate: { value: o.rate },
+ uSize: { value: o.size },
+ uBeat: { value: o.beat },
+ uKind: { value: o.kind },
+ uColor: { value: o.color },
+ uSun: { value: o.sun },
+ uSunCol: { value: o.sunCol },
+ uSky: { value: o.skyCol },
+ },
+ varyings: [
+ 'varying vec2 vUv; varying float vPhase;',
+ // x,y: the sun against the bird's own up and wing axes —
+ // the roll of the stroke rotates between them. z: how much
+ // the flock is BACKLIT from this camera. w: this bird's
+ // stroke depth, which is also its silhouette's bend.
+ 'varying vec4 vLit; varying vec3 vTint;',
+ ].join(' '),
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff;',
+ 'attribute vec4 iExtra;',
+ 'uniform vec3 uPath[8];',
+ 'uniform float uPathN; uniform float uRate;',
+ 'uniform float uSize; uniform float uBeat; uniform float uKind;',
+ 'uniform vec3 uColor; uniform vec3 uSun;',
+ // Indexed by a loop counter, which is the one form of array
+ // indexing every GLSL dialect here accepts.
+ 'vec3 flockPt(float i) {',
+ ' int idx = int(i + 0.5);',
+ ' vec3 p = uPath[0];',
+ ' for (int k = 0; k < 8; k++) { if (k == idx) p = uPath[k]; }',
+ ' return p;',
+ '}',
+ 'vec3 flockPath(float u) {',
+ ' float n = uPathN;',
+ ' float s = fract(u) * n;',
+ ' float i = floor(s), f = s - i;',
+ ' vec3 p0 = flockPt(mod(i - 1.0, n)), p1 = flockPt(mod(i, n));',
+ ' vec3 p2 = flockPt(mod(i + 1.0, n));',
+ ' vec3 p3 = flockPt(mod(i + 2.0, n));',
+ ' return 0.5 * (2.0 * p1 + (p2 - p0) * f',
+ ' + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * f * f',
+ ' + (3.0 * p1 - 3.0 * p2 + p3 - p0) * f * f * f);',
+ '}',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv;',
+ // The flock rides the loop as one; the bird's own lag is
+ // what makes it FOLLOW rather than march in a slab.
+ ' float u = uTime * uRate - iOff.z;',
+ ' vec3 c = flockPath(u);',
+ ' vec3 fwd = normalize(flockPath(u + 0.004) - c',
+ ' + vec3(1e-5, 0.0, 0.0));',
+ ' vec3 sd = cross(fwd, vec3(0.0, 1.0, 0.0));',
+ ' float sl = length(sd);',
+ ' sd = sl > 1e-4 ? sd / sl : vec3(1.0, 0.0, 0.0);',
+ ' vec3 ud = cross(sd, fwd);',
+ // Decorrelated bob: offsets under a few turns leave the
+ // flock breathing in unison, which reads as one object.
+ ' float st = astraStagger(iExtra.x);',
+ ' c += sd * (iOff.x + sin(uTime * 0.63 + st) * iExtra.w * 1.4)',
+ ' + ud * (iOff.y + sin(uTime * 0.91 + st * 1.7) * iExtra.w);',
+ ' vPhase = uTime * uBeat * iExtra.z * 6.2831 + iExtra.x;',
+ // Camera axes in LOCAL space (rows of modelViewMatrix), so
+ // the billboard survives a rotated or moved parent group.
+ ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',
+ ' modelViewMatrix[2][0]);',
+ ' vec3 camU = vec3(modelViewMatrix[0][1], modelViewMatrix[1][1],',
+ ' modelViewMatrix[2][1]);',
+ // Span across flight for a bird, along it for a fish; the
+ // quad takes its width from that axis PROJECTED on screen,
+ // so a bird coming at the camera loses its span.
+ ' vec3 ax = mix(sd, fwd, uKind);',
+ ' vec2 e = vec2(dot(ax, camR), dot(ax, camU));',
+ ' float el = length(e);',
+ ' vec2 ex = el > 1e-4 ? e / el : vec2(1.0, 0.0);',
+ ' vec2 ey = vec2(-ex.y, ex.x);',
+ ' ey = ey.y < 0.0 ? -ey : ey;',
+ ' float sz = uSize * iExtra.y;',
+ ' vec2 q = ex * (aCorner.x * 2.0 * sz * clamp(el, 0.34, 1.0))',
+ ' + ey * (aCorner.y * 2.0 * sz * 0.8);',
+ ' transformed = c + camR * q.x + camU * q.y;',
+ // ONE albedo across the flock is the tell of an instanced
+ // field. A skein is juveniles and adults, dry backs and
+ // wet ones: a value spread, plus a warm/cool tilt (not a
+ // hue rotation — that returns a near-grey bird unchanged).
+ ' float bv = astraHash11(iExtra.x * 7.13 + 3.1);',
+ ' float bw = astraHash11(iExtra.x * 3.77 + 11.9);',
+ ' float tw = (bw - 0.5) * 0.5;',
+ ' vTint = uColor * (0.62 + bv * 1.02)',
+ ' * vec3(1.0 + tw, 1.0, 1.0 - tw);',
+ // A fifth of any skein is gliding at any instant, wings
+ // held: a frozen frame in which every bird holds the same V
+ // is the second tell, after the flat colour.
+ ' float gl = astraHash11(iExtra.x * 13.31 + 0.7);',
+ // The sun in the bird's OWN frame (x against its up axis, y
+ // against its wing axis), so the fragment can roll each wing
+ // between the two through the stroke, and how backlit the
+ // flock is from this camera.
+ ' vLit = vec4(dot(ud, uSun), dot(sd, uSun),',
+ ' smoothstep(0.05, 0.85, dot(uSun, -vec3(',
+ ' modelViewMatrix[0][2], modelViewMatrix[1][2],',
+ ' modelViewMatrix[2][2]))),',
+ ' mix(0.30, 1.0, smoothstep(0.0, 0.32, gl)));',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform vec3 uColor; uniform vec3 uSun; uniform float uKind;',
+ 'uniform vec3 uSunCol; uniform vec3 uSky;',
+ ].join('\n'),
+ fragmentMain: [
+ ' vec2 q = vUv * 2.0 - 1.0;',
+ ' float au = abs(q.x);',
+ ' float cl, h;',
+ ' float stroke = 0.0;',
+ ' if (uKind < 0.5) {',
+ // Two strokes: one line per wing, tips lagging the root
+ // through the beat, thick at the body and gone at the tip.
+ ' stroke = sin(vPhase - au * 0.9);',
+ ' cl = stroke * 0.72 * pow(au, 1.3) * vLit.w;',
+ // A gaussian body summed onto the wing line gives a hard
+ // four-cornered DIAMOND at close range — the one place this
+ // mark is read as a shape rather than a speck. An ellipse
+ // for the body and a tapering wing keep the round back and
+ // the thin primaries a bird actually has.
+ ' float body = 0.25 * sqrt(max(0.0, 1.0 - au * au / 0.018));',
+ ' float wing = 0.068 * (1.0 - 0.5 * au)',
+ ' * (1.0 - smoothstep(0.78, 1.0, au));',
+ // Union by hypot, not max: a max leaves a crease at the
+ // shoulder, and the body's own axis is ACROSS the span, so
+ // the ellipse is narrow in x and long in y.
+ ' h = sqrt(body * body + wing * wing);',
+ ' } else {',
+ ' stroke = sin(vPhase + q.x * 2.6);',
+ ' cl = stroke * 0.15 * (0.32 + 0.68 * (0.5 - q.x * 0.5));',
+ ' h = 0.30 * sqrt(max(0.0, 1.0 - q.x * q.x))',
+ ' + 0.26 * smoothstep(-0.55, -1.0, q.x);',
+ ' }',
+ ' float d = abs(q.y - cl);',
+ // A bird is a handful of pixels: without gradient-width
+ // antialiasing the silhouette stipples out of the frame.
+ ' float aa = max(fwidth(d), 0.004);',
+ ' float a = 1.0 - smoothstep(h - aa, h + aa, d);',
+ ' if (a < 0.01) discard;',
+ // The wings are MIRROR images: through the stroke they roll
+ // opposite ways about the flight line, so one turns its
+ // upper surface into the sun while the other goes edge-on.
+ // That asymmetry is the shimmer of a real skein — a flash
+ // keyed on the beat alone lights every bird identically and
+ // reads as a flickering white speck field.
+ ' float roll = cos(vPhase - au * 0.9) * 1.15 * vLit.w',
+ ' * (q.x < 0.0 ? -1.0 : 1.0);',
+ // A fish rolls about its own long axis instead, and shows
+ // its FLANK: the axes swap.
+ ' float ndl = mix(vLit.x, vLit.y, uKind) * cos(roll)',
+ ' + mix(vLit.y, vLit.x, uKind) * sin(roll);',
+ ' float up = clamp(ndl, 0.0, 1.0);',
+ // Below the horizon there is no sun to catch, and the
+ // ambient goes with it — the flock is then a shape against
+ // whatever the sky still has.
+ ' float dayF = smoothstep(-0.18, 0.12, uSun.y);',
+ // IRRADIANCE, not a lerp weight. The open sky is a hemisphere
+ // of light: its integral is a multiple of the sky's own
+ // radiance, not a fraction of it, and a shaded bird lit at
+ // "0.26 of sky" landed on 7/255 — a hole punched in the
+ // frame. These two scalars put a dark bird's shaded side at
+ // ~24/255 with the sky's hue still in it, and its sunlit
+ // side four times that, which is where a rook photographs.
+ ' vec3 irr = (uSky * (1.34 + 0.40 * clamp(-ndl, 0.0, 1.0))',
+ ' * mix(0.30, 1.0, dayF)',
+ ' + uSunCol * (1.74 * up * dayF))',
+ // A fish is under WATER: the same sky arrives at it filtered
+ // and halved. Without this a silver flank (a genuine 40%
+ // albedo) meets full daylight and clips to white paper.
+ ' * mix(1.0, 0.45, uKind);',
+ ' vec3 c = vTint * irr;',
+ // The membrane is glossy: at the roll that lines a wing up
+ // with the sun the whole stroke flares. Narrow, and in the
+ // colour of the SUN — a flare toward white is the tell of
+ // a flock painted rather than lit.
+ ' c += uSunCol * (pow(up, 5.0) * dayF * 0.30',
+ ' * (1.0 - uKind * 0.3));',
+ // Backlit, the light comes THROUGH the wing: a flock
+ // against the sun is not a field of black specks, it is
+ // black BODIES with lit primaries. The band stops short of
+ // the outer tip, where the silhouette is one antialiased
+ // pixel and any glow lands on the sky instead of the bird.
+ ' float thin = smoothstep(0.22, 0.72, au)',
+ ' * (1.0 - smoothstep(0.86, 1.0, au));',
+ ' c += uSunCol * (vLit.z * dayF * 0.26 * (1.0 - uKind * 0.5)',
+ ' * thin * (0.45 + 0.55 * clamp(-ndl, 0.0, 1.0)));',
+ ' gl_FragColor = vec4(c, a);',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/flowers.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/flowers.js
new file mode 100644
index 00000000..72a45ecc
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/flowers.js
@@ -0,0 +1,964 @@
+/**
+ * Flowers: the colour a meadow carries above the grass, and the petals
+ * and leaves that come down out of the air.
+ *
+ * `makeFlowers` seats flowering plants on the caller's ground and nods
+ * their heads in the SAME wind grass.js rides — `windOf` is imported
+ * rather than re-read, so one scene's meadow and its flowers lean and
+ * gust together. A petal is a thin double-sided card whose rim is
+ * translucent and which is lit THROUGH — by `patchLeafSSS` on the
+ * plants, whose sun is stated, and by `patchTranslucency` on what is
+ * in the air, which takes its light from the scene's own lamps; the
+ * silhouette (a disc of petals, a cup, a spike) is a set of UNIFORMS
+ * and never baked GLSL, because `patchStandard` hands one compiled
+ * program to every material that shares a patch name.
+ *
+ * `makeFalling` is the other half: leaves or petals drifting DOWN
+ * through the air, each at its own rate, tumbling about its own axis
+ * and sliding sideways as it goes, because a leaf does not fall
+ * straight. The whole field wraps inside the volume it advertises, so
+ * the box it states is the box it occupies.
+ *
+ * Both are ONE draw call whose every moving part lives in the vertex
+ * shader, both are deterministic in `seed`, and both need driving from
+ * your `tick()` — `obj.userData.tick(t)` — or nothing moves.
+ */
+
+import * as THREE from 'three';
+
+import { windOf } from './grass.js';
+import { patchTranslucency } from './finish.js';
+import { patchLeafSSS } from './foliage_shade.js';
+import { mulberry32 } from './noise.js';
+import {
+ instancedQuad, keepOutOfDepthPasses, patchStandard, shadowLike,
+ tickShaders,
+} from './shader.js';
+
+const _TAU = Math.PI * 2;
+// Rows up a stem: 3 is where the bend of a 30 cm stalk stops faceting.
+const _STEM_ROWS = 3;
+// The most arc a stem is laid over by, and the largest the gust term
+// (0.25 + 1.25 * fbm) * (0.62 + 0.38 * sway) can reach. Both are read
+// by the CPU to state a box the shader cannot leave.
+const _MAX_BEND = 1.2;
+const _PUSH_MAX = 1.19;
+
+/**
+ * One row per silhouette. These numbers ARE the difference between the
+ * three flowers: `elev` lifts a petal off the head plane (flat disc,
+ * upright cup), `spike` spreads the florets DOWN the stem instead of
+ * gathering them at the tip, and `prof` is the petal's outline.
+ *
+ * The colour rows are the OTHER half. A patch needs a spread of petal
+ * colour or it reads as one moulded part, but that spread has to stay
+ * inside the species: `sib` is the sibling albedo, stated as an HSL
+ * offset from whatever petal colour the caller ends up with (so it
+ * follows `opts.color` too), and `hue` is how far a single plant may
+ * rotate off the line between them. `astraHueShift` is an RGB-space
+ * rotation about the grey axis: on a near-primary it drives a channel
+ * NEGATIVE and the clamp turns the swing into a fork, so a saturated
+ * kind gets a SMALL rotation and takes its variety from `sib` instead
+ * (measured: 0.25 rad on the poppy split the field into two lobes,
+ * amber at 20-40 deg and magenta at 330-355 deg, with nothing between).
+ */
+const _KINDS = {
+ daisy: {
+ petals: 13, cols: 1, rows: 3, step: _TAU / 13,
+ elev: 0.17, curl: -0.12, cup: 0.14, spike: 0,
+ len: 0.055, wid: 0.022, disc: 0.017, bulge: 0.008,
+ prof: [2.6, 0.40], blotch: 0,
+ height: 0.32, petal: 0xdedad0, throat: 0xc9c3a6, disc_: 0xbe8f10,
+ // Warm cream to a cool paper white: the swing a white flower
+ // really carries, and safe to rotate because it is barely coloured.
+ // The cool end drops SATURATION as it turns — a white that keeps
+ // its saturation across half the wheel is a blue flower.
+ sib: [0.42, -0.10, 0.015], hue: 0.30,
+ },
+ poppy: {
+ petals: 5, cols: 2, rows: 3, step: _TAU / 5,
+ elev: 0.74, curl: 0.34, cup: 0.60, spike: 0,
+ len: 0.060, wid: 0.052, disc: 0.013, bulge: 0.010,
+ prof: [1.6, 0.60], blotch: 0.8,
+ height: 0.44, petal: 0xa2200c, throat: 0x4a1208, disc_: 0x2a1e12,
+ // Scarlet to vermilion, the two ends of a field poppy — WARM, both
+ // of them. The other way round the wheel is carmine, which the
+ // pale transmitted lift then carries the rest of the way to pink.
+ sib: [0.020, 0.02, 0.045], hue: 0.07,
+ },
+ lavender: {
+ petals: 34, cols: 1, rows: 1, step: 2.39996,
+ elev: 1.00, curl: 0.10, cup: 0.30, spike: 0.30,
+ len: 0.026, wid: 0.019, disc: 0, bulge: 0,
+ prof: [2.0, 0.50], blotch: 0,
+ height: 0.52, petal: 0x8a72c8, throat: 0xa696d6, disc_: 0x6a5aa8,
+ sib: [-0.035, 0.10, -0.10], hue: 0.16,
+ },
+};
+
+/** The sibling albedo a kind spreads toward, from the caller's own. */
+function siblingOf(color, kind) {
+ return color.clone().offsetHSL(kind.sib[0], kind.sib[1], kind.sib[2]);
+}
+
+/**
+ * A patch of flowering plants, rooted on the caller's ground.
+ *
+ * Buys the one thing a green meadow is missing: colour that stands
+ * ABOVE the grass line and moves with it. Thin double-sided petals
+ * with translucent rims, a stem that bends on an arc of its own
+ * length, and a head that nods a beat behind the stem because a head
+ * is heavy. Every plant differs — height, head size, how far it has
+ * opened, hue, lean and the jitter of each petal — since a field of
+ * identical flowers is a texture, not a field.
+ *
+ * @param {object} [opts]
+ * `extent` metres of the square patch's side (default 6, centred on
+ * the group's origin); `density` plants per square metre (default 9;
+ * `maxPlants` caps it, default 12000); `height` stem height in metres
+ * (default per kind, 0.32-0.52, varied per plant); `kind` 'daisy'
+ * (default, a flat disc of narrow petals round a boss), 'poppy' (a
+ * deep cup of five broad petals with a dark throat) or 'lavender' (a
+ * spike of florets running down the stem); `color` petal colour, an
+ * ALBEDO not a screen colour — a scene sun runs at 5-6, so a hex that
+ * already looks sunlit tone-maps to paper, and the patch spreads
+ * ITSELF either side of whatever you pass (each plant sits somewhere
+ * between it and a sibling the kind states as an HSL offset, then
+ * leans a few degrees more); `shadows` cast into the shadow map
+ * (default false — a head is smaller than a shadow texel on a rig
+ * fitted to a whole scene, so it lands as a block; turn it on for a
+ * sun rig fitted to the patch); `heightAt` (x, z) => y, the
+ * caller's ground height (default flat y = 0); `wind` grass.js's
+ * option in either spelling — a strength multiplier or
+ * `{dir, strength, speed}` — so one wind moves a scene's grass and its
+ * flowers together; `seed` PRNG seed (default 7); `sunDir`
+ * THREE.Vector3 toward the sun, for the light coming THROUGH a petal;
+ * `name` group name.
+ * @returns {THREE.Group} Named `Flowers`, holding ONE instanced mesh
+ * `Plants` whose stated box is the box it occupies at any bend, with
+ * `userData.tick(t)` driving the wind.
+ */
+export function makeFlowers(opts = {}) {
+ const kind = _KINDS[opts.kind] || _KINDS.daisy;
+ const extent = Math.max(0.2, opts.extent === undefined ? 6 : opts.extent);
+ const density = Math.max(0.01,
+ opts.density === undefined ? 9 : opts.density);
+ const height = Math.max(0.02,
+ opts.height === undefined ? kind.height : opts.height);
+ const maxPlants = opts.maxPlants === undefined ? 12000 : opts.maxPlants;
+ const seed = opts.seed === undefined ? 7 : opts.seed;
+ const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const wind = windOf(opts.wind);
+ const petal = new THREE.Color(
+ opts.color === undefined ? kind.petal : opts.color);
+
+ const field = plantField(
+ extent, density, height, kind, wind, ground, seed, maxPlants);
+ const g = new THREE.Group();
+ g.name = opts.name || 'Flowers';
+ g.add(plantMesh(field, kind, extent, petal, wind, opts.sunDir,
+ opts.shadows === true));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/**
+ * Plant the patch, and state what it can reach.
+ *
+ * Reach is computed from the SAME arc the vertex shader draws, at the
+ * largest bend the gust term can produce, so the stated box holds at
+ * every t rather than at t = 0.
+ */
+function plantField(extent, density, height, kind, wind, ground, seed,
+ maxPlants) {
+ const want = Math.max(
+ 1, Math.min(Math.round(density * extent * extent), maxPlants));
+ const cells = Math.max(1, Math.round(Math.sqrt(want)));
+ const step = extent / cells;
+ const rand = mulberry32(seed);
+ const pos = [], shape = [], bend = [], vary = [];
+ let n = 0, reach = 0, low = Infinity, high = -Infinity;
+ for (let iz = 0; iz < cells && n < maxPlants; iz++) {
+ for (let ix = 0; ix < cells && n < maxPlants; ix++) {
+ const x = -extent / 2 + (ix + rand()) * step;
+ const z = -extent / 2 + (iz + rand()) * step;
+ const y = ground ? ground(x, z) : 0;
+ const h = height * (0.62 + 0.7 * rand());
+ // Head size, and how far this one has OPENED: a patch where every
+ // bloom is at full spread reads as plastic.
+ const hs = 0.8 + 0.55 * rand();
+ const open = 0.55 + 0.7 * rand();
+ const stiff = (0.7 + 0.6 * rand()) * (0.55 + 0.6 * h / height);
+ const lean = 0.05 + 0.16 * rand();
+ pos.push(x, y, z);
+ shape.push(h, height * (0.011 + 0.006 * rand()), hs, open);
+ bend.push(wind.amp * stiff, rand() * _TAU, lean, rand() * _TAU);
+ vary.push((rand() - 0.5) * kind.hue, rand() * _TAU, rand(),
+ 0.82 + 0.32 * rand());
+ const k = Math.min(_MAX_BEND, lean + wind.amp * stiff * _PUSH_MAX);
+ const head = headReach(kind, hs);
+ reach = Math.max(reach, h * (1 - Math.cos(k)) / k + head);
+ low = Math.min(low, y);
+ high = Math.max(high, y + h + head);
+ n++;
+ }
+ }
+ return { n, pos, shape, bend, vary, reach,
+ low: n ? low : 0, high: n ? high : 0 };
+}
+
+/** How far a head of scale `hs` sticks out past the stem's tip. */
+function headReach(kind, hs) {
+ const s = hs * 1.25;
+ return Math.max(
+ kind.disc * hs + kind.len * s * (1 + Math.abs(kind.curl))
+ + kind.wid * s * (1 + Math.abs(kind.cup)),
+ kind.disc * s * 1.5 + kind.bulge * s);
+}
+
+/**
+ * One plant as base geometry: a stem strip, its petals, its boss.
+ *
+ * Every copy is built in the vertex shader from `aCorner` and `aPart`
+ * (which part, which petal, how many), so the KIND lives in the layout
+ * and in uniforms — never in the GLSL, which one program serves for
+ * all three. `position` stays at zero for the GTAO reason
+ * `instancedQuad` documents.
+ */
+function plantLattice(kind, count) {
+ const pieces = [];
+ const stem = new THREE.PlaneGeometry(1, 1, 1, _STEM_ROWS);
+ stem.translate(0, 0.5, 0);
+ pieces.push([stem, 0, 0, 1]);
+ for (let i = 0; i < kind.petals; i++) {
+ pieces.push([new THREE.PlaneGeometry(1, 1, kind.cols, kind.rows),
+ 1, i, kind.petals]);
+ }
+ if (kind.disc > 0) pieces.push([new THREE.PlaneGeometry(1, 1), 2, 0, 1]);
+
+ let nv = 0, ni = 0;
+ for (const [geo] of pieces) {
+ nv += geo.attributes.position.count;
+ ni += geo.index.count;
+ }
+ const corner = new Float32Array(nv * 3);
+ const normal = new Float32Array(nv * 3);
+ const part = new Float32Array(nv * 3);
+ const index = new Uint16Array(ni);
+ let v = 0, i = 0;
+ for (const [geo, id, idx, total] of pieces) {
+ const p = geo.attributes.position.array;
+ const nm = geo.attributes.normal.array;
+ for (let k = 0; k < geo.index.count; k++) {
+ index[i++] = geo.index.array[k] + v;
+ }
+ for (let k = 0; k < geo.attributes.position.count; k++) {
+ corner.set([p[k * 3], p[k * 3 + 1], p[k * 3 + 2]], (v + k) * 3);
+ normal.set([nm[k * 3], nm[k * 3 + 1], nm[k * 3 + 2]], (v + k) * 3);
+ part.set([id, idx, total], (v + k) * 3);
+ }
+ v += geo.attributes.position.count;
+ }
+
+ const g = new THREE.InstancedBufferGeometry();
+ g.setIndex(new THREE.BufferAttribute(index, 1));
+ g.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(nv * 3), 3));
+ g.setAttribute('aCorner', new THREE.BufferAttribute(corner, 3));
+ g.setAttribute('aPart', new THREE.BufferAttribute(part, 3));
+ g.setAttribute('normal', new THREE.BufferAttribute(normal, 3));
+ g.instanceCount = count;
+ return g;
+}
+
+/** One mesh, one draw call: every plant lives in the vertex shader. */
+function plantMesh(field, kind, extent, petal, wind, sunDir,
+ shadows) {
+ const geom = plantLattice(kind, field.n);
+ const inst = (name, arr, size) => geom.setAttribute(
+ name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));
+ inst('iPos', field.pos, 3);
+ inst('iShape', field.shape, 4);
+ inst('iBend', field.bend, 4);
+ inst('iVar', field.vary, 4);
+ // position is zero, so the derived bounds would be a point at the
+ // origin: state the box a fully bent patch really occupies.
+ const half = extent / 2 + field.reach;
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-half, field.low, -half),
+ new THREE.Vector3(half, field.high, half));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());
+
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.62, metalness: 0,
+ side: THREE.DoubleSide, transparent: true, alphaTest: 0.08,
+ name: 'FlowerPlant',
+ });
+ patchStandard(mat, {
+ name: 'flowers:plant',
+ uniforms: {
+ uFlowWind: { value: wind.dir.clone() },
+ uFlowSpeed: { value: wind.speed },
+ uFlowBend: { value: _MAX_BEND },
+ uFlowNod: { value: 0.22 },
+ uFlowSpike: { value: kind.spike },
+ uFlowStep: { value: kind.step },
+ uFlowElev: { value: kind.elev },
+ uFlowCurl: { value: kind.curl },
+ uFlowCup: { value: kind.cup },
+ uFlowSize: { value: new THREE.Vector2(kind.len, kind.wid) },
+ uFlowDisc: { value: kind.disc },
+ uFlowBulge: { value: kind.bulge },
+ uFlowProf: { value: new THREE.Vector2(kind.prof[0], kind.prof[1]) },
+ uFlowBlotch: { value: kind.blotch },
+ uFlowPetal: { value: petal.clone() },
+ uFlowPetalB: { value: siblingOf(petal, kind) },
+ uFlowThroat: { value: new THREE.Color(kind.throat) },
+ uFlowDiscCol: { value: new THREE.Color(kind.disc_) },
+ uFlowStem: { value: new THREE.Color(0x4a6626) },
+ },
+ vertexHead: PLANT_VERTEX_HEAD,
+ vertexBody: PLANT_VERTEX,
+ fragmentHead: PLANT_FRAGMENT_HEAD,
+ fragmentBody: PLANT_FRAGMENT,
+ });
+ // A petal is thin and lit through, and this is the thin-leaf patch:
+ // one albedo lift toward the light behind it, no third copy of it.
+ // The tint stays close to the PETAL: light through a red petal comes
+ // out red, and a lift halfway to warm white desaturates a scarlet
+ // poppy to salmon on exactly the plants the sun is behind.
+ patchLeafSSS(mat, {
+ sunDir: sunDir, strength: 0.42, power: 2.4,
+ tint: petal.clone().lerp(new THREE.Color(0xfff2d0), 0.26),
+ });
+ // LAST in the chain, so it sees the transmitted lift as well as the
+ // rim brightening. Both are multiplied onto an albedo that already
+ // starts near paper on a white flower, and an albedo above 1 is not a
+ // brighter petal — it is a petal with no shading left: the tone map
+ // pins every pixel of it to the same white and the whole silhouette
+ // goes to a paper cut-out. Measured on the daisy: 0.73 base * 1.4 rim
+ // * 1.14 value + 0.20 transmitted = 1.36. The floor is the other end
+ // of the same rule: a poppy's blotch is a deep bruise, not a hole.
+ patchStandard(mat, {
+ name: 'flowers:albedoRange',
+ fragmentBody: ' diffuseColor.rgb = clamp(diffuseColor.rgb, '
+ + 'vec3(0.015), vec3(0.86));',
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Plants';
+ mesh.receiveShadow = true;
+ keepOutOfDepthPasses(mesh);
+ // A meadow's worth of flower heads in the shadow map stamps a hard
+ // black flower on the ground under each one, which reads as litter
+ // rather than shade. Opt-in, as grass and wheat already are.
+ if (!shadows) return mesh;
+ // The AO guard must not cost the patch its shadow: the shadow pass
+ // draws through its own hook with our depth material, so casting is
+ // turned back on AFTER the guard, with the displacement it needs.
+ shadowLike(mesh, 'flowers:plantDepth', PLANT_VERTEX_HEAD, PLANT_VERTEX);
+ return cutDepthToSilhouette(mesh);
+}
+
+/**
+ * Cut the shadow to the shape of the FLOWER, not of its cards.
+ *
+ * A petal is a rectangle that the fragment stage carves a petal out of,
+ * and three's depth shader never sees that carving: measured on this
+ * host, a shadowed daisy stamped thirteen hard slate parallelograms on
+ * the ground and the patch read as litter dropped round the plants
+ * rather than as shade. `patchStandard` writes a fragment body through
+ * `<color_fragment>`, which the depth shader does not have — the whole
+ * hook is silently dropped there — so the same cut is spliced in above
+ * three's own alpha test, which is the one place a depth pass may
+ * discard. The uniform map is the surface's own (`shadowLike` shares
+ * it), so the profile the shadow is cut by is the profile that is drawn.
+ */
+function cutDepthToSilhouette(mesh) {
+ const dep = mesh.customDepthMaterial;
+ const compile = dep.onBeforeCompile;
+ dep.onBeforeCompile = (shader, renderer) => {
+ compile(shader, renderer);
+ shader.fragmentShader = [
+ 'uniform vec2 uFlowProf;',
+ 'varying vec4 vFlow;',
+ PLANT_PROFILE,
+ shader.fragmentShader.replace(
+ '#include <alphatest_fragment>',
+ PLANT_DEPTH_CUT + '\n#include <alphatest_fragment>'),
+ ].join('\n');
+ };
+ dep.needsUpdate = true;
+ return mesh;
+}
+
+const PLANT_VERTEX_HEAD = [
+ 'uniform float uTime;',
+ 'uniform vec2 uFlowWind;',
+ 'uniform float uFlowSpeed;',
+ 'uniform float uFlowBend;',
+ 'uniform float uFlowNod;',
+ 'uniform float uFlowSpike;',
+ 'uniform float uFlowStep;',
+ 'uniform float uFlowElev;',
+ 'uniform float uFlowCurl;',
+ 'uniform float uFlowCup;',
+ 'uniform vec2 uFlowSize;',
+ 'uniform float uFlowDisc;',
+ 'uniform float uFlowBulge;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 aPart;',
+ 'attribute vec3 iPos;',
+ 'attribute vec4 iShape;',
+ 'attribute vec4 iBend;',
+ 'attribute vec4 iVar;',
+ 'varying vec4 vFlow;',
+ 'varying vec3 vFlowVar;',
+ // A world direction as the LOCAL offset that moves this surface one
+ // metre along it, valid while the basis columns stay orthogonal.
+ 'vec3 flowLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+ // The gust field grass.js rides: streaks running downwind, so a
+ // scene's meadow and its flowers are pushed by the same air.
+ 'float flowSway(vec3 root, float ph, float lag) {',
+ ' vec2 w = uFlowWind;',
+ ' float t = uTime * uFlowSpeed;',
+ ' float s = astraStagger(ph + root.x * 0.07 + root.z * 0.11);',
+ ' return (sin(t * 1.7 + s - lag)',
+ ' + 0.35 * sin(t * 2.9 + s * 1.7 - lag)) / 1.35;',
+ '}',
+ 'vec2 flowBend(vec3 root, vec4 b) {',
+ ' vec2 w = uFlowWind;',
+ ' vec2 q = vec2(dot(root.xz, w), dot(root.xz, vec2(-w.y, w.x)));',
+ ' float t = uTime * uFlowSpeed;',
+ ' float gust = astraFbm2(vec2(q.x * 0.055 - t * 0.5, q.y * 0.21), 2);',
+ ' float push = (0.25 + 1.25 * gust)',
+ ' * (0.62 + 0.38 * flowSway(root, b.w, 0.0));',
+ ' return vec2(cos(b.y), sin(b.y)) * b.z + w * (b.x * push);',
+ '}',
+ // A circular arc of the stem's own length: a translated tip would
+ // stretch the stem instead of laying it over.
+ 'void flowArc(float v, float h, float k, vec2 f, out vec3 p,',
+ ' out vec3 tn) {',
+ ' float a = k * v;',
+ ' float u = h * (1.0 - cos(a)) / k;',
+ ' p = vec3(f.x * u, h * sin(a) / k, f.y * u);',
+ ' tn = vec3(f.x * sin(a), cos(a), f.y * sin(a));',
+ '}',
+].join('\n');
+
+const PLANT_VERTEX = [
+ ' vec3 flRoot = iPos;',
+ ' vec2 flB = flowBend(flRoot, iBend);',
+ ' float flL = length(flB);',
+ ' vec2 flF = flL > 1e-5 ? flB / flL : vec2(1.0, 0.0);',
+ ' float flK = clamp(flL, 1e-3, uFlowBend);',
+ ' float flPart = aPart.x;',
+ // Florets ride DOWN the stem on a spike and gather at the tip on a
+ // disc or a cup: one uniform, three silhouettes.
+ ' float flV = flPart < 0.5 ? aCorner.y',
+ ' : 1.0 - uFlowSpike * (aPart.y / max(aPart.z - 1.0, 1.0));',
+ ' vec3 flP, flT;',
+ ' flowArc(flV, iShape.x, flK, flF, flP, flT);',
+ ' vec3 flAt = flRoot + flP;',
+ // hue lean, tone, and where this plant sits between the kind's two
+ // petal albedos — hashed off the whorl phase so it is decorrelated
+ // from both of the others and costs no attribute.
+ ' vFlowVar = vec3(iVar.x, iVar.w, astraHash11(iVar.y * 1.37 + 0.21));',
+ ' if (flPart < 0.5) {',
+ ' vec3 flW = (modelMatrix * vec4(flAt, 1.0)).xyz;',
+ ' vec3 flView = normalize(flowLocalDir(cameraPosition - flW));',
+ ' vec3 flC = cross(flT, flView);',
+ ' float flCl = length(flC);',
+ ' vec3 flSide = flCl > 1e-4 ? flC / flCl : vec3(1.0, 0.0, 0.0);',
+ ' float flX = aCorner.x * 2.0;',
+ ' float flWid = iShape.y * (0.55 + 0.45 * sqrt(max(1.0 - flV, 0.0)));',
+ ' transformed = flAt + flSide * (flX * flWid);',
+ ' vFlow = vec4(0.0, flV, flX, 0.0);',
+ '#ifndef FLAT_SHADED',
+ // The normal of a round stalk, not of a card.
+ ' vec3 flFace = normalize(cross(flSide, flT));',
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' flFace * sqrt(max(1.0 - flX * flX, 0.04)) + flSide * flX));',
+ '#endif',
+ ' } else {',
+ // The head is heavy, so it nods a beat BEHIND the stem it sits on.
+ ' vec3 flUp = normalize(flT + vec3(uFlowWind.x, 0.0, uFlowWind.y)',
+ ' * (uFlowNod * flowSway(flRoot, iBend.w, 0.9)));',
+ ' vec3 flRef = abs(flUp.z) < 0.9 ? vec3(0.0, 0.0, 1.0)',
+ ' : vec3(1.0, 0.0, 0.0);',
+ ' vec3 flR = normalize(cross(flUp, flRef));',
+ ' vec3 flFwd = cross(flR, flUp);',
+ ' float flJit = astraHash21(vec2(aPart.y, iVar.z));',
+ ' float flAng = (aPart.y + 0.5) * uFlowStep + iVar.y',
+ ' + (flJit - 0.5) * 0.45;',
+ ' vec3 flDir = cos(flAng) * flR + sin(flAng) * flFwd;',
+ ' vec3 flAx = normalize(cross(flUp, flDir));',
+ ' float flS = iShape.z * (0.75 + 0.5 * flJit);',
+ ' if (flPart > 1.5) {',
+ ' float flD = uFlowDisc * iShape.z * 2.0;',
+ ' float flQ = (aCorner.x * aCorner.x + aCorner.y * aCorner.y) * 4.0;',
+ ' transformed = flAt + flR * (aCorner.x * flD)',
+ ' + flFwd * (aCorner.y * flD)',
+ ' + flUp * (uFlowBulge * iShape.z * max(1.0 - flQ, 0.0));',
+ ' vFlow = vec4(2.0, aCorner.y, aCorner.x, 0.0);',
+ '#ifndef FLAT_SHADED',
+ // vNormal must match the WINDING, not the intent: three flips it by
+ // gl_FrontFacing on a double-sided face, so a normal that disagrees
+ // is turned away from the eye and the face renders unlit.
+ ' vNormal = normalize(normalMatrix * flUp);',
+ '#endif',
+ ' } else {',
+ // Lifted off the head plane by its own openness, curled along its
+ // length and cupped across it: flat disc, deep cup, or floret.
+ ' float flU = aCorner.y + 0.5;',
+ ' float flEl = uFlowElev * iShape.w;',
+ ' vec3 flOut = flDir * cos(flEl) + flUp * sin(flEl);',
+ ' float flLen = uFlowSize.x * flS;',
+ ' float flWid = uFlowSize.y * flS;',
+ ' vec3 flDu = flOut * flLen',
+ ' + flUp * (2.0 * uFlowCurl * flU * flLen);',
+ ' vec3 flDs = flAx * flWid',
+ ' + flUp * (2.0 * uFlowCup * aCorner.x * flWid);',
+ // Petals start at the RIM of the boss, or thirteen of them bury the
+ // one part of a daisy that says daisy.
+ ' transformed = flAt + flOut * (uFlowDisc * iShape.z)',
+ ' + flOut * (flU * flLen)',
+ ' + flUp * (uFlowCurl * flU * flU * flLen)',
+ ' + flAx * (aCorner.x * flWid)',
+ ' + flUp * (uFlowCup * aCorner.x * aCorner.x * flWid);',
+ ' vFlow = vec4(1.0, flU, aCorner.x * 2.0, flJit);',
+ '#ifndef FLAT_SHADED',
+ ' vNormal = normalize(normalMatrix * normalize(cross(flDu, flDs)));',
+ '#endif',
+ ' }',
+ ' }',
+].join('\n');
+
+// Half-width of a petal at u along it. (p, q) is the whole outline:
+// p toward 3 gives parallel sides with round ends, q under 0.5 a
+// blunt tip, both together a broad fan. Shared with the depth pass,
+// which cuts the shadow by the same curve.
+const PLANT_PROFILE = [
+ 'float flowProfile(float u, vec2 pq) {',
+ ' return pow(max(1.0 - pow(abs(2.0 * u - 1.0), pq.x), 0.0), pq.y);',
+ '}',
+].join('\n');
+
+// The colour pass discards outside the petal and inside nothing else;
+// this is that test with the shading taken out.
+//
+// What this CANNOT fix is a shadow texel wider than the flower: the
+// default `sunRig` fits its frustum to a 150 m scene, which is 7 cm a
+// texel at 4096, and a daisy head is 5 cm. At that ratio every kind of
+// flower casts the same one-texel slate block whatever shape it really
+// is, which is why `shadows` is opt-in and why the honest place to turn
+// it on is a scene whose sun rig is fitted to the patch (`bounds: 12`
+// puts six texels across a head, measured below).
+const PLANT_DEPTH_CUT = [
+ ' if (vFlow.x > 1.5) {',
+ ' if (length(vec2(vFlow.y, vFlow.z)) * 2.0 > 1.0) discard;',
+ ' } else if (vFlow.x > 0.5) {',
+ ' if (abs(vFlow.z) > flowProfile(vFlow.y, uFlowProf)) discard;',
+ ' }',
+].join('\n');
+
+const PLANT_FRAGMENT_HEAD = [
+ 'uniform vec2 uFlowProf;',
+ 'uniform float uFlowBlotch;',
+ 'uniform vec3 uFlowPetal;',
+ 'uniform vec3 uFlowPetalB;',
+ 'uniform vec3 uFlowThroat;',
+ 'uniform vec3 uFlowDiscCol;',
+ 'uniform vec3 uFlowStem;',
+ 'varying vec4 vFlow;',
+ 'varying vec3 vFlowVar;',
+ PLANT_PROFILE,
+].join('\n');
+
+const PLANT_FRAGMENT = [
+ ' vec3 flCol;',
+ ' float flA = 1.0;',
+ ' if (vFlow.x < 0.5) {',
+ // A patch is DEEP: the foot of a stem sits in its neighbours' shade.
+ ' flCol = uFlowStem * (0.42 + 0.58 * smoothstep(0.0, 0.5, vFlow.y));',
+ ' flCol *= 0.93 + 0.14 * astraNoise2(vec2(vFlow.y * 40.0, 3.0));',
+ // Green is the one hue a hue ROTATION cannot vary safely (it is the
+ // channel that would go negative), and a saturated kind rotates
+ // barely at all: this is the stem's own yellow-green to blue-green
+ // swing, on the same per-plant number the petals mix by.
+ ' flCol *= mix(vec3(1.10, 1.0, 0.84), vec3(0.88, 1.0, 1.10),',
+ ' vFlowVar.z);',
+ ' } else if (vFlow.x > 1.5) {',
+ ' float flR = length(vec2(vFlow.y, vFlow.z)) * 2.0;',
+ ' if (flR > 1.0) discard;',
+ // A boss is packed with florets, and darker at its heart.
+ ' flCol = uFlowDiscCol * (0.72 + 0.5 * astraNoise2(',
+ ' vec2(vFlow.y, vFlow.z) * 90.0));',
+ ' flCol *= 0.55 + 0.45 * smoothstep(0.15, 0.85, flR);',
+ ' } else {',
+ ' float flW = flowProfile(vFlow.y, uFlowProf);',
+ ' float flD = abs(vFlow.z) / max(flW, 1e-3);',
+ ' float flAa = max(fwidth(flD), 0.02);',
+ ' float flM = 1.0 - smoothstep(1.0 - flAa, 1.0 + flAa, flD);',
+ ' if (flM < 0.02) discard;',
+ // The rim of a petal is one cell thick: it passes light rather than
+ // reflecting it, so it goes both PALER and more transparent.
+ ' float flCore = 1.0 - smoothstep(0.45, 1.0, flD);',
+ ' flA = flM * (0.34 + 0.66 * flCore);',
+ // This plant's own place between the kind's two petal albedos, and
+ // THEN the throat: the gradient into the centre belongs to the
+ // flower actually being drawn, not to the row in the table.
+ ' vec3 flPet = mix(uFlowPetal, uFlowPetalB, vFlowVar.z);',
+ ' flCol = mix(uFlowThroat, flPet, smoothstep(0.0, 0.45, vFlow.y));',
+ ' flCol *= 1.0 + 0.25 * (1.0 - flCore);',
+ // Veins run out from the base, and the throat of a poppy is a
+ // blotch rather than a gradient — a deep bruise of the petal's own
+ // colour, never a hole punched through it.
+ ' flCol *= 0.94 + 0.13 * astraStroke(vFlow.z * 2.5, 0.22);',
+ ' flCol = mix(flCol, max(uFlowThroat * 0.42, vec3(0.02)),',
+ ' uFlowBlotch * (1.0 - smoothstep(0.02, 0.34, vFlow.y)));',
+ // Petal to petal inside ONE head: a little tone, and a little warm
+ // to cool with it, because a head is a cup whose near side is lit by
+ // the sun and whose far side is lit by the sky.
+ ' flCol *= 0.88 + 0.24 * vFlow.w;',
+ ' flCol *= mix(vec3(1.035, 1.0, 0.955), vec3(0.965, 1.0, 1.045),',
+ ' vFlow.w);',
+ ' }',
+ // Clamped at zero: astraHueShift is a rotation in RGB, and on a
+ // saturated albedo it drives the small channels NEGATIVE. Left to run
+ // on through the multiply, half a poppy field comes back magenta.
+ ' flCol = max(astraHueShift(flCol, vFlowVar.x), vec3(0.0)) * vFlowVar.y;',
+ ' diffuseColor.rgb = flCol;',
+ ' diffuseColor.a *= flA;',
+].join('\n');
+
+/**
+ * One row per falling kind: how it is shaped and how it comes down.
+ * A leaf is longer, heavier and tumbles faster than a petal, which
+ * hangs in the air and slides much further sideways per metre fallen.
+ */
+const _FALL_KINDS = {
+ petal: {
+ size: 0.030, aspect: 0.72, fall: 0.42, spin: 1.6, wob: 0.42,
+ curl: 0.22, prof: [2.4, 0.52], notch: 0.55, vein: 0.06, hue: 0.15,
+ color: 0xe8b3c0, sib: [-0.045, 0.10, -0.08],
+ },
+ leaf: {
+ size: 0.075, aspect: 0.46, fall: 0.85, spin: 2.8, wob: 0.30,
+ curl: 0.38, prof: [1.9, 0.55], notch: 0, vein: 0.22, hue: 0.22,
+ color: 0xb0641c, sib: [-0.040, 0.05, -0.09],
+ },
+};
+
+// Two octaves with a fixed envelope, so the slide is bounded by 1 and
+// the stated volume is exactly the volume the field occupies. The GLSL
+// below is these two functions, spelled the same.
+function _wobX(f, p, t) {
+ return Math.sin(f * t + p) * 0.75 + Math.sin(f * 1.9 * t + p * 2.1) * 0.25;
+}
+
+function _wobZ(f, p, t) {
+ return Math.cos(f * t + p) * 0.75 + Math.cos(f * 2.3 * t + p * 1.6) * 0.25;
+}
+
+const _FALL_WOB_GLSL = [
+ 'float flowFallWobX(float f, float p, float t) {',
+ ' return sin(f * t + p) * 0.75 + sin(f * 1.9 * t + p * 2.1) * 0.25;',
+ '}',
+ 'float flowFallWobZ(float f, float p, float t) {',
+ ' return cos(f * t + p) * 0.75 + cos(f * 2.3 * t + p * 1.6) * 0.25;',
+ '}',
+].join('\n');
+
+/** Wrap v into [-lim, lim), the CPU mirror of GLSL mod(). */
+function _wrap(v, lim) {
+ return v - Math.floor((v + lim) / (2 * lim)) * 2 * lim;
+}
+
+/**
+ * Leaves or petals drifting DOWN through the air.
+ *
+ * This is the cue that says autumn, or a cherry in bloom: the air
+ * itself carrying something. A leaf does not fall straight, so no two
+ * come down alike — each has its own fall rate, its own tumble about
+ * its own axis (which turns it edge-on and back, the flicker that
+ * reads as a leaf) and its own sideways slide, a curve that goes
+ * nowhere in particular while the wind carries the whole field
+ * downwind.
+ *
+ * The field WRAPS inside the volume it advertises — `extent` square,
+ * `height` tall, its foot on y = 0 — so it never leaves the box it
+ * states, and the box is what three culls it by.
+ *
+ * @param {object} [opts]
+ * `extent` metres square the field covers (default 8); `height`
+ * metres it stands (default 5); `count` pieces in the air (default
+ * 240 — one draw call regardless); `kind` 'petal' (default, small,
+ * slow, notched at the tip, sliding far) or 'leaf' (longer, heavier,
+ * tumbling faster); `size` length in metres (default 0.030 petal /
+ * 0.075 leaf); `color` albedo, not a screen colour, and spread either
+ * side of itself per piece the way the planted patch spreads its
+ * petals; `wind` grass.js's
+ * option in either spelling, so the drift matches the meadow's gusts;
+ * `seed` PRNG seed (default 13); `name` group name. The light coming
+ * THROUGH a piece is read from the scene's OWN lights, so there is no
+ * sun to state and nothing to keep in step.
+ * @returns {THREE.Group} Named `Falling`, holding ONE instanced mesh
+ * `Drift`, with `userData.tick(t)` advancing the fall and
+ * `userData.sample(i, t)` giving piece i's group-local position — the
+ * CPU mirror of the vertex shader.
+ */
+export function makeFalling(opts = {}) {
+ const kind = _FALL_KINDS[opts.kind] || _FALL_KINDS.petal;
+ const extent = Math.max(0.5, opts.extent === undefined ? 8 : opts.extent);
+ const height = Math.max(0.3, opts.height === undefined ? 5 : opts.height);
+ const count = Math.max(1, Math.round(
+ opts.count === undefined ? 240 : opts.count));
+ const size = Math.max(0.002, opts.size === undefined ? kind.size : opts.size);
+ const seed = opts.seed === undefined ? 13 : opts.seed;
+ const wind = windOf(opts.wind);
+ const color = new THREE.Color(
+ opts.color === undefined ? kind.color : opts.color);
+ // grass.js states wind as radians of tip bend; a metre per second of
+ // downwind drift per 0.5 of it is a breeze that matches that sway.
+ const drift = wind.dir.clone().multiplyScalar(2 * wind.amp);
+ const wob = kind.wob * size / kind.size;
+ const fall = kind.fall;
+
+ const rand = mulberry32(seed);
+ const pos = new Float32Array(count * 3);
+ const fal = new Float32Array(count * 4);
+ const axis = new Float32Array(count * 3);
+ const swing = new Float32Array(count * 4);
+ const vary = new Float32Array(count * 2);
+ // Half the quad's own diagonal, plus the widest slide, is the room
+ // the wrap has to leave so the field cannot cross its own box.
+ const span = 0.5 * size * (1 + kind.aspect) * 1.35;
+ const lim = Math.max(1e-3, extent / 2 - span - wob);
+ const drop = Math.max(1e-3, height - 2 * span);
+ for (let i = 0; i < count; i++) {
+ pos[i * 3] = (rand() * 2 - 1) * lim;
+ pos[i * 3 + 1] = rand() * drop;
+ pos[i * 3 + 2] = (rand() * 2 - 1) * lim;
+ // Its own fall rate, its own tumble: a field that comes down at
+ // one speed reads as a sheet of confetti.
+ fal[i * 4] = 0.62 + 0.76 * rand();
+ fal[i * 4 + 1] = 0.75 + 0.55 * rand();
+ fal[i * 4 + 2] = (rand() < 0.5 ? -1 : 1) * (0.5 + rand());
+ fal[i * 4 + 3] = rand() * _TAU;
+ const a = rand() * _TAU;
+ const y = rand() * 1.4 - 0.7;
+ const r = Math.sqrt(Math.max(1 - y * y, 0));
+ axis[i * 3] = Math.cos(a) * r;
+ axis[i * 3 + 1] = y;
+ axis[i * 3 + 2] = Math.sin(a) * r;
+ swing[i * 4] = 0.5 + 1.1 * rand();
+ swing[i * 4 + 1] = rand() * _TAU;
+ swing[i * 4 + 2] = 0.5 + 1.1 * rand();
+ swing[i * 4 + 3] = rand() * _TAU;
+ vary[i * 2] = (rand() - 0.5) * kind.hue;
+ vary[i * 2 + 1] = 0.72 + 0.5 * rand();
+ }
+
+ // The REAL radius: `position` is all zeros, so this sphere is the
+ // only thing three can cull the field by, and the box below is the
+ // same volume stated the way the asset census reads it.
+ const radius = 0.5 * Math.sqrt(2 * extent * extent + height * height);
+ const geom = instancedQuad(count, 1, 1, radius);
+ geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));
+ geom.setAttribute('aFall', new THREE.InstancedBufferAttribute(fal, 4));
+ geom.setAttribute('aAxis', new THREE.InstancedBufferAttribute(axis, 3));
+ geom.setAttribute('aWob', new THREE.InstancedBufferAttribute(swing, 4));
+ geom.setAttribute('aVar', new THREE.InstancedBufferAttribute(vary, 2));
+ // instancedQuad ships no `normal`, and a zero one NaNs through the
+ // shadow-bias path of every lit material; the shader overwrites it.
+ geom.setAttribute('normal', new THREE.PlaneGeometry(1, 1).attributes.normal);
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-extent / 2, 0, -extent / 2),
+ new THREE.Vector3(extent / 2, height, extent / 2));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());
+
+ const mesh = new THREE.Mesh(geom, fallMaterial({
+ kind, size, color, drift, wob, fall, lim, drop, span,
+ }));
+ mesh.name = 'Drift';
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = opts.name || 'Falling';
+ g.add(keepOutOfDepthPasses(mesh));
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.sample = (i, t) => {
+ const k = Math.min(count - 1, Math.max(0, i | 0));
+ const y = (pos[k * 3 + 1] - fall * fal[k * 4] * t) % drop;
+ return new THREE.Vector3(
+ _wrap(pos[k * 3] + drift.x * t, lim)
+ + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),
+ (y < 0 ? y + drop : y) + span,
+ _wrap(pos[k * 3 + 2] + drift.y * t, lim)
+ + wob * _wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t));
+ };
+ return g;
+}
+
+/** Fall, tumble, slide and silhouette — all of it in GLSL. */
+function fallMaterial(cfg) {
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.68, metalness: 0,
+ side: THREE.DoubleSide, transparent: true, alphaTest: 0.08,
+ name: 'FallingLeaf',
+ });
+ // FIRST, so this patch's body runs after it and can hand it the
+ // world normal: a piece in the air takes every attitude, and the
+ // half turned away from the sun is exactly the half lit THROUGH.
+ // A piece in the air is nearly always seen against the SKY, and a
+ // thin backlit petal against a bright sky is the one thing that has
+ // to glow or it reads as a speck of dirt on the lens — measured
+ // here: at 0.9/3 the drift over the horizon came back tan-brown at
+ // half the sky's luminance. A wider lobe (lower power) is what puts
+ // the light back into the pieces that are only half turned away.
+ patchTranslucency(mat, {
+ thickness: 0.0004, strength: 1.35, power: 2.2,
+ color: cfg.color.clone().lerp(new THREE.Color(0xfff2d0), 0.5),
+ });
+ patchStandard(mat, {
+ name: 'flowers:fall',
+ uniforms: {
+ uFallDrift: { value: cfg.drift.clone() },
+ uFallRate: { value: cfg.fall },
+ uFallSize: { value: new THREE.Vector2(
+ cfg.size * cfg.kind.aspect, cfg.size) },
+ uFallSpin: { value: cfg.kind.spin },
+ uFallCurl: { value: cfg.kind.curl },
+ uFallWob: { value: cfg.wob },
+ uFallLim: { value: cfg.lim },
+ uFallDrop: { value: cfg.drop },
+ uFallFoot: { value: cfg.span },
+ uFallProf: { value: new THREE.Vector2(
+ cfg.kind.prof[0], cfg.kind.prof[1]) },
+ uFallNotch: { value: cfg.kind.notch },
+ uFallVein: { value: cfg.kind.vein },
+ uFallColor: { value: cfg.color.clone() },
+ uFallColorB: { value: siblingOf(cfg.color, cfg.kind) },
+ },
+ vertexHead: FALL_VERTEX_HEAD,
+ vertexBody: FALL_VERTEX,
+ fragmentHead: FALL_FRAGMENT_HEAD,
+ fragmentBody: FALL_FRAGMENT,
+ });
+ return mat;
+}
+
+const FALL_VERTEX_HEAD = [
+ 'uniform float uTime;',
+ 'uniform vec2 uFallDrift;',
+ 'uniform float uFallRate;',
+ 'uniform vec2 uFallSize;',
+ 'uniform float uFallSpin;',
+ 'uniform float uFallCurl;',
+ 'uniform float uFallWob;',
+ 'uniform float uFallLim;',
+ 'uniform float uFallDrop;',
+ 'uniform float uFallFoot;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 aPos;',
+ 'attribute vec4 aFall;',
+ 'attribute vec3 aAxis;',
+ 'attribute vec4 aWob;',
+ 'attribute vec2 aVar;',
+ 'varying vec4 vFall;',
+ 'varying vec3 vFallVar;',
+ // finish.js's shared world pair. Its own vertex body reads the
+ // `normal` ATTRIBUTE, which for geometry built in the vertex shader
+ // is a constant — so this patch runs last and supplies the truth.
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+ _FALL_WOB_GLSL,
+].join('\n');
+
+const FALL_VERTEX = [
+ ' vec2 flW = vec2(flowFallWobX(aWob.x, aWob.y, uTime),',
+ ' flowFallWobZ(aWob.z, aWob.w, uTime));',
+ // Every piece wraps inside the stated box: its own fall rate down,
+ // the shared wind across, its own slide on top of that.
+ ' float flY = mod(aPos.y - uFallRate * aFall.x * uTime, uFallDrop);',
+ ' vec2 flXZ = mod(aPos.xz + uFallDrift * uTime + uFallLim,',
+ ' 2.0 * uFallLim) - uFallLim + uFallWob * flW;',
+ ' vec3 flP = vec3(flXZ.x, flY + uFallFoot, flXZ.y);',
+ // The tumble axis lies IN the leaf, so the face turns edge-on and
+ // back once a turn — that flicker is what reads as falling.
+ ' vec3 flA = normalize(aAxis + 0.3 * vec3(flW.x, 0.0, flW.y));',
+ ' vec3 flRef = abs(flA.y) < 0.9 ? vec3(0.0, 1.0, 0.0)',
+ ' : vec3(1.0, 0.0, 0.0);',
+ ' vec3 flE1 = normalize(cross(flA, flRef));',
+ ' vec3 flE2 = cross(flA, flE1);',
+ ' float flAng = uFallSpin * aFall.z * uTime + aFall.w;',
+ ' vec3 flX = flE1 * cos(flAng) + flE2 * sin(flAng);',
+ ' vec2 flS = uFallSize * aFall.y;',
+ // A dry leaf is CURVED across its width, so its shading is a
+ // gradient: flat cards turned from the sun read as black confetti.
+ ' vec3 flN = cross(flA, flX);',
+ ' transformed = flP + flX * (aCorner.x * flS.x)',
+ ' + flA * (aCorner.y * flS.y)',
+ ' + flN * (uFallCurl * aCorner.x * aCorner.x * flS.x);',
+ ' vFall = vec4(uv, aFall.y, 0.0);',
+ // hue lean, tone, and where this piece sits between the kind's two
+ // albedos — hashed off its own slide phase, so no attribute grows.
+ ' vFallVar = vec3(aVar, astraHash11(aWob.y * 1.37 + 0.21));',
+ ' vec3 flNc = normalize(flN - 2.0 * uFallCurl * aCorner.x * flX);',
+ ' vAstraWorld = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(flNc, 0.0)).xyz);',
+ '#ifndef FLAT_SHADED',
+ // The quad's own winding, y cross x: three flips this by
+ // gl_FrontFacing, so the opposite sign leaves half the field unlit.
+ ' vNormal = normalize(normalMatrix * flNc);',
+ '#endif',
+].join('\n');
+
+const FALL_FRAGMENT_HEAD = [
+ 'uniform vec2 uFallProf;',
+ 'uniform float uFallNotch;',
+ 'uniform float uFallVein;',
+ 'uniform vec3 uFallColor;',
+ 'uniform vec3 uFallColorB;',
+ 'varying vec4 vFall;',
+ 'varying vec3 vFallVar;',
+ 'float flowFallProfile(float u, vec2 pq) {',
+ ' return pow(max(1.0 - pow(abs(2.0 * u - 1.0), pq.x), 0.0), pq.y);',
+ '}',
+].join('\n');
+
+const FALL_FRAGMENT = [
+ ' float flU = vFall.y;',
+ ' float flX = vFall.x * 2.0 - 1.0;',
+ ' float flW = flowFallProfile(flU, uFallProf);',
+ // A cherry petal is notched at its tip; a leaf runs to a point.
+ ' flW -= uFallNotch * flW',
+ ' * (1.0 - smoothstep(0.0, 0.30, length(vec2(flX, flU - 1.0))));',
+ ' float flD = abs(flX) / max(flW, 1e-3);',
+ ' float flAa = max(fwidth(flD), 0.03);',
+ ' float flM = 1.0 - smoothstep(1.0 - flAa, 1.0 + flAa, flD);',
+ ' if (flM < 0.02) discard;',
+ // Thin at the rim: it passes light instead of reflecting it, so the
+ // edge goes paler AND more transparent.
+ ' float flCore = 1.0 - smoothstep(0.4, 1.0, flD);',
+ // Its own place between the kind's two albedos first, then a SMALL
+ // rotation clamped at zero: on a rust leaf a wide rotation drives
+ // blue negative one way and green the other, and the field forks into
+ // olive and pink instead of running through the browns between them.
+ ' vec3 flCol = mix(uFallColor, uFallColorB, vFallVar.z);',
+ ' flCol = max(astraHueShift(flCol, vFallVar.x), vec3(0.0)) * vFallVar.y;',
+ ' flCol *= 1.0 + 0.45 * (1.0 - flCore);',
+ ' flCol *= 1.0 - uFallVein * (1.0 - smoothstep(0.0, 0.09, abs(flX)))',
+ ' * smoothstep(0.02, 0.2, flU);',
+ ' flCol *= 0.93 + 0.12 * astraStroke(flU * 6.0, 0.24);',
+ // The rim brightening and the tone jitter both multiply, and an
+ // albedo over 1 is a piece with no shading left on it: the tone map
+ // pins every pixel of it to the same white.
+ ' diffuseColor.rgb = min(flCol, vec3(0.86));',
+ ' diffuseColor.a *= flM * (0.42 + 0.58 * flCore);',
+].join('\n');
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.js
new file mode 100644
index 00000000..3e0248cd
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/foliage_shade.js
@@ -0,0 +1,308 @@
+/**
+ * Three patches that make a plant read as ALIVE rather than as green
+ * geometry: leaves that transmit the sun from behind, a sway that bends
+ * at the tip and holds at the base, and the litter ring where a trunk
+ * meets the ground.
+ *
+ * All three go through `patchStandard`, so the material keeps its
+ * lighting, shadows, fog and depth chunks, and they compose: leaves
+ * that both glow and sway are two calls on one leaf material.
+ */
+
+import * as THREE from 'three';
+import { patchStandard } from './shader.js';
+
+// three applies instanceMatrix in <project_vertex>, AFTER the body
+// patched in here, so anything that needs world space at this point has
+// to apply it by hand. That is the whole reason these helpers exist.
+const SHARED_VERTEX_HEAD = [
+ 'varying vec3 vAstraFol;',
+ 'vec3 astraFolWorld(vec3 p) {',
+ '#ifdef USE_INSTANCING',
+ ' return (modelMatrix * instanceMatrix * vec4(p, 1.0)).xyz;',
+ '#else',
+ ' return (modelMatrix * vec4(p, 1.0)).xyz;',
+ '#endif',
+ '}',
+ // A world direction as the LOCAL offset that moves this surface one
+ // metre along it. compose(pos, quat, scale) leaves the basis columns
+ // orthogonal, so that inverse is one projection per column.
+ 'vec3 astraFolLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ '#ifdef USE_INSTANCING',
+ ' m = m * mat3(instanceMatrix);',
+ '#endif',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+// Goes on once however many patches a material carries: patchStandard
+// chains them and dedupes varyings, but a second copy of a FUNCTION is
+// a GLSL redefinition error that takes the whole plant with it.
+const SHARED_PATCH = {
+ name: 'foliageBase',
+ vertexHead: SHARED_VERTEX_HEAD,
+ vertexBody: ' vAstraFol = astraFolWorld(transformed);',
+ fragmentHead: 'varying vec3 vAstraFol;',
+};
+
+/**
+ * Apply one patch once, over the shared world-space preamble.
+ *
+ * `patchStandard` chains patches and injects each body at its hook, so
+ * every patch here has to stand on its own — none may read a local a
+ * sibling declared. A repeat call retunes the uniforms rather than
+ * injecting the same declarations twice.
+ */
+function addPatch(material, part) {
+ const applied = material.userData.astraFoliage || {};
+ material.userData.astraFoliage = applied;
+ if (applied[part.name]) {
+ for (const key of Object.keys(part.uniforms)) {
+ material.userData.uniforms[key].value = part.uniforms[key].value;
+ }
+ return material;
+ }
+ if (!applied.base) {
+ applied.base = true;
+ patchStandard(material, SHARED_PATCH);
+ }
+ applied[part.name] = true;
+ return patchStandard(material, part);
+}
+
+/**
+ * Backlit leaves glow — the strongest single cue that a tree is alive.
+ *
+ * One transmission term: light arriving from BEHIND the surface and
+ * scattering out toward the eye. It is clamped at zero, so the crown
+ * lifts only where the camera looks into the sun through it and a
+ * front-lit leaf is left exactly as it was. The term rides on the
+ * ALBEDO, the one hook `patchStandard` gives the fragment stage, so a
+ * backlit leaf lightens toward `tint` instead of emitting on its own.
+ *
+ * Before the glow goes on, the PIGMENT is broken up. A crown built from
+ * one material is one flat green over every leaf it owns, and a flat
+ * green is the tell that says "geometry": a real canopy runs warm
+ * yellow-green where new growth caught the sun and cool blue-green in
+ * the mass behind it, at clump scale and again a metre down. The break
+ * is `astraHueBreak` at two scales plus a value swing on the coarser
+ * one's own field — so the transmission lands on a varied albedo
+ * instead of washing a single tone paler. Measured on the showcase
+ * pair: the crown's hue spread went 27 -> 35 degrees close in, 35 -> 45
+ * at 20 m, and the share of it sitting in one value bin fell from 0.49
+ * (no patch) to 0.30.
+ *
+ * @param {THREE.Material} material Leaf material, patched in place.
+ * @param {object} [opts] `sunDir` (THREE.Vector3) direction TOWARD the
+ * sun — the same vector as the sun light's position, because the term
+ * asks whether the eye is looking into it (default a day sun, well
+ * above the horizon); at night pass the rig's `lightDir` (the moon),
+ * never its `sunDir`, which points under the ground; `tint`
+ * (THREE.Color) the transmitted colour, the warm yellow-green a leaf
+ * turns when lit through; `light` (THREE.Color) the key light's own
+ * colour, multiplied into that tint so a golden or moonlit rig
+ * transmits its own light rather than a hardcoded noon (default
+ * white); `strength` (default 0.55) how far it lifts the albedo;
+ * `power` (default 3) how tight the lobe is around the sun — lower
+ * spreads the glow wider off axis; `variance` (default 0.6) the
+ * pigment swing, 0 to leave the albedo alone; `varyScale` (default 1)
+ * scales the break-up in world metres — raise it for grass and small
+ * leaves, lower it for a canopy read from far away.
+ * @returns {THREE.Material} The same material.
+ */
+export function patchLeafSSS(material, opts = {}) {
+ const sun = (opts.sunDir || new THREE.Vector3(0.45, 0.75, 0.35))
+ .clone().normalize();
+ const tint = new THREE.Color(
+ opts.tint === undefined ? 0xccd966 : opts.tint);
+ if (opts.light !== undefined) tint.multiply(new THREE.Color(opts.light));
+ const strength = opts.strength === undefined ? 0.55 : opts.strength;
+ const power = opts.power === undefined ? 3 : opts.power;
+ const variance = opts.variance === undefined ? 0.6 : opts.variance;
+ const varyScale = opts.varyScale === undefined ? 1 : opts.varyScale;
+ return addPatch(material, {
+ name: 'leaf',
+ uniforms: {
+ uLeafSun: { value: sun },
+ uLeafTint: { value: tint },
+ uLeafAmt: { value: strength },
+ uLeafPow: { value: power },
+ uLeafVar: { value: variance },
+ uLeafVarS: { value: varyScale },
+ },
+ fragmentHead: [
+ 'uniform vec3 uLeafSun;',
+ 'uniform vec3 uLeafTint;',
+ 'uniform float uLeafAmt;',
+ 'uniform float uLeafPow;',
+ 'uniform float uLeafVar;',
+ 'uniform float uLeafVarS;',
+ ].join('\n'),
+ fragmentBody: [
+ // PIGMENT first, so everything below rides varied leaves. y is
+ // folded into the horizontal sample so a crown breaks up through
+ // its depth too — an xz-only field paints the same tone down a
+ // whole column of leaves.
+ ' vec2 lP = vAstraFol.xz + vAstraFol.y * 0.8;',
+ // Two scales, both COARSE. astraHueBreak's stated foliage swing is
+ // a ground mat's, and a crown needs the hue to travel further, so
+ // the swing is 3x it at clump scale (~2 m: this bough against
+ // that one) and half that a metre down (~0.5 m: within a clump).
+ // A third, finer octave was tried and cut — smooth noise under a
+ // metre stops reading as leaves and starts reading as camouflage
+ // sprayed over the mass.
+ ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb, lP,',
+ ' 0.55 * uLeafVarS, uLeafVar * 3.0);',
+ ' diffuseColor.rgb = astraHueBreak(diffuseColor.rgb, lP,',
+ ' 1.9 * uLeafVarS, uLeafVar * 1.4);',
+ // Value too, or the crown is one brightness in many hues — and on
+ // the SAME field as the clump break (astraHueBreak's own 2-octave
+ // sample at that scale), because the two are one story: new growth
+ // that caught the sun is warm AND light, the mass behind it is
+ // cool AND dark. Run at an unrelated scale instead — which is
+ // where this started — the warm swing lands as often on a dark
+ // clump as a light one and the crown goes olive. Stretched to the
+ // field's own range and CLAMPED: unbounded, a rare tail would take
+ // a leaf past the albedo range at either end.
+ ' float lVar = clamp((astraFbm2(lP * 0.55 * uLeafVarS, 2)',
+ ' - 0.375) * 2.6, -1.0, 1.0);',
+ ' diffuseColor.rgb *= 1.0 + uLeafVar * 0.5 * lVar;',
+ ' vec3 lV = normalize(cameraPosition - vAstraFol);',
+ ' float lB = max(dot(lV, -uLeafSun), 0.0);',
+ ' float lT = uLeafAmt * pow(lB, uLeafPow);',
+ // A crown is not a lamp: what reaches the eye is dappled by how
+ // much leaf mass the light crossed, which also leaves
+ // neighbouring trees uncorrelated. Two scales — the gaps between
+ // clumps, and the leaves themselves — because one makes the glow
+ // a soft blob and both make it sparkle.
+ ' lT *= 0.42 + 0.72 * astraFbm2(vAstraFol.xz * 1.7 + vAstraFol.y,'
+ + ' 3)',
+ ' + 0.36 * astraFbm2(vAstraFol.xz * 7.3 - vAstraFol.y * 3.1,'
+ + ' 2);',
+ ' diffuseColor.rgb += uLeafTint * lT;',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Wind sway: the plant bends at the tip and stays planted at the base.
+ *
+ * The bend is normalised by the plant's own height and squared, so the
+ * base cannot move and the tip carries the whole travel. The phase
+ * comes from each plant's WORLD origin, staggered by several turns:
+ * a per-vertex phase would tear one plant apart and a shared phase
+ * makes a whole row nod in step. Deterministic — the world position is
+ * the seed, there is no PRNG. Drive it with `tickShaders(scene, t)`;
+ * an un-advanced uTime is a frozen plant, not a broken patch.
+ *
+ * Works on an InstancedMesh as well as a Mesh (instanceMatrix is
+ * applied by hand here), but a swaying plant's SHADOW stays still:
+ * three draws shadows with a depth material this patch never sees.
+ *
+ * @param {THREE.Material} material Leaf or bark material, patched in
+ * place.
+ * @param {object} [opts] `strength` metres of travel at full bend
+ * (default 0.25); `speed` (default 0.9) radians per second; `height`
+ * (default 4) the plant's height in its OWN units, which the bend is
+ * normalised by — the asset's base must sit at y = 0 for that to
+ * mean anything; `dir` (THREE.Vector2) wind direction over world XZ
+ * (default a light south-easterly), normalised for you.
+ * @returns {THREE.Material} The same material.
+ */
+export function patchWind(material, opts = {}) {
+ const dir = (opts.dir || new THREE.Vector2(1, 0.35)).clone().normalize();
+ const strength = opts.strength === undefined ? 0.25 : opts.strength;
+ const speed = opts.speed === undefined ? 0.9 : opts.speed;
+ const height = opts.height === undefined ? 4 : opts.height;
+ return addPatch(material, {
+ name: 'wind',
+ uniforms: {
+ uWindAmp: { value: strength },
+ uWindSpeed: { value: speed },
+ uWindH: { value: height },
+ uWindDir: { value: dir },
+ },
+ vertexHead: [
+ // patchStandard declares uTime wherever it is read — its withTime
+ // pass runs before the body is injected — so a body that reads
+ // uTime without this line fails to compile.
+ 'uniform float uTime;',
+ 'uniform float uWindAmp;',
+ 'uniform float uWindSpeed;',
+ 'uniform float uWindH;',
+ 'uniform vec2 uWindDir;',
+ ].join('\n'),
+ vertexBody: [
+ ' float wB = clamp(transformed.y / max(uWindH, 1e-3), 0.0, 1.0);',
+ ' vec3 wO = astraFolWorld(vec3(0.0));',
+ ' 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
+ // gives every instance a different yaw.
+ ' vec3 wD = astraFolLocalDir(vec3(uWindDir.x, 0.0, uWindDir.y));',
+ ' transformed += wD * (uWindAmp * wB * wB * wS);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Seat a trunk in the ground: contact shade plus a ring of litter.
+ *
+ * Nothing in a photograph meets anything else with a hard edge, and a
+ * trunk whose colour stops dead at the ground reads as a cylinder
+ * standing ON a plane. This darkens the last `band` metres above the
+ * plant's own base and tints them toward fallen leaves, with the ring's
+ * height moved by horizontal noise so the line runs ragged AROUND the
+ * trunk instead of sitting level like a decal.
+ *
+ * @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).
+ * @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-leaf
+ * colour the base tints toward.
+ * @returns {THREE.Material} The same material.
+ */
+export function patchRootContact(material, opts = {}) {
+ const band = opts.band === undefined ? 0.5 : opts.band;
+ const darken = opts.darken === undefined ? 0.45 : opts.darken;
+ const litter = new THREE.Color(
+ opts.litter === undefined ? 0x4a3a26 : opts.litter);
+ return addPatch(material, {
+ name: 'root',
+ uniforms: {
+ uRootBand: { value: band },
+ uRootDark: { value: darken },
+ uRootLitter: { value: litter },
+ },
+ vertexHead: 'varying float vAstraRootH;',
+ vertexBody: ' vAstraRootH = astraFolWorld(transformed).y'
+ + ' - astraFolWorld(vec3(0.0)).y;',
+ fragmentHead: [
+ 'varying float vAstraRootH;',
+ 'uniform float uRootBand;',
+ 'uniform float uRootDark;',
+ 'uniform vec3 uRootLitter;',
+ ].join('\n'),
+ fragmentBody: [
+ // The band's own structure runs across it: horizontal noise moves
+ // the HEIGHT the litter reaches, so its edge is ragged around the
+ // trunk rather than a level ring. The field is sampled at 7 per
+ // metre, not 3: a trunk is half a metre wide, and one cycle
+ // across it is a tilted line, not a ragged one.
+ ' float rH = vAstraRootH - uRootBand * 0.55 *',
+ ' (astraFbm2(vAstraFol.xz * 7.0, 3) - 0.4);',
+ ' float rK = astraContact(rH, uRootBand);',
+ // Fallen leaves are not one brown: warm dry litter next to damp
+ // dark, at the scale of a handful of leaves.
+ ' vec3 rL = astraHueBreak(uRootLitter, vAstraFol.xz, 9.0, 0.7);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, rL, rK * rK * 0.7);',
+ ' diffuseColor.rgb *= 1.0 - uRootDark * rK;',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/godrays.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/godrays.js
new file mode 100644
index 00000000..54bf87af
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/godrays.js
@@ -0,0 +1,655 @@
+/**
+ * Shafts of light that read as LIGHT, not as glowing cylinders.
+ *
+ * A beam is not a surface. What the eye sees is the light scattered
+ * back out of the air along its line of sight, so the brightness of a
+ * pixel is the LENGTH OF THE CHORD it cuts through the beam — greatest
+ * through the core, zero at the silhouette. For a tube that chord is
+ * exactly |n . v|, which is `astraFacing`, so weighting an additive
+ * double-sided shell by it turns the shell into its own volume
+ * integral. Skip that weight and the front and back faces stack at the
+ * rim into a bright OUTLINE: that outline IS the solid-cylinder look,
+ * and no amount of colour tuning removes it.
+ *
+ * The rest is what stops it reading as geometry. Every shaft shares ONE
+ * direction, because parallel rays converge on the sun through
+ * perspective alone and a fanned set converges nowhere. They widen as
+ * they fall, they are brightest at the gap they came through, their
+ * striations run ACROSS the beam rather than along it, they hand over
+ * to a pool of light on the floor instead of stopping at a rim, and
+ * dust drifts inside them — a beam with nothing in it has no air.
+ *
+ * And a beam is not ONE colour. The air that makes it visible is also
+ * what scatters the blue back out of it, so every part of the effect
+ * carries two tints: the source hue at the gap and in the core, an AIR
+ * hue at the far end and at the feathered rim. Both are derived from
+ * the caller's own `color` (or handed over as `hazeColor`), so a scene
+ * that tints its sun tints its air with it and nothing here states a
+ * light colour of its own.
+ */
+
+import * as THREE from 'three';
+
+import {
+ instancedQuad, makeShaderMaterial, sweepProfile, tickShaders, keepOutOfDepthPasses } from './shader.js';
+
+const _UP = new THREE.Vector3(0, 1, 0);
+
+// Additive light must FADE with distance. three's fog chunk mixes
+// toward the fog colour, which on an additive pass ADDS haze instead of
+// removing contrast, so the alpha carries the recession itself.
+const _FOG_FADE = [
+ '#ifdef USE_FOG',
+ ' #ifdef FOG_EXP2',
+ ' a *= exp(-fogDensity * fogDensity * vFogDepth * vFogDepth);',
+ ' #else',
+ ' a *= 1.0 - smoothstep(fogNear, fogFar, vFogDepth);',
+ ' #endif',
+ '#endif',
+].join('\n');
+
+/**
+ * Build a field of light shafts, their floor pools and their dust.
+ *
+ * Encodes the constraint that makes the effect read: the shafts are
+ * ADDITIVE, volumeless and weighted by `astraFacing`, so they brighten
+ * whatever is behind them and vanish at their own silhouette. They are
+ * never opaque, never depth-writing and never vertical — a vertical
+ * prism of constant width is the shape that reads as a pipe.
+ *
+ * @param {object} [opts]
+ * `count` shafts (default 7); `height` metres from the gap they come
+ * through down to the floor (default 6); `maxLength` metres a shaft
+ * may actually run (default `1.6 * height`): the length is the drop
+ * divided by the slant, so a low sun turns a stated drop into a
+ * spear several times longer — a shaft cut short fades out in the
+ * air and throws no floor pool; `width` shaft width where it
+ * enters (default 0.55 — it lands ~1.4x wider); `spread` metres the
+ * shafts are spread across (default width * count * 1.7); `sunDir`
+ * direction the light TRAVELS, THREE.Vector3 or [x,y,z] (default
+ * [-0.38,-1,-0.26]; a vector aimed AT the sun is flipped, a
+ * near-horizontal one is tilted until it reaches the floor);
+ * `ambient` how bright the SURROUNDINGS are, 0 an unlit interior to 1
+ * open daylight (default 0.85). Added light cannot see what it adds
+ * to: over a pale backdrop it clips at any visible strength, so at
+ * 0.35 and above the shafts scatter instead — normal blending, pale,
+ * low alpha — which lowers the contrast behind them the way a
+ * daylight shaft does. Scattering is the DEFAULT because a caller
+ * handed a 0-to-1 range picks the middle, and the middle used to be
+ * the mode that clips; `color` light colour (default warm daylight);
+ * `hazeColor` what the AIR scatters back — the far end of every beam,
+ * the rim, the outside of each pool (default: `color` tilted the way
+ * Rayleigh tilts it, cooler and paler at the same luminance; pass the
+ * scene's own sky or fog colour to tie the shafts to it);
+ * `softness` 0..1 how far the edge feathers into the air (default
+ * 0.55); `seed` PRNG seed (default 11).
+ * @returns {THREE.Group} Named `GodRays`, resting on y = 0, with
+ * `userData.tick(t)` driving every shader in it.
+ */
+export function makeGodRays(opts = {}) {
+ const count = Math.max(1, Math.round(
+ opts.count === undefined ? 7 : opts.count));
+ const height = opts.height === undefined ? 6 : opts.height;
+ const width = opts.width === undefined ? 0.55 : opts.width;
+ const spread = opts.spread === undefined
+ ? width * count * 1.7 : opts.spread;
+ const color = opts.color
+ ? new THREE.Color(opts.color) : new THREE.Color(0xffeecb);
+ const air = airColor(color, opts.hazeColor);
+ const soft = opts.softness === undefined ? 0.55 : opts.softness;
+ // Added light adds to whatever is behind it, and no shader can read
+ // that. Measured on one asset: the shafts that read as light in a
+ // dark room blew 12.8% of a pale frame past 0.97 unchanged. So the
+ // caller states how bright the surroundings are — 0 an unlit
+ // interior, 1 open daylight — and the default assumes it was not
+ // asked, which is the case that failed.
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.85 : opts.ambient, 0), 1);
+ // Dimming does not save it: measured over a pale backdrop, cutting
+ // the gain 3.6x moved the blown-out area from 12.8% to 11.3%,
+ // because 0.94 + anything visible still clips. So past this point
+ // the shafts stop ADDING light and start scattering it — which is
+ // what a daylight shaft actually does to the contrast behind it.
+ // Added light only survives a DARK frame, so scattering is
+ // the default and adding is the exception you ask for. A
+ // composer handed '0 interior, 1 daylight' picks the middle,
+ // and the middle used to be the mode that clips.
+ const hazy = ambient >= 0.35;
+ // Added light STACKS. The additive gain was tuned on the default
+ // seven 0.55 m shafts; a nave asking for eight 2.2 m ones adds
+ // about five times the light through the same air and the frame
+ // clips — measured, 1.9% of a dark interior blown pure white, and
+ // the judge called the result "physical beams" rather than light.
+ // Normalising by the beam load leaves the default untouched and
+ // damps only the configurations that would clip.
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+
+ const dir = slantDir(opts.sunDir);
+ const side = new THREE.Vector3().crossVectors(_UP, dir);
+ if (side.lengthSq() < 1e-8) side.set(1, 0, 0);
+ side.normalize();
+ // In the slant plane and across it: the only frame in which a
+ // section keeps a fixed width whatever the sun's azimuth is.
+ const perp = new THREE.Vector3().crossVectors(dir, side).normalize();
+ const run = new THREE.Vector3(dir.x, 0, dir.z);
+ const runLen = run.length();
+ if (runLen > 1e-6) run.divideScalar(runLen); else run.set(0, 0, 1);
+
+ const rnd = prng(seed);
+ const shafts = [];
+ const drop = height / -dir.y;
+ // A shaft's LENGTH is the drop divided by the slant, so a low sun
+ // turns a stated 32 m into a 103 m spear across the whole scene:
+ // measured on a delivered gorge at an 18 deg sun, where the judge
+ // called them "disproportionately massive" solid meshes. The drop
+ // is what the caller stated; the drawn length is capped, and a
+ // shaft cut short simply fades out in the air.
+ const maxLen = opts.maxLength === undefined
+ ? height * 1.6
+ : Math.max(opts.maxLength, height * 0.5);
+
+ // Length counts as much as width: the light a shaft adds is the
+ // screen area it covers, and a 35 m shaft puts nearly four times
+ // what a 9 m one does through the same air. Reference is the
+ // default seven 0.55 m shafts at their own capped length.
+ const slantLen = Math.min(
+ maxLen, height / Math.max(0.15, Math.abs(dir.y)));
+ const beam = (count * width * slantLen) / (7 * 0.55 * 1.6 * 6);
+ const load = Math.pow(Math.max(1, beam), 0.75);
+ // The hazy branch was a FLAT gain, so outdoors — where ambient is
+ // always high — nothing was ever damped: four 35 m shafts came out
+ // as solid white wedges across the frame.
+ const gain = (hazy ? 0.34 : 0.62 * (1 - 0.5 * ambient)) / load;
+ // The pools and the dust are added light too, and only the SHAFTS
+ // were ever taught what a bright frame costs. Measured on the eight
+ // 2.2 m outdoor rig the shafts had already been fixed for: the dust
+ // came out as white bokeh balls hanging in the SKY and the pools as
+ // blown discs on sunlit dirt — 0.21% of the frame past 0.97, all of
+ // it from these two. Both are additive marks laid ON a background,
+ // so what clips them is how bright that background already is; the
+ // load enters at its square root, because a heavier rig multiplies
+ // how MANY marks there are far more than it stacks them.
+ const spread_ = Math.sqrt(load);
+ const poolAmp = (hazy ? 0.62 : 1) / spread_;
+ const moteAmp = (hazy ? 0.55 : 1) / spread_;
+ for (let i = 0; i < count; i++) {
+ const u = count === 1 ? 0 : (i / (count - 1)) * 2 - 1;
+ const rTop = width * 0.5 * (0.68 + 0.64 * rnd());
+ const flare = 1.28 + 0.34 * rnd();
+ const ratio = 1.0 + 0.45 * rnd();
+ const roll = rnd() * Math.PI;
+ const cs = Math.cos(roll), sn = Math.sin(roll);
+ const b1 = side.clone().multiplyScalar(cs)
+ .addScaledVector(perp, sn);
+ const b2 = side.clone().multiplyScalar(-sn)
+ .addScaledVector(perp, cs);
+ // Land the LOWEST vertex of the last section on y = 0 exactly,
+ // so the group rests on the floor it lights.
+ const kY = Math.abs(perp.y)
+ * Math.sqrt(ratio * ratio * sn * sn + cs * cs);
+ const yEnd = rTop * flare * kY;
+ const full = (height - yEnd) / -dir.y;
+ const len = Math.min(full, maxLen);
+ // Only a shaft that still reaches the floor throws a pool.
+ const lands = len >= full - 1e-6;
+ const top = new THREE.Vector3(0, height, 0)
+ .addScaledVector(side, u * spread * 0.5
+ + (rnd() - 0.5) * spread * 0.5 / count)
+ .addScaledVector(run, (rnd() - 0.4) * spread * 0.16
+ - runLen * drop * 0.5);
+ shafts.push({ top, len, rTop, flare, ratio, b1, b2, lands });
+ }
+
+ const g = new THREE.Group();
+ g.name = 'GodRays';
+ g.add(shaftMesh(shafts, dir, color, air, soft, gain, hazy));
+ const landed = shafts.filter((s) => s.lands);
+ if (landed.length) {
+ g.add(poolMesh(landed, dir, run, side, color, air, poolAmp));
+ }
+ g.add(moteMesh(shafts, dir, side, perp, width, color, air,
+ moteAmp, seed));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/**
+ * What the AIR gives back, derived from the light it is lit by.
+ *
+ * Not a stated blue: a hardcoded haze colour under a red sun is a beam
+ * whose far end disagrees with its own scene. Scattering takes the long
+ * wavelengths out and puts the short ones back, which is a MULTIPLIER
+ * on the source, and renormalising to the source luminance keeps it a
+ * change of hue rather than a second, dimmer lamp. Hue interpolation
+ * would have to cross green to get from a warm sun to a cool sky; this
+ * crosses white, which is where the real transition goes.
+ */
+function airColor(c, over) {
+ if (over) return new THREE.Color(over);
+ const a = c.clone().multiply(new THREE.Color(0.80, 0.95, 1.20));
+ const lum = (x) => 0.2126 * x.r + 0.7152 * x.g + 0.0722 * x.b;
+ const k = lum(c) / Math.max(lum(a), 1e-4);
+ return a.multiplyScalar(Math.min(k, 4));
+}
+
+/** Where the light travels: downward, and steeply enough to land. */
+function slantDir(v) {
+ const d = Array.isArray(v)
+ ? new THREE.Vector3(v[0], v[1], v[2])
+ : (v && v.isVector3 ? v.clone() : new THREE.Vector3(-0.38, -1, -0.26));
+ if (d.lengthSq() < 1e-8) d.set(-0.38, -1, -0.26);
+ d.normalize();
+ if (d.y > 0) d.negate();
+ if (d.y > -0.25) { d.y = -0.25; d.normalize(); }
+ return d;
+}
+
+/** 16807 LCG: same seed, same field, on every machine. */
+function prng(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);
+}
+
+/**
+ * How far the field reaches from the group's own origin.
+ *
+ * The instanced lattices keep `position` at zero for the GTAO override,
+ * so three's own bounding sphere would be a point; culling reads the
+ * sphere, and a point at the origin culls the whole field the moment
+ * the origin leaves frame. This states the real extent instead.
+ */
+function fieldRadius(shafts, dir) {
+ let r = 1;
+ for (const s of shafts) {
+ const x = s.top.x + dir.x * s.len;
+ const y = s.top.y + dir.y * s.len;
+ const z = s.top.z + dir.z * s.len;
+ r = Math.max(r, Math.hypot(s.top.x, s.top.y, s.top.z),
+ Math.hypot(x, y, z) + s.rTop * s.flare * s.ratio);
+ }
+ return r;
+}
+
+/** Every shaft in one geometry, tagged by `aShaft` so they differ. */
+function mergeShafts(parts) {
+ let nv = 0, ni = 0;
+ for (const p of parts) {
+ nv += p.geometry.attributes.position.count;
+ ni += p.geometry.index.count;
+ }
+ const pos = new Float32Array(nv * 3), nor = new Float32Array(nv * 3);
+ const uv = new Float32Array(nv * 2), tag = new Float32Array(nv);
+ const idx = new Uint32Array(ni);
+ let v = 0, k = 0;
+ for (const p of parts) {
+ const a = p.geometry.attributes;
+ pos.set(a.position.array, v * 3);
+ nor.set(a.normal.array, v * 3);
+ uv.set(a.uv.array, v * 2);
+ for (let i = 0; i < a.position.count; i++) tag[v + i] = p.tag;
+ const src = p.geometry.index.array;
+ for (let i = 0; i < src.length; i++) idx[k + i] = src[i] + v;
+ v += a.position.count;
+ k += src.length;
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ g.setAttribute('aShaft', new THREE.BufferAttribute(tag, 1));
+ g.setIndex(new THREE.BufferAttribute(idx, 1));
+ return g;
+}
+
+/** The beams themselves: swept tubes carrying a volume integral. */
+function shaftMesh(shafts, dir, color, air, soft, gain, hazy) {
+ const parts = shafts.map((s, i) => ({
+ tag: (i + 0.5) / shafts.length,
+ geometry: sweepProfile(
+ (t) => ({
+ x: s.top.x + dir.x * s.len * t,
+ y: s.top.y + dir.y * s.len * t,
+ z: s.top.z + dir.z * s.len * t,
+ }),
+ (a, t) => {
+ // Widens as it falls: a constant section is a pipe, and
+ // the eye names it one.
+ const r = s.rTop * (1 + (s.flare - 1) * t);
+ const p = Math.cos(a) * r * s.ratio, q = Math.sin(a) * r;
+ return {
+ x: s.b1.x * p + s.b2.x * q,
+ y: s.b1.y * p + s.b2.y * q,
+ z: s.b1.z * p + s.b2.z * q,
+ };
+ },
+ { nu: 28, nv: 22 }),
+ }));
+ const mesh = new THREE.Mesh(
+ mergeShafts(parts),
+ shaftMaterial(dir, color, air, soft, gain, hazy));
+ mesh.name = 'Shafts';
+ mesh.renderOrder = 3;
+ return mesh;
+}
+
+/** Chord-weighted scattering, striated across the beam. */
+function shaftMaterial(dir, color, air, soft, gain, hazy) {
+ // Scattering, not adding: a pale, low-alpha normal blend lowers the
+ // contrast behind the shaft instead of clipping a bright frame.
+ // The paling used to be a 0.55 lerp to WHITE, which is why an
+ // outdoor field of shafts came out as grey smoke — the one thing
+ // sunlight through a gap never looks like. A third of that keeps
+ // the veil safe over a bright frame (alpha is what clips, and alpha
+ // is untouched) and the DEPTH of air, not the mode, is what takes
+ // the colour out of the far end.
+ const tint = hazy ? color.clone().lerp(new THREE.Color(0xffffff), 0.18)
+ : color;
+ // A NORMAL blend replaces what is behind it, so the colour has to
+ // carry the luminance the alpha carries in the additive branch.
+ // At 1.0 the veil tone-maps to 0.915 while this sky sits at 0.94 —
+ // a shaft of light that DARKENS the sky it crosses, which is the
+ // grey-smoke look these came out as. Straight into the ACES
+ // shoulder instead: 1.9 lands at 0.96, brighter than the sky by a
+ // hair and far brighter than the shade, and the shoulder is what
+ // keeps it from clipping. The additive branch is untouched —
+ // there the alpha already IS the brightness.
+ const lift = hazy ? 1.9 : 1.0;
+ return makeShaderMaterial({
+ name: 'GodRayShaft',
+ uniforms: {
+ uColor: { value: tint.clone().multiplyScalar(lift) },
+ uAir: { value: air.clone().multiplyScalar(lift) },
+ // How much air the shaft is seen through before the depth
+ // term adds any: none in a room, a haze outdoors.
+ uAirMix: { value: hazy ? 0.22 : 0.0 },
+ uDir: { value: dir.clone() },
+ uSoft: { value: 1.0 + 2.0 * Math.min(Math.max(soft, 0), 1) },
+ uGain: { value: gain },
+ },
+ varyings: 'varying vec2 vUv; varying vec3 vN; varying vec3 vW;'
+ + ' varying float vShaft;',
+ vertexHead: 'attribute float aShaft;',
+ vertexMain: [
+ ' vUv = uv;',
+ ' vShaft = aShaft;',
+ ' vN = normalize(normalMatrix * normal);',
+ ' vW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'
+ + ' uniform float uAirMix; uniform vec3 uDir;'
+ + ' uniform float uSoft;'
+ + ' uniform float uGain;',
+ fragmentMain: [
+ ' float v = clamp(vUv.y, 0.0, 1.0);',
+ ' vec3 eye = normalize(cameraPosition - vW);',
+ // The chord the eye cuts through the beam. Zero at the
+ // silhouette, so the shell never draws its own outline.
+ ' float face = astraFacing(vN, eye);',
+ ' float chord = pow(face, uSoft);',
+ // |n.v| is the chord only ACROSS the beam; looking down it
+ // the walls turn edge-on while the real chord grows.
+ ' float axial = abs(dot(eye, uDir));',
+ ' chord *= 1.0 / max(sqrt(1.0 - axial * axial), 0.62);',
+ ' float sd = astraStagger(vShaft);',
+ // Sampled on a circle so the pattern has no seam where the
+ // section closes, and drifts far slower ALONG than across.
+ ' float ang = vUv.x * 6.2831853;',
+ ' vec2 ring = vec2(cos(ang), sin(ang)) * 2.7;',
+ ' float striae = 0.46 + 0.72 * astraFbm2(ring + vec2(sd,',
+ ' v * 1.4 - uTime * 0.05), 3);',
+ // Brightest at the gap it came through; the air eats the
+ // rest on the way down.
+ ' float fade = exp(-v * 1.15);',
+ ' float ends = smoothstep(0.0, 0.11, v)',
+ ' * (1.0 - smoothstep(0.86, 1.0, v));',
+ // Beams of one brightness are a fence; real gaps let
+ // through what they let through.
+ ' float amp = 0.55 + 0.8 * astraHash11(vShaft * 13.0 + 0.5);',
+ ' float a = uGain * amp * chord * striae * fade * ends;',
+ _FOG_FADE,
+ // Rolled off instead of clamped: a beam that saturates
+ // draws a flat white band with a hard rim, which is the
+ // cylinder again.
+ ' a = 1.0 - exp(-a * 1.25);',
+ // Colour along the beam, not one flat tint for all six.
+ // Depth of air cools it toward the floor, the feathered rim
+ // is nothing BUT air, and each shaft stands in its own
+ // amount of it — so the field carries a spread of tints the
+ // way a photograph does instead of one stencilled hue.
+ ' float hz = astraHash11(vShaft * 7.0 + 2.3);',
+ ' float mist = clamp(uAirMix + 0.42 * v',
+ ' + 0.26 * (1.0 - face) + (hz - 0.5) * 0.26, 0.0, 1.0);',
+ ' vec3 c = mix(uColor, uAir, mist) * (0.72 + 0.5 * chord);',
+ ' c = astraHueShift(c, (hz - 0.5) * 0.14);',
+ // A beam is one long, very shallow ramp — exactly the
+ // gradient 8-bit output bands. A sub-LSB shake of the alpha
+ // turns the terraces back into noise.
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.005;',
+ ' if (a < 0.002) discard;',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,
+ side: THREE.DoubleSide,
+ depthWrite: false,
+ });
+}
+
+/** Where each beam lands: a soft ellipse, so it hands over. */
+function poolMesh(shafts, dir, run, side, color, air, spark) {
+ const n = shafts.length;
+ // A stated radius, not the 10 km default: every rig that
+ // frames on the sphere would otherwise frame a kilometre
+ // of empty air around a 20 m shaft. It has to be a NUMBER —
+ // `run + side * 2` on two Vector3s is the string
+ // "[object Object]NaN", and a bounding sphere of NaN radius is
+ // one `frustumCulled = true` away from a field that never draws.
+ const geom = instancedQuad(n, 2, 2, fieldRadius(shafts, dir));
+ const pos = new Float32Array(n * 3), size = new Float32Array(n * 2);
+ shafts.forEach((s, i) => {
+ const rBot = s.rTop * s.flare;
+ pos[i * 3] = s.top.x + dir.x * s.len;
+ pos[i * 3 + 1] = 0.02;
+ pos[i * 3 + 2] = s.top.z + dir.z * s.len;
+ // A slanted beam meets the floor in an ellipse stretched by the
+ // slant; the glow margin is what keeps it off its own rim.
+ size[i * 2] = rBot * s.ratio * 2.3 / Math.max(-dir.y, 0.25);
+ size[i * 2 + 1] = rBot * 2.3;
+ });
+ geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));
+ geom.setAttribute('aSize', new THREE.InstancedBufferAttribute(size, 2));
+ const mat = makeShaderMaterial({
+ name: 'GodRayPool',
+ uniforms: {
+ uColor: { value: color.clone() },
+ uAir: { value: air.clone() },
+ uAmp: { value: spark },
+ uRun: { value: run.clone() },
+ uSide: { value: side.clone() },
+ },
+ varyings: 'varying vec2 vUv;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'
+ + ' attribute vec2 aSize;'
+ + ' uniform vec3 uRun; uniform vec3 uSide;',
+ vertexMain: [
+ ' vUv = uv;',
+ ' transformed = aPos + uRun * (aCorner.x * aSize.x)',
+ ' + uSide * (aCorner.y * aSize.y);',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uAir;'
+ + ' uniform float uAmp;',
+ fragmentMain: [
+ ' float d = length(vUv * 2.0 - 1.0);',
+ ' if (d > 1.0) discard;',
+ ' float shim = 0.72 + 0.28 * astraFbm2(vUv * 5.0',
+ ' + vec2(uTime * 0.05, 0.0), 3);',
+ // Two falloffs: the wide one is the scattered margin, the
+ // narrow one the patch of floor the beam actually stands
+ // on. One power alone is a soft blob with no centre.
+ ' float a = (pow(1.0 - d, 2.9) * 0.44',
+ ' + pow(1.0 - d, 7.0) * 0.26) * shim * uAmp;',
+ _FOG_FADE,
+ // A pool has a hot heart and a scattered margin: holding one
+ // tint out to the rim is what makes it read as a decal.
+ ' vec3 c = mix(uColor, uAir, smoothstep(0.15, 1.0, d) * 0.7);',
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.005;',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ blending: THREE.AdditiveBlending,
+ depthWrite: false,
+ });
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Pools';
+ mesh.frustumCulled = false;
+ mesh.renderOrder = 2;
+ return mesh;
+}
+
+/** Dust drifting inside the beams, as GTAO-safe billboards. */
+function moteMesh(shafts, dir, side, perp, width, color, air, spark, seed) {
+ const n = Math.max(30, shafts.length * 44);
+ const geom = instancedQuad(n, 1, 1, fieldRadius(shafts, dir) + width);
+ const rnd = prng((seed >>> 0) * 7 + 13);
+ const org = new Float32Array(n * 3), off = new Float32Array(n * 3);
+ const data = new Float32Array(n * 4);
+ for (let i = 0; i < n; i++) {
+ const s = shafts[i % shafts.length];
+ // Placed by sqrt of a uniform draw, or every mote crowds the
+ // axis and the beam looks threaded on a wire.
+ const r = s.rTop * Math.sqrt(rnd());
+ const a = rnd() * Math.PI * 2;
+ const p = Math.cos(a) * r * s.ratio, q = Math.sin(a) * r;
+ org[i * 3] = s.top.x; org[i * 3 + 1] = s.top.y;
+ org[i * 3 + 2] = s.top.z;
+ off[i * 3] = s.b1.x * p + s.b2.x * q;
+ off[i * 3 + 1] = s.b1.y * p + s.b2.y * q;
+ off[i * 3 + 2] = s.b1.z * p + s.b2.z * q;
+ data[i * 4] = rnd();
+ // Dust, and dust is SMALL. Sized off the beam it rides, a mote
+ // was a tenth of the shaft's width across — 25-odd pixels of
+ // white disc at close range, which reads as falling snow or a
+ // dirty lens, never as air. A third of that lands in the 3-8 px
+ // range a real glint occupies, and the spread across the field
+ // is widened so they are not all one bead size.
+ data[i * 4 + 1] = width * (0.024 + 0.052 * rnd() * rnd());
+ data[i * 4 + 2] = s.len;
+ data[i * 4 + 3] = s.flare;
+ }
+ geom.setAttribute('aOrigin', new THREE.InstancedBufferAttribute(org, 3));
+ geom.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 3));
+ geom.setAttribute('aSeed', new THREE.InstancedBufferAttribute(data, 4));
+ const mesh = new THREE.Mesh(
+ geom, moteMaterial(dir, side, perp, color, air, spark, width));
+ mesh.name = 'Motes';
+ mesh.frustumCulled = false;
+ mesh.renderOrder = 4;
+ return mesh;
+}
+
+/** Billboarded dust: its own view-space projection, so raw sources. */
+function moteMaterial(dir, side, perp, color, air, spark, width) {
+ return makeShaderMaterial({
+ name: 'GodRayMotes',
+ uniforms: {
+ // Lit BY the beam, so it keeps the beam's hue: the old 0.45
+ // lerp to white made the dust whiter than the light that
+ // lights it, which is the bokeh look.
+ // Declared even though makeShaderMaterial supplies it: this
+ // is the one material here that ships a RAW vertex shader,
+ // and the harness's own audit (runtime_js/lib/glsl_audit.mjs)
+ // reads the JS for a binding and the GLSL for a declaration
+ // rather than trusting the factory.
+ uTime: { value: 0 },
+ uColor: { value: color.clone().lerp(new THREE.Color(1, 1, 1),
+ 0.22) },
+ uAir: { value: air.clone() },
+ uAmp: { value: spark },
+ // Wobble is a distance in metres and size is a radius; they
+ // rode one attribute, so shrinking the dust also froze it.
+ uWob: { value: Math.max(width, 1e-3) * 0.22 },
+ uDir: { value: dir.clone() },
+ uSide: { value: side.clone() },
+ uPerp: { value: perp.clone() },
+ },
+ vertexShader: [
+ '#include <common>',
+ '#include <logdepthbuf_pars_vertex>',
+ '#include <fog_pars_vertex>',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 aOrigin;',
+ 'attribute vec3 aOff;',
+ 'attribute vec4 aSeed;',
+ // One line, because the audit only reads quoted strings long
+ // enough to look like GLSL: `uniform float uTime;` alone is
+ // 20 characters and is skipped, so the file it sits in reads
+ // as using uTime without declaring it.
+ 'uniform float uTime; uniform vec3 uDir; uniform vec3 uSide;',
+ 'uniform vec3 uPerp; uniform float uWob;',
+ 'varying vec2 vUv;',
+ 'varying float vLife;',
+ 'varying float vTwinkle;',
+ 'varying float vMist;',
+ 'void main() {',
+ ' vUv = uv;',
+ ' float k = fract(aSeed.x + uTime * 0.035);',
+ ' vLife = k;',
+ ' float ph = aSeed.x * 6.2831853;',
+ // Deeper in the beam is deeper in air: the far dust goes to
+ // the air hue while the near dust keeps the light's own.
+ ' vMist = clamp(0.25 + 0.5 * k + 0.35 * fract(aSeed.x * 7.3),',
+ ' 0.0, 1.0);',
+ // Dust does not fall straight: it hangs and wanders, so the
+ // wobble is wider than the drift is fast.
+ ' float wb = uWob * (0.55 + aSeed.x);',
+ ' vec3 wob = uSide * sin(uTime * 0.5 + ph) * wb',
+ ' + uPerp * cos(uTime * 0.37 + ph * 1.7) * wb * 0.82;',
+ ' vec3 c = aOrigin + aOff * (1.0 + (aSeed.w - 1.0) * k)',
+ ' + uDir * (aSeed.z * k) + wob;',
+ ' vTwinkle = 0.55 + 0.45 * sin(uTime * 2.1 + ph * 3.0);',
+ ' vec4 mvPosition = modelViewMatrix * vec4(c, 1.0);',
+ ' mvPosition.xy += aCorner.xy * aSeed.y;',
+ ' 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 uColor; uniform vec3 uAir; uniform float uAmp;',
+ 'varying vec2 vUv;',
+ 'varying float vLife;',
+ 'varying float vTwinkle;',
+ 'varying float vMist;',
+ 'void main() {',
+ '#include <logdepthbuf_fragment>',
+ ' float d = length(vUv - 0.5) * 2.0;',
+ ' if (d > 1.0) discard;',
+ // Lives and dies inside the beam so nothing pops at the
+ // wrap, and dims with it toward the floor.
+ ' float life = sin(vLife * 3.14159265);',
+ // A glint has a core and a hint of halo, not one soft disc:
+ // the sharper power is what stops a 6 px sprite reading as
+ // a ball of cotton.
+ ' float a = (pow(1.0 - d, 3.4) + 0.14 * pow(1.0 - d, 1.3))',
+ ' * life * vTwinkle * exp(-vLife * 1.2) * 1.05 * uAmp;',
+ '#ifdef USE_FOG',
+ ' #ifdef FOG_EXP2',
+ ' a *= exp(-fogDensity * fogDensity * vFogDepth * vFogDepth);',
+ ' #else',
+ ' a *= 1.0 - smoothstep(fogNear, fogFar, vFogDepth);',
+ ' #endif',
+ '#endif',
+ ' if (a < 0.003) discard;',
+ ' gl_FragColor = vec4(mix(uColor, uAir, vMist),',
+ ' clamp(a, 0.0, 1.0));',
+ '#include <fog_fragment>',
+ '}',
+ ].join('\n'),
+ transparent: true,
+ blending: THREE.AdditiveBlending,
+ depthWrite: false,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/grass.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/grass.js
new file mode 100644
index 00000000..2a42b7e1
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/grass.js
@@ -0,0 +1,574 @@
+/**
+ * Grass: a field that reads as a field, from a low camera and from
+ * above.
+ *
+ * Ground here is bare coloured geometry, and the two ways a first
+ * attempt fails are opposite. From eye height a field of camera-facing
+ * quads reads as coloured shards, so a blade is a real tapered strip
+ * with WIDTH, a natural lean and a circular-arc bend — it curves, it
+ * does not hinge, and it never stretches. From above, upright blades
+ * present only their tips and the field reads as a scatter of dots, so
+ * the blades ride on a `Sward` mat that carries the SAME clump field
+ * they were placed by: the field is continuous where they are dense and
+ * hands over to dry ground where they thin out.
+ *
+ * The blades are ONE draw call — one instanced strip whose every copy
+ * is built in the vertex shader from per-blade attributes. `position`
+ * stays at zero for the GTAO reason `instancedQuad` documents.
+ *
+ * Not `patchWind` from foliage_shade.js: that bends a plant from its
+ * INSTANCE ORIGIN (`instanceMatrix`, one phase per plant) and moves the
+ * tip by a straight translation. These blades have no instanceMatrix —
+ * they are attributes on one geometry, so every blade would take the
+ * world origin's phase and the whole field would nod in step — and a
+ * translated tip stretches a blade that must instead lie down along an
+ * arc of its own fixed length. Hence its own vertex path.
+ */
+
+import * as THREE from 'three';
+import { fbm2, mulberry32 } from './noise.js';
+import { patchStandard, shadowLike, tickShaders } from './shader.js';
+
+// Blade shape: enough rows to curve, one column because the width is
+// swept in the shader. 4 rows is where a bent blade stops faceting.
+const BLADE_ROWS = 4;
+
+// A world direction as the LOCAL offset that moves this surface one
+// metre along it — the same projection foliage_shade.js uses, valid
+// because compose() leaves the basis columns orthogonal.
+const LOCAL_DIR = [
+ 'vec3 grassLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+/**
+ * Cover a patch of ground in grass.
+ *
+ * The whole field is deterministic in `seed`: same seed, same blades.
+ * Drive it from your `tick()` — `grass.userData.tick(t)` — or the wind
+ * never blows.
+ *
+ * @param {object} [opts]
+ * `extent` metres of the square patch's side (default 24, centred on
+ * the group's origin); `density` blades per square metre (default
+ * 180; `maxBlades` caps it by widening the spacing, never by
+ * dropping a corner); `height` blade height in metres (default 0.42,
+ * taller in the clumps); `color` the lush green of a clump;
+ * `dryColor` the straw of the thin ground between them; `wind`
+ * strength multiplier, or `{dir, strength, speed}` with `dir` a
+ * THREE.Vector2 / [x, z] the direction it BLOWS TOWARD over world XZ
+ * (default a light breeze toward +X, strength 1, speed 1 = a
+ * two-second sway); `heightAt` (x, z) => y, the caller's ground
+ * height — blades and mat both follow it; `seed` PRNG seed (default
+ * 11); `patchy` 0..1 how bare the ground goes between clumps (default
+ * 0.5); `maxBlades` hard cap (default 60000); `sward` draw the ground
+ * mat (default true — pass false when the ground already carries a
+ * grass splat); `shadows` cast blade shadows through a displaced
+ * depth pass (default false — tens of thousands of instances in the
+ * shadow map are a real cost on SwiftShader; wheat set the same
+ * default); `name` group name.
+ * @returns {THREE.Group} Named `Grass`, resting on y = 0 (or on
+ * `heightAt`), holding `Blades` (one draw call) and `Sward`, with
+ * `userData.tick(t)` driving both.
+ */
+export function makeGrass(opts = {}) {
+ const extent = opts.extent === undefined ? 24 : opts.extent;
+ const density = opts.density === undefined ? 180 : opts.density;
+ const height = opts.height === undefined ? 0.42 : opts.height;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const patchy = clamp01(opts.patchy === undefined ? 0.5 : opts.patchy);
+ const maxBlades = opts.maxBlades === undefined ? 60000 : opts.maxBlades;
+ // Albedos, not screen colours: a scene sun runs at 5-6, so a hex
+ // that already looks like sunlit grass tone-maps to pale felt.
+ // CHROMA, though, has to be spent up front. The sky fill is blue at
+ // 1.2-1.4 and the env is a blue-white dome, so every green here is
+ // washed toward mint on the way to the frame: measured on this
+ // renderer, the old 0x44631f field landed at saturation 0.28 with a
+ // mean luminance of 0.56 — pale felt by a different route.
+ const lush = new THREE.Color(
+ opts.color === undefined ? 0x375e18 : opts.color);
+ const dry = new THREE.Color(
+ opts.dryColor === undefined ? 0x706333 : opts.dryColor);
+ const wind = windOf(opts.wind);
+ const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const clumpAt = clumpField(seed, extent);
+
+ const g = new THREE.Group();
+ g.name = opts.name || 'Grass';
+ const field = plantField(
+ extent, density, maxBlades, height, patchy, seed, clumpAt, ground);
+ g.add(bladeMesh(field, extent, lush, dry, wind, opts.shadows === true));
+ if (opts.sward !== false) {
+ g.add(swardMat(extent, density, lush, dry, clumpAt, ground));
+ }
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/** Clamp to 0..1 without importing MathUtils for two calls. */
+function clamp01(v) {
+ return Math.max(0, Math.min(1, v));
+}
+
+/**
+ * Read the `wind` option in either of its two spellings.
+ *
+ * Exported because one scene's wind has to move its meadow,
+ * its reeds and its trees as ONE wind: a library that
+ * re-implements this reader is a library that will drift
+ * away from it.
+ */
+export function windOf(w) {
+ const o = (w && typeof w === 'object') ? w : { strength: w };
+ const d = o.dir;
+ const dir = new THREE.Vector2(
+ d ? (d.x === undefined ? d[0] : d.x) : 1,
+ d ? (d.y === undefined ? d[1] : d.y) : 0.45);
+ if (dir.lengthSq() < 1e-9) dir.set(1, 0);
+ return {
+ dir: dir.normalize(),
+ // Radians of tip bend at a full gust, from a 1 = breeze strength.
+ amp: 0.5 * (o.strength === undefined ? 1 : o.strength),
+ speed: o.speed === undefined ? 1 : o.speed,
+ };
+}
+
+/**
+ * The tussock field, on the CPU so blades and mat agree on it.
+ *
+ * GLSL_UTIL's noise is NOT noise.js's, so a shader-side clump field
+ * would put the mat's green somewhere else entirely; this one value
+ * feeds the placement, the height, the colour and the mat's vertices.
+ */
+function clumpField(seed, extent) {
+ const o = { seed, octaves: 4, gain: 0.62 };
+ const raw = (x, z) => fbm2(x * 0.38, z * 0.38, o);
+ // Measured: fbm2 spans about +-0.25 here, off-centre by as much as
+ // half of that, and by a different amount per seed and per region.
+ // Uncalibrated, `patchy` would mean a different field every time.
+ const n = 24;
+ let sum = 0, sq = 0;
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ const v = raw(extent * ((i + 0.5) / n - 0.5),
+ extent * ((j + 0.5) / n - 0.5));
+ sum += v;
+ sq += v * v;
+ }
+ }
+ const mean = sum / (n * n);
+ const sd = Math.sqrt(Math.max(sq / (n * n) - mean * mean, 1e-9));
+ return (x, z) => {
+ // Contrast, or every patch lands mid-field and the whole extent is
+ // one wash: a tussock is either there or it is not.
+ const v = clamp01(0.5 + (raw(x, z) - mean) / (2.6 * sd));
+ return 0.45 * v + 0.55 * v * v * (3 - 2 * v);
+ };
+}
+
+/**
+ * Place the blades on a fully jittered grid, thinned by the clumps.
+ *
+ * Full-cell jitter, not scatterGrid's 0.35: from directly above, a
+ * partly jittered lattice still shows its rows, which is the "grid of
+ * dots" this library exists to avoid.
+ */
+function plantField(extent, density, maxBlades, height, patchy, seed,
+ clumpAt, ground) {
+ const area = extent * extent;
+ const want = Math.max(1, Math.min(Math.round(density * area), maxBlades));
+ // Over-provisioned for the clump rejection, so `density` survives
+ // `patchy`; and a maxBlades cap widens the CELL instead of dropping a
+ // corner, which makes a capped field thinner and not smaller.
+ const cells = Math.max(1, Math.round(Math.sqrt(want / (1 - patchy * 0.4))));
+ const step = extent / cells;
+ const rand = mulberry32(seed);
+ const pos = [], shape = [], vary = [];
+ let n = 0, maxH = 0;
+ for (let iz = 0; iz < cells && n < maxBlades; iz++) {
+ for (let ix = 0; ix < cells && n < maxBlades; ix++) {
+ const x = -extent / 2 + (ix + rand()) * step;
+ const z = -extent / 2 + (iz + rand()) * step;
+ const c = clumpAt(x, z);
+ if (rand() > 1 - patchy * (1 - c)) continue;
+ // A few seed stalks stand well clear of the sward: without them
+ // the field's top edge is a ruled line from any low camera.
+ const tall = rand() < 0.06 * c ? 1.5 + 0.7 * rand() : 1;
+ const h = height * tall * (0.55 + 0.75 * c) * (0.8 + 0.45 * rand());
+ pos.push(x, ground ? ground(x, z) : 0, z);
+ // A blade droops in its own direction; the wind adds to that
+ // vector in the shader, so a still field leans every which way.
+ shape.push(h, h * (0.042 + 0.030 * rand()),
+ 0.16 + 0.42 * rand() * (1.2 - c), rand() * Math.PI * 2);
+ // Dryness follows the CLUMP with only a little blade-to-blade
+ // jitter: more, and the patches dissolve into per-blade noise.
+ // Hue per blade, and it has to be WIDE: a meadow is yellow-green
+ // to blue-green to dried straw, not one green shaded by light.
+ // Measured, +-6 deg read as a single albedo at any distance
+ // (local hue spread 8 deg against 25-45 in a photograph).
+ vary.push((rand() - 0.5) * 1.3, rand(),
+ clamp01(0.75 * (1 - c) + (rand() - 0.5) * 0.18),
+ (rand() - 0.5) * 0.85);
+ maxH = Math.max(maxH, h);
+ n++;
+ }
+ }
+ return { n, pos, shape, vary, maxH };
+}
+
+/**
+ * The blade lattice: ONE instanced strip with `position` pinned at 0.
+ *
+ * GTAOPass redraws with an override material that ignores this vertex
+ * shader, so a real blade left in `position` would stack every copy at
+ * the world origin and burn a black slab there. The strip rides
+ * `aCorner` (x across, y from root to tip) as `instancedQuad` does.
+ */
+function bladeLattice(count) {
+ const base = new THREE.PlaneGeometry(1, 1, 1, BLADE_ROWS);
+ base.translate(0, 0.5, 0);
+ const g = new THREE.InstancedBufferGeometry();
+ g.index = base.index;
+ g.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(base.attributes.position.count * 3), 3));
+ g.setAttribute('aCorner', base.attributes.position);
+ g.setAttribute('normal', base.attributes.normal);
+ g.setAttribute('uv', base.attributes.uv);
+ g.instanceCount = count;
+ return g;
+}
+
+/** One mesh, one draw call: every blade lives in the vertex shader. */
+function bladeMesh(field, extent, lush, dry, wind, shadows) {
+ const geom = bladeLattice(field.n);
+ const inst = (name, arr, size) => geom.setAttribute(
+ name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));
+ inst('iPos', field.pos, 3);
+ inst('iShape', field.shape, 4);
+ inst('iVar', field.vary, 4);
+ // position is zero, so the derived bounds would be a point at the
+ // origin: state the field's real box, and never cull on it.
+ let low = 0, high = 0;
+ for (let i = 1; i < field.pos.length; i += 3) {
+ low = Math.min(low, field.pos[i]);
+ high = Math.max(high, field.pos[i]);
+ }
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-extent / 2, low, -extent / 2),
+ new THREE.Vector3(extent / 2, high + field.maxH, extent / 2));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(
+ new THREE.Sphere());
+
+ // PHYSICAL, not Standard, for one uniform: `specularIntensity`.
+ // Measured on this renderer — blade albedo forced to BLACK and the
+ // environment off — the field still came back at luminance 0.36,
+ // saturation 0.07: a flat neutral sheen over every blade, and 70% of
+ // what each pixel was made of. That is the dielectric's own
+ // reflection, and it is the whole reason no albedo could make this
+ // grass read as green. A Standard dielectric's F90 is pinned at 1.0,
+ // so a field seen nearly edge-on from a low camera reflects the sky
+ // at full strength everywhere; only `specularIntensity` (which
+ // scales F0 AND F90) can turn it down, and a blade of grass is a
+ // waxy leaf, not polished glass. The cost is the physical fragment
+ // path for one material and one draw call.
+ const mat = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff, roughness: 0.78, metalness: 0,
+ specularIntensity: 0.30,
+ side: THREE.DoubleSide, name: 'GrassBlade',
+ // And the AO this host does not have: the reference ran GTAO over
+ // the field, we have no post chain, and a blade standing in a
+ // sward sees a slot of sky rather than a dome.
+ envMapIntensity: 0.62,
+ });
+ patchStandard(mat, {
+ name: 'grass:blade',
+ uniforms: {
+ uGrassLush: { value: lush.clone() },
+ uGrassDry: { value: dry.clone() },
+ uGrassWind: { value: wind.dir.clone() },
+ uGrassAmp: { value: wind.amp },
+ uGrassSpeed: { value: wind.speed },
+ },
+ vertexHead: BLADE_HEAD,
+ vertexBody: BLADE_VERTEX,
+ fragmentHead: [
+ 'uniform vec3 uGrassLush;',
+ 'uniform vec3 uGrassDry;',
+ 'varying vec3 vGrass;',
+ 'varying vec2 vGrassW;',
+ ].join('\n'),
+ fragmentBody: BLADE_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Blades';
+ mesh.frustumCulled = false;
+ mesh.receiveShadow = true;
+ // Without the displaced depth pass a shadow pass draws only the
+ // degenerate zero-position quads, so casting stays off by default.
+ mesh.castShadow = false;
+ if (shadows) {
+ shadowLike(mesh, 'grass:bladeDepth', BLADE_HEAD, BLADE_VERTEX);
+ }
+ return mesh;
+}
+
+const BLADE_HEAD = [
+ 'uniform float uTime;',
+ 'uniform vec2 uGrassWind;',
+ 'uniform float uGrassAmp;',
+ 'uniform float uGrassSpeed;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iPos;',
+ 'attribute vec4 iShape;',
+ 'attribute vec4 iVar;',
+ 'varying vec3 vGrass;',
+ 'varying vec2 vGrassW;',
+ LOCAL_DIR,
+].join('\n');
+
+const BLADE_VERTEX = [
+ ' vec3 grBase = iPos;',
+ ' float grV = aCorner.y;',
+ // Gusts are streaks running downwind, so the field is compressed
+ // ALONG the wind and travels with it; across it, structure is fine.
+ ' vec2 grW = uGrassWind;',
+ ' vec2 grP = vec2(dot(grBase.xz, grW),',
+ ' dot(grBase.xz, vec2(-grW.y, grW.x)));',
+ ' float grGust = astraFbm2(',
+ ' vec2(grP.x * 0.055 - uTime * uGrassSpeed * 0.5, grP.y * 0.21), 2);',
+ // Neighbours out of phase: offsets under a full turn leave a whole
+ // row nodding in step.
+ ' float grPh = astraStagger(iVar.y + grBase.x * 0.07',
+ ' + grBase.z * 0.11);',
+ ' float grT = uTime * uGrassSpeed;',
+ ' float grS = (sin(grT * 2.1 + grPh)',
+ ' + 0.35 * sin(grT * 3.7 + grPh * 1.7)) / 1.35;',
+ ' float grPush = uGrassAmp * (0.25 + 1.25 * grGust)',
+ ' * (0.62 + 0.38 * grS);',
+ // Droop and push ADD as vectors: still, the field leans every which
+ // way; in a gust the whole of it turns downwind together.
+ ' vec2 grLean = vec2(cos(iShape.w), sin(iShape.w)) * iShape.z;',
+ ' vec2 grBend = grLean + grW * grPush;',
+ ' float grA = min(length(grBend), 1.35);',
+ ' vec2 grF = grA > 1e-4 ? normalize(grBend) : vec2(1.0, 0.0);',
+ // A circular arc of the blade's own length: a translated tip would
+ // stretch the blade instead of laying it down.
+ ' float grK = max(grA, 1e-3);',
+ ' float grH = iShape.x;',
+ ' float grSin = sin(grK * grV), grCos = cos(grK * grV);',
+ ' vec3 grSpine = grBase + vec3(grF.x * grH * (1.0 - grCos) / grK,',
+ ' grH * grSin / grK, grF.y * grH * (1.0 - grCos) / grK);',
+ ' vec3 grTan = vec3(grF.x * grSin, grCos, grF.y * grSin);',
+ ' vec3 grPerp = vec3(-grF.y, 0.0, grF.x);',
+ ' vec3 grUp = normalize(cross(grTan, grPerp));',
+ // Twist: without it every blade in a gust turns its edge to the same
+ // side and the field goes to slivers all at once.
+ ' vec3 grSide = normalize(grPerp * cos(iVar.x) + grUp * sin(iVar.x));',
+ ' vec3 grWpos = (modelMatrix * vec4(grSpine, 1.0)).xyz;',
+ ' vec3 grView = normalize(grassLocalDir(cameraPosition - grWpos));',
+ ' vec3 grCross = cross(grTan, grView);',
+ ' float grCl = length(grCross);',
+ // Edge-on, a strip IS a line. Turn it partway toward the eye and
+ // widen what is left, or a low camera sees a scatter of shards.
+ ' vec3 grFace = grCl > 1e-3 ? grCross / grCl : grSide;',
+ ' float grEdge = abs(dot(grSide, grView));',
+ ' grSide = normalize(mix(grSide,',
+ ' grFace * (dot(grFace, grSide) < 0.0 ? -1.0 : 1.0),',
+ ' 0.5 * grEdge * grEdge));',
+ ' float grWid = iShape.y * sqrt(max(1.0 - grV * grV, 0.0))',
+ ' * (1.0 + 0.9 * grEdge * grEdge);',
+ ' transformed = grSpine + grSide * (aCorner.x * grWid);',
+ // The blade's ROOT in world XZ, not its bending spine: the mat under
+ // it reads the same coordinate, so a straw patch is straw in both,
+ // and a value that moved with the gust would make the field's colour
+ // slide about under the wind.
+ ' vGrassW = (modelMatrix * vec4(grBase, 1.0)).xz;',
+ // Dryness swings at the METRE as well as per blade. The clump field
+ // already dries the thin ground, but a meadow also goes to straw in
+ // bands that have nothing to do with how dense it is — sun, drainage,
+ // where it was cut — and those bands are what a still frame reads.
+ ' float grDry = clamp(iVar.z',
+ ' + (astraFbm2(vGrassW * 0.35 + 5.0, 2) - 0.375) * 0.7, 0.0, 1.0);',
+ ' vGrass = vec3(grV, grDry, iVar.w);',
+ '#ifndef FLAT_SHADED',
+ // Cupped across its width, so a blade shades as a channel and not as
+ // a flat card — and wound the way the STRIP is, which is the fix for
+ // the worst bug in this file.
+ //
+ // The sweep sends the plane's x to grSide and its y to grTan, so the
+ // face three rasterises as the front one has the normal
+ // cross(grSide, grTan). This wrote cross(grTan, grSide) — the other
+ // one. DOUBLE_SIDED cannot rescue it: three multiplies vNormal by
+ // gl_FrontFacing, and gl_FrontFacing is decided by the same winding
+ // vNormal was built from, so both flip together and the product is
+ // invariant. Every blade shaded by its BACK face, always.
+ //
+ // Backlit that reads as merely soft. Front-lit it is a black field:
+ // measured on our night rig, the whole meadow came back at luminance
+ // 0.009 with a lit rock and lit ground beside it, and forcing a flat
+ // 0.18 albedo proved the moon was reaching none of it. With the
+ // winding right, the same frame lands at 0.049 and the frame's dark
+ // fraction falls from 0.42 to 0.19.
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' cross(grSide, grTan) - grSide * aCorner.x * 1.2));',
+ '#endif',
+].join('\n');
+
+const BLADE_FRAGMENT = [
+ ' vec3 grC = mix(uGrassLush, uGrassDry, vGrass.y);',
+ ' grC = astraHueShift(grC, vGrass.z);',
+ // Broken colour at the METRE, on top of the per-blade jitter. One
+ // blade is a couple of pixels wide, so its own hue averages straight
+ // back out at any distance — measured, quadrupling the per-blade
+ // swing moved the frame by under two degrees. Warm where the sun
+ // lands, cool where only the sky reaches, over half a metre, is what
+ // survives to the frame, and the mat reads the same field.
+ ' grC = astraHueBreak(grC, vGrassW, 0.55, 0.62);',
+ // The sward is DEEP: a blade's base sits in the shade of its
+ // neighbours, and that gradient is most of what reads as grass.
+ // Deeper than it looks, too — this host has no AO pass, so the
+ // occlusion the reference got from GTAO has to live here or the
+ // field has no dark interior at all (measured: p05 0.33 over the
+ // field, against 0.08-0.15 in a photograph of one).
+ // A POWER, not a smoothstep: a smoothstep that reaches the root is
+ // already back at 0.9 by mid-blade, which is where most of the
+ // field's pixels are, so the frame keeps none of it. Light falls
+ // through a sward roughly as a power of the height, and 1.7 is what
+ // put this field's fifth percentile in a photograph's range.
+ ' float grDepth = pow(clamp(vGrass.x, 0.0, 1.0), 1.7);',
+ ' grC *= 0.22 + 0.78 * grDepth;',
+ ' grC += uGrassLush * 0.10 * smoothstep(0.68, 1.0, vGrass.x);',
+ // TRANSLUCENCY. A blade is a fraction of a millimetre of sap: with
+ // the sun behind it most of what reaches the eye came THROUGH it,
+ // and that gold is the difference between a meadow and a green
+ // carpet. Albedo cannot say it — the lit side of this fragment is
+ // the side facing AWAY — so it goes in as emitted radiance, read off
+ // the scene's own key light in view space (direction AND colour, so
+ // it cannot disagree with the sun, and a night rig's moon drives it
+ // just as well). Sap is yellower than the leaf, and a negative
+ // rotation about the grey axis takes a green toward yellow.
+ '#if NUM_DIR_LIGHTS > 0',
+ '#ifndef FLAT_SHADED',
+ ' vec3 grN = normalize(vNormal);',
+ ' vec3 grEye = normalize(vViewPosition);',
+ ' vec3 grL = directionalLights[0].direction;',
+ // Both tests, or a front-lit field glows as brightly as a backlit
+ // one: the light has to be on the far side of the blade FROM THE
+ // EYE, and the eye has to be looking back down the beam.
+ ' float grThru = clamp(-dot(grN, grL) * sign(dot(grN, grEye)),',
+ ' 0.0, 1.0);',
+ ' float grBeam = pow(clamp(dot(grEye, -grL) * 0.5 + 0.5, 0.0, 1.0),',
+ ' 3.0);',
+ ' vec3 grSap = astraHueShift(grC, -0.30) * 2.4;',
+ // 0.75 is not a garnish. Once the shading normal faces the eye, a
+ // backlit blade's DIFFUSE response is nearly zero — that is what
+ // backlit means — so this term is not decorating the light on the
+ // field, it IS the light on the field, exactly as it is in the
+ // photograph. Weighted by the depth so the glow stops where the
+ // sward closes over: a field that glows to its roots is fog.
+ ' totalEmissiveRadiance += directionalLights[0].color * grSap',
+ ' * (0.75 * grThru * grBeam * grDepth * grDepth);',
+ '#endif',
+ '#endif',
+ ' diffuseColor.rgb = grC;',
+].join('\n');
+
+/**
+ * The mat the blades stand in, carrying the same clump field.
+ *
+ * Without it a top view sees only blade TIPS and the field reads as a
+ * scatter of dots; with it the ground is already grass-coloured where
+ * the blades are dense and dry where they thin out, and the blades add
+ * their silhouette to a surface that is continuous underneath.
+ */
+function swardMat(extent, density, lush, dry, clumpAt, ground) {
+ const segs = Math.max(8, Math.min(96, Math.round(extent / 0.5)));
+ const geom = new THREE.PlaneGeometry(extent, extent, segs, segs);
+ geom.rotateX(-Math.PI / 2);
+ const pos = geom.attributes.position;
+ const clump = new Float32Array(pos.count);
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), z = pos.getZ(i);
+ // 12 mm of lift: level with the caller's ground it z-fights, higher
+ // than that and the blades look planted in a tray.
+ pos.setY(i, (ground ? ground(x, z) : 0) + 0.012);
+ clump[i] = clumpAt(x, z);
+ }
+ pos.needsUpdate = true;
+ geom.computeVertexNormals();
+ geom.setAttribute('aClump', new THREE.BufferAttribute(clump, 1));
+
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.95, metalness: 0, name: 'GrassSward',
+ // Under the canopy, so it sees LESS sky than the blades standing in
+ // it — the same missing-AO correction, one step further down,
+ // because a blade's uniform is a compromise weighted to its tips
+ // and this surface is the bottom of the sward.
+ envMapIntensity: 0.4,
+ });
+ patchStandard(mat, {
+ name: 'grass:sward',
+ uniforms: {
+ uGrassLush: { value: lush.clone() },
+ uGrassDry: { value: dry.clone() },
+ // Grain at the blade spacing: coarser and the mat reads as felt.
+ uGrassGrain: { value: Math.max(1, Math.sqrt(density)) },
+ },
+ vertexHead: 'attribute float aClump;\nvarying vec3 vSward;',
+ vertexBody:
+ ' vSward = vec3((modelMatrix * vec4(transformed, 1.0)).xz, aClump);',
+ fragmentHead: [
+ 'uniform vec3 uGrassLush;',
+ 'uniform vec3 uGrassDry;',
+ 'uniform float uGrassGrain;',
+ 'varying vec3 vSward;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float swN = astraFbm2(vSward.xy * 3.5, 3);',
+ // Bare ground between tussocks is still GRASS ground: let it
+ // fall to a quarter green, not to bald straw. The metre-scale
+ // term is the SAME field the blades dry themselves by, with the
+ // sign flipped because this one measures green and theirs
+ // measures straw — the two have to name the same patch.
+ ' float swC = clamp(0.24 + 0.86 * vSward.z + (swN - 0.45) * 0.3',
+ ' - (astraFbm2(vSward.xy * 0.35 + 5.0, 2) - 0.375) * 0.7,',
+ ' 0.0, 1.0);',
+ ' vec3 swCol = mix(uGrassDry, uGrassLush, swC);',
+ // The MAT is most of the pixels — blades are a thin overlay — so
+ // per-blade hue never reaches the frame on its own: measured, a
+ // 4x wider blade jitter moved the frame's hue spread 4.8 to 6.7
+ // degrees against 25-45 in a photograph. A meadow is yellow-green
+ // through blue-green to straw across half a metre, so the mat
+ // carries that swing itself — and now at the same scale and
+ // swing as the blades standing in it, so the two agree instead of
+ // laying one hue field over a different one.
+ ' swCol = astraHueBreak(swCol, vSward.xy, 0.55, 0.62);',
+ // Tufts, not a wash: strokes at the blade spacing, their
+ // direction wandering so nothing rules a line across the field.
+ ' float swA = astraFbm2(vSward.xy * 0.5, 2) * 6.28;',
+ ' float swU = dot(vSward.xy, vec2(cos(swA), sin(swA)));',
+ // A THIN stroke: astraStroke's aa is clamped at 0.30 while its
+ // self-kill runs w*1.5 to w*5, so a half-width past ~0.20
+ // never vanishes and the tufts alias instead of dissolving.
+ ' float swG = astraStroke(swU * uGrassGrain * 1.8, 0.10);',
+ ' swCol *= 0.82 + 0.26 * swG;',
+ // The mat lies UNDER a canopy, so it is always in shade, and
+ // deep grass swallows what thin dry ground bounces back. Deeper
+ // here than the reference set it: with no AO pass on this host,
+ // the mat IS the field's dark interior — everything a photograph
+ // of a meadow has between the blades comes from this line.
+ ' swCol *= 0.66 - 0.30 * swC;',
+ ' diffuseColor.rgb = swCol;',
+ ].join('\n'),
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Sward';
+ mesh.receiveShadow = true;
+ return mesh;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.js
new file mode 100644
index 00000000..201ff314
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/indoor.js
@@ -0,0 +1,835 @@
+/**
+ * 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/instancing.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/instancing.js
new file mode 100644
index 00000000..6bb837b0
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/instancing.js
@@ -0,0 +1,392 @@
+/**
+ * Place one asset hundreds of times for the cost of building it once.
+ * Hand-instancing is fiddly enough that no delivered scene ever did
+ * it, so the capability ships as a function.
+ */
+
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+
+/**
+ * Build one prototype and stamp it across many transforms.
+ *
+ * The prototype is built ONCE. Every mesh inside it becomes one
+ * InstancedMesh sharing that mesh's geometry and material, so a 200-copy
+ * placement costs the prototype's triangles once on the CPU side and one
+ * draw call per (geometry, material) pair.
+ *
+ * A mesh carrying an ARRAY of materials is split along its geometry
+ * groups first, so a box whose door face is a second material keeps it:
+ * merging by `material[0]` alone painted every face with the first one.
+ *
+ * @param {(opts: object) => THREE.Object3D} build The asset's exported
+ * build function.
+ * @param {Array<{position?: number[]|THREE.Vector3, rotationY?: number,
+ * scale?: number|number[], color?: number[]|THREE.Color|number|string}>}
+ * placements One entry per copy. `rotationY` is radians; `scale` is
+ * uniform when a number. `color` MULTIPLIES that copy's albedo — no
+ * `vertexColors` needed, three defines `USE_INSTANCING_COLOR` off the
+ * instance buffer alone. Give it as a LINEAR `[r, g, b]` (what
+ * `scatterGrid` emits) or a `THREE.Color`; a hex or a CSS string is
+ * read as sRGB, so `0x808080` is not "half" but a quarter — the trap
+ * that turns a tint into a dimmer.
+ * @param {object} [opts] `buildOpts` is passed to `build` for the
+ * prototype; `name` names the returned group.
+ * @returns {THREE.Group} A group of InstancedMeshes, positioned in world
+ * space by the placements. Empty group when there are no placements.
+ */
+export function instanceAsset(build, placements, opts = {}) {
+ const group = new THREE.Group();
+ group.name = opts.name || 'InstancedAsset';
+ if (!placements || placements.length === 0) return group;
+
+ const proto = build(opts.buildOpts || {});
+ proto.updateMatrixWorld(true);
+
+ // Collect meshes with transforms RELATIVE to the prototype root,
+ // then MERGE by material — unmerged, a 1418-mesh asset would cost
+ // 1418 draw calls per placement batch; merged, one per material.
+ const buckets = new Map();
+ const inv = new THREE.Matrix4().copy(proto.matrixWorld).invert();
+ proto.traverse((n) => {
+ if (!n.isMesh || n.isInstancedMesh || !n.geometry) return;
+ const mats = Array.isArray(n.material) ? n.material : [n.material];
+ if (!mats[0]) return;
+ const xf = new THREE.Matrix4().copy(inv).multiply(n.matrixWorld);
+ for (const { material, geometry } of splitByMaterial(n.geometry, mats)) {
+ const g = geometry;
+ g.applyMatrix4(xf);
+ // Merging needs identical attribute sets; drop the extras.
+ for (const name of Object.keys(g.attributes)) {
+ // `color` stays: a vertexColors material with no color
+ // attribute renders BLACK, and mergeStatic() returns one.
+ if (!['position', 'normal', 'uv', 'color'].includes(name)) {
+ g.deleteAttribute(name);
+ }
+ }
+ if (!g.attributes.normal) g.computeVertexNormals();
+ if (!g.attributes.uv) {
+ const n2 = g.attributes.position.count;
+ g.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(n2 * 2), 2));
+ }
+ if (!buckets.has(material.uuid)) {
+ buckets.set(material.uuid, { material, geos: [] });
+ }
+ buckets.get(material.uuid).geos.push(g);
+ }
+ });
+ const parts = [];
+ for (const { material, geos } of buckets.values()) {
+ for (const geometry of mergeBucket(geos)) {
+ parts.push({ geometry, material, local: new THREE.Matrix4() });
+ }
+ }
+ if (!parts.length) return group;
+
+ const world = placements.map((p) => {
+ const pos = p.position instanceof THREE.Vector3
+ ? p.position
+ : new THREE.Vector3(...(p.position || [0, 0, 0]));
+ const s = Array.isArray(p.scale)
+ ? new THREE.Vector3(...p.scale)
+ : new THREE.Vector3(1, 1, 1).multiplyScalar(
+ typeof p.scale === 'number' ? p.scale : 1);
+ return new THREE.Matrix4().compose(
+ pos,
+ new THREE.Quaternion().setFromEuler(
+ new THREE.Euler(0, p.rotationY || 0, 0)),
+ s);
+ });
+
+ const m = new THREE.Matrix4();
+ const tint = new THREE.Color();
+ for (const part of parts) {
+ const mesh = new THREE.InstancedMesh(
+ part.geometry, part.material, placements.length);
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ let tinted = false;
+ for (let i = 0; i < placements.length; i++) {
+ m.copy(world[i]).multiply(part.local);
+ mesh.setMatrixAt(i, m);
+ const c = placements[i].color;
+ if (c !== undefined && c !== null) {
+ // An array is LINEAR — the space the multiply happens in, and the
+ // only way to say "1.06 of the albedo". set() reads a hex or a
+ // string as sRGB.
+ if (Array.isArray(c)) tint.setRGB(c[0], c[1], c[2]);
+ else tint.set(c);
+ mesh.setColorAt(i, tint);
+ tinted = true;
+ }
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ if (tinted && mesh.instanceColor) mesh.instanceColor.needsUpdate = true;
+ mesh.frustumCulled = false; // one bbox for the whole spread
+ group.add(mesh);
+ }
+ return group;
+}
+
+/**
+ * One geometry per material the mesh actually draws with.
+ *
+ * A multi-material mesh draws its groups with different materials; taking
+ * `material[0]` for the whole geometry paints the door, the glass and the
+ * roof with the wall's material and the copy loses every second colour it
+ * had. Each group becomes its own geometry, de-indexed so it carries only
+ * the vertices it uses.
+ * @private
+ */
+function splitByMaterial(geo, mats) {
+ const groups = geo.groups || [];
+ if (mats.length < 2 || groups.length === 0) {
+ return [{ material: mats[0], geometry: geo.clone() }];
+ }
+ const out = [];
+ const idx = geo.index;
+ const total = idx ? idx.count : geo.attributes.position.count;
+ for (const gr of groups) {
+ const start = Math.max(0, gr.start | 0);
+ const count = Math.min(gr.count === Infinity ? total : gr.count | 0,
+ total - start);
+ const material = mats[gr.materialIndex || 0] || mats[0];
+ if (count <= 0 || !material) continue;
+ let piece;
+ if (idx) {
+ piece = geo.clone();
+ piece.clearGroups();
+ piece.setIndex(Array.from(idx.array.slice(start, start + count)));
+ piece = piece.toNonIndexed(); // drops the vertices this group misses
+ } else {
+ piece = new THREE.BufferGeometry();
+ for (const name of Object.keys(geo.attributes)) {
+ const a = geo.attributes[name];
+ piece.setAttribute(name, new THREE.BufferAttribute(
+ a.array.slice(start * a.itemSize, (start + count) * a.itemSize),
+ a.itemSize, a.normalized));
+ }
+ }
+ out.push({ material, geometry: piece });
+ }
+ return out.length ? out : [{ material: mats[0], geometry: geo.clone() }];
+}
+
+/**
+ * Merge one material's geometries into as few draws as possible.
+ *
+ * `mergeGeometries` returns NULL — silently — when the inputs disagree on
+ * their attribute set or on being indexed, and the old code dropped that
+ * bucket: the asset rendered with a part MISSING and nothing said so.
+ * Harmonise what can be harmonised (a white `color` for the geometries
+ * that lack one, de-index the mixed case) and fall back to separate draws
+ * rather than to a hole.
+ * @private
+ */
+function mergeBucket(geos) {
+ if (geos.length <= 1) return geos;
+ let list = geos;
+ if (list.some((g) => g.index) && list.some((g) => !g.index)) {
+ list = list.map((g) => (g.index ? g.toNonIndexed() : g));
+ }
+ if (list.some((g) => g.attributes.color)) {
+ for (const g of list) {
+ if (g.attributes.color) continue;
+ const n = g.attributes.position.count;
+ g.setAttribute('color',
+ new THREE.BufferAttribute(new Float32Array(n * 3).fill(1), 3));
+ }
+ }
+ const merged = mergeGeometries(list, false);
+ return merged ? [merged] : list;
+}
+
+/**
+ * Fill a rectangle with placements on a jittered grid.
+ *
+ * A perfect lattice reads as wallpaper and an unconstrained random
+ * scatter clumps and overlaps; a jittered grid is the middle that reads
+ * as a city block or an orchard. Deterministic: pass your seeded PRNG.
+ *
+ * Every copy also gets its OWN albedo. One prototype means one colour,
+ * and a field of thirty identical greens or thirty identical roof reds
+ * is the flat "high repetition of identical towers" read however much
+ * the silhouettes vary — no orchard has two leaves the same hue. `tint`
+ * is a per-copy LINEAR multiplier averaging 0.96, so the field keeps the
+ * albedo the asset was authored with and mostly gains SPREAD: pass a
+ * number to scale the default strength, `{ chroma, value }` to set the
+ * hue swing and the light/dark swing apart, or `false` for the old flat
+ * field (a copy that must match a stated brand colour exactly).
+ *
+ * @param {object} area `{x, z, w, d}` — centre and extents in metres.
+ * @param {number} spacing Nominal metres between copies.
+ * @param {() => number} rand Seeded PRNG returning [0, 1).
+ * @param {object} [opts] `jitter` (0-1, default 0.35) fraction of
+ * spacing to offset by; `yaw` true (default) for random Y rotation,
+ * false for none, or a NUMBER of radians to snap to — `Math.PI / 2`
+ * is the built fabric that faces its street instead of spinning
+ * freely, with `yawJitter` (default 0.035 rad) of hand-placed slop
+ * on top; `scaleVar` (default 0.12) uniform scale spread;
+ * `heightVar`/`widthVar` (default 0) per-instance NON-uniform
+ * stretch — a city fabric wants heightVar 0.4-0.7 so the block is
+ * not one model repeated; `clearance` metres of centre-to-centre
+ * room every copy is given (jitter plus scaleVar routinely lands two
+ * copies inside each other, and two coincident roofs z-fight);
+ * `tint` per-copy albedo variation (see below); `height` a
+ * function (x, z) => y for the ground under each copy; `skip` a
+ * predicate (x, z) => boolean to leave gaps (streets, water, parks).
+ * @returns {Array<object>} Placements for `instanceAsset`.
+ */
+export function scatterGrid(area, spacing, rand, opts = {}) {
+ const jitter = opts.jitter ?? 0.35;
+ const scaleVar = opts.scaleVar ?? 0.12;
+ // Per-instance SHAPE variation, not just yaw: cheap repetition is
+ // not density. heightVar/widthVar stretch each copy independently,
+ // free through the per-instance matrix.
+ const heightVar = opts.heightVar ?? 0;
+ const widthVar = opts.widthVar ?? 0;
+ const tint = tintAmount(opts.tint);
+ const clearance = Math.max(0, opts.clearance ?? 0);
+ const yawStep = typeof opts.yaw === 'number' ? Math.abs(opts.yaw) : 0;
+ const yawSlots = yawStep > 0
+ ? Math.max(1, Math.round((Math.PI * 2) / yawStep)) : 0;
+ const yawSlop = opts.yawJitter ?? 0.035;
+ const kept = clearance > 0 ? new Map() : null;
+ const out = [];
+ const nx = Math.max(1, Math.round(area.w / spacing));
+ const nz = Math.max(1, Math.round(area.d / spacing));
+ for (let ix = 0; ix < nx; ix++) {
+ for (let iz = 0; iz < nz; iz++) {
+ const x = area.x - area.w / 2 + (ix + 0.5) * (area.w / nx)
+ + (rand() - 0.5) * spacing * jitter;
+ const z = area.z - area.d / 2 + (iz + 0.5) * (area.d / nz)
+ + (rand() - 0.5) * spacing * jitter;
+ if (opts.skip && opts.skip(x, z)) continue;
+ if (kept && crowded(kept, x, z, clearance)) continue;
+ const base = 1 + (rand() - 0.5) * 2 * scaleVar;
+ const scale = (heightVar || widthVar)
+ ? [base * (1 + (rand() - 0.5) * 2 * widthVar),
+ base * (1 + (rand() - 0.5) * 2 * heightVar),
+ base * (1 + (rand() - 0.5) * 2 * widthVar)]
+ : base;
+ let rotationY = 0;
+ if (opts.yaw !== false) {
+ rotationY = yawSlots
+ ? Math.floor(rand() * yawSlots) * yawStep
+ + (rand() - 0.5) * 2 * yawSlop
+ : rand() * Math.PI * 2;
+ }
+ const p = {
+ position: [x, opts.height ? opts.height(x, z) : 0, z],
+ rotationY,
+ scale,
+ };
+ if (tint) p.color = tintOf(rand, tint);
+ out.push(p);
+ if (kept) remember(kept, x, z, clearance);
+ }
+ }
+ return out;
+}
+
+// Default per-copy albedo spread, set against the crown measurement the
+// canopy work landed on — 9.4 degrees of hue across one tree, where a
+// photograph carries 25-45. Measured over 400 copies of the showcase
+// assets, this pair gives a 5-95 hue spread of 5.3 deg on the terracotta
+// roof, 13.8 on the leaf green and 28.6 on the near-neutral plaster
+// (whose hue is the least stable and moves furthest for the least
+// perceived change), with a 5-95 lightness spread of 0.072 / 0.058 /
+// 0.114. The roof moves least in HUE because terracotta already sits on
+// the warm axis the swing runs along — there it spends itself on
+// saturation and value instead, which is what a batch of tiles does.
+// Half of this measured 2.7 / 6.9 / 12.3 and the widest pixel gap
+// between a tinted field and a flat one was 10/255: real, and invisible.
+const TINT = { chroma: 0.22, value: 0.22 };
+
+// The value swing is wider DOWNWARD (x0.6 up, x1.2 down). A copy that
+// has stood in weather is darker than the reference far more often than
+// brighter, and the up-swing has a ceiling the down-swing does not: an
+// albedo authored near the top of the 0.02-0.8 band has no room to be
+// multiplied, and a surface pushed past it has no shading left in it.
+const VALUE_UP = 0.6, VALUE_DOWN = 1.2;
+
+// How much of the chroma swing goes ACROSS the warm-cool axis (the
+// green-magenta one). Well under half: see tintOf.
+const ACROSS = 0.45;
+
+/** Normalise the `tint` option to amounts, or null for none. @private */
+function tintAmount(spec) {
+ if (spec === false || spec === 0 || spec === null) return null;
+ if (spec === undefined || spec === true) return TINT;
+ if (typeof spec === 'number') {
+ return { chroma: TINT.chroma * spec, value: TINT.value * spec };
+ }
+ return { chroma: spec.chroma ?? TINT.chroma, value: spec.value ?? TINT.value };
+}
+
+/**
+ * One copy's albedo multiplier, in LINEAR space and centred on white.
+ *
+ * The hue part is an offset in the plane PERPENDICULAR to the grey axis
+ * — the only directions that change hue without changing brightness —
+ * drawn over an ELLIPSE, not a disc: 1.0 along warm-cool (red up, blue
+ * down) and 0.45 across it. A disc spreads a near-neutral copy in any
+ * direction at all, and a violet wall beside an olive one reads as a
+ * bug; the same spread laid on the temperature axis reads as different
+ * limewash under the same sun, which is what the eye expects of a row of
+ * houses. `value` then scales the whole triple, so the field is moved
+ * APART rather than lifted or dimmed (its mean lands at 0.96 of the
+ * authored albedo, the weathering skew).
+ *
+ * It is a MULTIPLIER and not a hue rotation on purpose: a rotation about
+ * the grey axis drives the small channels of a near-primary negative and
+ * the clamp then forks one swing into two lobes — the failure the flower
+ * field was measured splitting into an amber half and a magenta half. A
+ * positive multiplier cannot leave the hue's own quadrant.
+ * @private
+ */
+function tintOf(rand, amt) {
+ const a = rand() * Math.PI * 2;
+ const m = amt.chroma * Math.sqrt(rand());
+ const r = (rand() - 0.5) * 2;
+ const v = 1 + amt.value * r * (r < 0 ? VALUE_DOWN : VALUE_UP);
+ const warm = Math.cos(a) * m, cast = Math.sin(a) * m * ACROSS;
+ // A guard, not a shaper: the defaults' corner is 1.31 and 1600 copies
+ // measured a widest channel of 1.29.
+ const clamp = (c) => Math.min(1.35, Math.max(0.5, c));
+ return [
+ clamp(v * (1 + 0.70711 * warm - 0.40825 * cast)),
+ clamp(v * (1 + 0.81650 * cast)),
+ clamp(v * (1 - 0.70711 * warm - 0.40825 * cast)),
+ ];
+}
+
+// Kept centres in a hash grid of `clearance`-sized cells: the 3x3
+// neighbourhood holds every copy close enough to matter, so the test
+// stays O(1) per candidate instead of O(n) against the whole field.
+const cellKey = (i, j) => `${i},${j}`;
+
+/** @private */
+function crowded(kept, x, z, cell) {
+ const i = Math.floor(x / cell), j = Math.floor(z / cell);
+ const r2 = cell * cell;
+ for (let di = -1; di <= 1; di++) {
+ for (let dj = -1; dj <= 1; dj++) {
+ const a = kept.get(cellKey(i + di, j + dj));
+ if (!a) continue;
+ for (let n = 0; n < a.length; n += 2) {
+ const dx = a[n] - x, dz = a[n + 1] - z;
+ if (dx * dx + dz * dz < r2) return true;
+ }
+ }
+ }
+ return false;
+}
+
+/** @private */
+function remember(kept, x, z, cell) {
+ const k = cellKey(Math.floor(x / cell), Math.floor(z / cell));
+ const a = kept.get(k);
+ if (a) a.push(x, z);
+ else kept.set(k, [x, z]);
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.js
new file mode 100644
index 00000000..2d7a7c5e
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/lights.js
@@ -0,0 +1,287 @@
+/**
+ * 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/materials.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/materials.js
new file mode 100644
index 00000000..4007b09c
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/materials.js
@@ -0,0 +1,393 @@
+/**
+ * Shared material library: every factory returns a MeshStandardMaterial
+ * with procedural value-noise map + roughnessMap + bumpMap and a seeded
+ * variant knob (flat albedo is the strongest "plastic toy" tell).
+ * Deterministic, DOM-free (DataTexture), imports only three.
+ */
+
+import * as THREE from 'three';
+
+// ---------------------------------------------------------------- noise
+
+function hash2(x, y, seed) {
+ let h = Math.sin(x * 127.1 + y * 311.7 + seed * 74.7) * 43758.5453;
+ return h - Math.floor(h);
+}
+
+// PERIODIC value noise: the lattice indices wrap at (px, py) cells, so a
+// texture sampled over exactly px x py cells is seamless when tiled. An
+// unwrapped lattice is the source of the hard grid lines every repeated
+// surface in this library carried — measured on a 120 m ground at
+// repeat 10, where the 12 m seams read as paving joints in the dirt.
+function valueNoise(x, y, px, py, seed) {
+ const xi = Math.floor(x), yi = Math.floor(y);
+ const xf = x - xi, yf = y - yi;
+ const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
+ const wx = ((xi % px) + px) % px, wx1 = ((xi + 1) % px + px) % px;
+ const wy = ((yi % py) + py) % py, wy1 = ((yi + 1) % py + py) % py;
+ const a = hash2(wx, wy, seed), b = hash2(wx1, wy, seed);
+ const c = hash2(wx, wy1, seed), d = hash2(wx1, wy1, seed);
+ return (a * (1 - u) + b * u) * (1 - v) + (c * (1 - u) + d * u) * v;
+}
+
+// Lacunarity is 2, not 2.03: a wrapped lattice needs every octave's
+// period to divide the texture, and the octaves cannot line up into a
+// grid here anyway because each carries its own hash seed.
+function fbm(x, y, px, py, seed, octaves = 4) {
+ let v = 0, amp = 0.5, f = 1;
+ for (let i = 0; i < octaves; i++) {
+ v += amp * valueNoise(x * f, y * f, px * f, py * f, seed + i * 17);
+ f *= 2;
+ amp *= 0.5;
+ }
+ return v;
+}
+
+/** Cells per texture on an axis: at least 1, and a whole number so it wraps. */
+const cells = (n) => Math.max(1, Math.round(n));
+
+const _texCache = new Map();
+
+/**
+ * Grayscale/tinted noise DataTexture, cached by its parameters.
+ * @param {object} o size, scale, seed, contrast, tint [r,g,b], base
+ * @returns {THREE.DataTexture}
+ */
+export function noiseTexture(o = {}) {
+ const size = o.size || 256;
+ const scale = o.scale || 8;
+ const seed = o.seed === undefined ? 1 : o.seed;
+ const contrast = o.contrast === undefined ? 0.35 : o.contrast;
+ const base = o.base === undefined ? 1 : o.base;
+ const tint = o.tint || [1, 1, 1];
+ const streak = o.streak || 0; // 0 = isotropic, 1 = wood-like
+ // A colour map multiplies the authored colour, so a HUE break here
+ // reaches every material at once. Value noise alone is what the
+ // palette probe names "one flat hue per surface": stone, plaster and
+ // sand all shipped as one albedo shaded by luminance.
+ const hueBreak = o.hueBreak || 0;
+ const key = [size, scale, seed, contrast, base, streak,
+ o.linear ? 1 : 0, hueBreak, ...tint].join(':');
+ if (_texCache.has(key)) return _texCache.get(key);
+ // A colour map MULTIPLIES the authored colour, so the field has to
+ // average 0.5 or the delivered colour is not the one the asset asked
+ // for — an un-normalised fBm mean wanders with the seed (measured: a
+ // conifer green shipped 20% bright on one seed and dark on another).
+ // Whole cell counts per axis; every sub-octave below spans a whole
+ // count too, or the wrap leaks a seam back in.
+ const pu = cells(scale);
+ const pv = cells(scale * (streak ? 0.12 + 0.88 * (1 - streak) : 1));
+ const su = cells(pu * 0.4); // the streak's slow cross-grain
+ const field = new Float32Array(size * size);
+ let sum = 0;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const fx = x / size, fy = y / size;
+ let n = fbm(fx * pu, fy * pv, pu, pv, seed);
+ if (streak) {
+ n = 0.65 * n + 0.35 * fbm(fx * su, fy * pv * 6, su, pv * 6, seed + 91, 3);
+ }
+ field[y * size + x] = n;
+ sum += n;
+ }
+ }
+ const shift = 0.5 - sum / (size * size);
+ // The hue field is its OWN pattern at its own scale — tied to the
+ // value field it would only make the light patches warm, which is
+ // shading, not broken colour. Centred on its measured mean so the
+ // delivered colour is still the one the asset asked for.
+ let hueF = null;
+ if (hueBreak > 0) {
+ hueF = new Float32Array(size * size);
+ const hu = cells(pu * 0.45), hv = cells(pv * 0.45);
+ let hs = 0;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const n = fbm((x / size) * hu, (y / size) * hv, hu, hv, seed + 613);
+ hueF[y * size + x] = n;
+ hs += n;
+ }
+ }
+ const hm = hs / (size * size);
+ for (let i = 0; i < hueF.length; i++) hueF[i] -= hm;
+ }
+ const data = new Uint8Array(size * size * 4);
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const n = field[y * size + x] + shift;
+ const lum = Math.max(0, Math.min(1, base * (1 - contrast / 2 + contrast * n)));
+ const i = (y * size + x) * 4;
+ // Warm/cool along the blue-orange axis, which is the swing
+ // daylight itself makes: sun-warm where the light lands, sky-cool
+ // where it does not. A rotation about the grey axis would return
+ // white unchanged, so the tint is a bias, not a rotation.
+ const h = hueF ? hueF[y * size + x] * hueBreak * 2 : 0;
+ // CLAMPED, because a Uint8Array assignment takes the value mod
+ // 256: `lum` alone can never exceed 1, so nothing here needed a
+ // clamp until the hue term multiplied past it — and a texel that
+ // wrapped came back as a near-black speck, which read as the
+ // material getting DARKER and less colourful, the exact opposite
+ // of the change (measured: a cathedral lost 17% of its chroma).
+ const px = (v) => Math.max(0, Math.min(255, Math.round(v)));
+ data[i] = px(255 * lum * tint[0] * (1 + h));
+ data[i + 1] = px(255 * lum * tint[1] * (1 + h * 0.15));
+ data[i + 2] = px(255 * lum * tint[2] * (1 - h));
+ data[i + 3] = 255;
+ }
+ }
+ const tex = new THREE.DataTexture(data, size, size);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.colorSpace = o.linear ? THREE.NoColorSpace : THREE.SRGBColorSpace;
+ tex.needsUpdate = true;
+ _texCache.set(key, tex);
+ return tex;
+}
+
+// ------------------------------------------------------------ factories
+
+function shade(hex, k) {
+ const c = new THREE.Color(hex);
+ // Spread is a RATIO of the colour's own lightness, never a fixed
+ // subtraction: dark colours have tiny linear-space lightness, and a
+ // fixed step clamped them to BLACK — an albedo that cannot be lit.
+ const hsl = c.getHSL({ h: 0, s: 0, l: 0 });
+ c.setHSL(hsl.h, hsl.s, Math.max(hsl.l * 0.5, hsl.l + k));
+ return c;
+}
+
+// ONE MATERIAL PER DISTINCT LOOK, not per call. A city fabric asking for
+// a fresh material per building measured 2,552 of them in one scene, each
+// its own state change and its own 256 px texture pair (1,309 textures,
+// 436 MB). Variant is quantised first: nobody can tell 2,552 shades apart
+// across a +-4% lightness spread, and the buckets collapse textures too.
+const _matCache = new Map();
+const _tintCache = new Map();
+// ODD count on purpose: variant 0.5 means THE COLOUR THE AUTHOR
+// WROTE, and an even bucket count has no midpoint to land on.
+const _VARIANT_STEPS = 9;
+// Seed only picks WHICH noise pattern, not what the surface looks like.
+// Assets hand a fresh seed per copy, so an unbucketed seed gave every
+// one of 770 trees its own material and its own texture pair.
+const _SEED_BUCKETS = 6;
+
+function _quantise(v) {
+ const c = Math.min(1, Math.max(0, v));
+ return Math.round(c * (_VARIANT_STEPS - 1)) / (_VARIANT_STEPS - 1);
+}
+
+function _seedBucket(s) {
+ return Math.abs(Math.round(s === undefined ? 3 : s)) % _SEED_BUCKETS;
+}
+
+/** Cache key for a RESOLVED option set, or null when uncacheable. */
+function _matKey(o, variant) {
+ if (o.unique) return null;
+ try {
+ const rest = Object.assign({}, o);
+ delete rest.variant;
+ delete rest.unique;
+ rest.seed = _seedBucket(o.seed);
+ return JSON.stringify([rest, variant], (k, v) =>
+ (v && v.isColor ? v.getHex() : v));
+ } catch (err) {
+ return null;
+ }
+}
+
+/**
+ * Build a textured MeshStandardMaterial.
+ *
+ * Identical options return the SAME material instance; pass
+ * `unique: true` when a caller means to mutate its own copy.
+ *
+ * @param {object} o color, roughness, metalness, scale, seed, variant,
+ * repeat, streak, contrast, bump, tintNoise, extra, unique
+ * @returns {THREE.MeshStandardMaterial}
+ */
+function make(o) {
+ // Unspecified variant = THE COLOUR THE AUTHOR WROTE (0.5, the
+ // midpoint); defaulting to 0 handed every caller the dark extreme.
+ const variant = _quantise(o.variant === undefined ? 0.5 : o.variant);
+ const key = _matKey(o, variant);
+ if (key !== null && _matCache.has(key)) return _matCache.get(key);
+ const seed = _seedBucket(o.seed) + Math.round(variant * 97);
+ const col = shade(o.color, (variant - 0.5) * (o.spread === undefined ? 0.08 : o.spread));
+ const map = noiseTexture({
+ scale: o.scale || 6, seed, contrast: o.contrast === undefined ? 0.3 : o.contrast,
+ streak: o.streak || 0, size: 256,
+ // Mineral surfaces carry the most hue break (a granite face is
+ // pink, grey and near-black at arm's length); paint and metal the
+ // least, because a factory finish really is one colour.
+ hueBreak: o.hueBreak === undefined ? 0.12 : o.hueBreak,
+ });
+ const rough = noiseTexture({
+ scale: (o.scale || 6) * 1.7, seed: seed + 41,
+ contrast: 0.5, base: 1, streak: o.streak || 0, linear: true, size: 256,
+ });
+ const rep = o.repeat || 1;
+ const m = new THREE.MeshStandardMaterial(Object.assign({
+ color: col,
+ map,
+ roughnessMap: rough,
+ bumpMap: o.bump === 0 ? null : map,
+ bumpScale: o.bump === undefined ? 0.015 : o.bump,
+ roughness: o.roughness,
+ metalness: o.metalness === undefined ? 0 : o.metalness,
+ }, o.extra || {}));
+ if (rep !== 1) {
+ m.map = map.clone();
+ m.map.repeat.set(rep, rep);
+ m.map.needsUpdate = true;
+ m.roughnessMap = rough.clone();
+ m.roughnessMap.repeat.set(rep, rep);
+ m.roughnessMap.needsUpdate = true;
+ m.bumpMap = m.map;
+ }
+ if (key !== null) {
+ m.userData.shared = true;
+ _matCache.set(key, m);
+ }
+ return m;
+}
+
+export const plaster = (o = {}) => make(Object.assign(
+ { color: 0xeae0d0, roughness: 0.85, scale: 5, contrast: 0.22, bump: 0.01 }, o));
+export const brick = (o = {}) => make(Object.assign(
+ { color: 0x9c4a35, roughness: 0.9, scale: 14, contrast: 0.4, bump: 0.03 }, o));
+export const travertine = (o = {}) => make(Object.assign(
+ { color: 0xd9cdb4, roughness: 0.7, scale: 4, contrast: 0.3, streak: 0.4 }, o));
+export const granite = (o = {}) => make(Object.assign(
+ { color: 0x8d8b88, roughness: 0.6, scale: 22, contrast: 0.45,
+ hueBreak: 0.16 }, o));
+export const cobble = (o = {}) => make(Object.assign(
+ { color: 0x6f6a63, roughness: 0.88, scale: 26, contrast: 0.5, bump: 0.05,
+ hueBreak: 0.16 }, o));
+export const asphalt = (o = {}) => make(Object.assign(
+ { color: 0x2f3134, roughness: 0.82, scale: 30, contrast: 0.25 }, o));
+export const terracotta = (o = {}) => make(Object.assign(
+ { color: 0xb2593a, roughness: 0.78, scale: 10, contrast: 0.32 }, o));
+export const weatheredWood = (o = {}) => make(Object.assign(
+ { color: 0x7a5a3c, roughness: 0.92, scale: 8, contrast: 0.4, streak: 0.9,
+ bump: 0.03 }, o));
+export const paintedWood = (o = {}) => make(Object.assign(
+ { color: 0xc8b18a, roughness: 0.6, scale: 7, contrast: 0.18, streak: 0.8,
+ hueBreak: 0.05 }, o));
+export const paintedIron = (o = {}) => make(Object.assign(
+ { color: 0x2d3a3f, roughness: 0.45, metalness: 0.35, scale: 9,
+ contrast: 0.16, hueBreak: 0.04 }, o));
+export const brushedSteel = (o = {}) => make(Object.assign(
+ { color: 0xb9bfc4, roughness: 0.35, metalness: 0.85, scale: 18,
+ contrast: 0.12, streak: 0.95, bump: 0.004, hueBreak: 0.03 }, o));
+export const giltBronze = (o = {}) => make(Object.assign(
+ { color: 0xb08a3a, roughness: 0.32, metalness: 0.9, scale: 12,
+ contrast: 0.2 }, o));
+export const fabric = (o = {}) => make(Object.assign(
+ { color: 0xb04b46, roughness: 0.95, scale: 40, contrast: 0.22,
+ bump: 0.008 }, o));
+export const foliage = (o = {}) => make(Object.assign(
+ { color: 0x3f6b32, roughness: 0.8, scale: 16, contrast: 0.35,
+ hueBreak: 0.20, extra: { flatShading: false } }, o));
+export const soil = (o = {}) => make(Object.assign(
+ { color: 0x6a5540, roughness: 0.95, scale: 20, contrast: 0.4, bump: 0.04,
+ hueBreak: 0.18 }, o));
+export const skin = (o = {}) => make(Object.assign(
+ { color: 0xd9a17c, roughness: 0.68, scale: 30, contrast: 0.08, bump: 0,
+ hueBreak: 0.06 }, o));
+
+/**
+ * Water: low roughness + metalness so the scene environment carries the
+ * reflection, with a scrolling normal-ish bump for surface break-up.
+ * @param {object} o color, roughness, scale, variant
+ * @returns {THREE.MeshStandardMaterial}
+ */
+export const water = (o = {}) => {
+ // Water is a DIELECTRIC: metalness stays 0 and the ior-1.333 fresnel
+ // ramp produces the reflection. Any metalness makes a uniformly
+ // tinted mirror at every angle — the "dirty chrome puddle" look.
+ const base = make(Object.assign(
+ { color: 0x14414f, roughness: 0.06, metalness: 0, scale: 12,
+ contrast: 0.1, bump: 0.02 }, o));
+ const m = new THREE.MeshPhysicalMaterial({
+ color: base.color,
+ map: base.map,
+ roughnessMap: base.roughnessMap,
+ bumpMap: base.bumpMap,
+ bumpScale: base.bumpScale,
+ roughness: o.roughness === undefined ? 0.06 : o.roughness,
+ metalness: 0,
+ ior: o.ior === undefined ? 1.333 : o.ior,
+ // Deep water is not see-through at scene scale; the darkness IS the
+ // depth. Shallows pass `opacity` down to let the bed read through.
+ transparent: o.opacity !== undefined,
+ opacity: o.opacity === undefined ? 1 : o.opacity,
+ });
+ return Object.assign(m, o.extra || {});
+};
+
+/**
+ * Glass: needs a real scene.environment to read as glass.
+ * @param {object} o color, opacity
+ * @returns {THREE.MeshStandardMaterial}
+ */
+export const glass = (o = {}) => new THREE.MeshPhysicalMaterial(
+ Object.assign({
+ color: o.color === undefined ? 0xbfd6de : o.color,
+ roughness: 0.05,
+ // Dielectric like water: the ior-1.5 fresnel ramp mirrors sky on
+ // grazing faces while camera-facing glass stays readable.
+ metalness: 0,
+ ior: 1.5,
+ transparent: true,
+ opacity: o.opacity === undefined ? 0.35 : o.opacity,
+ envMapIntensity: 1.6,
+ }, o.extra || {}));
+
+/**
+ * Darken and roughen a material to read as weathered/dirty.
+ * @param {THREE.Material} mat material to age IN PLACE
+ * @param {number} amount 0..1
+ * @returns {THREE.Material} the same material
+ */
+export function weather(mat, amount = 0.35) {
+ if (!mat) return mat;
+ // A cached material is shared by every caller that asked for the same
+ // look, so ageing in place would age the whole city. Copy first.
+ const m = mat.userData && mat.userData.shared ? mat.clone() : mat;
+ if (m !== mat) m.userData = {};
+ // Ratio, never a fixed step: getHSL works in LINEAR space, where a
+ // dark colour's lightness is tiny — offsetHSL drove asphalt to pure
+ // black, an albedo nothing can light. Same fix `shade()` already has.
+ if (m.color) {
+ const hsl = m.color.getHSL({ h: 0, s: 0, l: 0 });
+ m.color.setHSL(hsl.h, hsl.s * (1 - 0.28 * amount),
+ hsl.l * (1 - 0.45 * amount));
+ }
+ if (typeof m.roughness === 'number') {
+ m.roughness = Math.min(1, m.roughness + 0.18 * amount);
+ }
+ if (typeof m.bumpScale === 'number') m.bumpScale *= 1 + amount;
+ return m;
+}
+
+/**
+ * Per-instance colour jitter: clone the material and shift hue/lightness
+ * so copies of one asset stop reading as duplicated geometry.
+ * @param {THREE.Material} mat template material (not mutated)
+ * @param {number} variant 0..1
+ * @returns {THREE.Material} the tinted clone
+ */
+export function tint(mat, variant = 0.5) {
+ const v = _quantise(variant);
+ const key = mat.uuid + ':' + v;
+ const hit = _tintCache.get(key);
+ if (hit) return hit;
+ const m = mat.clone();
+ m.userData = { shared: true };
+ if (m.color) {
+ m.color.offsetHSL((v - 0.5) * 0.04, 0, 0);
+ const hsl = m.color.getHSL({ h: 0, s: 0, l: 0 });
+ m.color.setHSL(hsl.h, hsl.s, hsl.l * (1 + (v - 0.5) * 0.5));
+ }
+ _tintCache.set(key, m);
+ return m;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/merge.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/merge.js
new file mode 100644
index 00000000..8f5495f1
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/merge.js
@@ -0,0 +1,236 @@
+/**
+ * Draw-call collapse for static props: many positioned meshes in, ONE
+ * mesh out. Software GL is DRAW-CALL-bound, making this the biggest
+ * SwiftShader perf lever (scene contract: <150 draw calls). Never
+ * merge anything tick() animates or a fix round must retarget alone.
+ *
+ * The merge is also where a batch stops looking like a batch: 40 stones
+ * cut from one material arrive as ONE albedo, and a wall of one albedo
+ * reads as an extruded solid, not as stone. `variance` (on by default)
+ * gives every piece its own small value/warmth offset, keyed to where
+ * the piece SITS, so the collapse costs the wall nothing in hue spread.
+ */
+
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+import { patchStandard } from './shader.js';
+
+const _KEEP = ['position', 'normal', 'uv', 'color'];
+const _WHITE = new THREE.Color(1, 1, 1);
+const _C = new THREE.Vector3();
+
+// Surface response carried over from the batch's first material. `color`
+// is deliberately absent — it becomes vertex colour. Everything else here
+// is what makes the merged mesh shade the way its pieces did; dropping
+// `emissive` renders merged lanterns as dead grey boxes, and dropping
+// `side` deletes every back-facing card in a DoubleSide batch.
+const _SCALARS = [
+ 'roughness', 'metalness', 'emissiveIntensity', 'envMapIntensity',
+ 'opacity', 'transparent', 'alphaTest', 'depthWrite', 'side', 'shadowSide',
+ 'flatShading', 'toneMapped', 'dithering', 'fog', 'aoMapIntensity',
+ 'bumpScale', 'displacementScale', 'displacementBias',
+];
+const _MAPS = [
+ 'map', 'roughnessMap', 'metalnessMap', 'normalMap', 'bumpMap', 'aoMap',
+ 'alphaMap', 'emissiveMap', 'lightMap', 'displacementMap',
+];
+
+/** Stable per-piece hash in [0,1) from a world position. */
+function _hash(x, y, z, k) {
+ const s = Math.sin(x * 127.1 + y * 311.7 + z * 74.7 + k * 37.3) * 43758.5453;
+ return s - Math.floor(s);
+}
+
+/**
+ * Reverse triangle winding in place (index triples, or the vertex runs of
+ * a non-indexed geometry). A mirrored placement — `scale.x = -1`, how a
+ * matching pair gets made — has a negative-determinant world matrix, and
+ * baking that flips which side of every triangle faces out. The piece then
+ * renders as its own interior: front faces culled, the back ones lit from
+ * behind. Un-baked it never showed, because three flips winding per draw
+ * from the matrix it can still see; after the bake there is no matrix left.
+ */
+function _flipWinding(g) {
+ if (g.index) {
+ const a = g.index.array;
+ for (let i = 0; i + 2 < a.length; i += 3) {
+ const t = a[i + 1]; a[i + 1] = a[i + 2]; a[i + 2] = t;
+ }
+ g.index.needsUpdate = true;
+ return;
+ }
+ for (const name of Object.keys(g.attributes)) {
+ const at = g.attributes[name];
+ const n = at.itemSize;
+ const arr = at.array;
+ for (let i = 0; i + 2 < at.count; i += 3) {
+ for (let k = 0; k < n; k++) {
+ const p = (i + 1) * n + k;
+ const q = (i + 2) * n + k;
+ const t = arr[p]; arr[p] = arr[q]; arr[q] = t;
+ }
+ }
+ at.needsUpdate = true;
+ }
+}
+
+/** What one material contributes to the shared surface response. */
+function _sig(m) {
+ if (!m) return '';
+ return [m.type, m.side, m.transparent === true, m.flatShading === true,
+ m.roughness, m.metalness, m.emissive ? m.emissive.getHexString() : '',
+ m.emissiveIntensity, m.map ? m.map.uuid : ''].join('|');
+}
+
+/**
+ * Merge positioned static meshes into one vertex-coloured Mesh.
+ * World matrices and material colours are baked in; pieces may differ
+ * ONLY by colour — the FIRST mesh's material supplies the shared
+ * surface response (and a batch that disagrees about it says so in the
+ * console, rather than losing half its look silently). A merge that
+ * fails throws rather than shipping a partial scene.
+ *
+ * Invisible pieces are skipped: `visible = false` is how a scene hides
+ * an LOD stand-in, and baking one in would make it permanent.
+ *
+ * @param {Array<THREE.Object3D>} meshes Positioned meshes (or groups
+ * of meshes) to consume. Add the RETURNED mesh to the scene instead
+ * of these.
+ * @param {object} opts
+ * `variance` (default 0.12, 0 disables) per-piece albedo spread: each
+ * piece's baked colour is nudged in value by ±variance and in warm/cool
+ * by ±0.6·variance, from a hash of where the piece sits — so the offset
+ * is stable across runs, independent of input order, and two pieces of
+ * one material stop being the same flat swatch. Set 0 when the baked
+ * colours are data (colour-coded parts, a legend, a gradient you built).
+ * @returns {THREE.Mesh} One shadow-casting mesh named 'MergedStatic'
+ * — one draw call. Rename it to the zone it forms.
+ * @throws {Error} When the input holds no mesh or the geometries
+ * cannot merge.
+ */
+export function mergeStatic(meshes, opts = {}) {
+ const { variance = 0.12 } = opts;
+ if (!meshes || meshes.length === 0) {
+ throw new Error('mergeStatic: got an empty input array');
+ }
+
+ // Collect leaf meshes with world matrices up to date (parents too:
+ // a group's own transform must reach its children's bakes).
+ const found = [];
+ for (const root of meshes) {
+ root.updateWorldMatrix(true, true);
+ root.traverse((n) => {
+ if (!n.isMesh || n.isInstancedMesh || !n.geometry) return;
+ if (!n.geometry.attributes || !n.geometry.attributes.position) return;
+ for (let p = n; p; p = p.parent) {
+ if (!p.visible) return;
+ if (p === root) break;
+ }
+ found.push(n);
+ });
+ }
+ if (found.length === 0) {
+ throw new Error('mergeStatic: no meshes found in the input');
+ }
+
+ // mergeGeometries refuses to mix indexed and non-indexed inputs; if
+ // both appear, expand the indexed ones.
+ const mixed = found.some((m) => m.geometry.index === null);
+
+ const geos = [];
+ let firstMat = null;
+ let odd = 0;
+ for (const mesh of found) {
+ let g = mesh.geometry.clone();
+ if (mixed && g.index) g = g.toNonIndexed();
+ g.applyMatrix4(mesh.matrixWorld); // bake pos + rot + scale
+ // applyMatrix4 carries normals through the normal matrix, which is
+ // right even under a mirror — but the winding is not.
+ if (mesh.matrixWorld.determinant() < 0) _flipWinding(g);
+ g.morphAttributes = {};
+ for (const name of Object.keys(g.attributes)) {
+ if (!_KEEP.includes(name)) g.deleteAttribute(name);
+ }
+ if (!g.attributes.normal) g.computeVertexNormals();
+ const count = g.attributes.position.count;
+ if (!g.attributes.uv) {
+ g.setAttribute(
+ 'uv', new THREE.BufferAttribute(new Float32Array(count * 2), 2));
+ }
+ const mat = Array.isArray(mesh.material)
+ ? mesh.material[0] : mesh.material;
+ if (!firstMat && mat) firstMat = mat;
+ else if (_sig(mat) !== _sig(firstMat)) odd++;
+ // The piece's material colour becomes vertex colour, modulating
+ // any colours the geometry already carries (strata bands etc.).
+ const tint = mat && mat.color ? mat.color : _WHITE;
+ const old = g.attributes.color;
+ // Per-piece spread, hashed from where the piece ended up: same seed
+ // every run, unchanged if the caller reorders the batch, and different
+ // for two copies of one prop standing apart.
+ let val = 1;
+ let warm = 0;
+ if (variance > 0) {
+ g.computeBoundingBox();
+ g.boundingBox.getCenter(_C);
+ val = 1 + (_hash(_C.x, _C.y, _C.z, 1) - 0.5) * 2 * variance;
+ warm = (_hash(_C.x, _C.y, _C.z, 7) - 0.5) * 1.2 * variance;
+ }
+ const rgb = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ rgb[i * 3] = Math.min(
+ 1, tint.r * (old ? old.getX(i) : 1) * val * (1 + warm));
+ rgb[i * 3 + 1] = Math.min(1, tint.g * (old ? old.getY(i) : 1) * val);
+ rgb[i * 3 + 2] = Math.min(
+ 1, tint.b * (old ? old.getZ(i) : 1) * val * (1 - warm));
+ }
+ g.setAttribute('color', new THREE.BufferAttribute(rgb, 3));
+ geos.push(g);
+ }
+
+ const merged = mergeGeometries(geos, false);
+ if (!merged) {
+ throw new Error(
+ 'mergeStatic: geometries would not merge (incompatible '
+ + 'attribute sets) — merge compatible pieces per batch');
+ }
+
+ // ONE material: colour lives per-vertex; surface response comes from
+ // the first piece (colour-only differences by contract).
+ const material = new THREE.MeshStandardMaterial({ vertexColors: true });
+ if (firstMat) {
+ for (const k of _SCALARS) {
+ if (firstMat[k] !== undefined) material[k] = firstMat[k];
+ }
+ for (const k of _MAPS) {
+ if (firstMat[k]) material[k] = firstMat[k];
+ }
+ if (firstMat.emissive) material.emissive.copy(firstMat.emissive);
+ if (firstMat.normalMap && firstMat.normalScale) {
+ material.normalScale.copy(firstMat.normalScale);
+ }
+ // A shader-patched material does not survive being rebuilt, and
+ // Material.clone() would not have saved it either (it copies
+ // userData but NOT onBeforeCompile — a dead chain holding a live
+ // cache key). Replay the chain instead, sharing the SOURCE uniform
+ // map so one tickShaders still advances both.
+ const patches = firstMat.userData && firstMat.userData.astraPatches;
+ if (patches && patches.length) {
+ material.userData.uniforms = firstMat.userData.uniforms;
+ for (const p of patches) patchStandard(material, p);
+ }
+ }
+ if (odd) {
+ console.warn(
+ `mergeStatic: ${odd} of ${found.length} pieces disagree with the `
+ + 'first material about the shared surface response (side, '
+ + 'emissive, roughness, map…) — those differences are LOST. '
+ + 'Merge one material family per batch; only colour may vary.');
+ }
+
+ const out = new THREE.Mesh(merged, material);
+ out.name = 'MergedStatic';
+ out.castShadow = true;
+ out.receiveShadow = true;
+ return out;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.js
new file mode 100644
index 00000000..e3f504cc
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/mirror.js
@@ -0,0 +1,597 @@
+/**
+ * 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.js
new file mode 100644
index 00000000..76f6acc9
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/neon.js
@@ -0,0 +1,800 @@
+/**
+ * Neon: the light a sign MAKES, not the sign itself.
+ *
+ * A night city assembled rather than lit fails in one specific way —
+ * bright signs on unlit walls. These three break that: a bent tube with
+ * a core hot enough to clip white and a halo that pools where the glass
+ * bends back past itself; the light that tube throws onto the brick
+ * behind it and the pavement below; and the head- and tail-light
+ * streaks along a road, the only motion a still frame can show.
+ *
+ * All three ADD light, because added light survives a DARK frame and
+ * clips over a bright one — and a night city is exactly the dark frame
+ * where adding is correct. Each factory still takes an `ambient` escape
+ * (0 an unlit street, 1 open daylight): from 0.35 up it stops adding
+ * and paints a pale, normal-blended tube instead, so the 0.5 a composer
+ * 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).
+ */
+
+import * as THREE from 'three';
+
+import {
+ keepOutOfDepthPasses, makeShaderMaterial, patchStandard, sweepProfile,
+ tickShaders } from './shader.js';
+
+const _UP = new THREE.Vector3(0, 1, 0);
+
+// How many spill sources one program carries. The array length is baked
+// into the GLSL and `patchStandard` gives every spill patch ONE cache
+// key, so it is a constant here and the live count is a uniform.
+const SPILL_MAX = 8;
+
+// A failing tube does not blink on a clock: it holds, drops out for a
+// frame or two, then buzzes at the mains while it strikes again.
+// Shared verbatim by the tube and the spill so one seed stutters both.
+const FLICK_GLSL = [
+ 'float astraNeonFlick(float t, float key, float amt) {',
+ ' if (amt <= 0.0) return 1.0;',
+ ' float s = astraHash11(floor(t * 14.0) * 1.13 + key);',
+ ' float dip = step(s, amt * 0.30);',
+ ' float buzz = 0.86 + 0.14 * sin(t * 96.0 + key);',
+ ' return mix(1.0, mix(buzz, 0.08 + 0.22 * s, dip), amt);',
+ '}',
+].join('\n');
+
+// HOW WHITE THE MIDDLE OF THE GLASS GOES, and it is not very white.
+// This renderer tone maps in the FRAGMENT TAIL with no post chain, so
+// additive layers sum in DISPLAY space: the near and far walls of a
+// double-sided shell plus the halo twice stack four deep on the middle
+// of a tube, and every channel a colour carries is multiplied by that
+// stack. Whitening the colour BEFORE it threw the gas away — measured,
+// a cyan sign rendered as a white strip light with a cyan edge. A tube
+// IS meant to clip, toward its OWN hue, which the stack does by itself
+// once the colour stays saturated. So: a fifth of the way to white dead
+// centre, gone two thirds out — a hot line in coloured glass.
+const FILAMENT_GLSL = [
+ 'float astraNeonFilament(float face, float hot) {',
+ ' return pow(face, 14.0) * hot * 0.22;',
+ '}',
+].join('\n');
+
+// One vehicle's colour temperature, as a signed offset off the lane's
+// own colour. Spent two ways at the call site because a lane's colour
+// can be anything: a hue rotation moves a saturated tail-light, a
+// warm/cool tilt is the only thing that moves a near-white head-light.
+const TEMP_GLSL = [
+ 'float astraTrailTemp(float id, float vary) {',
+ ' return (astraHash11(id * 5.71 + 1.9) - 0.5) * vary;',
+ '}',
+].join('\n');
+
+/** A seed becomes a far-apart hash offset, not a one-cell shift. */
+function seedKey(seed) {
+ const s = Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973;
+ return ((s * 16807) % 9973) * 0.011;
+}
+
+/** 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);
+}
+
+/** A point in any accepted spelling as its own Vector3. */
+function toVec(p) {
+ if (p && p.isVector3) return p.clone();
+ if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2]);
+ return new THREE.Vector3(p.x || 0, p.y || 0, p.z || 0);
+}
+
+/**
+ * One polyline or a set of them, always as an array of strokes.
+ *
+ * A sign is lettering as often as it is a single bent tube, and a
+ * caller holding one stroke per character should not have to wrap it.
+ */
+function toStrokes(path) {
+ if (!Array.isArray(path) || !path.length) return [];
+ const head = path[0];
+ const nested = Array.isArray(head)
+ && (Array.isArray(head[0]) || (head[0] && head[0].isVector3)
+ || (head[0] && typeof head[0] === 'object'));
+ const raw = nested ? path : [path];
+ return raw.map((s) => {
+ const out = [];
+ for (const p of s) {
+ const v = toVec(p);
+ // A repeated point is a zero-length segment, and a
+ // zero-length segment has no tangent to build a frame on.
+ if (!out.length || out[out.length - 1].distanceTo(v) > 1e-6) {
+ out.push(v);
+ }
+ }
+ return out;
+ }).filter((s) => s.length >= 2);
+}
+
+/**
+ * Round every corner: glass bends on a radius.
+ *
+ * A mitred corner is a thing no glassblower makes, and the sweep would
+ * pinch there. Each corner becomes a quadratic through points `bend`
+ * back along both legs, which keeps the tube within `bend / 4` of the
+ * polyline it was given.
+ */
+function filletPath(pts, bend) {
+ if (pts.length < 3 || bend <= 0) return pts.map((p) => p.clone());
+ const out = [pts[0].clone()];
+ for (let i = 1; i < pts.length - 1; i++) {
+ const a = pts[i - 1], b = pts[i], c = pts[i + 1];
+ const u = new THREE.Vector3().subVectors(a, b);
+ const w = new THREE.Vector3().subVectors(c, b);
+ const la = u.length(), lc = w.length();
+ const k = Math.min(bend, la * 0.45, lc * 0.45);
+ if (k < 1e-5) { out.push(b.clone()); continue; }
+ u.multiplyScalar(k / la);
+ w.multiplyScalar(k / lc);
+ for (let j = 0; j <= 6; j++) {
+ const t = j / 6, s = 1 - t;
+ out.push(new THREE.Vector3(
+ s * s * (b.x + u.x) + 2 * s * t * b.x
+ + t * t * (b.x + w.x),
+ s * s * (b.y + u.y) + 2 * s * t * b.y
+ + t * t * (b.y + w.y),
+ s * s * (b.z + u.z) + 2 * s * t * b.z
+ + t * t * (b.z + w.z)));
+ }
+ }
+ out.push(pts[pts.length - 1].clone());
+ return out;
+}
+
+/** Stations spaced by ARC LENGTH, so v is metres and pulses ride it. */
+function resample(pts, n) {
+ const acc = [0];
+ for (let i = 1; i < pts.length; i++) {
+ acc.push(acc[i - 1] + pts[i].distanceTo(pts[i - 1]));
+ }
+ const total = acc[acc.length - 1];
+ const out = [];
+ let j = 0;
+ for (let i = 0; i <= n; i++) {
+ const d = total * (i / n);
+ while (j < acc.length - 2 && acc[j + 1] < d) j++;
+ const seg = Math.max(acc[j + 1] - acc[j], 1e-9);
+ const f = Math.min(Math.max((d - acc[j]) / seg, 0), 1);
+ out.push(pts[j].clone().lerp(pts[j + 1], f));
+ }
+ return { pts: out, length: total };
+}
+
+/**
+ * A rotation-minimising frame at every station.
+ *
+ * Rebuilding the section from a fixed up-vector spins the profile
+ * through every bend and shears the tube; transporting the previous
+ * normal keeps it steady.
+ */
+function frames(pts) {
+ const n = pts.length;
+ const tan = [];
+ for (let i = 0; i < n; i++) {
+ const a = pts[Math.max(i - 1, 0)];
+ const b = pts[Math.min(i + 1, n - 1)];
+ const t = new THREE.Vector3().subVectors(b, a);
+ if (t.lengthSq() < 1e-12) t.copy(tan[i - 1] || _UP);
+ tan.push(t.normalize());
+ }
+ let nrm = Math.abs(tan[0].y) > 0.9
+ ? new THREE.Vector3(1, 0, 0) : _UP.clone();
+ const out = [];
+ for (let i = 0; i < n; i++) {
+ nrm = nrm.clone().addScaledVector(tan[i], -nrm.dot(tan[i]));
+ if (nrm.lengthSq() < 1e-10) {
+ nrm.set(tan[i].y, -tan[i].x, 0);
+ if (nrm.lengthSq() < 1e-10) nrm.set(1, 0, 0);
+ }
+ nrm.normalize();
+ out.push({
+ p: pts[i], t: tan[i].clone(), n: nrm.clone(),
+ b: new THREE.Vector3().crossVectors(tan[i], nrm).normalize(),
+ });
+ }
+ return out;
+}
+
+/** Concatenate position / normal / uv geometries into one draw. */
+function mergeGeoms(list) {
+ let nv = 0, ni = 0;
+ for (const g of list) {
+ nv += g.attributes.position.count;
+ ni += g.index.count;
+ }
+ const pos = new Float32Array(nv * 3), nor = new Float32Array(nv * 3);
+ const uv = new Float32Array(nv * 2), idx = new Uint32Array(ni);
+ let v = 0, k = 0;
+ for (const g of list) {
+ const a = g.attributes;
+ pos.set(a.position.array, v * 3);
+ nor.set(a.normal.array, v * 3);
+ uv.set(a.uv.array, v * 2);
+ const src = g.index.array;
+ for (let i = 0; i < src.length; i++) idx[k + i] = src[i] + v;
+ v += a.position.count;
+ k += src.length;
+ }
+ const out = new THREE.BufferGeometry();
+ out.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ out.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ out.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ out.setIndex(new THREE.BufferAttribute(idx, 1));
+ return out;
+}
+
+/** One stroke as a swept circular section around its own frame. */
+function tubeGeometry(st, radius, nu) {
+ const nv = st.length - 1;
+ const at = (t) => st[Math.min(nv, Math.max(0, Math.round(t * nv)))];
+ return sweepProfile(
+ (t) => at(t).p,
+ (a, t) => {
+ const s = at(t);
+ const c = Math.cos(a) * radius, d = Math.sin(a) * radius;
+ return {
+ x: s.n.x * c + s.b.x * d,
+ y: s.n.y * c + s.b.y * d,
+ z: s.n.z * c + s.b.z * d,
+ };
+ },
+ { nu, nv });
+}
+
+/** Stations for every stroke of a path, filleted and arc-length even. */
+function strokeStations(strokes, bend, step) {
+ return strokes.map((s) => {
+ const smooth = filletPath(s, bend);
+ const rough = resample(smooth, 4).length;
+ const n = Math.min(400, Math.max(8, Math.round(rough / step)));
+ const r = resample(smooth, n);
+ return { frames: frames(r.pts), length: r.length };
+ });
+}
+
+/**
+ * The glowing gas, as a chord integral through the shell.
+ *
+ * `astraFacing` is exactly the chord the eye cuts through a tube:
+ * longest down the axis, zero at the silhouette. Skip it and the front
+ * and back faces of the shell stack at the rim into a bright OUTLINE,
+ * which is the solid-plastic-rod look no colour tuning removes.
+ *
+ * `toe` is the second half of that: the chord is exact for a CYLINDER
+ * and the mesh is an n-gon, so at the outermost facet the normal is
+ * still up to 180/n degrees off perpendicular and the shell ends on a
+ * live alpha — a crease that draws the halo's own polygon around the
+ * letter. Fading the chord out over `toe` puts that under the discard.
+ */
+function tubeMaterial(name, color, gain, core, hot, flicker, key, hazy,
+ toe, vary) {
+ // Pale, not white: over a bright wall a core that clips to white is
+ // a tube you cannot read, which is the day failure mirrored.
+ const tint = hazy
+ ? color.clone().lerp(new THREE.Color(1, 1, 1), 0.20) : color.clone();
+ const hotv = hazy ? hot * 0.25 : hot;
+ return makeShaderMaterial({
+ name,
+ additive: !hazy,
+ uniforms: {
+ uColor: { value: tint },
+ uGain: { value: gain },
+ uCore: { value: core },
+ uHot: { value: hotv },
+ uFlicker: { value: flicker },
+ uKey: { value: key },
+ uToe: { value: toe },
+ uVary: { value: vary },
+ },
+ varyings:
+ 'varying vec3 vNeonN; varying vec3 vNeonW; varying vec2 vNeonUv;',
+ vertexMain: [
+ ' vNeonN = normalize(mat3(modelMatrix) * normal);',
+ ' vNeonW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' vNeonUv = uv;',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform vec3 uColor; uniform float uGain; uniform float uCore;',
+ 'uniform float uHot; uniform float uFlicker;',
+ 'uniform float uKey; uniform float uToe; uniform float uVary;',
+ FLICK_GLSL,
+ FILAMENT_GLSL,
+ ].join('\n'),
+ fragmentMain: [
+ ' vec3 eye = normalize(cameraPosition - vNeonW);',
+ ' float face = astraFacing(vNeonN, eye);',
+ ' float body = pow(face, uCore) * smoothstep(0.0, uToe, face);',
+ ' float a = uGain * body',
+ ' * astraNeonFlick(uTime, uKey, uFlicker);',
+ // Rolled off, not clamped: a tube that saturates draws a
+ // flat band with a hard rim, which is the rod again.
+ ' a = 1.0 - exp(-a * 1.6);',
+ // One tube is not one colour: electrodes run hotter, the
+ // phosphor is not evenly laid, the glass is not evenly
+ // thick. The drift rides each stroke's own v, so a word
+ // bent one stroke per letter drifts per LETTER — which is
+ // what stops four letters reading as one printed decal.
+ ' float drift = astraNoise2(vec2(vNeonUv.y * 9.0, uKey))',
+ ' - 0.5;',
+ ' vec3 gas = astraHueShift(uColor, drift * uVary);',
+ ' vec3 c = mix(gas, vec3(1.0),',
+ ' astraNeonFilament(face, uHot));',
+ // A halo is a wide, shallow ramp: in 8-bit output that is
+ // exactly the gradient that bands into rings.
+ ' a += (astraHash21(gl_FragCoord.xy + uKey) - 0.5) * 0.005;',
+ ' if (a < 0.003) discard;',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,
+ side: THREE.DoubleSide,
+ depthWrite: false,
+ });
+}
+
+/**
+ * A bent glass tube that GLOWS — core, halo and its own colour bleed.
+ *
+ * Two shells swept along the same path: a thin one carrying the hot
+ * core and a fat one carrying the halo, both weighted by the chord the
+ * eye cuts through them, both ADDITIVE. Additive is what makes the
+ * colour bleed onto itself where the tube bends back past its own halo,
+ * and additive is right here because added light survives a DARK frame
+ * and clips over a bright one — a night street is that dark frame. Over
+ * anything brighter, say so with `ambient` and the tube switches to a
+ * pale normal-blended glass instead of clipping the sky out.
+ *
+ * @param {object} [opts]
+ * `path` a polyline (`[[x,y,z], ...]` or Vector3s) OR an array of
+ * those — one stroke per character of a word (default a 2 m bar);
+ * `radius` tube radius in metres (default 0.05: real glass is ~0.008,
+ * but a tube thinner than a pixel renders as a dashed line);
+ * `color` the gas colour, as its MEAN — the hue drifts a few degrees
+ * along each stroke, so a word bent one stroke per letter is four
+ * related colours rather than one flat fill (default 0xff2e6a);
+ * `intensity` overall gain
+ * (default 1); `halo` how many tube radii the glow reaches (default
+ * 3.6); `bend` corner radius in metres (default 6 * radius, capped at
+ * 45% of the shorter leg — the tube stays within bend/4 of the
+ * polyline); `flicker` 0..1 failing-tube stutter (default 0, OFF —
+ * a whole sign stuttering is a story, and most signs work);
+ * `ambient` how bright the surroundings are, 0 an unlit street to 1
+ * open daylight (default 0.15, this being a night library; from 0.35
+ * up the tube stops adding light and turns pale and normal-blended,
+ * so a composer who is unsure and picks 0.5 gets the mode that cannot
+ * clip); `seed` the flicker phase (default 3).
+ * @returns {THREE.Group} Named `NeonTube`, guarded by
+ * `keepOutOfDepthPasses` (a glow card is a solid wall to the GTAO
+ * override pass, and a light source must cast no shadow), with
+ * `userData.tick(t)` and `userData.spillSources()` — the world points
+ * to hand straight to `patchNeonSpill`.
+ */
+export function makeNeonTube(opts = {}) {
+ const radius = Math.max(1e-3,
+ opts.radius === undefined ? 0.05 : opts.radius);
+ const strokes = toStrokes(opts.path && opts.path.length ? opts.path
+ : [[-1, 0, 0], [1, 0, 0]]);
+ const color = toColor(opts.color, 0xff2e6a);
+ const intensity = opts.intensity === undefined ? 1 : opts.intensity;
+ const halo = opts.halo === undefined ? 3.6 : opts.halo;
+ const bend = opts.bend === undefined ? radius * 6 : opts.bend;
+ const flicker = Math.min(Math.max(
+ opts.flicker === undefined ? 0 : opts.flicker, 0), 1);
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);
+ const key = seedKey(opts.seed === undefined ? 3 : opts.seed);
+ const hazy = ambient >= 0.35;
+
+ const g = new THREE.Group();
+ g.name = 'NeonTube';
+ if (!strokes.length) return g;
+ const st = strokeStations(strokes, bend,
+ Math.max(0.02, Math.min(radius * 2.2, bend * 0.25)));
+ const gain = Math.max(0, intensity) * (hazy ? 1.9 : 1.05);
+ // THE ADDITIVE BUDGET (see FILAMENT_GLSL for why display space is
+ // what stacks). The old gains laid four layers of ~0.8 and ~0.44 on
+ // the middle of the glass — a sum near 2.5, where every channel of
+ // every colour clips and the sign renders white whatever gas it
+ // holds. Budgeted to ~1.4 instead: the strong channel still clips,
+ // as a tube must, and the weak ones keep the hue.
+ // 18 sides, not 10: the halo is `halo` times the radius of the
+ // glass, so its silhouette is the widest polygon here and a 10-gon
+ // draws that polygon around the letter (measured: a 2% alpha step
+ // at the outermost facet). The core's facets fit inside a pixel.
+ g.add(shell(st, radius * Math.max(1.2, halo), 18, tubeMaterial(
+ 'NeonHalo', color, gain * (hazy ? 0.12 : 0.148), 2.6, 0.10,
+ flicker, key, hazy, 0.45, 0.20), 'NeonHalo', 2));
+ g.add(shell(st, radius, 14, tubeMaterial(
+ 'NeonCore', color, gain * (hazy ? 1.0 : 0.41), 0.85, 0.9,
+ flicker, key, hazy, 0.10, 0.13), 'NeonCore', 3));
+ g.userData.tick = (t) => tickShaders(g, t);
+ // Sources for `patchNeonSpill`, read through the group's CURRENT
+ // world matrix, so placing the sign moves the light it throws.
+ g.userData.spillSources = (n) => sampleSources(g, st, color, n);
+ return keepOutOfDepthPasses(g);
+}
+
+/** One merged mesh for every stroke at one radius. */
+function shell(st, radius, nu, material, name, order) {
+ const mesh = new THREE.Mesh(
+ mergeGeoms(st.map((s) => tubeGeometry(s.frames, radius, nu))),
+ material);
+ mesh.name = name;
+ mesh.renderOrder = order;
+ return mesh;
+}
+
+/** Evenly spaced points along the whole sign, in world space. */
+function sampleSources(group, st, color, count) {
+ const n = Math.min(SPILL_MAX, Math.max(1,
+ count === undefined ? 4 : Math.round(count)));
+ const all = [];
+ for (const s of st) for (const f of s.frames) all.push(f.p);
+ group.updateWorldMatrix(true, false);
+ const out = [];
+ for (let i = 0; i < n; i++) {
+ const k = Math.round((i + 0.5) / n * (all.length - 1));
+ out.push({
+ position: all[k].clone().applyMatrix4(group.matrixWorld),
+ color: color.clone(),
+ });
+ }
+ return out;
+}
+
+const SPILL_VARYINGS =
+ 'varying vec3 vNeonSW;\nvarying vec3 vNeonSN;';
+
+// `transformed` is still object-space at <begin_vertex>, so an
+// instanced wall needs instanceMatrix folded in by hand.
+const SPILL_VERTEX = [
+ ' vec4 nsP = vec4(transformed, 1.0);',
+ ' vec3 nsN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' nsP = instanceMatrix * nsP;',
+ ' nsN = mat3(instanceMatrix) * nsN;',
+ '#endif',
+ ' vNeonSW = (modelMatrix * nsP).xyz;',
+ ' vNeonSN = normalize((modelMatrix * vec4(nsN, 0.0)).xyz);',
+].join('\n');
+
+const SPILL_HEAD = [
+ 'uniform vec3 uNeonPos[' + SPILL_MAX + '];',
+ 'uniform vec3 uNeonCol[' + SPILL_MAX + '];',
+ 'uniform float uNeonCount;',
+ 'uniform float uNeonRadius;',
+ 'uniform float uNeonGain;',
+ 'uniform float uNeonFlicker;',
+ 'uniform float uNeonKey;',
+ // Windowed inverse square: 1 at the source, EXACTLY 0 at radius and
+ // beyond. A bare 1/d^2 never reaches zero, so every wall in the
+ // scene keeps a wash of every sign in it and the night goes flat.
+ 'float astraNeonFall(float d, float r) {',
+ ' float x = clamp(d / max(r, 1e-4), 0.0, 1.0);',
+ ' float w = 1.0 - x * x;',
+ ' return w * w / (1.0 + 12.0 * x * x);',
+ '}',
+ FLICK_GLSL,
+].join('\n');
+
+const SPILL_BODY = [
+ ' vec3 nsSum = vec3(0.0);',
+ ' vec3 nsN = normalize(vNeonSN);',
+ ' for (int i = 0; i < ' + SPILL_MAX + '; i++) {',
+ ' if (float(i) >= uNeonCount) break;',
+ ' vec3 dv = uNeonPos[i] - vNeonSW;',
+ ' float d = length(dv);',
+ // A sign is a broad source, not a point: a hard lambert terminator
+ // would cut the pavement off right under the tube that lights it.
+ ' float lam = dot(nsN, dv / max(d, 1e-4)) * 0.5 + 0.5;',
+ ' lam = clamp(lam, 0.0, 1.0);',
+ ' nsSum += uNeonCol[i] * (astraNeonFall(d, uNeonRadius) * lam * lam);',
+ ' }',
+ ' nsSum *= uNeonGain * astraNeonFlick(uTime, uNeonKey, uNeonFlicker);',
+ // A pool is a metres-wide ramp on a flat wall — the widest, softest
+ // gradient in the library and the one that rings in 8-bit output.
+ // Proportional, so an unlit wall stays unlit instead of gaining a
+ // floor of noise.
+ ' nsSum *= 1.0 + (astraHash21(gl_FragCoord.xy + uNeonKey) - 0.5)',
+ ' * 0.03;',
+ // Arriving light is REFLECTED, so it takes the wall's own colour —
+ // but never all of it, or a dark wall swallows the sign entirely.
+ ' totalEmissiveRadiance +=',
+ ' nsSum * mix(vec3(0.30), diffuseColor.rgb, 0.70);',
+].join('\n');
+
+/**
+ * The light a sign throws onto the wall behind and the road below.
+ *
+ * Without this a neon sign is a bright decal on an unlit wall, which is
+ * the single tell that a night scene was assembled rather than lit. Each
+ * source adds a windowed inverse square, wrapped by how the surface
+ * faces it and reflected through the surface's own albedo, straight
+ * into `totalEmissiveRadiance` — so it ADDS light, correct over the
+ * dark frame a night city is and clipping over a bright one, which is
+ * what `ambient` is for. It is a `patchStandard`, so it needs a LIT
+ * material (MeshStandard/MeshPhysical, not Basic), and it chains
+ * happily with `patchWindowInteriors` and `patchMicroBreakup`.
+ *
+ * The one constraint it cannot solve: nothing is occluded. Light
+ * reaches the far side of a wall as readily as the near one, so keep
+ * `radius` to what the sign really reaches (a few metres) and put the
+ * sources on the face they light.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place. Clone a shared `materials.js` instance first.
+ * @param {object} [opts]
+ * `sources` up to 8 world points with colours — a Vector3, an
+ * `[x,y,z]`, or `{ position, color }`; `makeNeonTube().userData
+ * .spillSources()` hands back exactly this; `radius` metres the
+ * light reaches, ZERO beyond it (default 4); `strength` how bright
+ * the pool reads (default 1); `ambient` how bright the surroundings
+ * are, 0 an unlit street to 1 open daylight (default 0.15 — from
+ * 0.35 up the spill is cut back hard, because emissive added to an
+ * already-lit wall is the same clip); `flicker`/`seed` pass the SAME
+ * pair as the tube and the wall stutters with it (default 0, off);
+ * `name` the program cache key (default 'neon:spill' — every option
+ * here is a UNIFORM, so one name is correct and two differently lit
+ * walls still share one compiled program).
+ * @returns {THREE.Material} The same material; its uniforms live on
+ * `material.userData.uniforms`, so a scene can move or dim the
+ * sources per frame.
+ */
+export function patchNeonSpill(material, opts = {}) {
+ const radius = Math.max(1e-3,
+ opts.radius === undefined ? 4 : opts.radius);
+ const strength = Math.max(0,
+ opts.strength === undefined ? 1 : opts.strength);
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);
+ const flicker = Math.min(Math.max(
+ opts.flicker === undefined ? 0 : opts.flicker, 0), 1);
+ const list = (Array.isArray(opts.sources) ? opts.sources : [])
+ .slice(0, SPILL_MAX);
+ const pos = [], col = [];
+ for (let i = 0; i < SPILL_MAX; i++) {
+ const s = list[i];
+ const p = s && (s.position || s.point || s);
+ pos.push(s ? toVec(p) : new THREE.Vector3());
+ col.push(s ? toColor(s.color, 0xff2e6a) : new THREE.Color(0, 0, 0));
+ }
+ return patchStandard(material, {
+ name: opts.name || 'neon:spill',
+ uniforms: {
+ uNeonPos: { value: pos },
+ uNeonCol: { value: col },
+ uNeonCount: { value: list.length },
+ uNeonRadius: { value: radius },
+ // Emissive added to a wall the sun already lit clips the
+ // same way an additive pass does, so the escape is a gain.
+ uNeonGain: { value: strength * (1 - 0.85 * ambient) },
+ uNeonFlicker: { value: flicker },
+ uNeonKey: { value: seedKey(opts.seed === undefined ? 3
+ : opts.seed) },
+ },
+ vertexHead: SPILL_VARYINGS,
+ vertexBody: SPILL_VERTEX,
+ fragmentHead: [SPILL_VARYINGS, SPILL_HEAD].join('\n'),
+ fragmentBody: SPILL_BODY,
+ });
+}
+
+/** A flat ribbon riding the road, u across and v along the arc. */
+function ribbonGeometry(fr, offset, halfW, lift) {
+ const n = fr.length;
+ const pos = new Float32Array(n * 2 * 3);
+ const nor = new Float32Array(n * 2 * 3);
+ const uv = new Float32Array(n * 2 * 2);
+ const idx = new Uint32Array((n - 1) * 6);
+ const lat = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ lat.crossVectors(fr[i].t, _UP);
+ if (lat.lengthSq() < 1e-9) lat.set(1, 0, 0);
+ lat.normalize();
+ const v = i / (n - 1);
+ for (let s = 0; s < 2; s++) {
+ const k = (i * 2 + s);
+ const w = offset + (s === 0 ? -halfW : halfW);
+ pos[k * 3] = fr[i].p.x + lat.x * w;
+ pos[k * 3 + 1] = fr[i].p.y + lift;
+ pos[k * 3 + 2] = fr[i].p.z + lat.z * w;
+ nor[k * 3 + 1] = 1;
+ uv[k * 2] = s;
+ uv[k * 2 + 1] = v;
+ }
+ if (i < n - 1) {
+ const a = i * 2;
+ idx.set([a, a + 1, a + 2, a + 1, a + 3, a + 2], i * 6);
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ g.setIndex(new THREE.BufferAttribute(idx, 1));
+ return g;
+}
+
+/**
+ * Comet-shaped pulses riding v, one lane per material.
+ *
+ * The head is a hot point and everything behind it is the smear a long
+ * exposure leaves; `uDir` flips which way along the path that is, so
+ * the two lanes run against each other from one shared source.
+ */
+function trailMaterial(name, color, dir, count, rate, gain, hot, fore,
+ key, hazy, vary) {
+ const tint = hazy
+ ? color.clone().lerp(new THREE.Color(1, 1, 1), 0.20) : color.clone();
+ const hotv = hazy ? hot * 0.25 : hot;
+ return makeShaderMaterial({
+ name,
+ additive: !hazy,
+ uniforms: {
+ uColor: { value: tint },
+ uDir: { value: dir },
+ uCount: { value: count },
+ uRate: { value: rate },
+ uGain: { value: gain },
+ uHot: { value: hotv },
+ uFore: { value: fore },
+ uKey: { value: key },
+ uVary: { value: vary },
+ },
+ varyings: 'varying vec2 vTrailUv;',
+ vertexMain: ' vTrailUv = uv;',
+ fragmentHead: [
+ 'uniform vec3 uColor; uniform float uDir; uniform float uCount;',
+ 'uniform float uRate; uniform float uGain; uniform float uHot;',
+ 'uniform float uFore; uniform float uKey; uniform float uVary;',
+ // The phase one vehicle rides. Written as its own function
+ // so the direction it travels is a property of the source,
+ // not something only a rendered frame could tell you.
+ 'float astraTrailPhase(float v, float dir, float t,',
+ ' float rate, float count) {',
+ ' return fract(dir * v * count - t * rate);',
+ '}',
+ TEMP_GLSL,
+ ].join('\n'),
+ fragmentMain: [
+ ' float u = vTrailUv.x * 2.0 - 1.0;',
+ ' float s = uDir * vTrailUv.y * uCount - uTime * uRate;',
+ ' float f = fract(s);',
+ ' float id = floor(s) + uKey;',
+ // A lane is not one vehicle: each sits at its own place
+ // across the lane and carries its own brightness.
+ ' float du = u - (astraHash11(id * 1.37) - 0.5) * 0.55;',
+ ' float amp = 0.45 + 1.0 * astraHash11(id * 2.13 + 3.1);',
+ ' float head = pow(f, 26.0);',
+ ' float tail = pow(f, 3.2);',
+ // A lamp lights the road IN FRONT of itself. Without this
+ // the smear stops dead at the head and the cut reads as a
+ // straight-edged slab laid across the lane.
+ ' float fore = exp(-f * 12.0) * uFore;',
+ ' float core = exp(-du * du * 26.0);',
+ // The road catching the same lamp: wider, dimmer, and the
+ // reason a streak is not a floating line. It must reach
+ // ZERO at the ribbon edge or the road wears a hard slab.
+ ' float rim = 1.0 - u * u;',
+ ' float wash = exp(-du * du * 2.2) * 0.42 * rim * rim;',
+ ' float ends = smoothstep(0.0, 0.05, vTrailUv.y)',
+ ' * (1.0 - smoothstep(0.95, 1.0, vTrailUv.y));',
+ ' float a = uGain * amp * ends',
+ ' * ((head + (tail + fore) * 0.42) * core',
+ ' + (tail + fore) * wash);',
+ ' a = 1.0 - exp(-a * 1.6);',
+ // No two vehicles carry the same lamp: halogen against cold
+ // LED one way, a braked tail-light against a coasting one
+ // the other.
+ ' float w = astraTrailTemp(id, uVary);',
+ ' vec3 lamp = astraHueShift(uColor, w)',
+ ' * vec3(1.0 + w, 1.0 + w * 0.15, 1.0 - w);',
+ ' vec3 c = mix(lamp, vec3(1.0), head * uHot);',
+ // The wash is a metre-wide ramp across tarmac: the one
+ // gradient in this effect wide enough to band.
+ ' a += (astraHash21(gl_FragCoord.xy + uKey) - 0.5) * 0.005;',
+ ' if (a < 0.003) discard;',
+ ' gl_FragColor = vec4(c, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ blending: hazy ? THREE.NormalBlending : THREE.AdditiveBlending,
+ side: THREE.DoubleSide,
+ depthWrite: false,
+ });
+}
+
+/**
+ * Head- and tail-light streaks along a road: motion in a still frame.
+ *
+ * Two ribbons laid on the road, one per lane, each carrying comet
+ * pulses that ride the path's own arc length — so the streaks BEND with
+ * the road instead of crossing it. Warm white runs one way and red the
+ * other, which is what tells a reader the traffic has two directions.
+ * The pulses ADD light, correct over the dark frame a night road is and
+ * wrong over a bright one; `ambient` is the escape.
+ *
+ * @param {object} [opts]
+ * `path` the road centreline as a polyline (`[[x,y,z], ...]` or
+ * Vector3s; default a 40 m straight); `count` streaks per lane
+ * (default 5); `speed` metres per second along the path (default 14);
+ * `warm` the lane running FORWARD along the path, head-lights
+ * (default 0xffeec8); `cool` the lane running back, tail-lights
+ * (default 0xff1e14 — `cool` names the lane, not the hue). Each is
+ * the lane's MEAN: every vehicle rotates a few degrees off it, so a
+ * lane reads as traffic rather than as eight copies of one lamp;
+ * `width`
+ * streak width in metres (default 0.5; the ribbon carrying its wash
+ * is six times that, so the road wants `2 * lane + 6 * width` of
+ * tarmac); `lane` metres from the centreline to each lane (default
+ * width * 4); `lift` metres above
+ * the road (default 0.03, enough to clear z-fighting); `ambient`
+ * 0 an unlit street to 1 open daylight (default 0.15 — from 0.35 up
+ * the streaks turn pale and normal-blended instead of clipping);
+ * `seed` per-vehicle jitter (default 7).
+ * @returns {THREE.Group} Named `LightTrails`, holding `TrailsWarm` and
+ * `TrailsCool`, guarded by `keepOutOfDepthPasses` (an additive card
+ * is an opaque wall to the GTAO override pass, and a moving light
+ * must cast no shadow), with `userData.tick(t)`.
+ */
+export function makeLightTrails(opts = {}) {
+ const strokes = toStrokes(opts.path && opts.path.length ? opts.path
+ : [[0, 0, -20], [0, 0, 20]]);
+ const count = Math.max(1, Math.round(
+ opts.count === undefined ? 5 : opts.count));
+ const speed = opts.speed === undefined ? 14 : opts.speed;
+ const width = Math.max(0.02,
+ opts.width === undefined ? 0.5 : opts.width);
+ const lane = opts.lane === undefined ? width * 4 : opts.lane;
+ const lift = opts.lift === undefined ? 0.03 : opts.lift;
+ const ambient = Math.min(Math.max(
+ opts.ambient === undefined ? 0.15 : opts.ambient, 0), 1);
+ const key = seedKey(opts.seed === undefined ? 7 : opts.seed);
+ const hazy = ambient >= 0.35;
+
+ const g = new THREE.Group();
+ g.name = 'LightTrails';
+ if (!strokes.length) return g;
+ const line = strokes[0];
+ const smooth = filletPath(line, Math.max(lane, width) * 2);
+ const rough = resample(smooth, 4).length;
+ const r = resample(smooth, Math.min(600, Math.max(24,
+ Math.round(rough * 1.5))));
+ const fr = frames(r.pts);
+ // Pulses per second along the path: `speed` is metres, and v is
+ // metres because the stations were spaced by arc length.
+ const rate = speed * count / Math.max(r.length, 1e-3);
+ const gain = hazy ? 0.55 : 1.15;
+ const half = width * 3;
+ // 0.5, not 0.7, on the head-lights: a lamp that whitens hard has
+ // no colour temperature left to vary, and with no bloom pass here
+ // the white it clips to is the last thing the frame records.
+ g.add(laneMesh(fr, -lane, half, lift, trailMaterial(
+ 'NeonTrailWarm', toColor(opts.warm, 0xffeec8), 1, count, rate,
+ gain, 0.5, 0.60, key, hazy, 0.40), 'TrailsWarm'));
+ g.add(laneMesh(fr, lane, half, lift, trailMaterial(
+ 'NeonTrailCool', toColor(opts.cool, 0xff1e14), -1, count, rate,
+ gain, 0.15, 0.22, key + 5.3, hazy, 0.16), 'TrailsCool'));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/** One lane's ribbon, named so a test and a composer can find it. */
+function laneMesh(fr, offset, halfW, lift, material, name) {
+ const mesh = new THREE.Mesh(
+ ribbonGeometry(fr, offset, halfW, lift), material);
+ mesh.name = name;
+ mesh.renderOrder = 2;
+ return mesh;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/noise.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/noise.js
new file mode 100644
index 00000000..0d7832f8
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/noise.js
@@ -0,0 +1,166 @@
+/**
+ * Seeded noise substrate: fBm fields, procedural DataTextures, and
+ * terrain displacement. ImprovedNoise is UNSEEDED and the platform's
+ * global RNG is banned, so `mulberry32` is the one sanctioned PRNG and
+ * fbm2/fbm3 seed the lattice via per-octave domain offsets. Other lib
+ * modules build on this — keep the exported signatures stable.
+ * (The ban is stated without naming the call: the scene_threejs lint
+ * greps sources for it and a doc comment is not an exemption.)
+ */
+
+import * as THREE from 'three';
+import { ImprovedNoise } from 'three/addons/math/ImprovedNoise.js';
+
+const _noise = new ImprovedNoise();
+
+/**
+ * The sanctioned seeded PRNG — same seed, same sequence, every run.
+ * Never the platform's global RNG.
+ *
+ * @param {number} seed Any integer.
+ * @returns {() => number} A function returning uniform values in [0, 1).
+ */
+export function mulberry32(seed) {
+ let a = seed | 0;
+ return function () {
+ a = (a + 0x6D2B79F5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// Seed-derived per-octave domain offsets; they also de-align octave
+// zeros so grid artifacts can't stack. Cached: fbm runs per vertex.
+const _offsetCache = new Map();
+
+function _offsets(seed, octaves) {
+ const key = seed + ':' + octaves;
+ let offs = _offsetCache.get(key);
+ if (!offs) {
+ const rand = mulberry32(seed);
+ offs = [];
+ for (let o = 0; o < octaves; o++) {
+ offs.push([rand() * 256, rand() * 256, rand() * 256]);
+ }
+ _offsetCache.set(key, offs);
+ }
+ return offs;
+}
+
+/**
+ * Seeded 3D fractal Brownian motion over ImprovedNoise.
+ *
+ * @param {number} x Sample coordinate.
+ * @param {number} y Sample coordinate.
+ * @param {number} z Sample coordinate.
+ * @param {object} [opts] `octaves` (default 4), `lacunarity` (default
+ * 2), `gain` (default 0.5), `seed` (default 1).
+ * @returns {number} Normalized field value in measured about +-0.25 with a seed- and region-dependent bias, NOT the [-1, 1] the octave sum suggests.
+ */
+export function fbm3(x, y, z, opts = {}) {
+ const octaves = opts.octaves || 4;
+ const lacunarity = opts.lacunarity || 2;
+ const gain = opts.gain === undefined ? 0.5 : opts.gain;
+ const offs = _offsets(opts.seed === undefined ? 1 : opts.seed, octaves);
+ let amp = 1;
+ let freq = 1;
+ let sum = 0;
+ let norm = 0;
+ for (let o = 0; o < octaves; o++) {
+ const off = offs[o];
+ sum += amp * _noise.noise(
+ x * freq + off[0], y * freq + off[1], z * freq + off[2]);
+ norm += amp;
+ amp *= gain;
+ freq *= lacunarity;
+ }
+ return sum / norm;
+}
+
+/**
+ * Seeded 2D fBm — the terrain/map workhorse. Feed it PRE-SCALED
+ * coordinates: `fbm2(x * f, z * f)` where `f ~ 1 / featureMetres`
+ * (0.02 gives ~50 m hills).
+ *
+ * @param {number} x Sample coordinate.
+ * @param {number} z Sample coordinate.
+ * @param {object} [opts] Same options as `fbm3`.
+ * @returns {number} Normalized field value in measured about +-0.25 with a seed- and region-dependent bias, NOT the [-1, 1] the octave sum suggests.
+ */
+export function fbm2(x, z, opts = {}) {
+ return fbm3(x, 0, z, opts);
+}
+
+/**
+ * Bake a per-pixel function into a tiling RGBA DataTexture — the only
+ * way to get a texture in this pipeline (npm three ships no image
+ * assets, and asset modules are DOM-free so no canvas).
+ *
+ * @param {number} [size] Texture width and height in px (default 256).
+ * @param {(u: number, v: number) => (number|Array<number>)} [fn]
+ * Called per pixel with u, v in [0, 1); returns a 0..1 grey value or
+ * an [r, g, b] / [r, g, b, a] array of 0..1 channels. Defaults to a
+ * mid-grey fBm breakup field. RepeatWrapping is set, but seamless
+ * tiling is the fn's job — build tiling fns from integer-frequency
+ * sines or sample fbm2 at a low frequency so the seam stays subtle.
+ * @returns {THREE.DataTexture} RepeatWrapping, needsUpdate already set.
+ */
+export function noiseDataTexture(size = 256, fn) {
+ const f = fn ||
+ ((u, v) => 0.5 + 0.35 * fbm2(u * 6, v * 6, { seed: 1 }));
+ const data = new Uint8Array(size * size * 4);
+ const byte = (c) => Math.max(0, Math.min(255, Math.round(c * 255)));
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const v = f(x / size, y / size);
+ const i = (y * size + x) * 4;
+ if (typeof v === 'number') {
+ data[i] = data[i + 1] = data[i + 2] = byte(v);
+ data[i + 3] = 255;
+ } else {
+ data[i] = byte(v[0]);
+ data[i + 1] = byte(v[1]);
+ data[i + 2] = byte(v[2]);
+ data[i + 3] = v.length > 3 ? byte(v[3]) : 255;
+ }
+ }
+ }
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ // DataTexture defaults to NearestFilter with no mipmaps. Used as a
+ // puddle alpha mask on a ground plane, one screen pixel then spans
+ // dozens of texels and the wet/dry edge tears into stair-stepped
+ // slabs at grazing angles (2026-08-04 audit, Shibuya).
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+ tex.anisotropy = 8;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+/**
+ * Displace a geometry's Y by seeded fBm and refresh its normals.
+ * Expects an XZ-plane geometry (`PlaneGeometry` after `rotateX`);
+ * displacement ADDS to existing Y, so pre-shaped geometry keeps shape.
+ *
+ * @param {THREE.BufferGeometry} geometry Modified in place.
+ * @param {number} amp Peak displacement in metres (fBm spans ~[-1, 1],
+ * so peak-to-trough relief is up to ~2 * amp).
+ * @param {number} freq Spatial frequency, ~1 / featureMetres (0.02
+ * gives ~50 m hills).
+ * @param {number} [seed] Noise seed (default 1).
+ * @returns {THREE.BufferGeometry} The same geometry, for chaining.
+ */
+export function displaceY(geometry, amp, freq, seed) {
+ const pos = geometry.attributes.position;
+ const opts = { seed: seed === undefined ? 1 : seed };
+ for (let i = 0; i < pos.count; i++) {
+ pos.setY(i, pos.getY(i) +
+ amp * fbm2(pos.getX(i) * freq, pos.getZ(i) * freq, opts));
+ }
+ pos.needsUpdate = true;
+ geometry.computeVertexNormals();
+ return geometry;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/place.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/place.js
new file mode 100644
index 00000000..8769ded2
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/place.js
@@ -0,0 +1,666 @@
+/**
+ * Placement, derived instead of typed — hand-typed yaws and y's are
+ * what produce ungrounded geometry, backwards vehicles and
+ * back-to-front seating, so the arithmetic lives here as functions.
+ * Every function MUTATES and returns the object, so calls chain; the
+ * camera builders (`shot`, `establishingShot`) instead return a ready
+ * CAMERAS entry, and `route()` returns a stateless pose function.
+ */
+
+import * as THREE from 'three';
+
+const _ray = new THREE.Raycaster();
+const _down = new THREE.Vector3(0, -1, 0);
+const _box = new THREE.Box3();
+const _v = new THREE.Vector3();
+const _t = new THREE.Vector3();
+const DEG = Math.PI / 180;
+
+/** Unit vector for a `forward` string as reported by assets_api.json. */
+function fwdVec(forward) {
+ switch (forward) {
+ case '+X': return new THREE.Vector3(1, 0, 0);
+ case '-X': return new THREE.Vector3(-1, 0, 0);
+ case '+Z': return new THREE.Vector3(0, 0, 1);
+ default: return new THREE.Vector3(0, 0, -1); // '-Z', the three.js default
+ }
+}
+
+/**
+ * Every surface y over (x, z), highest first — one down-ray from `top`.
+ * `intersectObjects` already sorts by distance, and the ray points
+ * down, so the array comes back descending.
+ */
+function columnAt(x, z, targets, top, far, ignore) {
+ _ray.set(_v.set(x, top, z), _down);
+ _ray.far = far;
+ const ys = [];
+ for (const h of _ray.intersectObjects(targets, true)) {
+ if (ignore && (h.object === ignore || ignore.getObjectById(h.object.id))) {
+ continue;
+ }
+ ys.push(h.point.y);
+ }
+ return ys;
+}
+
+/**
+ * Which of those surfaces a body at height `y` actually rests on: the
+ * TOPMOST one at or below it — what is UNDER it, a quay beating the
+ * seabed — and only when nothing is under it the LOWEST one above (an
+ * object authored at y = 0 on a hillside is still lifted onto the hill).
+ *
+ * The split is the fix for a measured teleport: the down-ray starts far
+ * overhead, so its nearest hit is a ROOF, and anything with something
+ * over it flew up onto that roof — a crate under a 3 m arch seated at
+ * y 3.62, and an interior camera handed its room group (which is what
+ * the catalog tells composers to pass) shipped at eye 4.60 in a room
+ * whose ceiling tops out at 3.00 (2026-09-01 port probe).
+ */
+function restingY(ys, y) {
+ for (const v of ys) if (v <= y + 1e-4) return v;
+ return ys.length ? ys[ys.length - 1] : null;
+}
+
+/**
+ * Drop an object until it rests on whatever is under it.
+ * Casts down from base corners AND centre: per ray the surface UNDER
+ * the base wins (a quay beats the seabed), across rays the LOWEST wins
+ * (a wide object on a slope buries its uphill side instead of hovering
+ * on the high corner), then sinks `bite` metres so no seam shows.
+ *
+ * @param {THREE.Object3D} obj Already positioned in x/z.
+ * @param {THREE.Object3D|THREE.Object3D[]} surfaces Ground, terrain,
+ * decks, roofs — anything that can be stood on.
+ * @param {object} [opts] `bite` metres to sink (default 0.03),
+ * `maxDrop` how far down to look (default 500).
+ * @returns {THREE.Object3D} obj, or obj unchanged when nothing is below.
+ */
+export function seat(obj, surfaces, opts = {}) {
+ const targets = Array.isArray(surfaces) ? surfaces : [surfaces];
+ const bite = opts.bite === undefined ? 0.03 : opts.bite;
+ obj.updateMatrixWorld(true);
+ // The SURFACE's world matrix has to be current too: a ground group
+ // built and moved in the same tick still carries its old matrix, so
+ // every raycast hits the old height and the whole scene seats to it
+ // (measured 1.53 m under a quay, 2026-08-04 drawbridge repair).
+ for (const t of targets) if (t) t.updateMatrixWorld(true);
+ _box.setFromObject(obj);
+ if (_box.isEmpty()) return obj;
+ const y0 = _box.min.y;
+ const xs = [_box.min.x, _box.max.x, (_box.min.x + _box.max.x) / 2];
+ const zs = [_box.min.z, _box.max.z, (_box.min.z + _box.max.z) / 2];
+ const drop = opts.maxDrop || 500;
+ let best = null;
+ for (const x of xs) {
+ for (const z of zs) {
+ const y = restingY(
+ columnAt(x, z, targets, y0 + drop * 0.5, drop, obj), y0);
+ if (y !== null && (best === null || y < best)) best = y;
+ }
+ }
+ if (best === null) return obj;
+ obj.position.y += best - y0 - bite;
+ return obj;
+}
+
+/** Coerce a `surfaces` argument to an array, `undefined` to []. */
+function surfaceList(surfaces) {
+ if (surfaces === undefined || surfaces === null) return [];
+ return Array.isArray(surfaces) ? surfaces : [surfaces];
+}
+
+/**
+ * Lift a point so it clears the FLOOR under it — the surface
+ * `restingY()` picks, not whatever is highest in the column: handed a
+ * room group (which is exactly what the catalog tells composers to
+ * pass indoors) the old rule lifted the eye 1.6 m above the CEILING
+ * and the shot shipped from on top of the roof.
+ * Only ever lifts (an intentionally aerial camera is left where it
+ * is), and never through a low ceiling: in a room too short for the
+ * clearance the eye stops 0.25 m under it instead of leaving.
+ */
+function liftAbove(pos, targets, clearance) {
+ if (!targets.length) return pos;
+ for (const t of targets) if (t) t.updateMatrixWorld(true);
+ const ys = columnAt(pos.x, pos.z, targets, pos.y + 1000, 4000);
+ const floorY = restingY(ys, pos.y);
+ if (floorY === null) return pos;
+ let want = Math.max(pos.y, floorY + clearance);
+ let ceiling = null; // lowest surface above the floor
+ for (const v of ys) if (v > floorY + 0.05) ceiling = v;
+ if (ceiling !== null && want > ceiling - 0.25) {
+ want = Math.max(floorY + 0.3, ceiling - 0.25);
+ }
+ pos.y = want;
+ return pos;
+}
+
+/**
+ * How far the view from `pos` to `look` gets before something is in
+ * the way — ONE definition of "blocked" for both camera builders.
+ *
+ * @returns {{dir: THREE.Vector3, dist: number, hit: number}} `dir` unit
+ * eye-to-subject, `dist` their separation, `hit` distance to the
+ * first surface in between (Infinity when the view is clear).
+ */
+function probeView(pos, look, targets) {
+ const dir = new THREE.Vector3().subVectors(look, pos);
+ const dist = dir.length();
+ if (dist < 1e-6 || !targets.length) return { dir, dist, hit: Infinity };
+ dir.multiplyScalar(1 / dist);
+ _ray.set(pos, dir);
+ _ray.far = dist;
+ const hits = _ray.intersectObjects(targets, true);
+ return { dir, dist, hit: hits.length ? hits[0].distance : Infinity };
+}
+
+/** Nothing may fill the frame from closer than this. */
+function clearNeeded(dist) {
+ return Math.max(2, dist * 0.05);
+}
+
+/**
+ * Build a CAMERAS entry whose geometry is verified, not guessed.
+ * Two checks: (1) a down-ray over `surfaces` lifts the eye to at
+ * least 1.6 m above the first hit — never lowers it; (2) a ray toward
+ * `lookAt` must not hit anything closer than max(2 m, 5% of target
+ * distance), else the camera slides back and up until the frame clears.
+ *
+ * @param {string} name Camera name for the CAMERAS array.
+ * @param {THREE.Vector3|number[]} position Requested eye point.
+ * @param {THREE.Vector3|number[]} lookAt What the shot is of.
+ * @param {number} [fov] Vertical field of view (default 55).
+ * @param {THREE.Object3D|THREE.Object3D[]} [surfaces] Ground, terrain,
+ * decks, walls — everything the camera must clear.
+ * @returns {{name: string, position: number[], lookAt: number[],
+ * fov: number}} A ready CAMERAS entry.
+ */
+export function shot(name, position, lookAt, fov, surfaces) {
+ const pos = position instanceof THREE.Vector3
+ ? position.clone() : new THREE.Vector3(...position);
+ const look = lookAt instanceof THREE.Vector3
+ ? lookAt.clone() : new THREE.Vector3(...lookAt);
+ const targets = surfaceList(surfaces);
+ liftAbove(pos, targets, 1.6);
+ for (let i = 0; i < 12 && targets.length; i++) {
+ const v = probeView(pos, look, targets);
+ if (v.dist < 1e-6) break;
+ const clear = clearNeeded(v.dist);
+ if (v.hit >= clear) break;
+ pos.addScaledVector(v.dir, -(clear - v.hit + 0.25));
+ pos.y += 0.5;
+ liftAbove(pos, targets, 1.6);
+ }
+ // INDOORS THERE IS NOWHERE TO RETREAT TO: backing away from a screen
+ // walks into the wall behind, and the shot ships from inside the
+ // screen. If the view is still blocked, step FORWARD past the
+ // blocker instead — what a person holding the camera would do.
+ if (targets.length) {
+ const v = probeView(pos, look, targets);
+ if (v.dist > 1e-6 && v.hit < clearNeeded(v.dist)
+ && v.hit < v.dist * 0.6) {
+ pos.addScaledVector(v.dir, v.hit + 0.35);
+ liftAbove(pos, targets, 1.6);
+ }
+ }
+ return {
+ name,
+ position: [pos.x, pos.y, pos.z],
+ lookAt: [look.x, look.y, look.z],
+ fov: fov === undefined ? 55 : fov,
+ };
+}
+
+// Widest a view direction may sit from the sun before the low-sun mie
+// lobe washes the frame. 55 deg still bleached a third of it, 25 deg
+// blew the whole image, 120 deg rendered clean (theme-park run).
+const SUN_CLEAR_DEG = 90;
+
+/**
+ * Push a camera azimuth out of the sun's glare lobe.
+ *
+ * The rule has been in the composer prompt since the theme-park run and
+ * was violated by three of the next three low-sun establishing shots,
+ * so it is arithmetic now rather than advice. A camera at azimuth A
+ * LOOKS toward A, so the sun at S is in frame when |A - S| is small.
+ *
+ * @param {number} azDeg Requested camera azimuth in degrees.
+ * @param {number} [sunAzDeg] Sun azimuth, same convention; when absent
+ * the request passes through untouched.
+ * @returns {number} The nearest azimuth at least 90 deg off the sun.
+ */
+export function awayFromSun(azDeg, sunAzDeg) {
+ if (typeof sunAzDeg !== 'number' || !isFinite(sunAzDeg)) return azDeg;
+ const wrap = (d) => ((d % 360) + 540) % 360 - 180;
+ const off = wrap(azDeg - sunAzDeg);
+ if (Math.abs(off) >= SUN_CLEAR_DEG) return azDeg;
+ // Nearest legal side, so the requested composition moves as little as
+ // it can rather than jumping to the anti-sun default.
+ const side = off === 0 ? 1 : Math.sign(off);
+ return sunAzDeg + side * SUN_CLEAR_DEG;
+}
+
+/**
+ * Frame a hero object whole — the bbox-fitted establishing CAMERAS
+ * entry, derived instead of eyeballed: project the 8 world-bbox
+ * corners, dolly until the widest NDC extent hits `coverage`, seat the
+ * eye with the same down-ray as `shot()`, and — when something stands
+ * between the eye and the hero — slide along the fit sphere (up first,
+ * then around) until the hero is actually visible, rather than shipping
+ * a frame full of ridge.
+ *
+ * @param {string} name Camera name for the CAMERAS array.
+ * @param {THREE.Object3D} heroObj The subject to fit whole.
+ * @param {object} [opts] `azDeg` view azimuth (default 35), `elDeg`
+ * elevation (default 22), `fov` (default 45), `coverage` how much of
+ * the frame the hero spans, 0.5-0.9 (default 0.7), `surfaces` to
+ * keep the eye at least 1.6 m above the ground, `sunAzDeg` to have
+ * the azimuth pushed clear of the sun's glare lobe automatically.
+ * @returns {{name: string, position: number[], lookAt: number[],
+ * fov: number}} A ready CAMERAS entry.
+ */
+export function establishingShot(name, heroObj, opts = {}) {
+ // `azDeg` is where the EYE stands; it looks back at the centre, so
+ // the view direction is azDeg + 180 and that is what must clear the
+ // sun. Correcting the eye azimuth directly would aim it AT the glare.
+ const azDeg = awayFromSun(
+ (opts.azDeg === undefined ? 35 : opts.azDeg) + 180,
+ opts.sunAzDeg) - 180;
+ const elDeg = opts.elDeg === undefined ? 22 : opts.elDeg;
+ const fov = opts.fov === undefined ? 45 : opts.fov;
+ const coverage = opts.coverage === undefined ? 0.7 : opts.coverage;
+ const targets = surfaceList(opts.surfaces);
+ heroObj.updateMatrixWorld(true);
+ _box.setFromObject(heroObj);
+ if (_box.isEmpty()) {
+ return { name, position: [10, 6, 10], lookAt: [0, 0, 0], fov };
+ }
+ const center = _box.getCenter(new THREE.Vector3());
+ const radius = Math.max(
+ _box.getSize(new THREE.Vector3()).length() / 2, 0.25);
+ const corners = [];
+ for (const cx of [_box.min.x, _box.max.x])
+ for (const cy of [_box.min.y, _box.max.y])
+ for (const cz of [_box.min.z, _box.max.z])
+ corners.push(new THREE.Vector3(cx, cy, cz));
+ // 16:9 is the harness's render aspect (800x450 / 1280x720).
+ const camera = new THREE.PerspectiveCamera(fov, 16 / 9, 0.1, 1e6);
+ /** The dolly distance that puts the widest bbox extent on `coverage`. */
+ const fit = (dirVec) => {
+ let d = radius / Math.sin((fov / 2) * DEG);
+ for (let it = 0; it < 5; it++) {
+ camera.position.copy(center).addScaledVector(dirVec, d);
+ camera.lookAt(center);
+ camera.updateMatrixWorld(true);
+ let maxExt = 1e-6;
+ for (const c of corners) {
+ _v.copy(c).project(camera);
+ maxExt = Math.max(maxExt, Math.abs(_v.x), Math.abs(_v.y));
+ }
+ d = d * (maxExt / coverage);
+ }
+ return d;
+ };
+ const eyeDir = (aDeg, eDeg) => {
+ const a = aDeg * DEG;
+ const e = eDeg * DEG;
+ return new THREE.Vector3(Math.cos(e) * Math.cos(a), Math.sin(e),
+ Math.cos(e) * Math.sin(a));
+ };
+ // MOVE ON THE FIT SPHERE, NEVER BACKWARDS. `shot()` retreats from a
+ // blocker, which is right for a street camera and wrong here: backing
+ // away shrinks the hero the establishing shot exists to show. Look
+ // OVER the obstacle first (raise the elevation — what a person with a
+ // camera does), then step around it (swing the azimuth), re-fitting at
+ // every candidate so the framing survives the move. Measured before
+ // this: a hero behind a 9 m ridge shipped a frame filled by ridge at
+ // 1.19 m of an 8.92 m shot — the "one wall fills the frame" failure
+ // the module was written to end (2026-09-01 port probe).
+ const arcs = [[0, 0], [0, 9], [0, 19], [0, 31], [24, 6], [-24, 6],
+ [24, 20], [-24, 20], [48, 10], [-48, 10], [0, 46]];
+ let pos = null;
+ let bestGap = -1;
+ for (const [dAz, dEl] of arcs) {
+ const a = dAz === 0 ? azDeg
+ : awayFromSun(azDeg + dAz + 180, opts.sunAzDeg) - 180;
+ const dir = eyeDir(a, Math.min(70, elDeg + dEl));
+ const p = center.clone().addScaledVector(dir, fit(dir));
+ liftAbove(p, targets, 1.6);
+ const v = probeView(p, center, targets);
+ if (v.hit >= clearNeeded(v.dist)) { pos = p; break; }
+ // Nothing clears: keep whichever candidate sees furthest into the
+ // scene, so the shot degrades toward the most open direction.
+ if (v.hit > bestGap) { bestGap = v.hit; pos = p; }
+ }
+ return {
+ name,
+ position: [pos.x, pos.y, pos.z],
+ lookAt: [center.x, center.y, center.z],
+ fov,
+ };
+}
+
+/**
+ * Turn an object so its own forward axis points at a target.
+ *
+ * @param {THREE.Object3D} obj
+ * @param {THREE.Vector3|number[]} target World point to face.
+ * @param {string} [forward] The asset's forward as reported by
+ * assets_api.json ('+X' | '-X' | '+Z' | '-Z'); defaults to '-Z'.
+ * @returns {THREE.Object3D} obj
+ */
+export function faceToward(obj, target, forward) {
+ const p = target instanceof THREE.Vector3
+ ? target : new THREE.Vector3(...target);
+ _t.subVectors(p, obj.position);
+ _t.y = 0;
+ if (_t.lengthSq() < 1e-9) return obj;
+ return alignAlong(obj, _t, forward);
+}
+
+/**
+ * Turn an object so its forward axis runs along a direction — pass a
+ * route tangent, not a guessed angle (backwards vehicles came from
+ * guessed yaws).
+ *
+ * @param {THREE.Object3D} obj
+ * @param {THREE.Vector3|number[]} dir Direction of travel (y ignored).
+ * @param {string} [forward] Asset forward from assets_api.json.
+ * @returns {THREE.Object3D} obj
+ */
+export function alignAlong(obj, dir, forward) {
+ const d = dir instanceof THREE.Vector3
+ ? dir.clone() : new THREE.Vector3(...dir);
+ d.y = 0;
+ if (d.lengthSq() < 1e-9) return obj;
+ d.normalize();
+ const f = fwdVec(forward);
+ // Yaw that takes the asset's own forward onto d.
+ obj.rotation.y = Math.atan2(d.x, d.z) - Math.atan2(f.x, f.z);
+ return obj;
+}
+
+/**
+ * Face an object the same way as the thing it sits on or in — a
+ * person must look the way the chair looks, not AT the chair (the
+ * classic 180-degree seating error).
+ *
+ * @param {THREE.Object3D} obj The figure being seated.
+ * @param {THREE.Object3D} seatObj The chair/bench/stool.
+ * @param {string} [forward] The figure's forward from assets_api.json.
+ * @param {string} [seatForward] The seat's forward from assets_api.json.
+ * @returns {THREE.Object3D} obj
+ */
+export function matchFacing(obj, seatObj, forward, seatForward) {
+ const f = fwdVec(seatForward).applyEuler(
+ new THREE.Euler(0, seatObj.rotation.y, 0));
+ return alignAlong(obj, f, forward);
+}
+
+/**
+ * Sample a route as a closed or open path and walk objects along it.
+ *
+ * Returns positions AND tangents, so callers cannot place a vehicle
+ * without also having the direction it should face.
+ *
+ * A closed path divides into n equal arcs (the last sample is one arc
+ * short of the start, which is where it belongs). An OPEN path spans
+ * end to end — n samples, n-1 gaps: dividing by n instead left the row
+ * a whole gap short of its own last waypoint (6 posts over a 12 m quay
+ * stopped at x = 10, and the missing post is visible in the frame).
+ *
+ * @param {number[][]} points Control points [[x,y,z], ...].
+ * @param {number} n How many samples.
+ * @param {object} [opts] `closed` (default true).
+ * @returns {Array<{position: THREE.Vector3, tangent: THREE.Vector3}>}
+ */
+export function alongPath(points, n, opts = {}) {
+ const closed = opts.closed !== false;
+ const curve = new THREE.CatmullRomCurve3(
+ points.map((p) => new THREE.Vector3(...p)), closed);
+ const out = [];
+ const span = closed ? n : Math.max(1, n - 1);
+ for (let i = 0; i < n; i++) {
+ const t = i / span;
+ out.push({
+ position: curve.getPointAt(t),
+ tangent: curve.getTangentAt(t).setY(0).normalize(),
+ });
+ }
+ return out;
+}
+
+/**
+ * A teleport-free, dt-free path mover — `alongPath()`'s animated twin.
+ * The pose is a pure function of absolute `t`: no internal state, no
+ * `+=` drift, a closed loop wraps continuously by construction, and
+ * an open path ping-pongs instead of the modulo jump to its start.
+ *
+ * @param {number[][]|THREE.Vector3[]} points Control points.
+ * @param {object} [opts] `closed` (default true; false ping-pongs),
+ * `speed` metres per second (default 1), `forward` the asset's
+ * forward from assets_api.json, `wheels` array of `{node, radius}`
+ * rotated by arcDistance/radius so wheels roll exactly the ground
+ * they cover, `lane` signed metres of sideways offset (positive =
+ * left of travel; a ping-pong return leg flips sides, so a two-way
+ * path keeps its directions apart), `phase` 0..1 head start along
+ * the path. `lane`/`phase` are pure per-walker constants — several
+ * walkers may share one path without ever meeting, and `crowdOn()`
+ * does that assignment arithmetic for a whole crowd. `avoid` the
+ * scene (or an array of roots): the path is re-projected clear of
+ * furniture-scale solids at build time — pass it whenever a route
+ * crosses furnished space; `clearance` kept margin in metres
+ * (default 0.45).
+ * @returns {{length: number, curve: THREE.CatmullRomCurve3,
+ * poseAt: function}} `poseAt(t, obj, over)` places, orients and
+ * rolls `obj` at absolute time `t` and returns it; without `obj` it
+ * returns `{position, tangent, u}`. `over` is an optional per-call
+ * `{lane, phase}` override — how `crowdOn()` walks many figures on
+ * one shared curve.
+ */
+/**
+ * Collect furniture-scale obstacle boxes under `avoid` — the SAME
+ * filter the renderer's mover-through-solid instrument uses, so what
+ * the path avoids and what the instrument flags stay one definition.
+ * Buildings are not obstacles (a covered lane sits INSIDE its bbox).
+ */
+function obstacleBoxes(avoid) {
+ const solids = [];
+ const roots = Array.isArray(avoid) ? avoid : [avoid];
+ for (const root of roots) {
+ if (!root || !root.traverse) continue;
+ if (root.updateMatrixWorld) root.updateMatrixWorld(true);
+ root.traverse((o) => {
+ if (!o.isMesh || solids.length >= 3000) return;
+ const nm = (o.name || (o.parent && o.parent.name) || '');
+ if (/ground|floor|terrain|road|path|water|sky|dome|wall|roof|ceiling/i
+ .test(nm)) return;
+ const b = new THREE.Box3().setFromObject(o);
+ if (b.isEmpty()) return;
+ const sx = b.max.x - b.min.x;
+ const sy = b.max.y - b.min.y;
+ const sz = b.max.z - b.min.z;
+ // Height alone is not architecture: fountains/columns/statues
+ // are tall AND collide — the footprint caps below are what
+ // separate an obstacle from a building.
+ if (sy < 0.3 || sy > 14) return;
+ if (Math.max(sx, sz) > 12 || sx * sz > 40) return;
+ if (Math.min(sx, sz) < 0.05) return;
+ solids.push(b);
+ });
+ }
+ return solids;
+}
+
+/** Push a point out of every expanded box via the cheapest face. */
+function pushClear(p, solids, clearance) {
+ for (let iter = 0; iter < 3; iter++) {
+ let moved = false;
+ for (const b of solids) {
+ if (p.x < b.min.x - clearance || p.x > b.max.x + clearance ||
+ p.z < b.min.z - clearance || p.z > b.max.z + clearance) {
+ continue;
+ }
+ if (b.min.y > p.y + 1.2 || b.max.y < p.y - 1.2) continue;
+ const dxMin = p.x - (b.min.x - clearance);
+ const dxMax = (b.max.x + clearance) - p.x;
+ const dzMin = p.z - (b.min.z - clearance);
+ const dzMax = (b.max.z + clearance) - p.z;
+ const m = Math.min(dxMin, dxMax, dzMin, dzMax);
+ if (m === dxMin) p.x = b.min.x - clearance;
+ else if (m === dxMax) p.x = b.max.x + clearance;
+ else if (m === dzMin) p.z = b.min.z - clearance;
+ else p.z = b.max.z + clearance;
+ moved = true;
+ }
+ if (!moved) break;
+ }
+ return p;
+}
+
+/**
+ * Densify a path to ~0.75 m samples and push every blocked sample
+ * clear, so a leg that CROSSES a stall mid-segment reroutes around
+ * it — waypoint-only checks miss exactly that case.
+ */
+function clearPath(pts, solids, clearance, closed) {
+ if (!solids.length || pts.length < 2) return pts;
+ const out = [];
+ const last = closed ? pts.length : pts.length - 1;
+ for (let i = 0; i < last; i++) {
+ const A = pts[i];
+ const B = pts[(i + 1) % pts.length];
+ const steps = Math.max(1, Math.ceil(A.distanceTo(B) / 0.75));
+ for (let k = 0; k < steps; k++) {
+ out.push(pushClear(A.clone().lerp(B, k / steps), solids, clearance));
+ }
+ }
+ if (!closed) out.push(pushClear(pts[pts.length - 1].clone(),
+ solids, clearance));
+ return out;
+}
+
+export function route(points, opts = {}) {
+ const closed = opts.closed !== false;
+ const speed = opts.speed === undefined ? 1 : opts.speed;
+ const lane0 = opts.lane === undefined ? 0 : opts.lane;
+ const phase0 = opts.phase === undefined ? 0 : opts.phase;
+ const wheels = opts.wheels || [];
+ let pts = points.map((p) => (p instanceof THREE.Vector3
+ ? p.clone() : new THREE.Vector3(...p)));
+ // `avoid: scene` makes furniture-clearance CONSTRUCTIVE: the path
+ // is re-projected off solids at build time, so a walker cannot
+ // stride through a stall whatever coordinates were authored.
+ if (opts.avoid) {
+ pts = clearPath(pts, obstacleBoxes(opts.avoid),
+ opts.clearance === undefined ? 0.45 : opts.clearance,
+ closed);
+ }
+ const curve = new THREE.CatmullRomCurve3(pts, closed);
+ const length = curve.getLength();
+ const poseAt = (t, obj, over) => {
+ const lane = over && over.lane !== undefined ? over.lane : lane0;
+ const phase = over && over.phase !== undefined ? over.phase : phase0;
+ const s = t * speed + phase * length;
+ let u = 0;
+ let dirSign = 1;
+ if (length > 1e-9) {
+ if (closed) {
+ u = ((s / length) % 1 + 1) % 1;
+ } else {
+ // Ping-pong: out along the path, back along the path — never
+ // the open-path modulo jump from the end to the start.
+ const p = ((s / length) % 2 + 2) % 2;
+ if (p <= 1) {
+ u = p;
+ } else {
+ u = 2 - p;
+ dirSign = -1;
+ }
+ }
+ }
+ const position = curve.getPointAt(u);
+ const tangent = curve.getTangentAt(u).multiplyScalar(dirSign);
+ if (lane) {
+ // Sideways offset in the horizontal plane, positive = left of
+ // travel; built from the dirSign-flipped tangent so a ping-pong
+ // path returns on its other side (two-way traffic self-separates).
+ const h = Math.hypot(tangent.x, tangent.z);
+ if (h > 1e-9) {
+ position.x += lane * (tangent.z / h);
+ position.z += lane * (-tangent.x / h);
+ }
+ }
+ if (!obj) return { position, tangent, u };
+ obj.position.copy(position);
+ alignAlong(obj, tangent, opts.forward);
+ // Roll from the arc distance actually COVERED, which on a ping-pong
+ // return leg decreases: `s` only ever grows, so a cart driving back
+ // along an open path spun its wheels forward while reversing
+ // (measured -0.4 m of travel against +0.8 rad of wheel, 2026-09-01).
+ // A closed loop keeps `s` — u wraps, and wrapping u would snap the
+ // wheel by length/radius once a lap.
+ const rolled = closed ? s : u * length;
+ for (const w of wheels) {
+ w.node.rotation.x = rolled / w.radius;
+ }
+ return obj;
+ };
+ return { length, curve, poseAt };
+}
+
+/**
+ * Give every figure on a shared route its own lane and phase, so a
+ * crowd can never bunch into one body. The guarantee is arithmetic,
+ * not a solver: one shared speed + equal phase slots keep the
+ * arc-length gap >= `spacing` forever (golden-ratio jitter is bounded
+ * by 80% of the slot slack, so it breaks the parade look without
+ * touching the bound); overflow opens parallel lanes at `laneStep`.
+ *
+ * @param {{length: number, poseAt: function}} routeObj From `route()`
+ * — one shared speed per route is what makes the gap permanent (two
+ * speeds on one path collide within seconds).
+ * @param {THREE.Object3D[]} figures The walkers, one entry each.
+ * @param {object} [opts] `spacing` minimum along-path gap in metres
+ * (default 2 — walker body plus clear air), `laneStep` sideways gap
+ * between overflow lanes (default 0.7 — shoulder width + margin).
+ * @returns {{assignments: Array<{lane: number, phase: number}>,
+ * tick: function}} `tick(t)` poses every figure at absolute time
+ * `t` (pure — call it from the scene's `tick`); `assignments` is
+ * the per-figure `{lane, phase}` in `figures` order, overriding the
+ * route's own `lane`/`phase` opts.
+ */
+export function crowdOn(routeObj, figures, opts = {}) {
+ const spacing = opts.spacing === undefined ? 2 : opts.spacing;
+ const laneStep = opts.laneStep === undefined ? 0.7 : opts.laneStep;
+ const n = figures.length;
+ const cap = Math.max(1, Math.floor(routeObj.length / spacing));
+ const lanes = Math.max(1, Math.ceil(n / cap));
+ const per = Math.ceil(n / lanes);
+ const assignments = [];
+ for (let i = 0; i < n; i++) {
+ const k = Math.floor(i / per); // lane index
+ const j = i - k * per; // slot within the lane
+ const m = Math.min(per, n - k * per); // walkers in this lane
+ const slot = 1 / m;
+ const spacingU = Math.min(spacing / routeObj.length, slot);
+ // Jitter spends at most 80% of the slack, so the consecutive gap
+ // slot - 2*jit stays >= spacingU: the bound survives the jitter.
+ const jit = 0.4 * (slot - spacingU);
+ const eps = (((j * 0.618034) % 1) - 0.5) * 2 * jit;
+ assignments.push({
+ lane: (k - (lanes - 1) / 2) * laneStep,
+ phase: k * (slot / lanes) + j * slot + eps,
+ });
+ }
+ return {
+ assignments,
+ tick(t) {
+ for (let i = 0; i < n; i++) {
+ routeObj.poseAt(t, figures[i], assignments[i]);
+ }
+ return figures;
+ },
+ };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js
new file mode 100644
index 00000000..c317f938
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/rain.js
@@ -0,0 +1,812 @@
+/**
+ * Rain: falling streaks, impact splashes on the surfaces the rain
+ * actually hits, a wet-material conversion and a rippling puddle.
+ * DOM-free (DataTexture only), seeded through mulberry32, no RTT and
+ * 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
+ * at the scene ROOT and drive them from `tick`: `obj.userData.update(t)`.
+ */
+
+import * as THREE from 'three';
+import { mulberry32, fbm2, noiseDataTexture } from './noise.js';
+import { makeShaderMaterial, keepOutOfDepthPasses } from './shader.js';
+
+const _UP = new THREE.Vector3(0, 1, 0);
+
+/**
+ * The scene's own air, read where every shader here already has it: the
+ * fog uniforms three refreshes each frame. Water is colourless — streak,
+ * ring and crown all show you the sky — so a hardcoded tint puts
+ * steel-blue rain in a golden dusk. `rainAirHue` takes the air's HUE at
+ * the caller's own luminance; `rainAirLit` its brightness, on a fourth
+ * root (a night scene is ~140x darker in linear light, and a plain
+ * multiply would delete the effect rather than dim it). `fogColor`
+ * exists only under USE_FOG: no fog, no change.
+ */
+const _AIR_GLSL = [
+ 'vec3 rainAirHue(vec3 c, float k) {',
+ '#ifdef USE_FOG',
+ ' float l = max(dot(fogColor, vec3(0.2126, 0.7152, 0.0722)), 1e-4);',
+ ' return mix(c, c * (fogColor / l), k);',
+ '#else',
+ ' return c;',
+ '#endif',
+ '}',
+ 'float rainAirLit(float dim) {',
+ '#ifdef USE_FOG',
+ ' float a = max(dot(fogColor, vec3(0.2126, 0.7152, 0.0722)), 0.0);',
+ ' return mix(dim, 1.0, clamp(pow(a, 0.25), 0.0, 1.0));',
+ '#else',
+ ' return 1.0;',
+ '#endif',
+ '}',
+].join('\n');
+
+/**
+ * Build the instanced quad geometry every effect here draws with.
+ *
+ * `position` is deliberately ZERO and the corners travel in `aCorner`:
+ * the render chain's GTAO pass re-draws the scene with an override
+ * material that ignores these shaders, and a real unit quad then
+ * printed a black AO slab at the world origin.
+ *
+ * @param {number} count Instances.
+ * @returns {THREE.InstancedBufferGeometry} Degenerate quad with
+ * `aCorner` + `uv`, instanceCount set.
+ */
+function _quads(count) {
+ const geo = new THREE.PlaneGeometry(1, 1);
+ const verts = geo.attributes.position.count;
+ const inst = new THREE.InstancedBufferGeometry();
+ inst.index = geo.index;
+ inst.setAttribute('position',
+ new THREE.BufferAttribute(new Float32Array(verts * 3), 3));
+ inst.setAttribute('aCorner', geo.attributes.position);
+ inst.attributes.uv = geo.attributes.uv;
+ inst.instanceCount = count;
+ return inst;
+}
+
+/**
+ * Falling rain as ONE instanced mesh of camera-facing streaks.
+ *
+ * Each instance is a quad stretched along the fall vector and rolled
+ * to face the camera, which is what makes rain legible in a still: a
+ * frozen drop is a point, a frozen STREAK is rain. The field wraps
+ * modulo a box that follows the camera, so any authored or orbit
+ * camera sits inside the weather without the scene knowing where it is.
+ *
+ * @param {object} [opts]
+ * `seed` (default 5) mulberry32 seed;
+ * `count` (default 7000) streaks — one draw call regardless. The
+ * box is small on purpose: density where the camera is, not a
+ * thin sprinkle across a stadium;
+ * `radius` (default 16) half-extent in X/Z of the wrap box in
+ * metres — streaks fade out over its last 45%;
+ * `height` (default 18) its Y extent;
+ * `speed` (default 14) fall speed in m/s (drives lean and drift);
+ * `length` (default 0.6) streak length in metres — this is the
+ * "exposure", the single strongest still-frame knob;
+ * `width` (default 0.014) streak width in metres;
+ * `wind` (default [1.4, 0]) horizontal drift [x, z] in m/s, which
+ * also tilts the streaks off vertical;
+ * `color` (default 0xdbe6f2) streak tint at the HEAD of the streak;
+ * `rimColor` (default 0x0b111a) the tail tint — that dark trail is
+ * the only thing that prints rain on a sky the tone map has already
+ * pushed to 0.94;
+ * `air` (default 0.55) how far both tints follow the scene's fog hue
+ * (0 keeps `color` exactly): a golden dusk gets golden rain;
+ * `opacity` (default 0.42) peak alpha before distance fade;
+ * `follow` (default true) wrap the box around the camera; false pins
+ * it to `center`;
+ * `center` (default [0, height / 2, 0]) box centre when not following.
+ * @returns {THREE.Mesh} Mesh named 'Rainfall', transparent and
+ * non-shadowing, with `userData.update(t)` advancing the fall.
+ */
+export function makeRain(opts = {}) {
+ const seed = opts.seed === undefined ? 5 : opts.seed;
+ const count = opts.count === undefined ? 7000 : opts.count;
+ const radius = opts.radius === undefined ? 16 : opts.radius;
+ const height = opts.height === undefined ? 18 : opts.height;
+ const speed = opts.speed === undefined ? 14 : opts.speed;
+ const length = opts.length === undefined ? 0.6 : opts.length;
+ const width = opts.width === undefined ? 0.014 : opts.width;
+ const wind = opts.wind || [1.4, 0];
+ const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;
+ const follow = opts.follow === false ? 0 : 1;
+ const center = opts.center || [0, height * 0.5, 0];
+
+ const rand = mulberry32(seed);
+ const inst = _quads(count);
+ const off = new Float32Array(count * 3);
+ const ext = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ off[i * 3] = (rand() - 0.5) * 2 * radius;
+ off[i * 3 + 1] = rand() * height;
+ off[i * 3 + 2] = (rand() - 0.5) * 2 * radius;
+ ext[i * 3] = 0.55 + rand() * 0.6; // length scale
+ ext[i * 3 + 1] = 0.45 + rand() * 0.55; // brightness
+ // Hue jitter: a field of one tint is a hatch pattern.
+ ext[i * 3 + 2] = rand();
+ }
+ inst.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
+ inst.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 3));
+
+ const mat = makeShaderMaterial({
+ name: 'Rainfall',
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ uniforms: {
+ // Declared and bound EXPLICITLY here and in both splash shaders:
+ // shader.js injects both, but glsl_audit.mjs reads the MODULE's
+ // source, and uTime undeclared there is two hard ERRORS in the
+ // scene build's preflight — every scene importing this file.
+ uTime: { value: 0 },
+ uVel: { value: new THREE.Vector3(wind[0], -speed, wind[1]) },
+ uBox: { value: new THREE.Vector3(radius * 2, height, radius * 2) },
+ uCenter: { value: new THREE.Vector3(...center) },
+ uFollow: { value: follow },
+ uLen: { value: length },
+ uWidth: { value: width },
+ uFar: { value: radius },
+ uColor: {
+ value: new THREE.Color(
+ opts.color === undefined ? 0xdbe6f2 : opts.color),
+ },
+ uRim: {
+ value: new THREE.Color(
+ opts.rimColor === undefined ? 0x0b111a : opts.rimColor),
+ },
+ uAir: { value: opts.air === undefined ? 0.55 : opts.air },
+ uOpacity: { value: opacity },
+ },
+ varyings: 'varying vec2 vUv; varying float vFade; varying float vJit;',
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff; attribute vec3 iExtra;',
+ 'uniform float uTime;',
+ 'uniform vec3 uVel; uniform vec3 uBox;',
+ 'uniform vec3 uCenter; uniform float uFollow;',
+ 'uniform float uLen; uniform float uWidth; uniform float uFar;',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv; vJit = iExtra.z;',
+ ' vec3 anchor = mix(uCenter, cameraPosition, uFollow);',
+ // Wrap the whole field into a box centred on the anchor: rain is
+ // everywhere the camera is, for a fixed instance budget.
+ ' vec3 p = mod(iOff + uVel * uTime - anchor + uBox * 0.5, uBox)',
+ ' - uBox * 0.5 + anchor;',
+ ' vec3 axis = normalize(uVel);',
+ ' vec3 toCam = p - cameraPosition;',
+ ' float dist = length(toCam);',
+ ' vec3 side = cross(axis, toCam / max(dist, 1e-4));',
+ ' float sl = length(side);',
+ ' side = sl > 1e-4 ? side / sl : vec3(1.0, 0.0, 0.0);',
+ ' transformed = p + axis * (aCorner.y * uLen * iExtra.x)',
+ ' + side * (aCorner.x * uWidth);',
+ ' vFade = iExtra.y * smoothstep(1.0, 6.0, dist)',
+ ' * (1.0 - smoothstep(uFar * 0.55, uFar, dist));',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform vec3 uColor; uniform vec3 uRim;',
+ 'uniform float uOpacity; uniform float uAir;',
+ _AIR_GLSL,
+ ].join('\n'),
+ fragmentMain: [
+ ' float core = smoothstep(0.0, 0.55,',
+ ' 1.0 - abs(vUv.x - 0.5) * 2.0);',
+ // v = 1 is the leading end (the axis points down): brightest
+ // there, tapered at both tips so the quad never reads as a bar.
+ ' float ends = smoothstep(0.0, 0.28, vUv.y)',
+ ' * (1.0 - smoothstep(0.70, 1.0, vUv.y));',
+ // HEAD BRIGHT, TAIL DARK — along the LENGTH: a streak is ~2 px
+ // wide, so a split across its width averages back to one tone in
+ // a single pixel. The head prints on anything dark, the tail is
+ // all that prints on a 0.94 sky (3/255 pale, 5-86 dark).
+ ' vec3 tint = uColor * mix(vec3(0.90, 0.97, 1.12),',
+ ' vec3(1.10, 1.00, 0.88), vJit);',
+ ' vec3 c = mix(rainAirHue(uRim, uAir), rainAirHue(tint, uAir),',
+ ' smoothstep(0.20, 0.92, vUv.y));',
+ ' float a = core * ends * (0.62 + 0.38 * vUv.y)',
+ ' * vFade * uOpacity;',
+ // A 0.6 m ramp bands into flat segments on a clean sky; dither.
+ ' a *= 0.97 + 0.06 * astraHash21(gl_FragCoord.xy);',
+ ' if (a < 0.004) discard;',
+ ' gl_FragColor = vec4(c, a);',
+ ].join('\n'),
+ });
+
+ const mesh = new THREE.Mesh(inst, mat);
+ mesh.name = 'Rainfall';
+ mesh.frustumCulled = false; // positions live in the shader
+ mesh.renderOrder = 4; // in front of splashes and puddles
+ mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
+ return keepOutOfDepthPasses(mesh);
+}
+
+/**
+ * Bake the splash crown alpha map — a starburst of thin rays rising
+ * from the bottom-centre impact point, with droplets at their tips.
+ *
+ * @param {number} [size] Cell width and height in px (default 64).
+ * @param {number} [variants] Grid side of an ATLAS of DIFFERENT crowns
+ * (default 1 — one crown, the whole texture). 2 bakes a 2x2 sheet of
+ * four, each with its own ray count, angles and rim shape;
+ * `makeSplashes` picks one per impact, which is what stops a field of
+ * 500 splashes reading as one stamp repeated 500 times. Every cell is
+ * transparent at its own border, so mips do not bleed across cells.
+ * @returns {THREE.DataTexture} White RGB, crowns in alpha,
+ * `size * variants` square.
+ */
+export function splashTexture(size = 64, variants = 1) {
+ const n = Math.max(1, Math.round(variants));
+ const W = size * n;
+ const data = new Uint8Array(W * W * 4);
+ for (let cell = 0; cell < n * n; cell++) {
+ const rand = mulberry32(31 + cell * 977);
+ const rays = [];
+ // 6..9 rays: the count is half of what makes two crowns look unlike.
+ const nRays = 6 + Math.floor(rand() * 4);
+ for (let k = 0; k < nRays; k++) {
+ const a = Math.PI * (0.2 + 0.6 * (k + rand() * 0.6) / nRays);
+ rays.push([Math.cos(a), Math.sin(a), 0.34 + rand() * 0.32]);
+ }
+ const rw = 0.30 + rand() * 0.09; // rim half-width
+ const rh = 0.16 + rand() * 0.06; // rim height
+ const cx0 = (cell % n) * size;
+ const cy0 = Math.floor(cell / n) * size;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const px = (x / size - 0.5) * 2;
+ const py = y / size;
+ // The crown itself: an elliptical rim of water thrown up around
+ // the impact. Without it the rays read as a firework, not a
+ // drop.
+ const e = Math.hypot(px / rw, py / rh);
+ let a = 0.85 * Math.exp(-((e - 1) ** 2) / 0.05)
+ * Math.min(1, py / 0.03);
+ for (const [dx, dy, len] of rays) {
+ const t = px * dx + py * dy;
+ if (t <= 0 || t >= len) continue;
+ const d = Math.abs(px * dy - py * dx);
+ const w = 0.032 * (1 - 0.5 * t / len);
+ const ray = 0.85 * Math.exp(-(d * d) / (w * w)) * (1 - t / len);
+ const tip = 0.8 * Math.exp(
+ -((px - dx * len) ** 2 + (py - dy * len) ** 2) / 0.0009);
+ a = Math.max(a, ray + tip);
+ }
+ // The whole crown rises OUT of the surface, rays included: only
+ // the rim faded in at the contact line, so the bottom pixel row
+ // held alpha 34 under the impact — a hard stub, and on an atlas
+ // a mip-level leak into the cell below.
+ const i = ((cy0 + y) * W + cx0 + x) * 4;
+ data[i] = data[i + 1] = data[i + 2] = 255;
+ data[i + 3] = Math.round(
+ 255 * Math.max(0, Math.min(1, a * Math.min(1, py / 0.05))));
+ }
+ }
+ }
+ const tex = new THREE.DataTexture(data, W, W, THREE.RGBAFormat);
+ // DataTexture defaults to NearestFilter with no mipmaps; a 64px crown
+ // seen 20 m away then stair-steps into a cluster of hard blocks.
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+ tex.anisotropy = 8;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+/**
+ * Sample impact points: raycast straight down onto real surfaces and
+ * fall back to the ground plane where nothing is in the way.
+ *
+ * @param {object} opts Same surface/area options as `makeSplashes`.
+ * @param {() => number} rand Seeded PRNG.
+ * @returns {Array<{p: THREE.Vector3, n: THREE.Vector3}>} World-space
+ * points already lifted off their surface, with world normals.
+ */
+function _impactPoints(opts, rand) {
+ // A number is truthy, so `area: 12` used to read x/w as
+ // undefined and every impact landed at NaN — 520 of 780
+ // offsets non-finite, with 260 instances still drawn.
+ const area = typeof opts.area === 'number'
+ ? { x: 0, z: 0, w: opts.area, d: opts.area }
+ : (opts.area || { x: 0, z: 0, w: 40, d: 40 });
+ const y = opts.y === undefined ? 0 : opts.y;
+ const ground = opts.ground !== false;
+ const surfaces = opts.surfaces || [];
+ const count = opts.count === undefined ? 260 : opts.count;
+ const lift = opts.lift === undefined ? 0.012 : opts.lift;
+ const bias = opts.surfaceBias === undefined ? 0.5 : opts.surfaceBias;
+ const minNy = Math.cos(THREE.MathUtils.degToRad(
+ opts.maxSlopeDeg === undefined ? 65 : opts.maxSlopeDeg));
+
+ const box = new THREE.Box3();
+ for (const s of surfaces) {
+ s.updateWorldMatrix(true, true);
+ box.expandByObject(s);
+ }
+ const hasBox = surfaces.length > 0 && !box.isEmpty();
+ const top = hasBox ? Math.max(box.max.y, y) + 1 : y + 1;
+
+ const ray = new THREE.Raycaster(
+ new THREE.Vector3(), new THREE.Vector3(0, -1, 0));
+ const nm = new THREE.Matrix3();
+ const out = [];
+ // Rejections (steep faces, undersides) re-sample; the budget stops a
+ // scene whose only "surface" is a wall from looping forever.
+ const attempts = Math.max(1, count) * 8;
+ for (let a = 0; a < attempts && out.length < count; a++) {
+ let x, z;
+ // Aim a share of the samples INSIDE the surfaces' footprint, or a
+ // car in a 40 m plaza collects three drops and reads as dry.
+ if (hasBox && rand() < bias) {
+ x = box.min.x + rand() * (box.max.x - box.min.x);
+ z = box.min.z + rand() * (box.max.z - box.min.z);
+ } else {
+ x = area.x + (rand() - 0.5) * area.w;
+ z = area.z + (rand() - 0.5) * area.d;
+ }
+ let hit = null;
+ if (surfaces.length) {
+ ray.ray.origin.set(x, top, z);
+ for (const h of ray.intersectObjects(surfaces, true)) {
+ if (h.face) { hit = h; break; }
+ }
+ }
+ if (hit) {
+ nm.getNormalMatrix(hit.object.matrixWorld);
+ const n = hit.face.normal.clone().applyMatrix3(nm).normalize();
+ if (n.y < minNy) continue;
+ out.push({ p: hit.point.clone().addScaledVector(n, lift), n });
+ } else if (ground) {
+ out.push({ p: new THREE.Vector3(x, y + lift, z), n: _UP.clone() });
+ }
+ }
+ return out;
+}
+
+/**
+ * Splashes where the rain lands: an expanding ring flat on each
+ * surface plus a crown of spray standing up off it.
+ *
+ * Pass `surfaces` and the impacts are RAYCAST onto them, so drops land
+ * on the car roof, the bonnet and the umbrella at their real heights
+ * and tilts; everything the rays miss falls through to the `y` ground
+ * plane. Per-instance phases are spread over the whole cycle, so one
+ * frozen frame shows rings at every radius — that is what reads as
+ * continuous rainfall rather than one synchronized pulse.
+ *
+ * @param {object} [opts]
+ * `seed` (default 11) mulberry32 seed;
+ * `count` (default 260) impacts;
+ * `surfaces` (default none) meshes/groups to raycast onto;
+ * `surfaceBias` (default 0.5) share of samples aimed inside the
+ * surfaces' footprint instead of `area`;
+ * `area` (default `{x: 0, z: 0, w: 40, d: 40}`) ground sampling rect;
+ * `y` (default 0) ground plane height;
+ * `ground` (default true) let misses land on that plane;
+ * `maxSlopeDeg` (default 65) reject faces tilted past this — rain
+ * does not splash on walls or undersides;
+ * `size` (default 0.26) ring diameter in metres at full expansion;
+ * `rate` (default 2.2) splash cycles per second;
+ * `color` (default 0xe6eef7) ring and crown tint — thrown water is
+ * colourless, so it takes the scene's fog hue and dims with it;
+ * `air` (default 0.6) how far the tint follows that hue;
+ * `dim` (default 0.4) what it keeps in a black scene, on a fourth
+ * root — half, not 1/140th (it had white-hot crowns before);
+ * `variants` (default 2) grid side of the crown atlas (4 crowns),
+ * mirrored per instance for 8 apparent stamps;
+ * `opacity` (default 0.6) peak ring alpha;
+ * `crowns` (default true) add the upright spray billboards;
+ * `crownScale` (default 1) multiplies crown size relative to `size`;
+ * `lift` (default 0.012) metres pushed along the normal (z-fighting).
+ * @returns {THREE.Group} Group named 'RainSplashes' holding
+ * 'SplashRings' (+ 'SplashCrowns'), world-space — add it at the
+ * scene ROOT — with `userData.update(t)` driving both.
+ */
+export function makeSplashes(opts = {}) {
+ const rand = mulberry32(opts.seed === undefined ? 11 : opts.seed);
+ const size = opts.size === undefined ? 0.26 : opts.size;
+ const rate = opts.rate === undefined ? 2.2 : opts.rate;
+ const opacity = opts.opacity === undefined ? 0.6 : opts.opacity;
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xe6eef7 : opts.color);
+ const group = new THREE.Group();
+ group.name = 'RainSplashes';
+
+ const pts = _impactPoints(opts, rand);
+ if (!pts.length) {
+ group.userData.update = () => {};
+ return group;
+ }
+
+ const n = pts.length;
+ const variants = Math.max(1, Math.round(
+ opts.variants === undefined ? 2 : opts.variants));
+ const off = new Float32Array(n * 3);
+ const nrm = new Float32Array(n * 3);
+ const tan = new Float32Array(n * 3);
+ const ext = new Float32Array(n * 4);
+ const t = new THREE.Vector3();
+ pts.forEach((q, i) => {
+ off[i * 3] = q.p.x; off[i * 3 + 1] = q.p.y; off[i * 3 + 2] = q.p.z;
+ nrm[i * 3] = q.n.x; nrm[i * 3 + 1] = q.n.y; nrm[i * 3 + 2] = q.n.z;
+ t.set(0, 0, 1).cross(q.n);
+ if (t.lengthSq() < 1e-8) t.set(1, 0, 0);
+ t.normalize();
+ tan[i * 3] = t.x; tan[i * 3 + 1] = t.y; tan[i * 3 + 2] = t.z;
+ ext[i * 4] = size * (0.65 + rand() * 0.7);
+ ext[i * 4 + 1] = rand(); // phase: spread so a still shows all radii
+ // Hue and the crown's mirror flip; the cell is drawn separately so
+ // the two never correlate into a pattern.
+ ext[i * 4 + 2] = rand();
+ ext[i * 4 + 3] = Math.floor(rand() * variants * variants);
+ });
+ const attrs = (geom) => {
+ geom.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
+ geom.setAttribute('iNrm', new THREE.InstancedBufferAttribute(nrm, 3));
+ geom.setAttribute('iTan', new THREE.InstancedBufferAttribute(tan, 3));
+ geom.setAttribute('iExtra',
+ new THREE.InstancedBufferAttribute(ext, 4));
+ return geom;
+ };
+ const air = opts.air === undefined ? 0.6 : opts.air;
+ const dim = opts.dim === undefined ? 0.4 : opts.dim;
+
+ const ringMat = makeShaderMaterial({
+ name: 'SplashRings',
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ uniforms: {
+ uTime: { value: 0 }, // see makeRain: the audit reads this file
+ uRate: { value: rate },
+ uColor: { value: color },
+ uOpacity: { value: opacity },
+ uAir: { value: air },
+ uDim: { value: dim },
+ },
+ varyings: [
+ 'varying vec2 vUv; varying float vPhase; varying float vJit;',
+ ].join('\n'),
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff; attribute vec3 iNrm; attribute vec3 iTan;',
+ 'attribute vec4 iExtra;',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv; vPhase = iExtra.y; vJit = iExtra.z;',
+ ' vec3 b = cross(iNrm, iTan);',
+ ' transformed = iOff + iTan * (aCorner.x * iExtra.x)',
+ ' + b * (aCorner.y * iExtra.x);',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform float uTime; uniform float uRate;',
+ 'uniform vec3 uColor; uniform float uOpacity;',
+ 'uniform float uAir; uniform float uDim;',
+ _AIR_GLSL,
+ ].join('\n'),
+ fragmentMain: [
+ ' float r = length(vUv * 2.0 - 1.0);',
+ ' if (r > 1.0) discard;',
+ ' float k = fract(vPhase + uTime * uRate);',
+ // Two crests, the trailing one fainter: one lone circle reads as
+ // a decal, a pair reads as a wave leaving the impact.
+ ' float w = 0.09 + 0.15 * k;',
+ ' float f = (r - k) / w;',
+ ' float g = (r - k * 0.55) / (w * 0.8);',
+ ' float a = (exp(-f * f) + 0.45 * exp(-g * g))',
+ ' * (1.0 - k) * (1.0 - smoothstep(0.72, 1.0, r))',
+ ' * uOpacity;',
+ // Two gaussians on flat road band; a fraction of a step hides it.
+ ' a *= 0.96 + 0.08 * astraHash21(gl_FragCoord.xy);',
+ ' if (a < 0.004) discard;',
+ // A sheet of water lifting off the ground shows you the sky.
+ ' vec3 c = rainAirHue(uColor, uAir) * rainAirLit(uDim)',
+ ' * (0.88 + 0.24 * vJit);',
+ ' gl_FragColor = vec4(c, a);',
+ ].join('\n'),
+ });
+ const rings = new THREE.Mesh(attrs(_quads(n)), ringMat);
+ rings.name = 'SplashRings';
+ rings.frustumCulled = false;
+ rings.renderOrder = 2;
+ group.add(rings);
+
+ let crownMat = null;
+ if (opts.crowns !== false) {
+ crownMat = makeShaderMaterial({
+ name: 'SplashCrowns',
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ uniforms: {
+ uTime: { value: 0 }, // see makeRain
+ uRate: { value: rate },
+ uColor: { value: color },
+ uScale: {
+ value: (opts.crownScale === undefined ? 1 : opts.crownScale)
+ * 0.7,
+ },
+ uAtlas: { value: variants },
+ uAir: { value: air },
+ uDim: { value: dim },
+ map: { value: splashTexture(64, variants) },
+ },
+ varyings: [
+ 'varying vec2 vUv; varying float vK;',
+ 'varying float vJit; varying float vCell;',
+ ].join('\n'),
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff; attribute vec3 iNrm;',
+ 'attribute vec4 iExtra;',
+ 'uniform float uTime; uniform float uRate; uniform float uScale;',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv; vJit = iExtra.z; vCell = iExtra.w;',
+ ' float k = fract(iExtra.y + uTime * uRate);',
+ ' vK = k;',
+ // Crowns pop fast and settle: sqrt growth, so a frozen frame
+ // catches most of them already open rather than as specks.
+ ' float s = iExtra.x * uScale * (0.3 + 0.9 * sqrt(k));',
+ ' vec3 up = iNrm;',
+ ' vec3 view = normalize(iOff - cameraPosition);',
+ ' vec3 right = cross(up, view);',
+ ' float rl = length(right);',
+ ' right = rl > 1e-4 ? right / rl : vec3(1.0, 0.0, 0.0);',
+ ' transformed = iOff + right * (aCorner.x * s)',
+ ' + up * ((aCorner.y + 0.5) * s);',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform sampler2D map; uniform vec3 uColor;',
+ 'uniform float uAtlas; uniform float uAir; uniform float uDim;',
+ _AIR_GLSL,
+ ].join('\n'),
+ fragmentMain: [
+ // ONE stamp repeated 500 times is the tell of an instanced
+ // field, and a crown is a shape the eye knows. Mirror per
+ // instance, then pick an atlas crown: 4 x 2 handednesses.
+ ' vec2 cuv = vec2(mix(vUv.x, 1.0 - vUv.x, step(0.5, vJit)),',
+ ' vUv.y);',
+ ' float cell = floor(vCell + 0.5);',
+ ' vec2 g = vec2(mod(cell, uAtlas), floor(cell / uAtlas));',
+ ' float a = texture2D(map, (cuv + g) / uAtlas).a',
+ ' * pow(1.0 - vK, 1.6) * smoothstep(0.0, 0.06, vK);',
+ ' if (a < 0.01) discard;',
+ // Spray is water in the air: the sky's hue, the sky's light —
+ // left white it was the brightest thing in a night frame.
+ ' vec3 c = rainAirHue(uColor, uAir) * rainAirLit(uDim)',
+ ' * (0.86 + 0.28 * fract(vJit * 7.3));',
+ ' gl_FragColor = vec4(c, a);',
+ ].join('\n'),
+ });
+ const crowns = new THREE.Mesh(attrs(_quads(n)), crownMat);
+ crowns.name = 'SplashCrowns';
+ crowns.frustumCulled = false;
+ crowns.renderOrder = 3;
+ group.add(crowns);
+ }
+
+ group.userData.update = (t2) => {
+ ringMat.uniforms.uTime.value = t2;
+ if (crownMat) crownMat.uniforms.uTime.value = t2;
+ };
+ return keepOutOfDepthPasses(group);
+}
+
+/**
+ * Wet a material (or every material under an object) IN PLACE: darker
+ * albedo, near-mirror roughness, stronger environment reflection.
+ *
+ * That triple is what "it has been raining" looks like — a wet surface
+ * absorbs more light AND reflects the sky harder at once, so darkening
+ * alone just reads as a repaint. Mutates in place like
+ * `materials.weather()`, so a material SHARED with dry objects wets
+ * them too — clone first when that matters.
+ *
+ * @param {THREE.Material|THREE.Object3D} target Material, or an object
+ * whose meshes' materials are all wetted (each one once).
+ * @param {number} [amount] 0..1 soak, default 0.7.
+ * @param {object} [opts] `minRoughness` (default 0.1) the wettest a
+ * surface may get; `darken` (default 0.45) peak albedo loss;
+ * `envGain` (default 0.6) peak envMapIntensity boost — three scales
+ * the DIFFUSE irradiance with it too, so a big gain LIGHTS the object
+ * up: at 1.2 the wet car roof measured 0.613 against a 0.568 dry
+ * control and read as white plastic. Keep `(1 - darken) * (1 +
+ * envGain)` under 1; `roughFactor` (default 0.25) share of its own
+ * roughness a surface keeps — a soaked brick is a damp sheen, and one
+ * flat floor made brick, dirt and paint identical; `floor` (default
+ * 0.02) darkest albedo a soak may leave, in linear light (a wet tyre
+ * sat at 0.0006 of a night frame: a hole, not a surface).
+ * @returns {THREE.Material|THREE.Object3D} The same target.
+ */
+export function wetten(target, amount = 0.7, opts = {}) {
+ const k = Math.max(0, Math.min(1, amount));
+ const minRough = opts.minRoughness === undefined ? 0.1
+ : opts.minRoughness;
+ const darken = opts.darken === undefined ? 0.45 : opts.darken;
+ const envGain = opts.envGain === undefined ? 0.6 : opts.envGain;
+ const roughFactor = opts.roughFactor === undefined ? 0.25
+ : opts.roughFactor;
+ const floor = opts.floor === undefined ? 0.02 : opts.floor;
+
+ const wetOne = (mat) => {
+ if (!mat) return;
+ if (mat.color) {
+ mat.color.multiplyScalar(1 - darken * k);
+ // A film makes a colour READ deeper, not just darker: it kills
+ // the diffuse haze washing the pigment out. A scalar multiply
+ // alone is a neutral-density filter.
+ mat.color.offsetHSL(0, 0.06 * k, 0);
+ const m = Math.max(mat.color.r, mat.color.g, mat.color.b);
+ if (m > 1e-6 && m < floor) mat.color.multiplyScalar(floor / m);
+ }
+ if (typeof mat.roughness === 'number') {
+ const wet = Math.max(minRough, mat.roughness * roughFactor);
+ mat.roughness = mat.roughness + (wet - mat.roughness) * k;
+ }
+ if (typeof mat.envMapIntensity === 'number') {
+ mat.envMapIntensity *= 1 + envGain * k;
+ }
+ // Water fills the micro-relief it is sitting in.
+ if (typeof mat.bumpScale === 'number') mat.bumpScale *= 1 - 0.6 * k;
+ if (mat.isMeshPhysicalMaterial) {
+ mat.clearcoat = Math.max(mat.clearcoat || 0, k);
+ mat.clearcoatRoughness = Math.min(
+ mat.clearcoatRoughness === undefined ? 1 : mat.clearcoatRoughness,
+ 0.04 + 0.1 * (1 - k));
+ }
+ mat.needsUpdate = true;
+ };
+
+ if (target && target.isMaterial) {
+ wetOne(target);
+ return target;
+ }
+ if (target && target.isObject3D) {
+ const seen = new Set();
+ target.traverse((o) => {
+ if (!o.isMesh || !o.material) return;
+ for (const m of (Array.isArray(o.material) ? o.material
+ : [o.material])) {
+ if (m && !seen.has(m.uuid)) { seen.add(m.uuid); wetOne(m); }
+ }
+ });
+ }
+ return target;
+}
+
+/**
+ * Standing water with rain ripples — concentric wavefronts spreading
+ * from drops that keep landing in new places.
+ *
+ * The ripples are REAL vertex displacement, not a normal map, so the
+ * scene's own lights and environment carry them; a still frame catches
+ * several rings mid-expansion because the drops are phase-staggered.
+ * Crest vertices are also brightened through vertex colours — and
+ * TINTED with them, cool on the crests that tip toward the sky, warm in
+ * the troughs that show the bed — so the rings stay legible under flat
+ * overcast light and the pool never reads as one flat hue.
+ *
+ * @param {number} w Puddle width (X) in metres.
+ * @param {number} d Puddle depth (Z) in metres.
+ * @param {object} [opts]
+ * `seed` (default 3) mulberry32 seed;
+ * `segments` (default: derived as 4 samples per wavelength, 24-96)
+ * grid resolution per axis — a ripple the mesh cannot resolve
+ * flattens into an invisible one, so raise `wavelength` rather
+ * than the cap on a large pool;
+ * `drops` (default 8) simultaneous ripple sources;
+ * `amplitude` (default 0.006) crest height in metres;
+ * `wavelength` (default 0.3) metres between crests;
+ * `speed` (default 0.7) wavefront speed in m/s;
+ * `life` (default 2.6) seconds a ripple lives before its drop
+ * relands elsewhere;
+ * `color` (default 0x121820) water tint (dark: depth IS the darkness);
+ * `roughness` (default 0.07) low so the sky reflects;
+ * `mask` (default true) fade the rectangle out with a seeded fBm
+ * alpha so the puddle has an organic shoreline.
+ * @returns {THREE.Mesh} Mesh named 'Puddle' lying at y = 0 (position it
+ * just above the road), with `userData.update(t)` driving the ripples;
+ * already stepped to t = 0, so it is never flat.
+ */
+export function makePuddle(w, d, opts = {}) {
+ const seed = opts.seed === undefined ? 3 : opts.seed;
+ const drops = opts.drops === undefined ? 8 : opts.drops;
+ const amp = opts.amplitude === undefined ? 0.006 : opts.amplitude;
+ const lambda = opts.wavelength === undefined ? 0.3 : opts.wavelength;
+ // Four samples per wavelength or the rings alias flat; capped
+ // because every vertex is re-evaluated on the CPU each update.
+ const seg = opts.segments === undefined
+ ? Math.max(24, Math.min(96, Math.round(Math.max(w, d) * 4 / lambda)))
+ : opts.segments;
+ const speed = opts.speed === undefined ? 0.7 : opts.speed;
+ const life = opts.life === undefined ? 2.6 : opts.life;
+
+ const geom = new THREE.PlaneGeometry(w, d, seg, seg);
+ geom.rotateX(-Math.PI / 2);
+ const pos = geom.attributes.position;
+ const col = new Float32Array(pos.count * 3).fill(1);
+ geom.setAttribute('color', new THREE.BufferAttribute(col, 3));
+
+ const mat = new THREE.MeshStandardMaterial({
+ color: opts.color === undefined ? 0x121820 : opts.color,
+ roughness: opts.roughness === undefined ? 0.07 : opts.roughness,
+ metalness: 0, // water is a dielectric; metalness makes dirty chrome
+ vertexColors: true,
+ envMapIntensity: 1.6,
+ });
+ if (opts.mask !== false) {
+ mat.transparent = true;
+ mat.alphaMap = noiseDataTexture(128, (u, v) => {
+ const r = Math.hypot(u - 0.5, v - 0.5) * 2;
+ const k = 1 - r + 0.42 * fbm2(u * 3.4, v * 3.4, { seed });
+ return Math.max(0, Math.min(1, (k - 0.18) * 3.2));
+ });
+ }
+
+ // Each source relands every `life` seconds; the cycle index seeds
+ // where, so the puddle is not eight fixed drip points forever.
+ const offs = [];
+ const rand = mulberry32(seed);
+ for (let i = 0; i < drops; i++) offs.push(rand());
+ const cache = offs.map(() => ({ cyc: NaN, x: 0, z: 0, r: 0, fade: 0 }));
+ const sigma = lambda * 1.1;
+ const k2 = (Math.PI * 2) / lambda;
+
+ const update = (t) => {
+ for (let i = 0; i < drops; i++) {
+ const phase = t / life + offs[i];
+ const cyc = Math.floor(phase);
+ const c = cache[i];
+ if (c.cyc !== cyc) {
+ const r = mulberry32((seed + i * 7919 + cyc * 104729) | 0);
+ c.cyc = cyc;
+ c.x = (r() - 0.5) * w;
+ c.z = (r() - 0.5) * d;
+ }
+ c.r = (phase - cyc) * life * speed; // wavefront radius
+ c.fade = 1 - (phase - cyc);
+ }
+ for (let vi = 0; vi < pos.count; vi++) {
+ const x = pos.getX(vi), z = pos.getZ(vi);
+ // Wind chop: rain-struck water is never glassy between drops.
+ let h = amp * 0.22 * Math.sin(x * 11.3 + t * 3.1) *
+ Math.sin(z * 9.7 - t * 2.6);
+ for (let i = 0; i < drops; i++) {
+ const c = cache[i];
+ const dist = Math.hypot(x - c.x, z - c.z);
+ const f = dist - c.r;
+ if (f > 3 * sigma || f < -3 * sigma) continue;
+ h += amp * Math.cos(f * k2) * Math.exp(-(f * f) / (2 * sigma * sigma))
+ * c.fade / (1 + dist * 1.4);
+ }
+ pos.setY(vi, h);
+ // Crest and trough are not the same water: a crest tips toward
+ // the sky it mirrors and goes cool, a trough shows the warm bed.
+ // One achromatic multiply left the pool on a single flat hue.
+ const s = h / amp;
+ const b = Math.max(0.72, Math.min(1.35, 1 + s * 0.14));
+ const w = Math.max(0, Math.min(1, 0.5 + 0.5 * s));
+ col[vi * 3] = b * (1.06 - 0.12 * w);
+ col[vi * 3 + 1] = b * (1.005 - 0.01 * w);
+ col[vi * 3 + 2] = b * (0.94 + 0.12 * w);
+ }
+ pos.needsUpdate = true;
+ geom.attributes.color.needsUpdate = true;
+ geom.computeVertexNormals();
+ };
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Puddle';
+ mesh.receiveShadow = true;
+ mesh.userData.update = update;
+ update(0);
+ return mesh;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/river.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/river.js
new file mode 100644
index 00000000..10f770b8
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/river.js
@@ -0,0 +1,529 @@
+/**
+ * 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/roadway.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/roadway.js
new file mode 100644
index 00000000..1ffd6556
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/roadway.js
@@ -0,0 +1,676 @@
+/**
+ * Roadway: the made surface underfoot, and the mess where it stops.
+ *
+ * A road, a path or a yard is in nearly every scene here, it is the
+ * surface a viewer walks on every day, and it arrives flat grey. These
+ * three patches give it the marks that say TRAFFIC: the aggregate it
+ * was mixed from, the two polished strips per lane where the wheels
+ * run, the repairs cut into it, the damp gutter at the kerb, the gravel
+ * and weeds where it meets the ground it was laid on, and the tracks
+ * pressed into whatever is soft beside it.
+ *
+ * All three go through `patchStandard`, so lighting, shadows, fog and
+ * the depth chunks survive; all three shade from world position and
+ * world normal, so none needs a UV; and all three CHAIN with
+ * `terrain_shade`, `surface_wear`, `aging`, `accumulation` and
+ * `strata` on one material.
+ *
+ * THE ROAD FRAME is what makes this a roadway rather than more noise.
+ * Every patch works in (ALONG, ACROSS) metres, taken from the mesh's
+ * OWN axis: `dir` is an object-space direction carried through
+ * `modelMatrix`, and across is the horizontal perpendicular measured
+ * from the mesh's own origin. A rut is a line of constant ACROSS, so a
+ * rut laid along a world axis would walk off the road the moment it
+ * turned; this one turns with it, and a curve built from rotated
+ * segments gets ruts that follow each one.
+ *
+ * ONE FRAME PER MATERIAL: `dir`, `halfWidth` and `center` belong to the
+ * ROAD and all three patches share them — an option left out inherits
+ * what an earlier call set, and the last call that gives one wins.
+ * Tracks that must run somewhere else on the same material take
+ * `offset` (metres across) rather than a second centreline.
+ *
+ * Gloss is per MATERIAL, not per pixel — `<color_fragment>` runs before
+ * `<roughnessmap_fragment>` — so each patch composes ONE factor through
+ * `composeRoughness`: polished ruts and a damp gutter drop it, grit and
+ * loose aggregate raise it.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, surface_wear, aging, accumulation and strata
+// name them, so a material wearing several libraries carries ONE world
+// position; vAstraRoad is this library's own and no neighbour's.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+ 'varying vec4 vAstraRoad;',
+].join('\n');
+
+// All three patches read these, so they are declared once, in the
+// frame. astraRoad*, not a neighbour's spelling: patchStandard THROWS
+// when two chained patches give one function name two different bodies.
+const ROAD_HEAD = [
+ 'vec3 astraRoadAxes(vec3 n) {',
+ ' vec3 w = abs(n * n * n);',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+ // Three world-plane projections blended by the normal: the top of a
+ // kerb and its face have to carry the same grit.
+ 'float astraRoadNoise(vec3 p, vec3 w) {',
+ ' return astraNoise2(p.yz + 31.7) * w.x',
+ ' + astraNoise2(p.zx + 67.3) * w.y',
+ ' + astraNoise2(p.xy + 13.9) * w.z;',
+ '}',
+ // A fine field is TEXTURE up close and STATIC once a pixel spans a
+ // cycle of it, so every grain here is faded out by the world size of
+ // its own pixel. `cycle` is metres per repeat.
+ 'float astraRoadFade(vec3 p, float cycle) {',
+ ' return 1.0 - smoothstep(0.30, 0.95,',
+ ' length(fwidth(p)) / max(cycle, 1e-4));',
+ '}',
+].join('\n');
+
+// `transformed` is still object-space after <begin_vertex>, so the
+// instance transform is folded in by hand or every copy takes its road
+// from the mesh origin.
+const FRAME_BODY = [
+ ' vec4 rwP = vec4(transformed, 1.0);',
+ ' vec3 rwN = normal;',
+ ' vec4 rwD = vec4(uRoadDir, 0.0);',
+ ' vec4 rwO = vec4(0.0, 0.0, 0.0, 1.0);',
+ '#ifdef USE_INSTANCING',
+ ' rwP = instanceMatrix * rwP;',
+ ' rwN = mat3(instanceMatrix) * rwN;',
+ // Each copy is its own segment UNLESS a centreline was given, which
+ // says every copy belongs to ONE road.
+ ' rwD = mix(instanceMatrix * rwD, rwD, uRoadCenter.w);',
+ ' rwO = mix(instanceMatrix * rwO, rwO, uRoadCenter.w);',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * rwP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(rwN, 0.0)).xyz);',
+ ' vec3 rwA = normalize((modelMatrix * rwD).xyz);',
+ // The centreline is OBJECT-space like the direction, so a road built
+ // inside a turned group needs no world arithmetic from its author.
+ ' rwO = mix(rwO, vec4(uRoadCenter.xyz, 1.0), uRoadCenter.w);',
+ ' vec3 rwC = (modelMatrix * rwO).xyz;',
+ // Across is the HORIZONTAL perpendicular, so the pair is a road frame
+ // and not the world axes; a road standing on end has no across.
+ ' vec3 rwX = cross(vec3(0.0, 1.0, 0.0), rwA);',
+ ' rwX = normalize(mix(vec3(1.0, 0.0, 0.0), rwX,',
+ ' step(1e-4, dot(rwX, rwX))));',
+ ' vAstraRoad = vec4(rwA, dot(vAstraWorld - rwC, rwX));',
+].join('\n');
+
+const FRAME_HEAD = [
+ 'uniform vec3 uRoadDir;',
+ 'uniform vec4 uRoadCenter;',
+ 'uniform float uRoadHalf;',
+].join('\n');
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed
+ * for every material sharing the cache key. The constants differ from
+ * surface_wear's, aging's and accumulation's, or one seed would lay
+ * this library's grit along that library's blotches.
+ */
+function seedOffset(seed, salt) {
+ return new THREE.Vector3(
+ hash11(seed + salt + 2.11), hash11(seed + salt + 6.37),
+ hash11(seed + salt + 11.83)).multiplyScalar(40);
+}
+
+/**
+ * A roughening factor one patch cannot push past fully rough.
+ *
+ * Grit and weeds are matte, roughness only means anything up to 1, and
+ * the material may start near it.
+ */
+function matteFactor(material, add) {
+ const store = material.userData.astraRoughness;
+ const base = store ? store.base : material.roughness;
+ return base > 0 ? Math.min(1 + add, 1 / base) : 1;
+}
+
+/** Read a direction option, never as a zero vector the GPU divides by. */
+function dirVector(value, fallback) {
+ const v = new THREE.Vector3();
+ v.fromArray(value.toArray ? value.toArray() : value);
+ if (!(v.lengthSq() > 1e-9)) return fallback.clone();
+ return v.normalize();
+}
+
+/**
+ * The road frame every patch here works in, applied once.
+ *
+ * Named, so a material wearing all three gets ONE copy of the base: two
+ * would declare the same vertex locals and redefine the same helpers,
+ * which is a compile error and a throw respectively. The frame belongs
+ * to the ROAD, not to a patch, so an option left out INHERITS what an
+ * earlier call set rather than resetting it to the default.
+ *
+ * @param {THREE.Material} material The material to patch, in place.
+ * @param {object} opts `dir` object-space direction of travel (default
+ * +Z); `halfWidth` metres from the centreline to the kerb (default
+ * 3.5); `center` THREE.Vector3 or [x, y, z], a point on the
+ * centreline in the MESH'S OWN space (default: the mesh's origin —
+ * and giving one also makes every instance share this one road).
+ * @returns {THREE.Material} The same material.
+ */
+function withFrame(material, opts) {
+ const live = material.userData.uniforms || {};
+ const was = (name, fallback) => (live[name] ? live[name].value : fallback);
+ const dir = opts.dir === undefined
+ ? was('uRoadDir', new THREE.Vector3(0, 0, 1))
+ : dirVector(opts.dir, new THREE.Vector3(0, 0, 1));
+ const half = opts.halfWidth === undefined
+ ? was('uRoadHalf', 3.5) : Math.max(0.05, opts.halfWidth);
+ const at = new THREE.Vector3();
+ if (opts.center) at.fromArray(
+ opts.center.toArray ? opts.center.toArray() : opts.center);
+ const center = opts.center === undefined
+ ? was('uRoadCenter', new THREE.Vector4(0, 0, 0, 0))
+ : new THREE.Vector4(at.x, at.y, at.z, 1);
+ return patchStandard(material, {
+ name: 'road:frame',
+ uniforms: {
+ uRoadDir: { value: dir.clone() },
+ uRoadCenter: { value: center.clone() },
+ uRoadHalf: { value: half },
+ },
+ vertexHead: [WORLD_VARYINGS, FRAME_HEAD].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, FRAME_HEAD, ROAD_HEAD].join('\n'),
+ vertexBody: FRAME_BODY,
+ });
+}
+
+/**
+ * Asphalt or gravel: aggregate, wheel ruts, repairs and a damp gutter.
+ *
+ * A road is not a grey plane and it is not evenly worn — it is worn in
+ * TWO STRIPS PER LANE, where the wheels run, with the drip line between
+ * them and the silt at its edge. That asymmetry is the whole cue: it is
+ * what says a surface is driven on rather than painted, and it is the
+ * one thing a flat material can never suggest. Four layers, all in the
+ * road's own (along, across) frame:
+ *
+ * AGGREGATE is the stone in the mix — a fine dark speckle at
+ * `aggregate` 0 (a hot-rolled asphalt), loose pale chips at 1 (a gravel
+ * track) — faded out once a pixel spans a stone, because past that it
+ * is not texture, it is static. RUTS are the polished wheel lines, a
+ * wandering pair 1.5 m apart in each lane — the road is divided into
+ * WHOLE lanes, so a single-track lane keeps one pair and a two-lane
+ * road gets four strips, and the lane centre between each pair keeps
+ * the darker drip line. PATCHES are repairs: saw-cut rectangles in the
+ * road's own frame, each its own batch of tar, sealed at the rim — a
+ * soft-edged blob is an oil stain, not a repair. GUTTER is the
+ * hand-span at the kerb that never dries: darker, greener and, through
+ * `composeRoughness`, glossier.
+ *
+ * ON A COLOUR THAT IS ALREADY THERE: this one RULES the hue — it is the
+ * made surface, and `color` is what it was made of — but it carries
+ * whatever is in `diffuseColor` through as a light/dark variation
+ * rather than assigning over it, so a `patchTriplanar` or a
+ * `patchMicroBreakup` under it still shows in the result.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` surfaces every mesh
+ * wearing it, so clone it first (and clone BEFORE patching).
+ * @param {object} [opts] `aggregate` fineness of the mix, 0 asphalt to
+ * 1 loose gravel (default 0.25); `wear` how polished the wheel ruts
+ * are, 0..1 (default 0.5); `patches` how much of it has been dug up
+ * and made good, 0..1 (default 0.25); `gutter` how damp and silted
+ * the kerb line is, 0..1 (default 0.35); `color` THREE.Color or hex,
+ * the surface's own tone (default a worn bitumen grey); `lane` metres
+ * of one traffic lane, which sets where the ruts run (default 3.4);
+ * `dir`/`halfWidth`/`center` the road frame (see `withFrame`);
+ * `seed` moves the aggregate and the repairs (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uRoadGutter` can wet down
+ * over a shot.
+ */
+export function patchRoadSurface(material, opts = {}) {
+ const agg = opts.aggregate === undefined ? 0.25 : unit(opts.aggregate);
+ const wear = opts.wear === undefined ? 0.5 : unit(opts.wear);
+ const patches = opts.patches === undefined ? 0.25 : unit(opts.patches);
+ const gutter = opts.gutter === undefined ? 0.35 : unit(opts.gutter);
+ const lane = opts.lane === undefined ? 3.4 : Math.max(0.5, opts.lane);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Polished ruts and a damp gutter are the reachable half of gloss;
+ // loose stone is the matte half — but this ONE factor is the whole
+ // material's, so it has to be the AREA-WEIGHTED average and not the
+ // polished rut's own value. Wheel strips cover about a quarter of a
+ // lane and the gutter a twelfth of the width; spending the rut's full
+ // polish on all of it turns the road into a sky mirror here, where
+ // there is no post chain, a bright sky environment is the specular
+ // source and a road is nearly always seen at a grazing angle.
+ // Measured 2026-09-01 on this renderer: the old factors composed a
+ // tarmac authored at 0.85 down to 0.63 and it read (171,172,175) — a
+ // white card — while these compose the same material to 0.86 and it
+ // reads (136,138,144), with the repairs, the pale wheel strips and the
+ // dark drip line all back in the frame.
+ composeRoughness(material, 'road:surface',
+ Math.min(matteFactor(material, 0.16 * agg),
+ 1 + 0.16 * agg - 0.09 * wear - 0.05 * gutter));
+ withFrame(material, opts);
+ return patchStandard(material, {
+ name: 'road:surface',
+ uniforms: {
+ uRoadAgg: { value: agg },
+ uRoadWear: { value: wear },
+ uRoadPatch: { value: patches },
+ uRoadGutter: { value: gutter },
+ uRoadColor: { value: toColor(opts.color, 0x565658) },
+ uRoadLane: { value: lane },
+ uRoadSeed: { value: seedOffset(seed, 0.9) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uRoadAgg;',
+ 'uniform float uRoadWear;',
+ 'uniform float uRoadPatch;',
+ 'uniform float uRoadGutter;',
+ 'uniform vec3 uRoadColor;',
+ 'uniform float uRoadLane;',
+ 'uniform vec3 uRoadSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float roU = dot(vAstraWorld, vAstraRoad.xyz);',
+ ' float roA = abs(vAstraRoad.w);',
+ // The road's tone rules, but it carries what is already in the
+ // albedo as a variation: assigning outright erases a neighbour.
+ ' float roKeep = dot(diffuseColor.rgb, vec3(0.3333));',
+ ' vec3 roCol = uRoadColor',
+ ' * mix(0.88, 1.12, clamp(roKeep * 1.7, 0.0, 1.0));',
+ // TWO STRIPS PER LANE, and they come FIRST: a polished rut is
+ // where the aggregate stopped showing, not a stripe painted on
+ // top of it. The road is divided into WHOLE lanes, so every lane
+ // centre lands inside it — a single-track lane keeps one pair.
+ ' float roN = max(floor(2.0 * uRoadHalf / max(uRoadLane, 0.5)), 1.0);',
+ ' float roLw = 2.0 * uRoadHalf / roN;',
+ ' float roK = clamp(floor((vAstraRoad.w + uRoadHalf) / roLw),',
+ ' 0.0, roN - 1.0);',
+ ' float roCen = (roK + 0.5) * roLw - uRoadHalf;',
+ // Nothing drives a ruled line: the wheel path wanders along the
+ // road, which is what stops the pair reading as rails.
+ ' float roWob = (astraNoise2(vec2(roU * 0.06, 3.7) + uRoadSeed.yz)',
+ ' - 0.5) * 0.30;',
+ ' float roTr = min(0.75, roLw * 0.32);',
+ ' float roRut = (1.0 - smoothstep(0.12, 0.38,',
+ ' abs(abs(vAstraRoad.w - roCen) - roTr + roWob)))',
+ ' * uRoadWear;',
+ // The stone in the mix, gone once a pixel spans one of them and
+ // polished away under the wheels.
+ ' float roGs = mix(0.018, 0.075, uRoadAgg);',
+ ' vec2 roQ = vec2(roU, vAstraRoad.w) / roGs + uRoadSeed.xy;',
+ ' float roFd = astraRoadFade(vAstraWorld, roGs) * (1.0 - roRut * 0.7);',
+ ' float roG1 = astraNoise2(roQ);',
+ ' float roG2 = astraNoise2(roQ * 2.7 + 19.3);',
+ // A THIRD octave, on roFd twice so it is the first to go: two
+ // octaves of value noise at one stone size read as soft blobs —
+ // digital camouflage, not aggregate — and the break-up that makes
+ // them stone is finer than the stone itself.
+ ' float roG3 = astraNoise2(roQ * 5.9 + 41.7);',
+ ' float roGrain = ((roG1 - 0.5) * 0.52 + (roG2 - 0.5) * 0.34',
+ ' + (roG3 - 0.5) * 0.30 * roFd) * roFd;',
+ ' roCol *= 1.0 + roGrain * mix(0.22, 0.60, uRoadAgg);',
+ // A chip is a STONE, and a road is never mixed from one stone: the
+ // exposed faces run warm (flint, limestone dust) to cool (granite,
+ // basalt) on a field decorrelated from the one that placed them.
+ ' float roChip = smoothstep(0.62, 0.74, roG1 * 0.45 + roG3 * 0.55)',
+ ' * uRoadAgg * roFd;',
+ ' vec3 roStone = roCol * 1.5 + vec3(0.035, 0.033, 0.030);',
+ ' roStone *= mix(vec3(1.07, 1.00, 0.90),',
+ ' vec3(0.93, 0.99, 1.09), roG2);',
+ ' roCol = mix(roCol, roStone, roChip * 0.7);',
+ ' roCol = mix(roCol, uRoadColor * mix(1.06, 1.42, uRoadWear),',
+ ' roRut * 0.85);',
+ // The drip strip down the lane centre, between the wheels.
+ ' float roOil = (1.0 - smoothstep(0.06, 0.34,',
+ ' abs(vAstraRoad.w - roCen))) * uRoadWear;',
+ ' roCol *= 1.0 - roOil * 0.30;',
+ // REPAIRS ARE SAW-CUT: a rectangle in the road's own frame with a
+ // sealed rim, one per cell of a coarse grid. A soft blob is an
+ // oil stain; only a straight edge reads as something dug up.
+ ' vec2 roPq = vec2(roU / 5.6, vAstraRoad.w / 3.3) + uRoadSeed.zx;',
+ ' vec2 roPi = floor(roPq);',
+ // Jittered inside its cell and never quite filling it, or the
+ // repairs line up on a lattice and read as paving slabs.
+ ' vec2 roPj = vec2(astraHash21(roPi + 5.3),',
+ ' astraHash21(roPi + 17.1)) - 0.5;',
+ ' vec2 roPf = abs(fract(roPq) - 0.5 + roPj * 0.22);',
+ ' vec2 roPs = vec2(0.13 + 0.25 * astraHash21(roPi + 3.1),',
+ ' 0.11 + 0.27 * astraHash21(roPi + 7.7));',
+ ' vec2 roPaa = fwidth(roPq) * 0.7 + 0.0015;',
+ ' vec2 roPe = smoothstep(roPs + roPaa, roPs - roPaa, roPf);',
+ ' float roPk = roPe.x * roPe.y',
+ ' * step(1.0 - uRoadPatch, astraHash21(roPi));',
+ ' vec2 roPn = smoothstep(roPs - 0.05 + roPaa, roPs - 0.05 - roPaa,',
+ ' roPf);',
+ ' float roRim = roPk * (1.0 - roPn.x * roPn.y);',
+ // A repair is a different BATCH, not a black rectangle: some are
+ // darker than the road it was cut into and some are paler.
+ ' float roPt = mix(0.80, 1.12, astraHash21(roPi + 11.9));',
+ ' roCol = mix(roCol, uRoadColor * roPt * (1.0 + roGrain * 1.2),',
+ ' roPk * 0.8);',
+ ' roCol *= 1.0 - roRim * 0.22;',
+ // METRE-SCALE WEATHER, and the only structure on this surface that
+ // survives to the horizon: every field above is finer than a pixel
+ // within a few metres of the camera and fades out BY DESIGN, which
+ // left the road one flat value past that — a grey card with a
+ // repair grid on it. Two slow octaves in the road's own frame, and
+ // a hue that walks with them from warm (dust, sun-bleached binder,
+ // limestone fines) to cool (fresh bitumen, the damp side of a
+ // patch), so the variance is in COLOUR and not only in level. The
+ // mix is centred, so the road's mean tone is the one it was given.
+ ' vec2 roMq = vec2(roU, vAstraRoad.w) + uRoadSeed.yx;',
+ ' float roBlot = (astraNoise2(roMq * 0.115) - 0.5) * 0.55',
+ ' + (astraNoise2(roMq * 0.034 + 4.7) - 0.5) * 0.45;',
+ ' float roHue = clamp(0.5 + roBlot * 1.7, 0.0, 1.0);',
+ ' roCol *= (1.0 + roBlot * 0.30)',
+ ' * mix(vec3(0.950, 0.984, 1.062),',
+ ' vec3(1.072, 1.012, 0.940), roHue);',
+ // The gutter never dries and it silts up; its inner edge is
+ // ragged, or it is a painted line. Two bands, not one: the damp
+ // strip inside the kerb goes dark and COOL, and the silt washed to
+ // the kerb line itself sits on top of it PALER and warm — a single
+ // flat darkening reads as a stripe someone painted there.
+ ' float roGw = mix(0.10, 0.60, uRoadGutter);',
+ ' float roGj = (astraNoise2(vec2(roU * 0.35, 9.1) + uRoadSeed.xy)',
+ ' - 0.5) * roGw * 0.7;',
+ ' float roGut = smoothstep(uRoadHalf - roGw + roGj,',
+ ' uRoadHalf + roGj, roA) * uRoadGutter;',
+ // Silt is washed along the kerb and dropped where the fall eases,
+ // so how much of it there is walks ALONG the road: an even pale
+ // line at the kerb is road marking, not dirt.
+ ' float roSilt = smoothstep(uRoadHalf - roGw * 0.34 + roGj,',
+ ' uRoadHalf + roGj, roA) * uRoadGutter',
+ ' * smoothstep(0.30, 0.72,',
+ ' astraNoise2(vec2(roU * 0.5, 2.3) + uRoadSeed.zx));',
+ ' roCol = mix(roCol, roCol * vec3(0.44, 0.49, 0.56),',
+ ' roGut * (1.0 - roSilt * 0.55));',
+ ' roCol = mix(roCol, roCol * vec3(1.58, 1.44, 1.17), roSilt * 0.62);',
+ // A metre-scale gradient across a near-neutral grey BANDS at eight
+ // bits, and the aggregate that would have hidden it has faded out
+ // by the distance the banding appears. Sub-LSB, per pixel, so it
+ // costs one hash and never reads as noise.
+ ' roCol *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.010;',
+ ' diffuseColor.rgb = roCol;',
+ ].join('\n'),
+ });
+}
+
+/**
+ * The gravel, grit and weeds where a made surface meets the ground.
+ *
+ * Nothing in a photograph meets anything else with a clean edge, and
+ * this is the paving version of that: tarmac does not stop at a ruled
+ * line on grass, it frays into the spill that was swept off it, the
+ * grit that washed off it, and the weeds that took the joint. A road
+ * with a clean edge reads as a decal on the ground however good the
+ * surface itself is, so this is the cheapest thing in the library.
+ *
+ * The band straddles the kerb line — |across| = `halfWidth` — and its
+ * half-width WANDERS between about half of what it was given and all
+ * of it, so the edge is ragged and still strictly inside `width`. Weeds
+ * take the joint and the ground side of it and never the made surface;
+ * the hairline of shadow in the joint itself is the only depth a patch
+ * that cannot displace geometry has, and it is faded out by its own
+ * pixel size before it can alias.
+ *
+ * ON A COLOUR THAT IS ALREADY THERE: it MIXES over it by the band mask
+ * and leaves everything outside the band untouched — so it lands on the
+ * road's material and on the verge's alike. On the verge, pass the
+ * road's `center` and `halfWidth`: a fragment on the grass cannot know
+ * where the tarmac ended.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material bands every mesh wearing it.
+ * @param {object} [opts] `width` metres the whole band spans, kerb line
+ * in the middle (default 0.5); `color` THREE.Color or hex, the grit
+ * and gravel (default a pale grey-brown); `weeds` how much has taken
+ * root, 0..1 (default 0.4); `dir`/`halfWidth`/`center` the road frame
+ * (see `withFrame`); `seed` moves the grit and the tufts (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms` — `uSeamWeed` is the weed tone, so
+ * a dry season can yellow it.
+ */
+export function patchSeamBand(material, opts = {}) {
+ const width = opts.width === undefined ? 0.5 : Math.max(1e-3, opts.width);
+ const weeds = opts.weeds === undefined ? 0.4 : unit(opts.weeds);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Grit and weeds are matte, and they cover only the band, so this is
+ // the smallest gloss move in the library.
+ composeRoughness(material, 'road:seam',
+ matteFactor(material, 0.06 + 0.08 * weeds));
+ withFrame(material, opts);
+ return patchStandard(material, {
+ name: 'road:seam',
+ uniforms: {
+ uSeamWidth: { value: width },
+ uSeamColor: { value: toColor(opts.color, 0x847a6d) },
+ uSeamWeeds: { value: weeds },
+ uSeamWeed: { value: new THREE.Color(0x53602f) },
+ uSeamSeed: { value: seedOffset(seed, 5.3) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uSeamWidth;',
+ 'uniform vec3 uSeamColor;',
+ 'uniform float uSeamWeeds;',
+ 'uniform vec3 uSeamWeed;',
+ 'uniform vec3 uSeamSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float smU = dot(vAstraWorld, vAstraRoad.xyz);',
+ // Signed metres past the kerb line, so the two sides can differ.
+ ' float smD = abs(vAstraRoad.w) - uRoadHalf;',
+ ' float smH = uSeamWidth * 0.5;',
+ // The half-width wanders along the road and never exceeds what it
+ // was given, so a ragged band is still a BOUNDED one.
+ ' float smR = mix(0.45, 1.0, astraNoise2(vec2(smU * 0.8, 5.7)',
+ ' + uSeamSeed.xy));',
+ ' float smK = 1.0 - smoothstep(smR * smH * 0.45, smR * smH,',
+ ' abs(smD));',
+ ' vec3 smW = astraRoadAxes(normalize(vAstraWorldN));',
+ ' vec3 smP = vAstraWorld * 22.0 + uSeamSeed;',
+ ' float smFd = astraRoadFade(vAstraWorld, 0.045);',
+ ' float smFc = astraRoadFade(vAstraWorld, 0.20);',
+ ' float smG = astraRoadNoise(smP, smW);',
+ ' float smC = astraRoadNoise(smP * 0.22, smW);',
+ // Grit is the fine half and gravel the coarse half. BOTH converge
+ // to their average as the pixel grows past them: a band that keeps
+ // its contrast into the distance is a dashed white line.
+ ' vec3 smCol = uSeamColor * mix(1.0, mix(0.84, 1.16, smC), smFc)',
+ ' * (1.0 + (smG - 0.5) * 0.40 * smFd);',
+ // Gravel is SWEPT UP off a road, not quarried from one stone: a
+ // slow field in the road's own frame (about a two-metre cycle, so
+ // it is still there when the grain has faded) walks the band from
+ // limestone-warm to granite-cool, and the same field splits the
+ // weeds into dry stems and green leaf below.
+ ' float smHue = astraNoise2(vec2(smU, vAstraRoad.w) * 0.55',
+ ' + uSeamSeed.zx);',
+ ' smCol *= mix(vec3(1.07, 1.00, 0.91), vec3(0.93, 0.99, 1.08), smHue);',
+ // WEEDS take the joint and the ground side of it: a tuft in the
+ // middle of the tarmac is a decal.
+ ' float smOut = smoothstep(-smH * 0.30, smH * 0.55, smD);',
+ ' float smTf = astraNoise2(vec2(smU, vAstraRoad.w) * 6.5',
+ ' + uSeamSeed.yz);',
+ ' float smWd = mix(0.26, smoothstep(0.60, 0.82, smTf), smFc)',
+ ' * mix(0.20, 1.0, smOut) * uSeamWeeds;',
+ ' vec3 smWc = uSeamWeed * mix(0.70, 1.20, smG)',
+ ' * mix(vec3(1.18, 1.05, 0.72),',
+ ' vec3(0.84, 1.02, 0.94), smHue);',
+ ' smCol = mix(smCol, smWc, smWd);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, smCol, smK * 0.88);',
+ // The joint itself, faded out by its own pixel size: a hairline
+ // that survives past the distance it can be resolved is moire.
+ ' float smJt = (1.0 - smoothstep(0.0, smH * 0.22, abs(smD)))',
+ ' * astraRoadFade(vAstraWorld, smH * 0.44);',
+ ' diffuseColor.rgb *= 1.0 - smJt * 0.45;',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Tyre tracks or footprints pressed into a soft surface.
+ *
+ * Mud, sand, snow and dust all record what crossed them, and a soft
+ * surface with nothing written on it reads as untouched ground however
+ * good its own texture is — which is why an otherwise finished yard,
+ * verge or beach still looks like a render. `count` tracks run along
+ * the road frame's direction, each wandering on its own field (a pair
+ * of ruled lines is a railway, not a vehicle).
+ *
+ * ALBEDO AND GLOSS ONLY: per-pixel DISPLACEMENT is not reachable from
+ * this hook — `fragmentBody` edits `diffuseColor`, and a vertex
+ * displacement would tear every hard-edged geometry open at its rim —
+ * so depth is sold two ways instead. The press is DARKER (turned-over,
+ * damp material) and the ground it displaced piles into a paler RIM
+ * just outside it. `depth` drives both.
+ *
+ * `kind` is a UNIFORM, not two sources: 'tyre' lays a continuous band
+ * with chevron tread (through `astraStroke`, which kills itself once a
+ * pixel spans a rib), 'foot' lays discrete prints one stride apart,
+ * each stepping to its own side of the line so a single trail reads as
+ * a walk rather than as a ladder.
+ *
+ * ON A COLOUR THAT IS ALREADY THERE: it MIXES over it, and the colour
+ * it mixes toward is that same albedo darkened — so the tracks are made
+ * OF the surface they are pressed into, whatever a neighbouring patch
+ * put there, and outside them nothing changes.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material tracks every mesh wearing it.
+ * @param {object} [opts] `dir` object-space direction of travel
+ * (default +Z); `count` how many parallel tracks, 1..8 (default 2 —
+ * one vehicle, one walker); `depth` how deep they are pressed, 0..1
+ * (default 0.5); `kind` 'tyre' or 'foot' (default 'tyre'); `gauge`
+ * metres between tracks (default 1.6 for tyre, 0.3 for foot);
+ * `offset` metres ACROSS the frame that the group runs at, so a
+ * vehicle can drive down one lane and a seam band on the same
+ * material can still sit on the centreline it belongs to (default 0);
+ * `center`/`halfWidth` the road frame (see `withFrame`); `seed` moves
+ * the wander and the prints (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`, so `uTrkDepth` can press in over
+ * a shot.
+ */
+export function patchTracks(material, opts = {}) {
+ const count = Math.max(1, Math.min(8, Math.round(
+ opts.count === undefined ? 2 : opts.count)));
+ const depth = opts.depth === undefined ? 0.5 : unit(opts.depth);
+ const foot = opts.kind === 'foot';
+ const gauge = opts.gauge === undefined
+ ? (foot ? 0.30 : 1.6) : Math.max(0.02, opts.gauge);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Pressed ground is packed and damp, which is smoother than the loose
+ // surface around it — over the width of the tracks, which is a tenth
+ // of the ground they cross, and this factor is the whole material's
+ // (see `patchRoadSurface`: an over-polished ground is a sky mirror at
+ // a grazing angle on this renderer).
+ composeRoughness(material, 'road:tracks', 1 - 0.08 * depth);
+ withFrame(material, opts);
+ return patchStandard(material, {
+ name: 'road:tracks',
+ uniforms: {
+ uTrkCount: { value: count },
+ uTrkDepth: { value: depth },
+ uTrkKind: { value: foot ? 1 : 0 },
+ uTrkGauge: { value: gauge },
+ uTrkOffset: { value: opts.offset === undefined ? 0 : opts.offset },
+ uTrkSeed: { value: seedOffset(seed, 8.7) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uTrkCount;',
+ 'uniform float uTrkDepth;',
+ 'uniform float uTrkKind;',
+ 'uniform float uTrkGauge;',
+ 'uniform float uTrkOffset;',
+ 'uniform vec3 uTrkSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float tkU = dot(vAstraWorld, vAstraRoad.xyz);',
+ ' float tkPress = 0.0;',
+ ' float tkWide = 0.0;',
+ ' float tkTread = 0.0;',
+ // A churned tyre rut is ~27 cm across and a boot 11; the stride
+ // and the rib pitch are the same constants for everyone.
+ ' float tkHw = mix(0.135, 0.055, uTrkKind);',
+ // Prints and ribs are gone before a pixel spans one of them, and
+ // a line of prints converges to the worn TRAIL it really is
+ // rather than to a row of sparkling dots.
+ ' float tkFd = astraRoadFade(vAstraWorld, 0.30);',
+ ' for (int i = 0; i < 8; i++) {',
+ ' if (float(i) >= uTrkCount) break;',
+ ' float tkO = (float(i) - (uTrkCount - 1.0) * 0.5) * uTrkGauge',
+ ' + uTrkOffset;',
+ ' float tkWob = (astraNoise2(vec2(tkU * 0.22, float(i) * 7.3)',
+ ' + uTrkSeed.xy) - 0.5) * 0.45;',
+ ' float tkX = vAstraRoad.w - tkO - tkWob;',
+ // TYRE: a continuous band with chevron ribs square across it.
+ ' float tkB = 1.0 - smoothstep(tkHw * 0.68, tkHw, abs(tkX));',
+ ' float tkBw = 1.0 - smoothstep(tkHw, tkHw * 1.7, abs(tkX));',
+ // Half-width 0.06, not a fat rib: astraStroke clamps its own
+ // antialias at 0.30 and self-kills between w * 1.5 and w * 5, so
+ // only a thin stroke ever reaches the kill instead of greying out.
+ ' float tkRb = astraStroke(tkU / 0.065 + abs(tkX) * 3.6,',
+ ' 0.06);',
+ // FOOT: one print per stride, each stepping to its own side.
+ ' float tkC = floor(tkU / 0.72);',
+ ' float tkAl = (tkU / 0.72 - tkC - 0.5) * 0.72 / 0.15;',
+ ' float tkAc = (tkX - (mod(tkC, 2.0) - 0.5) * 0.11) / 0.055;',
+ ' float tkE = length(vec2(tkAl, tkAc));',
+ ' float tkTr = (1.0 - smoothstep(0.9, 1.7, abs(tkAc))) * 0.45;',
+ ' float tkPr = mix(tkTr, 1.0 - smoothstep(0.74, 1.0, tkE), tkFd);',
+ ' float tkPw = 1.0 - smoothstep(1.0, 1.45, tkE);',
+ ' tkPress = max(tkPress, mix(tkB, tkPr, uTrkKind));',
+ ' tkWide = max(tkWide, mix(tkBw, tkPw, uTrkKind));',
+ ' tkTread = max(tkTread, mix(tkB * tkRb, tkPr * 0.5, uTrkKind));',
+ ' }',
+ ' float tkRim = clamp(tkWide - tkPress, 0.0, 1.0) * tkFd;',
+ // Made OF the surface it is pressed into: turned over and damp,
+ // so the same albedo, darker.
+ ' vec3 tkCol = diffuseColor.rgb * mix(1.0, 0.55, uTrkDepth)',
+ ' * (1.0 - tkTread * 0.17 * tkFd);',
+ // Turned-over material is DAMP as well as dark, and damp is cool:
+ // a press that only darkens reads as a shadow painted on the
+ // ground rather than as ground that was moved.
+ ' tkCol *= mix(vec3(1.0), vec3(0.94, 0.975, 1.045), uTrkDepth);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, tkCol,',
+ ' clamp(tkPress * uTrkDepth, 0.0, 1.0));',
+ // The material it displaced has to go somewhere, and the pale rim
+ // is the only thickness this hook can show — dry crumbs off the
+ // top of the surface, so it lifts WARM against the cool press.
+ ' diffuseColor.rgb *= 1.0 + tkRim * uTrkDepth',
+ ' * vec3(0.30, 0.25, 0.17);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.js
new file mode 100644
index 00000000..221c504c
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/scatter.js
@@ -0,0 +1,176 @@
+/**
+ * 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.js
new file mode 100644
index 00000000..e1b5025e
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/season.js
@@ -0,0 +1,463 @@
+/**
+ * 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/shader.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/shader.js
new file mode 100644
index 00000000..03768d20
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/shader.js
@@ -0,0 +1,888 @@
+/**
+ * Custom shaders that survive THIS renderer.
+ *
+ * Writing GLSL here has three ways to fail with no error at all — the
+ * effect is simply absent from the frame, which reads as "the idea was
+ * wrong" and ends in a retreat to a flat material. All three are
+ * boilerplate, so they live here instead of in your shader:
+ *
+ * 1. a renderer with `logarithmicDepthBuffer: true` DISCARDS a custom
+ * shader without the four depth chunks behind opaque geometry
+ * (`depthWrite: false` does not save it). THIS harness's renderer
+ * (runtime_js/lib/browser/renderer.js) leaves log depth OFF by
+ * default — the chunks then compile to nothing — but `--log-depth`
+ * is a host option for km-scale scenes, so they are always injected;
+ * 1b. every scene here sets `scene.fog`, and fog reaches a shader ONLY
+ * through its chunks — without them the effect keeps full contrast
+ * while the world around it recedes, which is the sticker look;
+ * 1c. this renderer has NO post chain: tone mapping (ACES, exposure
+ * 1.0) and the sRGB encode happen in the fragment tail, so a shader
+ * without three's two closing chunks renders dark and untonemapped
+ * next to every built-in — they are appended for you;
+ * 2. an `#include` sharing a line with anything else fails to compile;
+ * 3. GLSL 3.00 syntax in a material three compiles as GLSL ES 1.00.
+ *
+ * Write the BODY of main() and let this file assemble the rest:
+ *
+ * const mat = makeShaderMaterial({
+ * uniforms: { uColor: { value: new THREE.Color(0xff8844) } },
+ * varyings: 'varying vec2 vUv;',
+ * vertexMain: 'vUv = uv;', // position is done for you
+ * fragmentMain: 'gl_FragColor = vec4(uColor * vUv.y, 1.0);',
+ * });
+ *
+ * Verify before you render: the harness's `check_shaders` tool (CLI:
+ * `node runtime_js/check_shaders.mjs --ws <workspace>`) compiles every
+ * material on the headless GPU and maps errors back to file:line.
+ */
+
+import * as THREE from 'three';
+
+/**
+ * Shared GLSL helpers. Include with `${GLSL_UTIL}` in a head string.
+ *
+ * These are value noise over a hash, with no seed: they are NOT the
+ * Perlin field `noise.js` displaces geometry with, so a shader pattern
+ * and a CPU-built heightfield never line up. When both have to agree,
+ * build the field on the CPU and hand it over as an attribute.
+ */
+export const GLSL_UTIL = [
+ 'float astraHash11(float p) {',
+ ' p = fract(p * 0.1031);',
+ ' p *= p + 33.33;',
+ ' return fract(p * (p + p));',
+ '}',
+ 'float astraHash21(vec2 p) {',
+ ' vec3 p3 = fract(vec3(p.xyx) * 0.1031);',
+ ' p3 += dot(p3, p3.yzx + 33.33);',
+ ' return fract((p3.x + p3.y) * p3.z);',
+ '}',
+ 'float astraNoise2(vec2 p) {',
+ ' vec2 i = floor(p), f = fract(p);',
+ ' f = f * f * (3.0 - 2.0 * f);',
+ ' float a = astraHash21(i), b = astraHash21(i + vec2(1.0, 0.0));',
+ ' float c = astraHash21(i + vec2(0.0, 1.0));',
+ ' float d = astraHash21(i + vec2(1.0, 1.0));',
+ ' return mix(mix(a, b, f.x), mix(c, d, f.x), f.y);',
+ '}',
+ 'float astraFbm2(vec2 p, int octaves) {',
+ ' float s = 0.0, a = 0.5;',
+ ' for (int i = 0; i < 6; i++) {',
+ ' if (i >= octaves) break;',
+ ' s += a * astraNoise2(p);',
+ ' p *= 2.02; a *= 0.5;',
+ ' }',
+ ' return s;',
+ '}',
+ 'float astraFresnel(vec3 n, vec3 v, float power) {',
+ ' return pow(1.0 - clamp(dot(normalize(n), normalize(v)), 0.0, 1.0),',
+ ' power);',
+ '}',
+ // Contact transitions: nothing in a photograph meets anything else
+ // with a hard edge. `h` is height above the contact plane.
+ 'float astraContact(float h, float band) {',
+ ' return 1.0 - smoothstep(0.0, max(band, 1e-4), h);',
+ '}',
+ // BROKEN COLOUR. Not a hue rotation: rotating about the grey axis
+ // returns white unchanged, and the swing daylight actually makes is
+ // warm where the sun lands and cool where only the sky reaches. The
+ // field is centred on 0.375 because astraFbm2 at 2 octaves runs
+ // 0..0.75 about that mean — subtracting the half a caller expects
+ // both skews the swing cool and halves it (measured: a meadow's mat
+ // moved 8.2 degrees of local hue instead of the 25-45 a photograph
+ // carries). `swing` around 0.3 is stone, 0.6 is foliage.
+ 'vec3 astraHueBreak(vec3 c, vec2 p, float scale, float swing) {',
+ ' float h = (astraFbm2(p * scale, 2) - 0.375) * swing;',
+ ' return c * vec3(1.0 + h, 1.0 + h * 0.15, 1.0 - h);',
+ '}',
+ 'vec3 astraHueShift(vec3 c, float a) {',
+ ' const vec3 k = vec3(0.57735);',
+ ' float ca = cos(a);',
+ ' return c * ca + cross(k, c) * sin(a) + k * dot(k, c) * (1.0 - ca);',
+ '}',
+ // One stroke per period of v, half-width w, antialiased by its own
+ // screen gradient — and gone once a pixel spans more than the stroke
+ // itself, or a grazing surface turns solid instead of striped.
+ // The vanishing only works for a THIN stroke: aa is clamped at 0.30
+ // while the kill runs w*1.5 to w*5, so past w ~= 0.06 it never fully
+ // kills and past 0.20 it never starts — a fat stroke greys out to a
+ // flat mid tone instead of disappearing.
+ // fwidth is a FRAGMENT-stage function and this block ships in both,
+ // so the guard is not decoration: without it every vertex shader in
+ // the engine fails to compile.
+ '#ifdef ASTRA_FRAG',
+ 'float astraStroke(float v, float w) {',
+ ' float g = abs(fract(v) - 0.5);',
+ ' float aa = clamp(fwidth(v) * 0.5, 0.0004, 0.30);',
+ ' float m = 1.0 - smoothstep(max(w - aa, 0.0), w + aa, g);',
+ ' return m * (1.0 - smoothstep(w * 1.5, w * 5.0, aa));',
+ '}',
+ '#endif',
+ // 0 edge-on, 1 facing. A double-sided shell piles its front and back
+ // into the same pixels at the silhouette and stacks into a bright
+ // rib; fade by this.
+ 'float astraFacing(vec3 n, vec3 v) {',
+ ' return abs(dot(normalize(n), normalize(v)));',
+ '}',
+ // Free fall: distance goes as time squared, so a packet's AGE is the
+ // square root of how far it has dropped. Riding features at a
+ // constant rate in age is what makes falling water accelerate.
+ 'float astraFallAge(float drop) {',
+ ' return sqrt(clamp(drop, 0.0, 1.6));',
+ '}',
+ // Decorrelate neighbouring filaments. Offsets under 2*PI leave them
+ // correlated and their fronts weave a herringbone across the sheet.
+ 'float astraStagger(float x) {',
+ ' return (sin(x * 311.0) * 1.70 + sin(x * 137.0 + 1.1) * 1.15',
+ ' + sin(x * 57.0 + 2.3) * 0.60) * 4.3;',
+ '}',
+].join('\n');
+
+const FOG_PARS_V = '#include <fog_pars_vertex>';
+const FOG_V = '#include <fog_vertex>';
+const FOG_PARS_F = '#include <fog_pars_fragment>';
+const FOG_F = '#include <fog_fragment>';
+// What three appends to the end of every one of its OWN fragment
+// shaders. Both resolve per render target: identity into the
+// linear buffer a post chain reads, tone map + sRGB straight to
+// the canvas. This harness renders straight to the canvas (ACES,
+// exposure 1.0, no post chain today), so without them a custom
+// shader is dark and untonemapped next to every built-in.
+const OUT_F = [
+ ' #include <tonemapping_fragment>',
+ ' #include <colorspace_fragment>',
+].join('\n');
+const FOG_F_ADDITIVE = [
+ '#ifdef USE_FOG',
+ ' #ifdef FOG_EXP2',
+ ' float astraFogF = 1.0 - exp(-fogDensity * fogDensity',
+ ' * vFogDepth * vFogDepth);',
+ ' #else',
+ ' float astraFogF = smoothstep(fogNear, fogFar, vFogDepth);',
+ ' #endif',
+ ' gl_FragColor.a *= 1.0 - clamp(astraFogF, 0.0, 1.0);',
+ '#endif',
+].join('\n');
+const LOG_PARS_V = '#include <logdepthbuf_pars_vertex>';
+const LOG_V = '#include <logdepthbuf_vertex>';
+const LOG_PARS_F = '#include <logdepthbuf_pars_fragment>';
+const LOG_F = '#include <logdepthbuf_fragment>';
+
+/**
+ * Normalise interstage declarations to `varying`.
+ *
+ * Measured in three 0.184 (`WebGLProgram`): every non-raw material is
+ * compiled as `#version 300 es` regardless of `glslVersion`, with
+ * `#define varying out` in the vertex stage and `#define varying in` in
+ * the fragment stage — so `varying` is the ONE spelling that is correct
+ * in both. A shared declaration written `out vec3 vN;` becomes a second
+ * fragment OUTPUT, which knocks out three's `pc_fragColor` and takes
+ * `gl_FragColor` with it. Asking three for the GLSL3 dialect would not
+ * help: its only effect is that three stops defining `gl_FragColor` at
+ * all. So the author may write either dialect and this rewrites it.
+ * (The dialect option is named without its literal `key: value` here:
+ * the harness's GLSL audit sets a FILE-level GLSL3 flag from that token
+ * and then errors on every `gl_FragColor` in the file — a doc comment
+ * is not an exemption, measured on shader_preflight 2026-09-01.)
+ */
+function asVarying(decls) {
+ return decls.replace(
+ /^(\s*)(in|out)(\s+(?:lowp |mediump |highp )?(?:vec[234]|float|int|uint|mat[234])\s+\w+\s*;)/gm,
+ '$1varying$3');
+}
+
+/**
+ * Drop a repeated `varying <type> <name>;`, keeping the first.
+ *
+ * `varyings` is injected into BOTH stages, and an author who also
+ * declares it in their own head string gets 'redefinition' — measured
+ * on the first probe run, from a model that did exactly that.
+ */
+function dedupeVaryings(src) {
+ const seen = new Set();
+ return src.split('\n').filter((line) => {
+ const m = line.match(
+ /^\s*varying\s+(?:lowp |mediump |highp )?[a-z0-9]+\s+(\w+)\s*;/i);
+ if (!m) return true;
+ if (seen.has(m[1])) return false;
+ seen.add(m[1]);
+ return true;
+ }).join('\n');
+}
+
+
+/**
+ * Drop a repeated `uniform <type> <name>;`, keeping the first.
+ *
+ * Chained patches each declare what they need, and two of them wanting
+ * the same uniform — uTime above all — is a redefinition the author
+ * cannot see coming from inside one patch.
+ */
+function dedupeUniforms(src) {
+ const seen = new Set();
+ return src.split('\n').filter((line) => {
+ const m = line.match(
+ // The [n] is not optional decoration: without it
+ // `uniform vec3 uPos[8];` never matched, was never
+ // deduped, and two patches wanting one array hit the
+ // exact redefinition this function exists to prevent.
+ /^\s*uniform\s+(?:lowp |mediump |highp )?[a-z0-9]+\s+(\w+)\s*(?:\[[^\]]*\])?\s*;/i);
+ if (!m) return true;
+ if (seen.has(m[1])) return false;
+ seen.add(m[1]);
+ return true;
+ }).join('\n');
+}
+
+
+/** Declare `uniform float uTime;` where it is used but not declared. */
+function withTime(src) {
+ if (!/\buTime\b/.test(src)) return src;
+ if (/\buniform\s+float\s+uTime\s*;/.test(src)) return src;
+ return 'uniform float uTime;\n' + src;
+}
+
+/** Insert `line` as the first statement of main(), on its own line. */
+function intoMainTop(src, line) {
+ if (src.includes(line)) return src;
+ const i = src.search(/void\s+main\s*\([^)]*\)\s*\{/);
+ if (i < 0) {
+ throw new Error(
+ 'shader.js: no void main() to inject ' + line + ' into');
+ }
+ const open = src.indexOf('{', i) + 1;
+ return src.slice(0, open) + '\n ' + line + '\n' + src.slice(open);
+}
+
+/** Insert `line` as the last statement of main(), on its own line. */
+function intoMainEnd(src, line) {
+ if (src.includes(line)) return src;
+ const close = src.lastIndexOf('}');
+ if (close < 0) {
+ throw new Error(
+ 'shader.js: no closing brace to inject ' + line + ' before');
+ }
+ // A newline BEFORE the line too: a one-line raw source
+ // (`void main() { gl_FragColor = ...; }`) otherwise gets the
+ // #include on the same line as its last statement — the exact
+ // trap rule 2 at the top of this file describes, measured on the
+ // GPU compile of the raw-source path (2026-09-01).
+ return src.slice(0, close) + '\n ' + line + '\n' + src.slice(close);
+}
+
+/**
+ * Build a `ShaderMaterial` that is not silently discarded.
+ *
+ * Supply either the two mains (preferred — the boilerplate is written
+ * for you) or complete `vertexShader`/`fragmentShader` sources, in
+ * which case the depth chunks are injected into them.
+ *
+ * @param {object} opts
+ * `uniforms` THREE uniform map (uTime is added and driven by
+ * `tickShaders`); `varyings` declarations shared by both stages;
+ * `vertexHead`/`fragmentHead` code before main (functions,
+ * uniforms) — injected ABOVE three's own `<common>` and
+ * `<lights_pars_begin>`, so a head function cannot call
+ * `getDistanceAttenuation`, `saturate`, `pow2` or read
+ * `directionalLights`/`pointLights`; only a BODY can;
+ * `vertexMain`/`fragmentMain` the body of main; `vertexShader`/
+ * `fragmentShader` complete sources instead of the mains; `util`
+ * include GLSL_UTIL (default true); `fog` take part in scene fog
+ * (default true — false only for screen-space passes); `additive`
+ * this material ADDS light (shafts, neon, glints), which sets
+ * additive blending and fades it into distance through ALPHA — the
+ * ordinary fog chunk mixes toward the fog colour, so an added light
+ * would get BRIGHTER as it recedes; `name`
+ * material name; plus any
+ * THREE.ShaderMaterial option (transparent, side, depthWrite...).
+ * @returns {THREE.ShaderMaterial} With `userData.astraShader = true`.
+ */
+export function makeShaderMaterial(opts = {}) {
+ const {
+ uniforms = {}, varyings = '', vertexHead = '', fragmentHead = '',
+ vertexMain = '', fragmentMain = '', vertexShader, fragmentShader,
+ util = true, fog = true, additive = false,
+ name = 'AstraShader', ...rest
+ } = opts;
+
+ const util_ = util ? GLSL_UTIL : '';
+ const shared = asVarying(varyings);
+ let vs = vertexShader;
+ let fs = fragmentShader;
+ if (!vs) {
+ vs = [
+ '#include <common>', LOG_PARS_V, fog ? FOG_PARS_V : '',
+ shared, util_, vertexHead,
+ 'void main() {',
+ ' vec3 transformed = position;',
+ vertexMain,
+ // fog_vertex reads a variable named mvPosition, so the
+ // position has to be built in two steps whether or not this
+ // material ends up fogged.
+ ' vec4 mvPosition = modelViewMatrix * vec4(transformed, 1.0);',
+ ' gl_Position = projectionMatrix * mvPosition;',
+ LOG_V,
+ fog ? FOG_V : '',
+ '}',
+ ].filter(Boolean).join('\n');
+ }
+ if (!fs) {
+ fs = [
+ '#define ASTRA_FRAG',
+ // The checker's own advice is "pass fog:false to opt
+ // out", and it reads a source marker — so passing the
+ // option has to write one, or the advice does nothing.
+ // `3dcv: no-fog` is the marker THIS harness's GLSL audit
+ // (runtime_js/lib/glsl_audit.mjs) accepts.
+ fog ? '' : '// 3dcv: no-fog',
+ '#include <common>', LOG_PARS_F, fog ? FOG_PARS_F : '',
+ shared, util_, fragmentHead,
+ 'void main() {',
+ ' ' + LOG_F,
+ fragmentMain,
+ // Fog is the LAST thing that happens to a fragment. Mixing
+ // toward the fog colour is right for an opaque surface and
+ // backwards for added light, which must simply arrive less.
+ fog ? (additive ? FOG_F_ADDITIVE : ' ' + FOG_F) : '',
+ OUT_F,
+ '}',
+ ].filter(Boolean).join('\n');
+ }
+ // Raw sources still get the chunks: the trap does not care who wrote
+ // the shader.
+ if (!vs.includes(LOG_PARS_V)) vs = '#include <common>\n' + LOG_PARS_V + '\n' + vs;
+ if (!vs.includes(LOG_V)) vs = intoMainEnd(vs, LOG_V);
+ // Raw sources opt out the same way: the trap does not care who
+ // wrote the shader, and neither does the checker.
+ if (!fog && !/(3dcv|astra3d): no-fog/.test(fs)) {
+ fs = '// 3dcv: no-fog\n' + fs;
+ }
+ if (!fs.includes(LOG_PARS_F)) fs = '#include <common>\n' + LOG_PARS_F + '\n' + fs;
+ if (!fs.includes(LOG_F)) fs = intoMainTop(fs, LOG_F);
+ if (!fs.includes('colorspace_fragment')) {
+ fs = intoMainEnd(fs, OUT_F);
+ }
+ if (/^\s*#version/m.test(vs + '\n' + fs)) {
+ throw new Error(
+ 'shader.js: remove the #version directive — three prepends ' +
+ 'its own and a second one is a compile error');
+ }
+ // uTime always exists as a uniform, so a shader that reads it must
+ // also DECLARE it; forgetting that is a compile error whose message
+ // names a line in three\'s assembled source, not in yours.
+ vs = dedupeUniforms(dedupeVaryings(withTime(vs)));
+ fs = dedupeUniforms(dedupeVaryings(withTime(fs)));
+
+ if (additive) {
+ rest.blending = rest.blending === undefined
+ ? THREE.AdditiveBlending : rest.blending;
+ rest.transparent = rest.transparent === undefined
+ ? true : rest.transparent;
+ rest.depthWrite = rest.depthWrite === undefined
+ ? false : rest.depthWrite;
+ }
+ const mat = new THREE.ShaderMaterial({
+ // fogColor / fogDensity / fogNear / fogFar must EXIST in the map
+ // or the renderer has nowhere to write the scene's fog into, and
+ // the material silently renders unfogged.
+ uniforms: Object.assign({ uTime: { value: 0 } },
+ fog ? THREE.UniformsLib.fog : {}, uniforms),
+ vertexShader: vs,
+ fragmentShader: fs,
+ fog: !!fog,
+ ...rest,
+ });
+ mat.name = name;
+ mat.userData.astraShader = true;
+ return mat;
+}
+
+/**
+ * Patch a built-in material (lighting, shadows and depth chunks stay).
+ *
+ * Built-ins already carry the depth chunks, so the trap here is a
+ * different one: three caches programs by material type and parameters,
+ * so two differently-patched MeshStandardMaterials would SHARE one
+ * compiled program. `customProgramCacheKey` is set from `name`.
+ *
+ * @param {THREE.Material} material The material to patch, in place.
+ * Patches CHAIN: call it again on the same material and both run, in
+ * call order, sharing one uniform map and one cache key.
+ *
+ * It patches IN PLACE, and `materials.js` hands the same instance to
+ * every caller that asked for the same options — so patching a shared
+ * material patches everything wearing it. Clone first when that is not
+ * what you want, and clone BEFORE patching: `Material.clone()` copies
+ * userData but not `onBeforeCompile`, so a clone of a patched material
+ * is a dead chain that still claims the cache key.
+ *
+ * `vertexBody` runs after `<begin_vertex>`, which is BEFORE
+ * `<project_vertex>` — so `transformed` there has not had
+ * `instanceMatrix`, skinning or morphing applied. On an InstancedMesh
+ * (which is most of what this engine builds) a world position computed
+ * there is the mesh origin's for every copy unless you apply
+ * `instanceMatrix` yourself under `#ifdef USE_INSTANCING`.
+ *
+ * @param {object} opts
+ * `name` names this patch in the shared cache key — every distinct
+ * GLSL needs its own, and options must vary by UNIFORM rather than by
+ * baked-in source, because the first material to compile a key
+ * decides the source for all of them; `uniforms` extra uniforms
+ * (uTime added, driven by `tickShaders`); `vertexHead`/`fragmentHead`
+ * code before main; `vertexBody` runs after `<begin_vertex>` (edit
+ * `transformed`); `fragmentBody` runs after `<color_fragment>` (edit
+ * `diffuseColor`); `util` include GLSL_UTIL.
+ * @returns {THREE.Material} The same material.
+ */
+/**
+ * Fail loudly when two chained patches define the same GLSL function.
+ *
+ * Varyings and uniforms are DECLARATIONS — two identical ones dedupe
+ * safely. A function has a body, so the same name from two libraries is
+ * either the same helper twice (harmless, dropped) or two different
+ * helpers (a redefinition error whose message names neither patch).
+ *
+ * @param {string[]} heads One head string per patch, in call order.
+ * @param {string[]} names The patch names, parallel to `heads`.
+ * @param {string} stage 'vertex' or 'fragment', for the message.
+ * @returns {string[]} The heads, with exact repeats blanked out.
+ * @throws {Error} When one name carries two different bodies.
+ */
+function dedupeFunctions(heads, names, stage) {
+ const seen = new Map();
+ // Every GLSL ES 3.0 return type, not just the common four:
+ // a helper returning ivec3 or mat2x3 slipped the check
+ // entirely and collided at compile time instead.
+ const TYPE = '(?:void|float|u?int|bool|[biu]?vec[234]'
+ + '|mat[234](?:x[234])?)';
+ const re = new RegExp(
+ '^\\s*(?:lowp |mediump |highp )?' + TYPE
+ + '\\s+(\\w+)\\s*\\([^)]*\\)\\s*\\{', 'gm');
+ return heads.map((head, i) => {
+ let out = head;
+ for (const m of head.matchAll(re)) {
+ const fn = m[1];
+ // From the signature's first character, not the line start:
+ // the same helper indented two spaces in one patch and flush
+ // in another is the same helper, not a redefinition.
+ const body = fnBody(
+ head, m.index + (m[0].length - m[0].trimStart().length));
+ const prev = seen.get(fn);
+ if (!prev) { seen.set(fn, { body, from: names[i] }); continue; }
+ if (prev.body === body) {
+ out = out.replace(body, '');
+ continue;
+ }
+ throw new Error(
+ 'shader.js: patches "' + prev.from + '" and "' + names[i]
+ + '" both define ' + fn + '() in the ' + stage
+ + ' stage with different bodies. Prefix your helpers '
+ + '(astra<Lib>Name) — GLSL has one global namespace and '
+ + 'the compile error names neither patch.');
+ }
+ return out;
+ });
+}
+
+/** The source of one function, from its signature to its closing brace. */
+function fnBody(src, start) {
+ let depth = 0;
+ for (let i = src.indexOf('{', start); i < src.length; i++) {
+ if (src[i] === '{') depth++;
+ else if (src[i] === '}' && --depth === 0) {
+ return src.slice(start, i + 1);
+ }
+ }
+ return src.slice(start);
+}
+
+export function patchStandard(material, opts = {}) {
+ const {
+ name = 'AstraPatch', uniforms = {}, vertexHead = '',
+ fragmentHead = '', vertexBody = '', fragmentBody = '', util = true,
+ roughnessBody = '', metalnessBody = '', outputBody = '',
+ } = opts;
+ // Patches CHAIN. Assigning onBeforeCompile outright — which this did
+ // — silently dropped every earlier patch and its uniforms, and
+ // instanceVariation() patches from inside, so a varied instanced
+ // material plus any second patch lost one of them with no error.
+ if (material.userData.shared && !material.userData.astraShared) {
+ material.userData.astraShared = true;
+ console.warn(
+ 'patchStandard: ' + (material.name || material.type)
+ + ' is a SHARED material from materials.js — every mesh using '
+ + 'it takes this patch. Clone it first if that is not what '
+ + 'you want (and clone before patching, not after).');
+ }
+ const shared = material.userData.uniforms || { uTime: { value: 0 } };
+ Object.assign(shared, uniforms);
+ material.userData.uniforms = shared;
+ material.userData.astraShader = true;
+ const patches = material.userData.astraPatches || [];
+ const at = patches.findIndex((p) => p.name === name);
+ const patch = { name, vertexHead, fragmentHead, vertexBody, fragmentBody,
+ roughnessBody, metalnessBody, outputBody, util };
+ // Re-applying a patch retunes it (its uniforms are already merged);
+ // pushing it twice would declare its varyings twice.
+ if (at >= 0) patches[at] = patch;
+ else patches.push(patch);
+ material.userData.astraPatches = patches;
+ // The FIRST material to compile a given key decides the GLSL every
+ // material with that key gets, so the key must name every patch in
+ // the chain, in order. Vary behaviour by uniform, never by baking a
+ // value into the source under a fixed name.
+ material.customProgramCacheKey =
+ () => 'astra:' + patches.map((p) => p.name).join('+');
+ material.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, shared);
+ const util_ = patches.some((p) => p.util) ? GLSL_UTIL : '';
+ const live = patches.filter((p) => p.vertexHead || p.fragmentHead);
+ const vHead = dedupeFunctions(
+ live.map((p) => p.vertexHead || ''),
+ live.map((p) => p.name), 'vertex').filter(Boolean);
+ const fHead = dedupeFunctions(
+ live.map((p) => p.fragmentHead || ''),
+ live.map((p) => p.name), 'fragment').filter(Boolean);
+ // One replace per hook, bodies joined in CALL order: replacing
+ // the same #include per patch inserts each new body ABOVE the
+ // last, which runs the chain backwards.
+ const vBody = patches.map((p) => p.vertexBody).filter(Boolean)
+ .join('\n');
+ const fBody = patches.map((p) => p.fragmentBody).filter(Boolean)
+ .join('\n');
+ let vs = util_ + '\n' + asVarying(vHead.join('\n')) + '\n'
+ + shader.vertexShader;
+ let fs = '#define ASTRA_FRAG\n' + util_ + '\n'
+ + asVarying(fHead.join('\n')) + '\n' + shader.fragmentShader;
+ if (vBody) {
+ vs = vs.replace('#include <begin_vertex>',
+ '#include <begin_vertex>\n' + vBody);
+ }
+ if (fBody) {
+ fs = fs.replace('#include <color_fragment>',
+ '#include <color_fragment>\n' + fBody);
+ }
+ // The three LATER hooks. `<color_fragment>` is the albedo, and for
+ // years it was the only one — which is why a rust crust could only
+ // be sold by retuning the WHOLE material's roughness (a 30 % crust
+ // demattes 100 % of the surface), and why aerial perspective could
+ // only lift reflectance instead of adding airlight. Each is opt-in
+ // and empty by default, so no existing patch changes.
+ const join = (key) => patches.map((p) => p[key]).filter(Boolean)
+ .join('\n');
+ // after <roughnessmap_fragment>: `roughnessFactor` is in scope, and
+ // every fragmentBody local above it still is.
+ const rBody = join('roughnessBody');
+ if (rBody) {
+ fs = fs.replace('#include <roughnessmap_fragment>',
+ '#include <roughnessmap_fragment>\n' + rBody);
+ }
+ // after <metalnessmap_fragment>: `metalnessFactor` in scope.
+ const mBody = join('metalnessBody');
+ if (mBody) {
+ fs = fs.replace('#include <metalnessmap_fragment>',
+ '#include <metalnessmap_fragment>\n' + mBody);
+ }
+ // after <opaque_fragment>: `gl_FragColor` holds the LIT result, still
+ // linear — tonemapping and the colour-space convert come after this,
+ // and fog after those. This is the only hook that can add light
+ // rather than reflectance (airlight, emission veils).
+ const oBody = join('outputBody');
+ if (oBody) {
+ fs = fs.replace('#include <opaque_fragment>',
+ '#include <opaque_fragment>\n' + oBody);
+ }
+ // AFTER the bodies are in: uTime is read by the bodies far more
+ // often than by the heads, and declaring before they exist left
+ // every animated patch failing on an undeclared identifier.
+ shader.vertexShader = dedupeUniforms(dedupeVaryings(withTime(vs)));
+ shader.fragmentShader =
+ dedupeUniforms(dedupeVaryings(withTime(fs)));
+ };
+ material.needsUpdate = true;
+ return material;
+}
+
+
+/**
+ * Compose a roughness multiplier from several patches, in one place.
+ *
+ * This is the WHOLE-MATERIAL lever, and it stays the right one for a
+ * look that is uniform over the surface (a wet slab, a polished floor).
+ * For a look that covers only PART of it — a rust crust, a dust film —
+ * `patchStandard({ roughnessBody })` now reaches per-pixel roughness
+ * after `<roughnessmap_fragment>`; prefer that, because retuning the
+ * material demattes the clean 70 % along with the corroded 30 %.
+ *
+ * Two libraries each keeping
+ * their own "original" value cannot see one another: whichever runs
+ * second takes the first's result as the base, and re-applying either
+ * one re-bases it again. This keeps the true base and one factor per
+ * named patch, so any order and any number of re-applications land on
+ * the same number.
+ *
+ * @param {THREE.Material} material The material to retune, in place.
+ * @param {string} key The patch's name, one factor per key.
+ * @param {number} factor Multiplier on the material's ORIGINAL
+ * roughness; 1 removes this patch's contribution.
+ * @param {number} [floor] Lower clamp (default 0.04 — a perfect mirror
+ * is never what any of these effects mean).
+ * @returns {number} The resulting roughness, or NaN for a material that
+ * has none (MeshBasicMaterial and friends).
+ */
+export function composeRoughness(material, key, factor, floor = 0.04) {
+ if (typeof material.roughness !== 'number') return NaN;
+ const store = material.userData.astraRoughness
+ || { base: material.roughness, factors: {} };
+ store.factors[key] = factor;
+ material.userData.astraRoughness = store;
+ let r = store.base;
+ for (const k of Object.keys(store.factors).sort()) {
+ r *= store.factors[k];
+ }
+ // three does not clamp roughness, and every dirt/rust/dust patch
+ // needs a factor above 1 — two matte patches on an already-rough
+ // material compose straight past the top of the range.
+ material.roughness = Math.min(1, Math.max(floor, r));
+ return material.roughness;
+}
+
+
+/**
+ * Drive every astra shader under `root` from one call in `tick()`.
+ *
+ * @param {THREE.Object3D} root Scene or group to walk.
+ * @param {number} t Scene time in seconds.
+ * @returns {number} How many materials were advanced.
+ */
+export function tickShaders(root, t) {
+ let n = 0;
+ root.traverse((o) => {
+ for (const m of [].concat(o.material || [])) {
+ if (!m) continue;
+ const u = (m.uniforms && m.uniforms.uTime)
+ ? m.uniforms
+ : (m.userData && m.userData.uniforms);
+ if (u && u.uTime) { u.uTime.value = t; n++; }
+ }
+ });
+ return n;
+}
+
+/**
+ * Give a vertex-displaced mesh a shadow that moves with it.
+ *
+ * three draws the shadow map with its OWN MeshDepthMaterial, which
+ * never sees `patchStandard`: a displaced surface casts the shadow of
+ * its undisplaced geometry — and for the `position`-at-zero instanced
+ * lattices these libraries build, that is no shadow at all. This
+ * patches a depth material with the SAME head and body and shares the
+ * surface's uniform map, so one `tickShaders` advances both.
+ *
+ * The depth stage defines FLAT_SHADED, so a body whose vNormal write
+ * sits under `#ifndef FLAT_SHADED` (as every lib here does) can be
+ * passed WHOLE — a depth shader has no vNormal to write.
+ *
+ * @param {THREE.Mesh} mesh The mesh, its surface patched already.
+ * @param {string} name Cache-key name for this depth patch.
+ * @param {string} head The vertex head the body needs.
+ * @param {string} body The vertex body: the displacement, or the whole
+ * body when its normal half is FLAT_SHADED-guarded.
+ * @returns {THREE.Mesh} The same mesh, now casting.
+ */
+export function shadowLike(mesh, name, head, body) {
+ // A depth pass that matches the surface EXACTLY self-shadows into
+ // moire, and shadow bias belongs to a light this library cannot
+ // see: the offset is the surface's own, so it travels with it.
+ const dep = new THREE.MeshDepthMaterial({
+ depthPacking: THREE.RGBADepthPacking, side: THREE.DoubleSide,
+ polygonOffset: true, polygonOffsetFactor: 3, polygonOffsetUnits: 8,
+ });
+ dep.userData.uniforms = mesh.material.userData.uniforms;
+ patchStandard(dep, {
+ name,
+ vertexHead: '#define FLAT_SHADED 1\n' + head,
+ vertexBody: body,
+ });
+ mesh.customDepthMaterial = dep;
+ mesh.castShadow = true;
+ return mesh;
+}
+
+/**
+ * Give every instance its own hue, scale and phase.
+ *
+ * Two hundred pixel-identical copies is a large part of what the judge
+ * calls "primitives". This adds an `aVar` attribute (hue, scale, phase)
+ * and, for built-in materials, applies the hue and scale in the shader.
+ *
+ * @param {THREE.InstancedMesh} mesh The instanced mesh to vary.
+ * @param {object} [opts] `seed` (default 1); `hue` radians of hue swing
+ * (default 0.10); `scale` relative size swing (default 0.12);
+ * `apply` patch the material to consume it (default true).
+ * @returns {THREE.InstancedMesh} The same mesh.
+ */
+export function instanceVariation(mesh, opts = {}) {
+ // 0.10 rad is +-5.7 deg: measured across the delivered corpus
+ // that reads as one albedo, because hue rotation is invisible
+ // until the swing is wide enough to cross a colour name.
+ const { seed = 1, hue = 0.34, scale = 0.12, apply = true } = opts;
+ const count = mesh.count || 0;
+ if (!count) return mesh;
+ let s = seed >>> 0 || 1;
+ const rand = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+ const data = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ data[i * 3] = (rand() * 2 - 1) * hue;
+ data[i * 3 + 1] = 1 + (rand() * 2 - 1) * scale;
+ data[i * 3 + 2] = rand() * Math.PI * 2;
+ }
+ mesh.geometry.setAttribute(
+ 'aVar', new THREE.InstancedBufferAttribute(data, 3));
+ if (apply && mesh.material && !mesh.material.userData.astraVaried) {
+ patchStandard(mesh.material, {
+ name: 'variation:' + (mesh.material.name || mesh.uuid.slice(0, 8)),
+ vertexHead: 'attribute vec3 aVar;\nvarying vec3 vAstraVar;',
+ vertexBody: ' vAstraVar = aVar;\n transformed *= aVar.y;',
+ fragmentHead: 'varying vec3 vAstraVar;',
+ fragmentBody:
+ ' diffuseColor.rgb = astraHueShift(diffuseColor.rgb,' +
+ ' vAstraVar.x);',
+ });
+ mesh.material.userData.astraVaried = true;
+ }
+ return mesh;
+}
+
+/**
+ * Sweep a cross-section along a path — one body, not stacked sheets.
+ *
+ * Parallel planes betray themselves as separate layers the moment the
+ * eye is edge-on, and a single plane collapses to a line. A section
+ * swept along a curve keeps its body from every angle, and the closed
+ * loop naturally reads denser at the silhouette, where the surface
+ * turns away.
+ *
+ * @param {function(number): {x: number, y: number, z: number}} path
+ * Centre of the section at t in [0, 1].
+ * @param {function(number, number): {x: number, y: number, z: number}}
+ * section Offset from that centre at angle a in [0, 2pi) and the same
+ * t; return the shape of the cross-section there.
+ * @param {object} [opts] `nu` points around the section (default 48),
+ * `nv` steps along the path (default 64), `t0`/`t1` path range
+ * (default 0..1).
+ * @returns {THREE.BufferGeometry} With uv (u around, v along) and
+ * computed normals.
+ */
+export function sweepProfile(path, section, opts = {}) {
+ const { nu = 48, nv = 64, t0 = 0, t1 = 1 } = opts;
+ const pos = [], uv = [], idx = [];
+ for (let j = 0; j <= nv; j++) {
+ const t = t0 + (t1 - t0) * (j / nv);
+ const c = path(t);
+ for (let i = 0; i <= nu; i++) {
+ const a = (i / nu) * Math.PI * 2;
+ const o = section(a, t);
+ pos.push(c.x + o.x, c.y + o.y, c.z + o.z);
+ uv.push(i / nu, j / nv);
+ }
+ }
+ for (let j = 0; j < nv; j++) {
+ for (let i = 0; i < nu; i++) {
+ const a = j * (nu + 1) + i;
+ const b = a + 1;
+ const c = a + nu + 1;
+ idx.push(a, c, b, b, c, c + 1);
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setIndex(idx);
+ g.computeVertexNormals();
+ return g;
+}
+
+/**
+ * A billboard geometry that survives the ambient-occlusion pass.
+ *
+ * `GTAOPass` redraws the scene with an override material that does NOT
+ * run a custom vertex shader — it draws raw `position`. A quad kept in
+ * `position` and displaced in the shader therefore sits at the world
+ * origin during AO and burns a black rectangle there. Corners ride on
+ * `aCorner` instead, and `position` stays at zero.
+ *
+ * @param {number} count Instance count.
+ * @param {number} [w] Quad width. @param {number} [h] Quad height.
+ * @param {number} [radius] World radius the instances cover, for
+ * CULLING only: `position` is all zeros, so without a stated sphere
+ * three drops the whole field the moment the origin leaves frame.
+ * The bounding BOX is deliberately left alone — it is what measures
+ * the asset, and a stated one would put the asset's floor at
+ * -radius.
+ * @returns {THREE.InstancedBufferGeometry} With `aCorner`, `uv`
+ * and a flat `normal` — the last one for any built-in material
+ * put on this geometry, which would otherwise take NaN shadow
+ * coordinates from a zero normal.
+ */
+export function instancedQuad(count, w = 1, h = 1, radius = 1e4) {
+ const base = new THREE.PlaneGeometry(w, h);
+ const g = new THREE.InstancedBufferGeometry();
+ g.index = base.index;
+ g.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(base.attributes.position.count * 3), 3));
+ g.setAttribute('aCorner', base.attributes.position);
+ g.setAttribute('uv', base.attributes.uv);
+ // A built-in material reads `normal`, and without it objectNormal is
+ // zero: <shadowmap_vertex> normalizes vec3(0) and every shadow
+ // coordinate on a receiving mesh comes out NaN.
+ g.setAttribute('normal', base.attributes.normal);
+ g.instanceCount = count;
+ // Culling reads the SPHERE, and every measurement of the asset
+ // reads the BOX. Stating the sphere stops three culling the field
+ // the moment the origin leaves frame; leaving the box alone keeps
+ // min_y and the island check honest.
+ g.boundingSphere = new THREE.Sphere(new THREE.Vector3(), radius);
+ return g;
+}
+
+/**
+ * Keep a transparent mesh out of every pass that draws with an OVERRIDE
+ * material — which means out of ambient occlusion.
+ *
+ * GTAOPass rebuilds depth and normals by setting `scene.overrideMaterial`
+ * and drawing everything, and an override material is opaque: a stack of
+ * fog sheets, a curtain of rain or a shaft of light is a stack of SOLID
+ * FLOORS in that buffer, occluding whatever is behind it. Measured on
+ * the height fog with the bank made invisible but still present: 50/255
+ * of darkening on ground the fog never touched, with the footprint's own
+ * disc as a hard rim.
+ *
+ * The draw range is restored afterwards, so a raycast or a later frame
+ * cannot inherit an empty one. Shadow passes also draw with a foreign
+ * material, so a mesh guarded here stops casting too — which is right
+ * for anything you would call a veil and wrong for anything you would
+ * call a wall.
+ *
+ * @param {THREE.Object3D} obj Mesh, or a group whose meshes to guard.
+ * @returns {THREE.Object3D} The same object.
+ */
+export function keepOutOfDepthPasses(obj) {
+ obj.traverse((o) => {
+ if (!o.isMesh || o.userData.astraNoOverride) return;
+ const own = o.material;
+ o.userData.astraNoOverride = true;
+ // A shaft of light does not cast a shadow. three 0.184 draws
+ // the shadow map through its own hook, so the draw-range guard
+ // below never sees it — the flag is what keeps it out.
+ o.castShadow = false;
+ o.onBeforeRender = (r, s, cam, geo, m) => {
+ geo.setDrawRange(0, m === own ? Infinity : 0);
+ };
+ o.onAfterRender = (r, s, cam, geo) => {
+ geo.setDrawRange(0, Infinity);
+ };
+ });
+ return obj;
+}
+
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/signage.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/signage.js
new file mode 100644
index 00000000..dede75f0
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/signage.js
@@ -0,0 +1,299 @@
+/**
+ * Readable lettering: real extruded glyphs from the fonts the npm
+ * three package already ships — no new deps, no import-map edits.
+ * The load path is DUAL-RUNTIME and both halves are load-bearing:
+ * headless Chrome fetches over HTTP, plain node (census / assets_api)
+ * reads the same file off disk. `makeText` is async: await ONCE at
+ * module top level, `.clone()` per copy inside `build()`.
+ *
+ * Font path, ported 2026-09-01 — BOTH halves were broken on this host,
+ * because both assumed a `node_modules` next to the app:
+ * · browser — the workspace is served at `/` and three at
+ * `/__runtime/node_modules/`, so `../../node_modules/...` 404d and
+ * the module only survived by falling through to its CDN pin: it
+ * did not work offline, and the harness counts every 404 as a
+ * console error (2 per render, run marked not-ok).
+ * · node — a workspace / test probe has no parent `node_modules` at
+ * all, so `createRequire().resolve('three/examples/fonts/…')` threw
+ * MODULE_NOT_FOUND and every census-side makeText died.
+ * Both now ask `import.meta.resolve` where `three` itself came from —
+ * the page's import map in Chrome, the module resolver (our
+ * `resolve_three.mjs` hook included) in node — and the old guesses are
+ * kept as later candidates for the reference app's own layout.
+ *
+ * Grading, same pass: extruded letters lit only by sky + environment —
+ * the normal case, since a sign faces the viewer and the sun rarely
+ * does — used to read as a flat pale cutout. The glyphs now carry a
+ * paint-variance vertex colour (mottle + weathering + darker extrusion
+ * walls + a bright bevel rim), so the depth reads without a key light,
+ * they cast shadows by default, and an emissive sign carries its own
+ * practical so it LIGHTS the board it is bolted to instead of sitting
+ * on it as a decal.
+ */
+
+import * as THREE from 'three';
+import { FontLoader } from 'three/addons/loaders/FontLoader.js';
+import { TextGeometry } from 'three/addons/geometries/TextGeometry.js';
+
+const FONT_FILES = {
+ regular: 'helvetiker_regular.typeface.json',
+ bold: 'helvetiker_bold.typeface.json',
+};
+
+// The reference kept a CDN pin here as a last resort. It is deleted:
+// this contract forbids the network outright, the run is offline, and
+// the only thing it ever did on this host was mask the `../../node_modules`
+// 404 that `import.meta.resolve` (above) now resolves properly.
+const IS_NODE = typeof process !== 'undefined' &&
+ !!(process.versions && process.versions.node);
+
+const _fontCache = new Map();
+
+/** Font URLs to try, best first — ONE list for both runtimes.
+ * `import.meta.resolve` answers from the page's import map in Chrome and
+ * from the module resolver (our `resolve_three.mjs` hook included) in
+ * node, so "wherever three itself came from" is the same question in
+ * both, and this module has already proved three resolves: it imports
+ * it at the top. Everything after those two entries is a guess kept
+ * for other layouts. */
+function _fontUrls(file) {
+ const urls = [];
+ const add = (u) => { if (u && urls.indexOf(u) === -1) urls.push(u); };
+ const resolve = (typeof import.meta.resolve === 'function')
+ ? import.meta.resolve : null;
+ if (resolve) {
+ try {
+ // examples/jsm/loaders/FontLoader.js -> examples/fonts/
+ add(new URL('../../fonts/' + file,
+ resolve('three/addons/loaders/FontLoader.js')).href);
+ } catch (_e) { /* no such entry — try the next form */ }
+ try {
+ // build/three.module.js -> examples/fonts/
+ add(new URL('../examples/fonts/' + file, resolve('three')).href);
+ } catch (_e) { /* ditto */ }
+ }
+ // a node_modules sibling of src/ (the reference app's own layout)
+ add(new URL('../../node_modules/three/examples/fonts/' + file,
+ import.meta.url).href);
+ return urls;
+}
+
+async function _loadFontJson(file) {
+ const tried = [];
+ const urls = _fontUrls(file);
+ if (IS_NODE) {
+ // an app whose node_modules is a PARENT of this file resolves the
+ // font through the three exports map; a bare workspace (our runs,
+ // the test probes) does not, and falls back to the URL list.
+ try {
+ const { createRequire } = await import('node:module');
+ urls.push(createRequire(import.meta.url)
+ .resolve('three/examples/fonts/' + file));
+ } catch (_e) { /* no parent node_modules */ }
+ }
+ for (const url of urls) {
+ try {
+ if (IS_NODE && !/^https?:/.test(url)) {
+ const { readFile } = await import('node:fs/promises');
+ const { fileURLToPath } = await import('node:url');
+ const p = url.startsWith('file:') ? fileURLToPath(url) : url;
+ return JSON.parse(await readFile(p, 'utf-8'));
+ }
+ const r = await fetch(url);
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ return await r.json();
+ } catch (e) {
+ tried.push(url + ': ' + ((e && e.message) || e));
+ }
+ }
+ throw new Error('font load failed: ' + file + ' [' + tried.join(' | ') + ']');
+}
+
+/**
+ * Load a shipped helvetiker font, cached per variant.
+ *
+ * @param {object} [opts] `bold` (default false) picks the bold face.
+ * @returns {Promise<object>} A parsed `Font` for TextGeometry.
+ */
+export function loadHelvetiker(opts = {}) {
+ const file = FONT_FILES[opts.bold ? 'bold' : 'regular'];
+ let p = _fontCache.get(file);
+ if (!p) {
+ p = _loadFontJson(file).then((json) => new FontLoader().parse(json));
+ _fontCache.set(file, p);
+ }
+ return p;
+}
+
+/**
+ * Paint variance as a vertex colour, in place. Deterministic (a pure
+ * function of position + normal), so a re-render of the same string is
+ * byte-identical. Three parts, all measured on this pipeline against
+ * a sign lit by sky + environment only:
+ * · mottle — two sine octaves in glyph-relative units; paint, print
+ * and enamel are never one flat value, and the variance is what
+ * stops a big letter from reading as a screen-space cutout
+ * · weathering — the bottom of a letter is dirtier than its top
+ * · form — the extrusion WALLS go down to 0.80 (they see far less
+ * sky than the face) while the BEVEL rim, which does catch it,
+ * goes up to +10 %. Both are read off |n.z|, so this needs no
+ * material groups and survives any bevel setting.
+ */
+const MOTTLE = 0.070; // paint value swing, +/- (peak |m| is ~1.02)
+const MOTTLE_HUE = 0.034; // warm/cool swing riding the same signal
+// Everything below is NORMALISED to a ceiling of exactly 1.0, so a vertex
+// colour can only ever DARKEN: `color` stays the true albedo (the brief's
+// 0.02-0.8 linear band is a ceiling, and a rim that multiplied it by 1.14
+// would have quietly broken it).
+const FORM_PEAK = 1 + 0.10;
+const MOTTLE_PEAK = (1 + MOTTLE * 1.02) * (1 + MOTTLE_HUE * 1.02);
+
+function _paintVariance(geo, size, amount) {
+ const pos = geo.attributes.position;
+ const nrm = geo.attributes.normal;
+ if (!pos || !nrm) return;
+ const n = pos.count;
+ const col = new Float32Array(n * 3);
+ const s = 1 / Math.max(size, 1e-4);
+ for (let i = 0; i < n; i++) {
+ const x = pos.array[i * 3] * s;
+ const y = pos.array[i * 3 + 1] * s;
+ const nz = Math.abs(nrm.array[i * 3 + 2]);
+
+ // mottle in [-1, 1]-ish, hue-signed: warm where the paint is thick
+ const m = 0.46 * Math.sin(x * 2.7 + 0.9) +
+ 0.26 * Math.sin(x * 7.3 + y * 3.1 + 2.1) +
+ 0.30 * Math.sin(y * 4.6 - 1.3);
+ // grime in the first 0.35 of cap height
+ const grime = 1 - 0.06 * Math.max(0, 1 - Math.max(0, y) / 0.35);
+ // form: walls dark, bevel rim the brightest thing on the glyph
+ const wall = 1 - Math.min(1, nz * 1.6);
+ const rim = 4 * nz * (1 - nz);
+ const form = (1 - 0.22 * wall + 0.10 * rim) / FORM_PEAK;
+
+ const v = (1 + MOTTLE * m) * grime * form / MOTTLE_PEAK;
+ const hue = MOTTLE_HUE * m;
+ // `amount` lerps the whole thing back towards flat white
+ col[i * 3] = 1 + amount * (v * (1 + hue) - 1);
+ col[i * 3 + 1] = 1 + amount * (v - 1);
+ col[i * 3 + 2] = 1 + amount * (v * (1 - hue) - 1);
+ }
+ geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
+}
+
+/**
+ * Build one line of real extruded 3D text: centered on X/Z, BASELINE
+ * at y = 0, facing +Z (`userData.size` carries the measured bbox).
+ *
+ * @param {string} str One line of text (no newlines — stack meshes for
+ * multiple lines).
+ * @param {object} [opts] `size` glyph height in metres (default 1);
+ * `depth` extrusion depth (default 0.15 * size); `bold` (default
+ * false); `bevel` (default true — softened edges, razor edges read
+ * as CG, and the bevel rim is where a sky-lit letter gets its
+ * catchlight); `curveSegments` (default 8); `color` (default
+ * 0xe7e3da — a paint white: 0xffffff-class albedo bakes a letter to
+ * a flat blown slab under ACES at exposure 1.0), `roughness`
+ * (default 0.45), `metalness` (default 0.1); `variation` 0..1
+ * (default 1) scales the baked paint mottle / wall shading, 0 drops
+ * the vertex colours entirely (a `material` you pass in reads them
+ * only if it sets `vertexColors`); `emissive` + `emissiveIntensity`
+ * (default 1.6 when emissive is set — there is NO bloom pass in this
+ * pipeline, so 1.5-4 is the whole usable range and 20 is a white
+ * blob) make a neon / backlit sign; `light` the practical an
+ * emissive sign throws on its own board — `false` to drop it (do
+ * that for a facade carrying dozens of signs: this is one real
+ * PointLight per line), a number to set its candela directly. The
+ * default is derived — `1.8 * emissiveIntensity * inked area` —
+ * measured on a 0.42 m OPEN sign 0.4 m off its board: at night the
+ * board just above it went from r 0.174 / warmth +0.023 to r 0.265 /
+ * warmth +0.108, and by day the sun still owns the frame;
+ * `shadow: false` opts out of
+ * cast/receive shadows (on by default — the glyph shadow on the
+ * board is what says "extruded", not "decal"); `material` replaces
+ * the built material entirely; `font` supplies a pre-loaded Font and
+ * skips loading.
+ * @returns {Promise<THREE.Mesh>} Mesh named `SignText`; the practical,
+ * when there is one, is `mesh.userData.light`.
+ */
+export async function makeText(str, opts = {}) {
+ const font = opts.font || await loadHelvetiker({ bold: !!opts.bold });
+ const size = opts.size === undefined ? 1 : opts.size;
+ const depth = opts.depth === undefined ? 0.15 * size : opts.depth;
+ const bevel = opts.bevel === undefined ? true : !!opts.bevel;
+
+ const geo = new TextGeometry(String(str), {
+ font: font,
+ size: size,
+ depth: depth,
+ curveSegments:
+ opts.curveSegments === undefined ? 8 : opts.curveSegments,
+ bevelEnabled: bevel,
+ // A wider, rounder bevel than the reference's razor lip: this ring
+ // is the only part of a front-facing letter that sees the sky, and
+ // it carries the catchlight. `bevelSize` is in-plane, so it grows
+ // the glyph box — 0.015 is the most that keeps a size-1 line inside
+ // the 1.1 m the placement contract is measured against.
+ bevelThickness: 0.024 * size,
+ bevelSize: 0.015 * size,
+ bevelSegments: 3,
+ });
+ geo.computeBoundingBox();
+ const bb = geo.boundingBox;
+ geo.translate(
+ -0.5 * (bb.min.x + bb.max.x), 0, -0.5 * (bb.min.z + bb.max.z));
+
+ const variation = opts.variation === undefined
+ ? 1 : Math.max(0, Math.min(1, opts.variation));
+ if (variation > 0) _paintVariance(geo, size, variation);
+
+ let mat = opts.material;
+ if (!mat) {
+ mat = new THREE.MeshStandardMaterial({
+ color: opts.color === undefined ? 0xe7e3da : opts.color,
+ roughness: opts.roughness === undefined ? 0.45 : opts.roughness,
+ metalness: opts.metalness === undefined ? 0.1 : opts.metalness,
+ vertexColors: variation > 0,
+ });
+ if (opts.emissive !== undefined) {
+ mat.emissive = new THREE.Color(opts.emissive);
+ mat.emissiveIntensity = opts.emissiveIntensity === undefined
+ ? 1.6 : opts.emissiveIntensity;
+ }
+ }
+
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.name = 'SignText';
+ const w = bb.max.x - bb.min.x;
+ const h = bb.max.y - bb.min.y;
+ const d = bb.max.z - bb.min.z;
+ mesh.userData.size = { w: w, h: h, d: d };
+ // Lettering is MOUNTED — on a board, a facade, a plinth — so the
+ // host's settle pass (runtime_js/lib/host_placement.mjs) must never
+ // drop it onto the terrain the way it seats a floating crate.
+ mesh.userData.placement = 'free';
+ if (opts.shadow === undefined || opts.shadow) {
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+ }
+
+ // A neon / backlit sign that lights nothing is a decal. Derive the
+ // candela from what the letters actually emit: radiance x inked area
+ // (~28 % of the bbox for a line of caps) x a lambertian-ish gain.
+ const emi = mat.emissive;
+ const emiI = mat.emissiveIntensity === undefined ? 1 : mat.emissiveIntensity;
+ const lit = !!emi && (emi.r + emi.g + emi.b) > 0.01 && emiI > 0;
+ if (lit && opts.light !== false) {
+ const area = Math.max(0.02, 0.28 * w * h);
+ const cd = typeof opts.light === 'number'
+ ? opts.light : 1.8 * emiI * area;
+ const light = new THREE.PointLight(emi.clone(), cd, 0, 2);
+ light.name = 'SignGlow';
+ // just off the letter faces, at the optical centre of the line
+ light.position.set(0, 0.5 * h, 0.5 * d + 0.55 * size);
+ light.castShadow = false;
+ mesh.add(light);
+ mesh.userData.light = light;
+ }
+ return mesh;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/sky.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/sky.js
new file mode 100644
index 00000000..afd9709d
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/sky.js
@@ -0,0 +1,249 @@
+/**
+ * The physical atmosphere dome — a graded Preetham sky in one call.
+ * Contract: the dome only GLOWS — pair it with a key light on the
+ * SAME sun vector (`sunRig()` from ./environment.js) — and it owns
+ * the backdrop: `scene.background` stays null, never a second dome.
+ *
+ * Graded for THIS renderer (ACES filmic, exposure 1.0, no post chain,
+ * measured 2026-09-01): three's Sky shader gamma-encodes its radiance
+ * (`pow(x, 1/2.4)`) BEFORE the tone map, so on an exposure-1.0 canvas
+ * the whole dome landed at (240,244,246) — a white card, and the one
+ * defect every day frame carried. The patch below keeps the Preetham
+ * chroma and re-grades its transfer: zenith ~(105,152,195), horizon
+ * ~(218,222,224), sun-side haze brighter, nothing blown. Below the
+ * horizon the un-encoded Preetham is black, so a night gradient (deep
+ * blue zenith, fog-family horizon, an afterglow band toward the set
+ * sun) fades in with solar depression — one dome serves day, golden,
+ * dusk AND night. `skyRadiance()` is the same model on the CPU, so
+ * `sunRig()` can bake an environment map that matches what the dome
+ * shows: reflections and the sky the camera sees agree by construction.
+ */
+
+import * as THREE from 'three';
+import { Sky } from 'three/addons/objects/Sky.js';
+
+/**
+ * The battery-graded atmosphere and its transfer grade, shared with
+ * `sunRig()`'s environment bake (import, never restate).
+ * `gain`/`gamma`: retColor = gain * pow(tex, gamma / 2.4).
+ */
+export const SKY_GRADE = Object.freeze({
+ turbidity: 4.5, rayleigh: 1.6, mieCoefficient: 0.0035, mieDirectionalG: 0.8,
+ gain: 0.36, gamma: 1.7,
+ // Night gradient, LINEAR (pre-ACES); solved against three's ACES so
+ // the canvas reads zenith (9,13,32) / horizon (38,52,86).
+ nightZenith: [0.0109, 0.0137, 0.0312],
+ nightHorizon: [0.0368, 0.0526, 0.1052],
+ afterglow: [0.1741, 0.0742, 0.0335],
+ // Low-sun warmth multiplier toward the sun (golden hour).
+ warm: [1.0, 0.74, 0.5],
+});
+
+/** 0 with the sun up, 1 once it is ~9 deg below the horizon. */
+export function nightAmount(sunY) {
+ return THREE.MathUtils.smoothstep(-sunY, 0.0, 0.15);
+}
+
+/** Twilight afterglow weight: strongest just after sunset, gone by -20 deg. */
+export function afterglowAmount(sunY) {
+ if (sunY >= 0) return 0.35 * (1 - THREE.MathUtils.smoothstep(sunY, 0.0, 0.1));
+ return 1 - THREE.MathUtils.smoothstep(-sunY, 0.03, 0.34);
+}
+
+/** Golden-hour warmth weight: 1 at the horizon, 0 by 20 deg elevation. */
+export function lowSunAmount(sunY) {
+ return 1 - THREE.MathUtils.smoothstep(sunY, 0.02, 0.35);
+}
+
+const _up = new THREE.Vector3(0, 1, 0);
+const _tmp = new THREE.Vector3();
+
+/**
+ * The graded dome's LINEAR radiance for a view direction — three's
+ * Sky.js (r182) shader on the CPU, with the same grade the patched dome
+ * applies (gain/gamma, night gradient, afterglow, low-sun warmth). No
+ * solar disc: the caller decides how the sun reads in its bake.
+ *
+ * @param {THREE.Vector3} dir Unit view direction.
+ * @param {THREE.Vector3} sunDir Unit sun direction (may be below the horizon).
+ * @param {object} [opts] `turbidity`, `rayleigh`, `mieCoefficient`,
+ * `mieDirectionalG`, `gain`, `gamma` (SKY_GRADE defaults).
+ * @returns {[number, number, number]} Linear RGB radiance.
+ */
+export function skyRadiance(dir, sunDir, opts = {}) {
+ const T = opts.turbidity === undefined ? SKY_GRADE.turbidity : opts.turbidity;
+ const rayleigh = opts.rayleigh === undefined ? SKY_GRADE.rayleigh : opts.rayleigh;
+ const mieC = opts.mieCoefficient === undefined ? SKY_GRADE.mieCoefficient : opts.mieCoefficient;
+ const mieG = opts.mieDirectionalG === undefined ? SKY_GRADE.mieDirectionalG : opts.mieDirectionalG;
+ const gain = opts.gain === undefined ? SKY_GRADE.gain : opts.gain;
+ const gamma = opts.gamma === undefined ? SKY_GRADE.gamma : opts.gamma;
+
+ // --- vertex stage
+ const zc = Math.max(-1, Math.min(1, sunDir.y));
+ const sunE = 1000 * Math.max(0, 1 - Math.exp(-((1.6110731556870734 - Math.acos(zc)) / 1.5)));
+ const sunfade = 1 - Math.min(1, Math.max(0, 1 - Math.exp(sunDir.y / 450000)));
+ const rC = rayleigh - (1 - sunfade);
+ const betaR = [5.804542996261093e-6 * rC, 1.3562911419845635e-5 * rC, 3.0265902468824876e-5 * rC];
+ const mc = 0.434 * (0.2 * T) * 10e-18 * mieC;
+ const betaM = [mc * 1.8399918514433978e14, mc * 2.7798023919660528e14, mc * 4.0790479543861094e14];
+
+ // --- fragment stage
+ const za = Math.acos(Math.max(0, dir.y));
+ const inv = 1 / (Math.cos(za) + 0.15 * Math.pow(93.885 - (za * 180) / Math.PI, -1.253));
+ const sR = 8.4e3 * inv, sM = 1.25e3 * inv;
+ const cosT = dir.dot(sunDir);
+ const rPhase = 0.05968310365946075 * (1 + Math.pow(cosT * 0.5 + 0.5, 2));
+ const g2 = mieG * mieG;
+ const mPhase = 0.07957747154594767 * ((1 - g2) / Math.pow(1 - 2 * mieG * cosT + g2, 1.5));
+ const dusk = Math.min(1, Math.max(0, Math.pow(1 - sunDir.y, 5)));
+ const out = [0, 0, 0];
+ const bias = [0, 0.0003, 0.00075];
+ for (let k = 0; k < 3; k++) {
+ const fex = Math.exp(-(betaR[k] * sR + betaM[k] * sM));
+ const ratio = (betaR[k] * rPhase + betaM[k] * mPhase) / (betaR[k] + betaM[k]);
+ let lin = Math.pow(Math.max(0, sunE * ratio * (1 - fex)), 1.5);
+ lin *= (1 - dusk) + Math.sqrt(Math.max(0, sunE * ratio * fex)) * dusk;
+ const tex = (lin + 0.1 * fex) * 0.04 + bias[k];
+ out[k] = gain * Math.pow(Math.max(tex, 0), gamma / (1.2 + 1.2 * sunfade));
+ }
+ // Low-sun warmth toward the sun, then the night gradient + afterglow.
+ const low = lowSunAmount(sunDir.y);
+ if (low > 0) {
+ const w = low * (0.85 * Math.pow(Math.max(cosT, 0), 3) + 0.25 * Math.exp(-Math.max(dir.y, 0) * 6));
+ for (let k = 0; k < 3; k++) out[k] *= 1 + (SKY_GRADE.warm[k] - 1) * w;
+ }
+ const night = nightAmount(sunDir.y);
+ if (night > 0) {
+ const up = Math.max(0, Math.min(1, dir.y));
+ const t = Math.pow(up, 0.45);
+ _tmp.set(sunDir.x, 0, sunDir.z);
+ const along = _tmp.lengthSq() > 0 ? Math.max(0, _tmp.normalize().dot(new THREE.Vector3(dir.x, 0, dir.z).normalize())) : 0;
+ const glow = afterglowAmount(sunDir.y) * Math.pow(along, 6) * Math.exp(-up * 7);
+ for (let k = 0; k < 3; k++) {
+ const ns = SKY_GRADE.nightHorizon[k] + (SKY_GRADE.nightZenith[k] - SKY_GRADE.nightHorizon[k]) * t
+ + SKY_GRADE.afterglow[k] * glow;
+ out[k] = out[k] + (ns - out[k]) * night;
+ }
+ }
+ return out;
+}
+
+/**
+ * Build the atmosphere dome, add it to the scene, null the
+ * background, and return the normalized sun vector for the key light.
+ * Sun precedence: `rig` (slaves to rig.sunDir; hides the rig's flat
+ * disc — the Preetham shader draws its own; a NIGHT rig's disc is the
+ * moon and stays) > `sunDir` (normalized copy, input untouched) >
+ * `elevationDeg`/`azimuthDeg` (same convention as `sunRig()`).
+ *
+ * @param {THREE.Scene} scene The dome is added to it and its
+ * `background` is set to null (the dome IS the backdrop).
+ * @param {object} [opts]
+ * `rig` a `sunRig()` result to slave to; `sunDir` explicit sun
+ * vector; `elevationDeg` (default 15) / `azimuthDeg` (default 135)
+ * sun angles; `turbidity` (default 4.5), `rayleigh` (default 1.6),
+ * `mieCoefficient` (default 0.0035), `mieDirectionalG` (default
+ * 0.8) — the battery-graded atmosphere; `exposure` dome gain
+ * (default 0.36, graded for exposure 1.0 — the old ungraded dome is
+ * `exposure: 1, contrast: 1`); `contrast` transfer gamma (default
+ * 1.7, more = deeper zenith against the horizon); `scale` dome
+ * half-extent driver (default 4500).
+ * @returns {{sky: THREE.Mesh, sunDir: THREE.Vector3}} The dome
+ * (already in the scene) and the normalized sun direction — place
+ * the key light at `sunDir * distance`, aimed at the origin.
+ */
+export function makeSky(scene, opts = {}) {
+ const sky = new Sky();
+ sky.name = 'PhysicalSky';
+ sky.scale.setScalar(opts.scale || 4500);
+ // Layer between worldShell's gradient dome (-2) and its ridge (-1)
+ // / sun disc (-1.5): all depthWrite:false backdrops, paint order rules.
+ sky.renderOrder = -1.8;
+
+ const u = sky.material.uniforms;
+ u.turbidity.value = opts.turbidity === undefined ? SKY_GRADE.turbidity : opts.turbidity;
+ u.rayleigh.value = opts.rayleigh === undefined ? SKY_GRADE.rayleigh : opts.rayleigh;
+ u.mieCoefficient.value =
+ opts.mieCoefficient === undefined ? SKY_GRADE.mieCoefficient : opts.mieCoefficient;
+ u.mieDirectionalG.value =
+ opts.mieDirectionalG === undefined ? SKY_GRADE.mieDirectionalG : opts.mieDirectionalG;
+
+ let sunDir;
+ if (opts.rig && opts.rig.sunDir) {
+ sunDir = opts.rig.sunDir.clone().normalize();
+ // The Preetham shader draws its own solar disc; the rig's flat
+ // CircleGeometry disc on the same vector would double the sun. A
+ // night rig's disc is the MOON on another vector: it stays.
+ if (opts.rig.sunDisc && !opts.rig.night) opts.rig.sunDisc.visible = false;
+ } else if (opts.sunDir) {
+ sunDir = opts.sunDir.clone().normalize();
+ } else {
+ const el = (opts.elevationDeg === undefined ? 15
+ : opts.elevationDeg) *
+ Math.PI / 180;
+ const az = (opts.azimuthDeg === undefined ? 135 : opts.azimuthDeg) *
+ Math.PI / 180;
+ sunDir = new THREE.Vector3(
+ Math.cos(el) * Math.cos(az), Math.sin(el),
+ Math.cos(el) * Math.sin(az));
+ }
+ u.sunPosition.value.copy(sunDir);
+ // r184 Sky ships value-noise clouds ON by default — grid artifacts
+ // at readable contrast. Clouds come from ./clouds.js instead.
+ if (u.cloudCoverage) u.cloudCoverage.value = 0;
+
+ // THE GRADE. Extra uniforms on the addon's own material; the
+ // fragment's transfer line is rewritten in onBeforeCompile.
+ _tmp.set(sunDir.x, 0, sunDir.z);
+ if (_tmp.lengthSq() > 0) _tmp.normalize(); else _tmp.set(1, 0, 0);
+ Object.assign(u, {
+ uSkyGain: { value: opts.exposure === undefined ? SKY_GRADE.gain : opts.exposure },
+ uSkyGamma: { value: opts.contrast === undefined ? SKY_GRADE.gamma : opts.contrast },
+ uNight: { value: nightAmount(sunDir.y) },
+ uAfterglow: { value: afterglowAmount(sunDir.y) },
+ uLowSun: { value: lowSunAmount(sunDir.y) },
+ uSunAzimuth: { value: _tmp.clone() },
+ uNightZenith: { value: new THREE.Vector3().fromArray(SKY_GRADE.nightZenith) },
+ uNightHorizon: { value: new THREE.Vector3().fromArray(SKY_GRADE.nightHorizon) },
+ uAfterglowColor: { value: new THREE.Vector3().fromArray(SKY_GRADE.afterglow) },
+ uWarm: { value: new THREE.Vector3().fromArray(SKY_GRADE.warm) },
+ });
+ sky.material.customProgramCacheKey = () => 'astra:sky-grade';
+ sky.material.onBeforeCompile = (shader) => {
+ Object.assign(shader.uniforms, u);
+ const line = /vec3 retColor = pow\( texColor, vec3\( 1\.0 \/ \( 1\.2 \+ \( 1\.2 \* vSunfade \) \) \) \);/;
+ if (!line.test(shader.fragmentShader)) {
+ throw new Error('sky.js: three Sky.js transfer line moved — regrade makeSky');
+ }
+ shader.fragmentShader = shader.fragmentShader
+ .replace('uniform float mieDirectionalG;', [
+ 'uniform float mieDirectionalG;',
+ 'uniform float uSkyGain;', 'uniform float uSkyGamma;',
+ 'uniform float uNight;', 'uniform float uAfterglow;', 'uniform float uLowSun;',
+ 'uniform vec3 uSunAzimuth;', 'uniform vec3 uNightZenith;', 'uniform vec3 uNightHorizon;',
+ 'uniform vec3 uAfterglowColor;', 'uniform vec3 uWarm;',
+ ].join('\n'))
+ .replace(line, [
+ 'vec3 retColor = uSkyGain * pow( texColor, vec3( uSkyGamma / ( 1.2 + ( 1.2 * vSunfade ) ) ) );',
+ // Golden hour: warm toward the sun and along the horizon band.
+ 'float astraUp = clamp( direction.y, 0.0, 1.0 );',
+ 'float astraWarmW = uLowSun * ( 0.85 * pow( max( cosTheta, 0.0 ), 3.0 ) + 0.25 * exp( -astraUp * 6.0 ) );',
+ 'retColor *= mix( vec3( 1.0 ), uWarm, astraWarmW );',
+ // Night: the un-encoded Preetham is black below the horizon;
+ // blend to a graded gradient with an afterglow toward the set sun.
+ 'vec3 astraFlat = normalize( vec3( direction.x, 1e-4, direction.z ) );',
+ 'float astraAlong = max( dot( astraFlat, uSunAzimuth ), 0.0 );',
+ 'vec3 astraNight = mix( uNightHorizon, uNightZenith, pow( astraUp, 0.45 ) )',
+ ' + uAfterglowColor * uAfterglow * pow( astraAlong, 6.0 ) * exp( -astraUp * 7.0 );',
+ 'retColor = mix( retColor, astraNight, uNight );',
+ // Dither one code value against banding on the smooth gradient.
+ 'float astraDither = fract( sin( dot( gl_FragCoord.xy, vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );',
+ 'retColor += ( astraDither - 0.5 ) * 0.0015;',
+ ].join('\n\t\t\t'));
+ };
+ sky.material.needsUpdate = true;
+
+ scene.add(sky);
+ scene.background = null; // the dome IS the backdrop (measured req)
+ return { sky, sunDir };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/smalllife.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/smalllife.js
new file mode 100644
index 00000000..69adeca5
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/smalllife.js
@@ -0,0 +1,802 @@
+/**
+ * The small live things: a swarm in the air, a stand of reeds in the
+ * water. Both are motion a still scene is missing, and both are ONE
+ * draw call whose every moving part lives in the vertex shader.
+ *
+ * Insects are the small-and-many case of flock.js. A midge is two
+ * pixels, so nothing here is modelled: one seed per instance drives the
+ * whole path and the silhouette is drawn in the fragment. What tells
+ * the three kinds apart is how they MOVE — a midge jitters inside a
+ * knot that drifts, a butterfly wanders and settles, a firefly drifts
+ * and blinks — so the kind is a motion law, not a mesh.
+ *
+ * Reeds are the waterline case of grass.js: rooted on the bed, leaning
+ * into the SAME streaky gust field the grass above water rides (hand
+ * both libraries one `wind` and the meadow and the shallows move
+ * together). The submerged part bends less, slower and rounder because
+ * water damps it, and that break in the bend AT the waterline is what
+ * says "standing in water" rather than "standing on a blue floor".
+ */
+
+import * as THREE from 'three';
+
+import { mulberry32 } from './noise.js';
+// One reader, so a scene's meadow, its reeds and its trees
+// cannot drift apart on the same `wind` option.
+import { windOf } from './grass.js';
+import {
+ instancedQuad, makeShaderMaterial, patchStandard, shadowLike, tickShaders,
+} from './shader.js';
+
+const _TAU = Math.PI * 2;
+// Rows up a stem: 12 is where a two-arc bend stops faceting and the
+// top three can carry a seed head.
+const _REED_ROWS = 12;
+// Water damps what stands in it: the submerged stem takes this much of
+// the surface bend, on the slower of the two sway rates below.
+const _SUB_DAMP = 0.28;
+const _SWAY_RATE = new THREE.Vector2(1.6, 0.45);
+
+/**
+ * One row per insect kind. These numbers ARE the difference between the
+ * three animals: `wander`/`rise` are fractions of the stated volume,
+ * `rate` is the wander's rad/s, `beat` the wingbeat (or the firefly's
+ * blink), `drift` how far the whole swarm's centre travels.
+ */
+const _KINDS = {
+ midge: {
+ id: 0, wander: 0.07, rise: 0.12, rate: 5.2, beat: 44,
+ drift: 0.42, driftRate: 0.28, aspect: 0.52, hue: 0.5,
+ size: 0.022, color: 0x241d16,
+ },
+ butterfly: {
+ id: 1, wander: 0.58, rise: 0.40, rate: 0.62, beat: 24,
+ drift: 0, driftRate: 0, aspect: 0.88, hue: 0.26,
+ size: 0.085, color: 0xd8791c,
+ },
+ firefly: {
+ id: 2, wander: 0.20, rise: 0.15, rate: 0.30, beat: 1.15,
+ drift: 0, driftRate: 0, aspect: 1, hue: 0.18,
+ size: 0.055, color: 0xc8ff7a,
+ },
+};
+
+/** Read a Vector3, an array or an {x,y,z} into a Vector3. */
+function _toVec(p, fx = 0, fy = 0, fz = 0) {
+ 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 four calls. */
+function clamp01(v) {
+ return Math.max(0, Math.min(1, v));
+}
+
+// A swarm is drawn UNLIT, so the scene's own lights have to reach it as a
+// number. Re-read every `_RELIGHT` ticks: a traverse is cheap, but not 60
+// times a second in a scene of thousands of objects.
+const _RELIGHT = 24;
+// A billboard has no normal, so a direct light contributes its average
+// over the facings that see it; a point or spot light is somewhere else
+// in the scene and this cannot know how far, so it lands as a small
+// ambient rather than as nothing.
+const _DIRECT = 0.55;
+const _LOCAL = 0.06;
+const _INV_PI = 1 / Math.PI;
+const _lightAcc = new THREE.Color();
+
+/**
+ * What the scene's own lights put on an unlit billboard.
+ *
+ * Without it an insect is its own hex whatever the hour: measured on this
+ * showcase's night rig, the midge's hardcoded grey wing blur (0.5) came
+ * back BRIGHTER than the moonlit sky behind it — a knot of white dust
+ * over the water — and orange butterflies glowed like embers at midnight.
+ * One traverse, and it lands on 1.0 under the library's own day rig, so a
+ * daylight swarm keeps exactly the look it had.
+ *
+ * @returns {boolean} true if a lit Scene was found and `out` was filled.
+ */
+function sceneLight(obj, out) {
+ let root = obj;
+ while (root.parent) root = root.parent;
+ if (!root.isScene) return false;
+ _lightAcc.setRGB(0, 0, 0);
+ let n = 0;
+ root.traverse((o) => {
+ if (!o.isLight || o.visible === false || !(o.intensity > 0)) return;
+ n++;
+ const w = (o.isHemisphereLight || o.isAmbientLight) ? 1
+ : (o.isDirectionalLight ? _DIRECT : _LOCAL);
+ // A hemisphere light is its two halves averaged; every other kind
+ // averages its own colour with itself.
+ const c = o.color, g = o.groundColor || o.color, k = 0.5 * o.intensity * w;
+ _lightAcc.r += (c.r + g.r) * k;
+ _lightAcc.g += (c.g + g.g) * k;
+ _lightAcc.b += (c.b + g.b) * k;
+ });
+ if (!n) return false;
+ // Irradiance to reflected radiance, and a ceiling: a rig with a dozen
+ // lamps in it is not a reason for a midge to become one.
+ out.setRGB(Math.min(_lightAcc.r * _INV_PI, 2.5),
+ Math.min(_lightAcc.g * _INV_PI, 2.5),
+ Math.min(_lightAcc.b * _INV_PI, 2.5));
+ return true;
+}
+
+/**
+ * A swarm of insects, animated entirely from a per-instance seed.
+ *
+ * Buys the midges over a pond at dusk, the butterflies over a meadow,
+ * the fireflies after dark — at one draw call and one float per frame,
+ * so the count can be what a real swarm is. Drive it from your
+ * `tick()` — `insects.userData.tick(t)` — or nothing moves.
+ *
+ * The constraint: every insect, quad and all, stays inside the volume
+ * this advertises (`center` +- (`extent`, `height`/2, `extent`)), which
+ * is the bounding box it states and the sphere three culls it by.
+ *
+ * @param {object} [opts]
+ * `count` individuals (default 140); `kind` 'midge' (default, a tight
+ * jittery knot around a slowly moving centre), 'butterfly' (a wide
+ * wander that settles briefly, wings folding as they beat) or
+ * 'firefly' (a slow drift plus a pulse of light);
+ * `extent` horizontal radius in metres of the volume it fills
+ * (default 4); `height` that volume's full height in metres (default
+ * 2); `center` its centre ([x,y,z] or Vector3, default
+ * [0, height/2, 0] — the swarm's floor on y = 0); `size` body span in
+ * metres (default 0.022 midge / 0.085 butterfly / 0.055 firefly);
+ * `color` body or glow colour; `seed` PRNG seed (default 11); `name`
+ * group name.
+ * @returns {THREE.Group} Named `Insects`, holding ONE instanced mesh,
+ * with `userData.tick(t)` advancing the only thing that changes.
+ */
+export function makeInsects(opts = {}) {
+ const kind = _KINDS[opts.kind] || _KINDS.midge;
+ const count = Math.max(1, opts.count === undefined ? 140 : opts.count);
+ const extent = opts.extent === undefined ? 4 : opts.extent;
+ const height = opts.height === undefined ? 2 : opts.height;
+ const size = opts.size === undefined ? kind.size : opts.size;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const color = new THREE.Color(
+ opts.color === undefined ? kind.color : opts.color);
+ const center = _toVec(opts.center, 0, height * 0.5, 0);
+ const half = new THREE.Vector3(extent, height * 0.5, extent);
+ const amp = new THREE.Vector3(
+ kind.wander * extent, kind.rise * height * 0.5, kind.wander * extent);
+ const drift = new THREE.Vector3(
+ kind.drift * extent, kind.drift * height * 0.25, kind.drift * extent);
+
+ const field = swarmField(count, kind, center, half, amp, drift, size, seed);
+ const box = new THREE.Box3(
+ center.clone().sub(half), center.clone().add(half));
+ const geom = instancedQuad(count, 1, 1,
+ center.length() + half.length());
+ geom.setAttribute('iPos', new THREE.InstancedBufferAttribute(field.pos, 3));
+ geom.setAttribute('iAmp', new THREE.InstancedBufferAttribute(field.amp, 3));
+ geom.setAttribute('iSeed', new THREE.InstancedBufferAttribute(field.seed, 4));
+ geom.boundingBox = box;
+ geom.boundingSphere = box.getBoundingSphere(new THREE.Sphere());
+
+ const mat = insectMaterial(kind, size, drift, color);
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = kind.id === 0 ? 'Midges'
+ : (kind.id === 1 ? 'Butterflies' : 'Fireflies');
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = opts.name || 'Insects';
+ g.add(mesh);
+ // The swarm reads the rig it was added to, from the first tick on; a
+ // caller who never adds it to a scene keeps the neutral 1.0 it was
+ // built with, which is what an asset preview wants.
+ let age = 0;
+ g.userData.tick = (t) => {
+ if (age++ % _RELIGHT === 0) sceneLight(g, mat.uniforms.uLight.value);
+ tickShaders(g, t);
+ };
+ return g;
+}
+
+/**
+ * Where each insect lives and how far it strays from there.
+ *
+ * The base position is drawn from the volume MINUS its own wander, the
+ * swarm drift and the quad's own span, so containment is a property of
+ * the numbers rather than a hope about the shader.
+ */
+function swarmField(count, kind, center, half, amp, drift, size, seed) {
+ const rand = mulberry32(seed);
+ const room = new THREE.Vector3(
+ Math.max(half.x - amp.x - drift.x - size * 2, 0),
+ Math.max(half.y - amp.y - drift.y - size * 2, 0),
+ Math.max(half.z - amp.z - drift.z - size * 2, 0));
+ const pos = new Float32Array(count * 3);
+ const am = new Float32Array(count * 3);
+ const sd = new Float32Array(count * 4);
+ for (let i = 0; i < count; i++) {
+ const a = rand() * _TAU;
+ // A midge swarm is a knot with a dense middle; the other two hold
+ // territory, so they spread evenly over the ground they cover.
+ const r = kind.id === 0 ? Math.pow(rand(), 1.6) : Math.sqrt(rand());
+ const v = kind.id === 2 ? Math.pow(rand(), 1.7) * 2 - 1
+ : (kind.id === 0 ? rand() + rand() - 1 : rand() * 2 - 1);
+ pos[i * 3] = center.x + Math.cos(a) * r * room.x;
+ pos[i * 3 + 1] = center.y + v * room.y;
+ pos[i * 3 + 2] = center.z + Math.sin(a) * r * room.z;
+ am[i * 3] = amp.x * (0.45 + 0.55 * rand());
+ am[i * 3 + 1] = amp.y * (0.45 + 0.55 * rand());
+ am[i * 3 + 2] = amp.z * (0.45 + 0.55 * rand());
+ sd[i * 4] = rand() * _TAU;
+ sd[i * 4 + 1] = 0.75 + 0.5 * rand();
+ sd[i * 4 + 2] = 0.7 + 0.5 * rand();
+ sd[i * 4 + 3] = (rand() - 0.5) * kind.hue;
+ }
+ return { pos, amp: am, seed: sd };
+}
+
+/** The one material: path, beat, blink and silhouette, all in GLSL. */
+function insectMaterial(kind, size, drift, color) {
+ return makeShaderMaterial({
+ name: 'Insects',
+ uniforms: {
+ // Bound here though the wrapper supplies it: this harness's GLSL
+ // audit (runtime_js/lib/glsl_audit.mjs) reads THIS file, not the
+ // string the wrapper assembles, and reported two hard ERRORs
+ // against every shader here that reads uTime.
+ uTime: { value: 0 },
+ uKind: { value: kind.id },
+ uRate: { value: kind.rate },
+ uBeat: { value: kind.beat },
+ uSize: { value: size },
+ uAspect: { value: kind.aspect },
+ uDrift: { value: drift.clone() },
+ uDriftRate: { value: kind.driftRate },
+ uColor: { value: color },
+ uLight: { value: new THREE.Color(1, 1, 1) },
+ },
+ varyings: 'varying vec2 vUv; varying vec4 vSeed; varying float vBeat;'
+ + ' varying float vNear;',
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iPos;',
+ 'attribute vec3 iAmp;',
+ 'attribute vec4 iSeed;',
+ 'uniform float uTime; uniform float uKind; uniform float uRate;',
+ 'uniform float uBeat; uniform float uSize; uniform float uAspect;',
+ 'uniform vec3 uDrift; uniform float uDriftRate;',
+ // Every component stays within +-1, which is what keeps a swarm
+ // inside the volume its bounding box claims.
+ 'vec3 lifeOsc(float t, vec4 sd) {',
+ ' float p = sd.x, r = uRate * sd.y;',
+ ' if (uKind < 0.5) {',
+ ' return vec3(',
+ ' (sin(t * r + p) + 0.5 * sin(t * r * 2.7 + p * 1.7)) / 1.5,',
+ ' (sin(t * r * 1.3 + p * 2.1) + 0.5 * sin(t * r * 3.1 + p))',
+ ' / 1.5,',
+ ' (cos(t * r * 0.9 + p * 1.3) + 0.5 * cos(t * r * 2.3',
+ ' + p * 2.7)) / 1.5);',
+ ' }',
+ // A butterfly settles: warped time whose rate falls to almost
+ // nothing once a cycle, which is the pause on a flower.
+ ' if (uKind < 1.5) {',
+ ' float w = t * r + p;',
+ ' float u = w + 0.95 * sin(w);',
+ ' return vec3(sin(u), 0.85 * sin(u * 0.5 + p),',
+ ' cos(u * 0.77 + p * 0.5));',
+ ' }',
+ ' return vec3(sin(t * r + p), sin(t * r * 0.61 + p * 1.7),',
+ ' cos(t * r * 0.43 + p * 2.3));',
+ '}',
+ // The knot itself wanders; without it a midge swarm hangs in the
+ // air like a fixed cloud of dust.
+ 'vec3 lifeDrift(float t) {',
+ ' float d = t * uDriftRate;',
+ ' return uDrift * vec3(sin(d), sin(d * 0.73 + 1.1), cos(d * 0.61));',
+ '}',
+ 'vec3 lifeAt(float t, vec3 b, vec3 a, vec4 sd) {',
+ ' return b + a * lifeOsc(t, sd) + lifeDrift(t);',
+ '}',
+ ].join('\n'),
+ vertexMain: [
+ ' vUv = uv;',
+ ' vSeed = iSeed;',
+ ' vec3 c = lifeAt(uTime, iPos, iAmp, iSeed);',
+ ' vec3 vel = lifeAt(uTime + 0.08, iPos, iAmp, iSeed) - c;',
+ // Own phase per individual: a swarm beating or blinking in step
+ // reads as one object flickering, not as many animals.
+ ' float beat = uTime * uBeat * iSeed.y + astraStagger(iSeed.x);',
+ ' vBeat = beat;',
+ ' vec3 camR = vec3(modelViewMatrix[0][0], modelViewMatrix[1][0],',
+ ' modelViewMatrix[2][0]);',
+ ' vec3 camU = vec3(modelViewMatrix[0][1], modelViewMatrix[1][1],',
+ ' modelViewMatrix[2][1]);',
+ ' vec3 fwd = length(vel) > 1e-7 ? normalize(vel)',
+ ' : vec3(1.0, 0.0, 0.0);',
+ // A midge is smeared ALONG its flight, a butterfly spans ACROSS
+ // it; either axis is used as PROJECTED, so a bug flying at the
+ // camera loses its span instead of sliding sideways.
+ ' vec3 side = cross(fwd, vec3(0.0, 1.0, 0.0)) + vec3(1e-5, 0.0, 0.0);',
+ ' vec3 ax = uKind < 0.5 ? fwd : normalize(side);',
+ ' vec2 e = vec2(dot(ax, camR), dot(ax, camU));',
+ ' float el = length(e);',
+ ' vec2 ex = el > 1e-4 ? e / el : vec2(1.0, 0.0);',
+ ' vec2 ey = vec2(-ex.y, ex.x);',
+ ' float fold = uKind > 0.5 && uKind < 1.5',
+ ' ? 0.24 + 0.76 * abs(cos(beat)) : 1.0;',
+ // A glow has no axis to foreshorten; the other two do, and an
+ // ellipse where a lamp belongs reads as a smear.
+ ' float span = uKind < 1.5 ? clamp(el, 0.3, 1.0) : 1.0;',
+ ' float sz = uSize * iSeed.z;',
+ ' vec2 q = ex * (aCorner.x * 2.0 * sz * fold * span)',
+ ' + ey * (aCorner.y * 2.0 * sz * uAspect);',
+ ' transformed = c + camR * q.x + camU * q.y;',
+ // A swarm is a VOLUME, and a camera placed inside one gets an
+ // insect at arm's length: measured on a delivered meadow, a
+ // 17 cm butterfly 1 m from the lens filled a quarter of a 40 deg
+ // frame and the judge scored the scene's whole scale down for
+ // it. No lens focuses at 30 cm either, so the ones that close
+ // fade out instead of becoming the subject.
+ ' vec3 cW = (modelMatrix * vec4(c, 1.0)).xyz;',
+ ' vNear = smoothstep(0.35, 1.8, distance(cameraPosition, cW));',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform float uKind;'
+ + ' uniform vec3 uLight;',
+ fragmentMain: [
+ ' vec2 q = vUv * 2.0 - 1.0;',
+ // Hue AND value per individual: a swarm of one exact colour is
+ // the "primitives" look at any scale.
+ ' vec3 col = astraHueShift(uColor, vSeed.w)',
+ ' * (0.78 + 0.44 * fract(vSeed.x * 1.7));',
+ ' float a;',
+ ' if (uKind < 0.5) {',
+ // A hard little body inside a faint disc of wing blur: the blur
+ // is the whole difference between an insect and a speck of dirt.
+ ' float body = 1.0 - smoothstep(0.34, 0.72,',
+ ' length(q * vec2(0.62, 1.5)));',
+ ' float blur = 1.0 - smoothstep(0.2, 1.0,',
+ ' length(q * vec2(0.8, 1.15)));',
+ ' a = clamp(body + blur * 0.32 * (0.7 + 0.3 * sin(vBeat)),',
+ ' 0.0, 1.0);',
+ // The blur is LIGHTER than the body — wings scatter light, and a
+ // dark halo would only fatten the speck — but it is the BODY's
+ // own colour scattered, not a grey card: a fixed 0.5 grey is an
+ // albedo brighter than a moonlit sky, and it turned every night
+ // swarm into a knot of white dust.
+ ' vec3 haze = min(col * 3.4 + 0.015, vec3(0.55));',
+ ' col = mix(haze, col, body) * uLight;',
+ ' } else if (uKind < 1.5) {',
+ // A forewing tilted outward-forward with a hindwing tucked under
+ // it — two OVERLAPPING lobes, because two circles read as a bug.
+ ' float ax = abs(q.x);',
+ ' vec2 fp = vec2(ax - 0.42, q.y - 0.26);',
+ ' fp = vec2(fp.x * 0.93 + fp.y * 0.37, fp.y * 0.93 - fp.x * 0.37)',
+ ' / vec2(0.6, 0.32);',
+ ' float df = pow(pow(abs(fp.x), 2.4) + pow(abs(fp.y), 2.4), 0.417);',
+ ' float dh = length(vec2(ax - 0.26, q.y + 0.28) / vec2(0.3, 0.25));',
+ ' float aaf = max(fwidth(df), 0.03);',
+ ' float aah = max(fwidth(dh), 0.03);',
+ ' float wing = max(1.0 - smoothstep(1.0 - aaf, 1.0 + aaf, df),',
+ ' 1.0 - smoothstep(1.0 - aah, 1.0 + aah, dh));',
+ ' float body = (1.0 - smoothstep(0.04, 0.075, ax))',
+ ' * (1.0 - smoothstep(0.34, 0.46, abs(q.y)));',
+ // Two hairs and a club: the one detail that says butterfly
+ // instead of moth-shaped blob, and it costs four lines.
+ ' float an = abs(ax - (q.y - 0.36) * 0.5);',
+ ' float ant = (1.0 - smoothstep(0.012, 0.032, an))',
+ ' * step(0.36, q.y) * (1.0 - smoothstep(0.6, 0.72, q.y));',
+ ' a = clamp(wing + body + ant * 0.9, 0.0, 1.0);',
+ ' col = mix(col, col * 0.26, smoothstep(0.62, 1.0, min(df, dh)));',
+ ' col = mix(col, vec3(0.15, 0.11, 0.07), max(body, ant));',
+ // One wing catches the light as the pair opens.
+ ' col *= (0.72 + 0.42 * abs(cos(vBeat))) * uLight;',
+ ' } else {',
+ // Mostly dark, briefly a lamp: the blink is the firefly.
+ ' float d = length(q);',
+ ' float pulse = pow(max(sin(vBeat), 0.0), 9.0);',
+ // TWO lobes: one gaussian at this size is a speck the eye reads
+ // as a dead pixel, and a lamp has a core AND a falloff.
+ ' a = (0.74 * exp(-d * d * 9.0) + 0.32 * exp(-d * d * 1.5))',
+ ' * (0.04 + 0.96 * pulse);',
+ // The lantern is EMITTED, so it keeps its own hue whatever the
+ // rig is doing, and it peaks at 2.6 rather than at white: pushed
+ // to 1.0 the core clipped to a white dot that read as dust, while
+ // 2.6 rolls through the ACES shoulder as a hot core with a
+ // COLOURED skirt. `color` is that LANTERN — taken as the body
+ // albedo too, 0xc8ff7a is a near-white green, and every firefly
+ // in daylight was a chartreuse dot, flashing or not.
+ ' vec3 body = mix(vec3(dot(col, vec3(0.3333))), col, 0.4) * 0.2;',
+ ' vec3 lamp = col / max(max(col.r, max(col.g, col.b)), 1e-3);',
+ ' vec3 hot = mix(lamp, vec3(1.0, 0.97, 0.86), 0.42) * 2.6;',
+ // A lantern is only SEEN when it beats what is behind it: at noon
+ // the same flash is a beetle, and at full strength it landed on
+ // the day frame as a white speck that read as a dirty lens.
+ ' float dim = 1.0 - clamp(dot(uLight, vec3(0.5)), 0.0, 1.0);',
+ ' float lit = clamp(pulse * (0.4 + 0.6 * smoothstep(0.5, 0.0, d))',
+ ' * (0.25 + 0.75 * dim), 0.0, 1.0);',
+ ' col = mix(body * uLight, hot, lit);',
+ ' }',
+ ' a *= vNear;',
+ ' if (a < 0.01) discard;',
+ ' gl_FragColor = vec4(col, a);',
+ ].join('\n'),
+ // Ordinary blending, even for the firefly: added light clips a
+ // bright frame (godrays.js measured 12.8% of one blown past 0.97),
+ // and `additive: true` also loses the fog chunk the gate looks for.
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
+
+/**
+ * Reeds, rushes and kelp standing in water.
+ *
+ * Buys the one thing a plant on a shoreline has to prove: that it is
+ * IN the water, not on it. The stems are rooted on the bed (`heightAt`,
+ * the caller's ground truth), they thin out where the water gets too
+ * deep to stand in, and the bend breaks at the waterline — full,
+ * gusting sway above it; a slow, round, lagging fraction of it below,
+ * because water damps what it holds.
+ *
+ * Deterministic in `seed`, one draw call at any count, and every
+ * moving part in the vertex shader. Drive it from your `tick()` —
+ * `reeds.userData.tick(t)` — or the wind never blows.
+ *
+ * @param {object} [opts]
+ * `extent` metres of the square patch's side (default 12, centred on
+ * the group's origin); `density` stems per square metre (default 6;
+ * `maxStems` caps it, default 20000); `height` stem height in metres
+ * (default 1.8, varied per stem); `waterY` world y of the water
+ * surface (default 0.35); `heightAt` (x, z) => y, the caller's BED
+ * height (default flat y = 0); `color` the green of a live stem;
+ * `wind` grass.js's option, in either spelling — a strength
+ * multiplier or `{dir, strength, speed}` — so one wind moves a
+ * scene's grass and its reeds together; `dryColor` last year's dead
+ * straw, mixed in per stem; `waterColor` what a drowned stem loses
+ * its colour INTO (pass the water's own tint, or a stand in a green
+ * pond fades toward a blue-green that is not there); `shadows` cast
+ * stem shadows through a displaced depth pass (default false, see
+ * `stemMesh`); `seed` seed (default 11); `name` group name.
+ * @returns {THREE.Group} Named `Reeds`, holding ONE instanced mesh
+ * `Stems`, with `userData.tick(t)` driving the wind.
+ */
+export function makeReeds(opts = {}) {
+ const extent = opts.extent === undefined ? 12 : opts.extent;
+ const density = opts.density === undefined ? 6 : opts.density;
+ const height = opts.height === undefined ? 1.8 : opts.height;
+ const waterY = opts.waterY === undefined ? 0.35 : opts.waterY;
+ const seed = opts.seed === undefined ? 11 : opts.seed;
+ const maxStems = opts.maxStems === undefined ? 20000 : opts.maxStems;
+ const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const wind = windOf(opts.wind);
+ // Albedos, not screen colours: a scene sun runs at 5-6, so a hex that
+ // already looks like a sunlit reed tone-maps to pale card.
+ const color = new THREE.Color(
+ opts.color === undefined ? 0x5c6f30 : opts.color);
+ // Last year's stems are still standing, bleached: one green is a
+ // stand nobody has stood in front of.
+ const dry = new THREE.Color(
+ opts.dryColor === undefined ? 0x8f7a44 : opts.dryColor);
+ const deep = new THREE.Color(
+ opts.waterColor === undefined ? 0x24382c : opts.waterColor);
+
+ const field = reedField(
+ extent, density, height, waterY, ground, wind, seed, maxStems);
+ const g = new THREE.Group();
+ g.name = opts.name || 'Reeds';
+ g.add(stemMesh(field, extent, waterY, { color, dry, deep }, wind,
+ opts.shadows === true));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/**
+ * Plant the stand, and let the water decide where it grows.
+ *
+ * Reeds fringe a shoreline: none on the dry bank above the line, fewer
+ * where it is deeper than they are tall. That rule needs the bed and
+ * the waterline together, which is why placement is on the CPU.
+ */
+function reedField(extent, density, height, waterY, ground, wind, seed,
+ maxStems) {
+ const want = Math.max(
+ 1, Math.min(Math.round(density * extent * extent), maxStems));
+ const cells = Math.max(1, Math.round(Math.sqrt(want)));
+ const step = extent / cells;
+ const rand = mulberry32(seed);
+ const pos = [], shape = [], bend = [], vary = [];
+ let n = 0, maxH = 0, low = Infinity, high = -Infinity;
+ for (let iz = 0; iz < cells && n < maxStems; iz++) {
+ for (let ix = 0; ix < cells && n < maxStems; ix++) {
+ const x = -extent / 2 + (ix + rand()) * step;
+ const z = -extent / 2 + (iz + rand()) * step;
+ const bed = ground ? ground(x, z) : 0;
+ const depth = waterY - bed;
+ const h = height * (0.6 + 0.7 * rand());
+ const dry = clamp01(1 + depth / 0.3);
+ const deep = 1 - 0.6 * clamp01((depth - h * 0.7) / h);
+ if (rand() > dry * deep) continue;
+ // Radians of tip bend at a full gust: a taller stem is a longer
+ // lever, and each one carries its own stiffness.
+ const stiff = (0.7 + 0.6 * rand()) * (0.6 + 0.55 * h / height);
+ const head = rand() < 0.45 && depth < h * 0.85
+ ? 0.010 + 0.006 * rand() : 0;
+ pos.push(x, bed, z);
+ shape.push(h, 0.004 + 0.003 * rand(), clamp01(depth / h), head);
+ bend.push(wind.amp * stiff, wind.amp * stiff * _SUB_DAMP,
+ rand() * _TAU, 0.04 + 0.14 * rand());
+ // phase, hue, tone, dryness — dead stems a MINORITY, since a
+ // linear roll would bleach half the stand.
+ vary.push(rand() * _TAU, (rand() - 0.5) * 0.5, rand(),
+ Math.pow(rand(), 2.4));
+ maxH = Math.max(maxH, h);
+ low = Math.min(low, bed);
+ high = Math.max(high, bed + h);
+ n++;
+ }
+ }
+ return { n, pos, shape, bend, vary, maxH,
+ low: n ? low : 0, high: n ? high : 0 };
+}
+
+/**
+ * The stem lattice: ONE instanced strip with `position` pinned at 0.
+ *
+ * GTAOPass redraws with an override material that ignores this vertex
+ * shader, so a real stem left in `position` would stack every copy at
+ * the world origin and burn a black slab there.
+ */
+function reedLattice(count) {
+ const base = new THREE.PlaneGeometry(1, 1, 1, _REED_ROWS);
+ base.translate(0, 0.5, 0);
+ const g = new THREE.InstancedBufferGeometry();
+ g.index = base.index;
+ g.setAttribute('position', new THREE.BufferAttribute(
+ new Float32Array(base.attributes.position.count * 3), 3));
+ g.setAttribute('aCorner', base.attributes.position);
+ g.setAttribute('normal', base.attributes.normal);
+ g.setAttribute('uv', base.attributes.uv);
+ g.instanceCount = count;
+ return g;
+}
+
+/**
+ * One mesh, one draw call: every stem lives in the vertex shader.
+ *
+ * `shadows` is OPT-IN, exactly as grass.js's blades are, and for a
+ * measured reason: a stem is 4-10 mm across and this rig sizes its
+ * shadow map at ~0.05 m/texel, so a stem shadow cannot be narrower than
+ * ten stems. A stand of 3 000 painted 4.16% of the showcase bank with
+ * hard navy dashes at luminance 0.180 against mud at 0.375, each twenty
+ * times the area of the thing casting it. The depth material is still
+ * built when asked — a caller with a tight bound, or kelp with fat
+ * blades, can have it.
+ */
+function stemMesh(field, extent, waterY, palette, wind, shadows) {
+ const color = palette.color;
+ const geom = reedLattice(field.n);
+ const inst = (name, arr, size) => geom.setAttribute(
+ name, new THREE.InstancedBufferAttribute(new Float32Array(arr), size));
+ inst('iPos', field.pos, 3);
+ inst('iShape', field.shape, 4);
+ inst('iBend', field.bend, 4);
+ inst('iVar', field.vary, 4);
+ // position is zero, so the derived bounds would be a point at the
+ // origin: state the box the bent stand really occupies.
+ const reach = extent / 2 + field.maxH * 0.45 + 0.05;
+ geom.boundingBox = new THREE.Box3(
+ new THREE.Vector3(-reach, field.low, -reach),
+ new THREE.Vector3(reach, field.high, reach));
+ geom.boundingSphere = geom.boundingBox.getBoundingSphere(new THREE.Sphere());
+
+ const mat = new THREE.MeshStandardMaterial({
+ color: 0xffffff, roughness: 0.68, metalness: 0,
+ side: THREE.DoubleSide, name: 'ReedStem',
+ });
+ patchStandard(mat, {
+ name: 'reed:stem',
+ uniforms: {
+ uTime: { value: 0 },
+ uReedColor: { value: color.clone() },
+ uReedDry: { value: palette.dry.clone() },
+ uReedHead: { value: new THREE.Color(0x6b4526) },
+ uReedDeep: { value: palette.deep.clone() },
+ uReedWind: { value: wind.dir.clone() },
+ uReedSpeed: { value: wind.speed },
+ uReedRate: { value: _SWAY_RATE.clone() },
+ uReedWater: { value: waterY },
+ },
+ vertexHead: STEM_HEAD,
+ vertexBody: STEM_VERTEX,
+ fragmentHead: [
+ 'uniform vec3 uReedColor;',
+ 'uniform vec3 uReedDry;',
+ 'uniform vec3 uReedHead;',
+ 'uniform vec3 uReedDeep;',
+ 'varying vec4 vReed;',
+ 'varying vec4 vReedVar;',
+ 'varying vec2 vReedW;',
+ ].join('\n'),
+ fragmentBody: STEM_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geom, mat);
+ mesh.name = 'Stems';
+ mesh.frustumCulled = false;
+ mesh.receiveShadow = true;
+ mesh.castShadow = false;
+ // The default depth material never runs this vertex shader, so the
+ // shadow pass needs the same displacement or a stand casts nothing.
+ if (shadows) shadowLike(mesh, 'reed:stemDepth', STEM_HEAD, STEM_VERTEX);
+ return mesh;
+}
+
+const STEM_HEAD = [
+ // See the insect material's uTime note. On ONE line with the next
+ // uniform because that audit only reads quoted strings of 40
+ // characters or more.
+ 'uniform float uTime; uniform vec2 uReedWind;',
+ 'uniform float uReedSpeed;',
+ 'uniform vec2 uReedRate;',
+ 'uniform float uReedWater;',
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iPos;',
+ 'attribute vec4 iShape;',
+ 'attribute vec4 iBend;',
+ 'attribute vec4 iVar;',
+ 'varying vec4 vReed;',
+ 'varying vec4 vReedVar;',
+ 'varying vec2 vReedW;',
+ // A world direction as the LOCAL offset that moves this surface
+ // one metre along it, valid while the basis stays orthogonal.
+ 'vec3 reedLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+const STEM_VERTEX = [
+ ' vec3 rdRoot = iPos;',
+ ' float rdV = aCorner.y;',
+ ' float rdH = max(iShape.x, 1e-3);',
+ // Gusts are streaks running downwind — the same field grass.js rides,
+ // so a scene's meadow and its shallows lean together.
+ ' vec2 rdW = uReedWind;',
+ ' vec2 rdP = vec2(dot(rdRoot.xz, rdW),',
+ ' dot(rdRoot.xz, vec2(-rdW.y, rdW.x)));',
+ ' float rdT = uTime * uReedSpeed;',
+ ' float rdGust = astraFbm2(vec2(rdP.x * 0.055 - rdT * 0.5,',
+ ' rdP.y * 0.21), 2);',
+ ' float rdPh = astraStagger(iVar.x + rdRoot.x * 0.07 + rdRoot.z * 0.11);',
+ ' float rdSway = (sin(rdT * uReedRate.x + rdPh)',
+ ' + 0.35 * sin(rdT * uReedRate.x * 1.8 + rdPh * 1.7)) / 1.35;',
+ // Under water: one slow sine, no harmonic, and late — the surface has
+ // already turned before what it holds does.
+ ' float rdSubSway = sin(rdT * uReedRate.y + rdPh - 1.05);',
+ ' float rdPush = (0.25 + 1.25 * rdGust) * (0.62 + 0.38 * rdSway);',
+ ' float rdSubPush = (0.45 + 0.75 * rdGust) * (0.62 + 0.38 * rdSubSway);',
+ // Droop and push ADD as vectors, so a still stand leans every which
+ // way and a gust turns all of it downwind at once.
+ ' vec2 rdLean = vec2(cos(iBend.z), sin(iBend.z)) * iBend.w;',
+ ' vec2 rdAbove = rdLean + rdW * (iBend.x * rdPush);',
+ ' vec2 rdBelow = rdLean * 0.6 + rdW * (iBend.y * rdSubPush);',
+ ' vec2 rdF = length(rdAbove) > 1e-5 ? normalize(rdAbove)',
+ ' : vec2(1.0, 0.0);',
+ ' float rdKa = max(min(length(rdAbove), 1.3), 1e-3);',
+ ' float rdKb = max(min(length(rdBelow), 1.3), 1e-3);',
+ // Two circular arcs of the stem's own length, meeting at the
+ // waterline: the break in curvature IS the cue.
+ ' float rdVw = clamp(iShape.z, 0.0, 1.0);',
+ ' float rdA1 = rdKb * min(rdV, rdVw);',
+ ' float rdU = rdH * (1.0 - cos(rdA1)) / rdKb;',
+ ' float rdY = rdH * sin(rdA1) / rdKb;',
+ ' float rdA2 = rdA1 + rdKa * max(rdV - rdVw, 0.0);',
+ ' rdU += rdH * (cos(rdA1) - cos(rdA2)) / rdKa;',
+ ' rdY += rdH * (sin(rdA2) - sin(rdA1)) / rdKa;',
+ ' vec3 rdSpine = rdRoot + vec3(rdF.x * rdU, rdY, rdF.y * rdU);',
+ ' vec3 rdTan = vec3(rdF.x * sin(rdA2), cos(rdA2), rdF.y * sin(rdA2));',
+ // Seen THROUGH moving water a submerged stem wavers, and the step at
+ // the line is the break refraction really puts there.
+ ' float rdWet = step(rdV, rdVw);',
+ ' rdSpine.xz += vec2(-rdF.y, rdF.x) * (0.012 * rdWet',
+ ' * sin(rdT * 0.9 + rdPh + rdV * 7.0));',
+ ' float rdT2 = (rdV - 0.9) / 0.11;',
+ ' float rdHead = iShape.w * sqrt(max(1.0 - rdT2 * rdT2, 0.0));',
+ ' float rdWid = iShape.y * (0.55 + 0.45 * sqrt(max(1.0 - rdV, 0.0)))',
+ ' + rdHead;',
+ // A stem is round, so its strip faces the eye from every angle
+ // instead of collapsing to a line like a flat blade.
+ ' vec3 rdWp = (modelMatrix * vec4(rdSpine, 1.0)).xyz;',
+ ' vec3 rdView = normalize(reedLocalDir(cameraPosition - rdWp));',
+ ' vec3 rdC = cross(rdTan, rdView);',
+ ' float rdCl = length(rdC);',
+ ' vec3 rdSide = rdCl > 1e-4 ? rdC / rdCl : vec3(1.0, 0.0, 0.0);',
+ ' float rdX = aCorner.x * 2.0;',
+ ' transformed = rdSpine + rdSide * (rdX * rdWid);',
+ ' vReed = vec4(rdV, rdHead / max(iShape.w, 1e-4),',
+ ' rdWp.y - uReedWater, rdX);',
+ ' vReedVar = vec4(iVar.y, iVar.z, iVar.w, rdVw);',
+ // The metre-scale colour field is read at the ROOT: a stem is a few
+ // pixels wide, so a field sampled up its length streaks it instead of
+ // patching the stand.
+ ' vReedW = rdRoot.xz;',
+ '#ifndef FLAT_SHADED',
+ // The normal of a cylinder, not of a card: without it a stand of
+ // stems shades as a field of flat ribbons.
+ ' vec3 rdFace = normalize(cross(rdSide, rdTan));',
+ ' vNormal = normalize(normalMatrix * normalize(',
+ ' rdFace * sqrt(max(1.0 - rdX * rdX, 0.04)) + rdSide * rdX));',
+ '#endif',
+].join('\n');
+
+const STEM_FRAGMENT = [
+ // THREE scales of colour, because a stand read at one is a green
+ // fence: last year's bleached stems through this year's live ones,
+ // each stem's own hue and value, and the metre-scale field the meadow
+ // rides too (grass.js's astraHueBreak, so a stand and the field it
+ // fringes agree at the shoreline).
+ ' vec3 rdCol = mix(uReedColor, uReedDry, vReedVar.z);',
+ ' rdCol = astraHueShift(rdCol, vReedVar.x);',
+ ' rdCol = astraHueBreak(rdCol, vReedW, 0.5, 0.34);',
+ ' rdCol *= 0.82 + 0.36 * vReedVar.y;',
+ // A stand is DEEP: the foot of a stem sits in the shade of its
+ // neighbours, and that gradient is most of what reads as a stand.
+ // A POWER, not a smoothstep — a smoothstep is already back at 0.9 by
+ // mid-stem, which is where most of the stand's pixels are.
+ ' float rdDepth = pow(clamp(vReed.x, 0.0, 1.0), 1.3);',
+ ' rdCol *= 0.46 + 0.54 * rdDepth;',
+ ' rdCol = mix(rdCol, rdCol * vec3(1.5, 1.35, 0.75),',
+ ' vReedVar.y * smoothstep(0.45, 1.0, vReed.x));',
+ ' rdCol *= 0.93 + 0.14 * astraNoise2(vec2(vReed.x * 60.0,',
+ ' vReedVar.y * 30.0));',
+ // The seed head is velvet, not plastic: its own hue and value per
+ // stem, and a fine grain across it, or three thousand identical
+ // chocolate cigars stand over the water.
+ ' vec3 rdHeadCol = astraHueShift(uReedHead, vReedVar.x * 0.7)',
+ ' * (0.76 + 0.34 * vReedVar.z);',
+ ' rdHeadCol *= 0.9 + 0.2 * astraNoise2(vec2(vReed.w * 9.0,',
+ ' vReed.x * 150.0));',
+ ' float rdIsHead = smoothstep(0.15, 0.6, vReed.y);',
+ ' rdCol = mix(rdCol, rdHeadCol, rdIsHead);',
+ // THE WATERLINE, the whole cue: a dark wet skin the water has
+ // climbed, a bright meniscus where the surface grabs the stem, and
+ // below it a stem losing its colour into the water EXPONENTIALLY —
+ // light does not fall off linearly through water, and the old linear
+ // ramp to 0.55 m left a fringe stand with no underwater at all.
+ ' float rdSubm = 1.0 - exp(min(vReed.z, 0.0) * 3.6);',
+ ' rdCol *= 1.0 - 0.42 * (1.0 - smoothstep(0.0, 0.085, vReed.z));',
+ ' rdCol = mix(rdCol, uReedDeep, rdSubm * 0.85);',
+ // The meniscus reads the water it stands in, not a fixed white.
+ ' rdCol += (uReedDeep + vec3(0.1, 0.11, 0.1)) * 0.55',
+ ' * (1.0 - smoothstep(0.0, 0.02, abs(vReed.z)));',
+ // TRANSLUCENCY. A reed is a wet green straw: backlit, a good part of
+ // what reaches the eye came THROUGH it, and that is the difference
+ // between a stand and a picket fence. Albedo cannot say it (the lit
+ // side is the far one), so it goes in as emitted radiance read off
+ // the scene's OWN key light — direction and colour both, so a moon
+ // drives it as happily as a sun. Sap is yellower than the stem, and
+ // a negative turn about the grey axis is that way.
+ '#if NUM_DIR_LIGHTS > 0',
+ '#ifndef FLAT_SHADED',
+ ' vec3 rdN = normalize(vNormal);',
+ ' vec3 rdEye = normalize(vViewPosition);',
+ ' vec3 rdL = directionalLights[0].direction;',
+ ' float rdThru = clamp(-dot(rdN, rdL) * sign(dot(rdN, rdEye)),',
+ ' 0.0, 1.0);',
+ ' float rdBeam = pow(clamp(dot(rdEye, -rdL) * 0.5 + 0.5, 0.0, 1.0),',
+ ' 3.0);',
+ // A SEED HEAD IS NOT A LEAF: packed felt where the stem is a straw,
+ // and left in the term it lit up as a brick-red ember on every stem
+ // in the stand. Dead straw barely passes light either, and a drowned
+ // stem passes it only as far as the water allows.
+ ' vec3 rdSap = astraHueShift(rdCol, -0.20) * 1.7;',
+ ' totalEmissiveRadiance += directionalLights[0].color * rdSap',
+ ' * (0.44 * rdThru * rdBeam * rdDepth * (1.0 - 0.86 * rdIsHead)',
+ ' * (1.0 - 0.7 * vReedVar.z) * (1.0 - rdSubm));',
+ '#endif',
+ '#endif',
+ ' diffuseColor.rgb = rdCol;',
+].join('\n');
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/strata.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/strata.js
new file mode 100644
index 00000000..93f243d6
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/strata.js
@@ -0,0 +1,544 @@
+/**
+ * The two marks that make a cliff read as ROCK and not as brown
+ * geometry: the beds it was laid down in, and the runs the rain has cut
+ * down it. Neither is decoration — a face with no bedding reads as a
+ * displaced blob, and one with no runs reads as a clean model of rock.
+ *
+ * Both go through `patchStandard`, so the built-in's lighting, shadows,
+ * fog and depth chunks survive, and both shade from world position and
+ * world normal — no UV to author, and a face at any angle gets the same
+ * geology. They are meant to land ON TOP of `patchTriplanar` /
+ * `patchSlopeSplat`, whose noise keeps showing through both.
+ *
+ * The constraint that shapes them: a fragment sees its own position,
+ * its own normal and its own screen derivatives, and nothing else. So
+ * the beds ride world ALTITUDE — one stack for the whole scene, which
+ * is why two cliffs a hundred metres apart line up — and a run learns
+ * where water collects only from the way the surface BENDS under it (a
+ * gully across the flow, a lip along it) plus its own field smeared
+ * downslope, which is what gives a run a head and a tail.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade, aging, surface_wear and waterside name them,
+// so a material wearing several libraries carries ONE world position.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// Helpers both patches share, all astraStrata-prefixed: GLSL has one
+// global namespace, and a chained patch redefining a neighbour's
+// function is a compile error naming neither of them.
+const STRATA_HEAD = [
+ 'float astraStrataFbm(vec2 p) {',
+ ' return clamp(astraFbm2(p, 3) / 0.875, 0.0, 1.0);',
+ '}',
+ // The floor of bed `k`, offset by its own hash. Under half a bed, so
+ // the stack stays in order however the offsets fall and the bed
+ // holding a coordinate is always within one of its floor().
+ 'float astraStrataFloor(float k, float s) {',
+ ' return k + (astraHash21(vec2(k, s)) - 0.5) * 0.9;',
+ '}',
+ // Value noise in 3-D, built from the 2-D one: the run field is
+ // smeared along the fall line, which is no world axis, so an
+ // axis-projected field cannot carry it.
+ 'float astraStrataN3(vec3 p) {',
+ ' float k = floor(p.z), f = p.z - k;',
+ ' f = f * f * (3.0 - 2.0 * f);',
+ ' return mix(astraNoise2(p.xy + k * 37.13),',
+ ' astraNoise2(p.xy + (k + 1.0) * 37.13), f);',
+ '}',
+ // A run is the SMEAR of a source along the flow: taps UPSLOPE of here
+ // with decaying weight, so a feature is long downslope, narrow across
+ // it, and tapers out below where it started.
+ 'float astraStrataRun(vec3 p, vec3 d, float len, int taps) {',
+ ' float s = astraStrataN3(p), w = 1.0, a = 1.0, o = 0.0;',
+ // Unevenly spaced: at one tap per noise cell they would all land on
+ // the same lattice phase and comb the run into blocks. The count is
+ // the aspect ratio — a tap cannot reach past its neighbour's cell.
+ ' for (int i = 0; i < 6; i++) {',
+ ' if (i >= taps) break;',
+ ' o += len * (0.11 + 0.035 * float(i));',
+ ' a *= 0.78; w += a;',
+ ' s += a * astraStrataN3(p - d * o);',
+ ' }',
+ ' return clamp((s / w - 0.5) * 2.2 + 0.5, 0.0, 1.0);',
+ '}',
+ // Total curvature in 1/m: how far the normal turns per metre of
+ // surface under one pixel. Positive convex, negative the concave that
+ // holds water, and ZERO across a hard unwelded edge.
+ 'float astraStrataCurv(vec3 n, vec3 p) {',
+ ' vec3 dx = dFdx(p), dy = dFdy(p);',
+ ' float d = dot(dx, dx) + dot(dy, dy);',
+ ' return (dot(dFdx(n), dx) + dot(dFdy(n), dy)) / max(d, 1e-12);',
+ '}',
+ // The same, restricted to ONE surface direction. A lip is convex
+ // along the flow and a rib is convex across it, and they do opposite
+ // things to a run, so the two halves have to be separable.
+ 'float astraStrataBend(vec3 n, vec3 p, vec3 d) {',
+ ' float ax = dot(dFdx(p), d), ay = dot(dFdy(p), d);',
+ ' return (dot(dFdx(n), d) * ax + dot(dFdy(n), d) * ay)',
+ ' / max(ax * ax + ay * ay, 1e-12);',
+ '}',
+ // Only a bend the size of a run is a landform: `k` is curvature in
+ // run widths, and the pixel-scale wrinkle under it (k of 4 and up)
+ // is not a gully and must not be allowed to draw one.
+ 'float astraStrataBand(float k) {',
+ ' return smoothstep(0.15, 0.80, k) * (1.0 - smoothstep(2.0, 5.0, k));',
+ '}',
+].join('\n');
+
+// `transformed` is still object-space after <begin_vertex>, so the
+// instance transform is folded in by hand or every scattered boulder
+// takes its bedding from the mesh origin.
+const BASE = {
+ name: 'strata:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 stbP = vec4(transformed, 1.0);',
+ ' vec3 stbN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' stbP = instanceMatrix * stbP;',
+ ' stbN = mat3(instanceMatrix) * stbN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * stbP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(stbN, 0.0)).xyz);',
+ ].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, STRATA_HEAD].join('\n'),
+};
+
+// A pale sandstone, an iron-rich tan, a grey-green marl and a dark
+// red-brown mudstone: enough spread that a thin dark bed between two
+// thick pale ones is possible.
+//
+// The four differ in HUE and in saturation, not only in value. A ramp
+// that walks one hue from light to dark is a greyscale ramp with a
+// tint on it, and the beds then read as a barcode rather than as
+// geology.
+//
+// They are also authored WARM on purpose, and the reason is measured
+// rather than taste. Most of a cliff is in its own shade, and the fill
+// this library ships (`sunRig`: a hemisphere at 0x9db8e8 over warm
+// ground, plus a blue-sky environment) puts LINEAR (1, 1.56, 2.45) on
+// a shaded vertical face — a neutral grey albedo renders (88, 110,
+// 134) there. An albedo has to beat that ratio to come back as rock at
+// all: at G/R above ~0.64 linear the bed returns GREEN, which is how
+// the original palette's mid tones read. These are solved against that
+// measurement, so a shaded face returns roughly (1, 0.90, 0.73) for
+// the buff down to (1, 0.63, 0.40) for the mudstone — sandstone, and
+// under a neutral or overcast rig, red-rock sandstone. The four are
+// spread by SATURATION between those, never toward yellow: a bed that
+// reaches G/R = 1 in the render is one grain-multiply away from green.
+const BEDS = [0xcc9f78, 0x8e6541, 0x74583f, 0x5b3a23];
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 rocks differ.
+ *
+ * The offset is a UNIFORM: a seed baked into the GLSL would be fixed
+ * for every material sharing the cache key. The constants differ from
+ * aging's and surface_wear's, or one seed would lay these runs down the
+ * middle of that library's stains.
+ */
+function seedOffset(seed, salt) {
+ return new THREE.Vector3(
+ hash11(seed + salt + 1.63), hash11(seed + salt + 6.41),
+ hash11(seed + salt + 11.09)).multiplyScalar(52);
+}
+
+/**
+ * Resample any palette to the four tones the shader ramps through.
+ *
+ * The count is fixed because the GLSL is: an option may vary by
+ * uniform, never by source, so two cliffs with two-colour and
+ * five-colour palettes still share one compiled program.
+ */
+function palette4(colors) {
+ const list = (Array.isArray(colors) && colors.length ? colors : BEDS)
+ .map((c) => toColor(c, BEDS[1]));
+ if (list.length === 1) return [0, 1, 2, 3].map(() => list[0].clone());
+ return [0, 1, 2, 3].map((i) => {
+ const t = (i / 3) * (list.length - 1);
+ const k = Math.min(Math.floor(t), list.length - 2);
+ return list[k].clone().lerp(list[k + 1], t - k);
+ });
+}
+
+/**
+ * The normal of the bedding plane: world up, tipped by `tilt` degrees.
+ *
+ * The dip DIRECTION comes from the seed rather than from another
+ * option, so a scene sets one tilt and one seed and every cliff in it
+ * dips the same way.
+ */
+function beddingUp(tilt, seed) {
+ const dip = Math.max(-85, Math.min(85, tilt)) * Math.PI / 180;
+ const az = hash11(seed + 0.71) * Math.PI * 2;
+ return new THREE.Vector3(
+ Math.sin(dip) * Math.cos(az), Math.cos(dip),
+ Math.sin(dip) * Math.sin(az)).normalize();
+}
+
+/**
+ * Lay sedimentary beds through the rock, by world ALTITUDE.
+ *
+ * A cliff reads as rock because it shows the layers it was deposited
+ * in, and the eye checks them against each other: beds have to run
+ * THROUGH the scene, so the band at 12 m on this face continues at
+ * 12 m on the one across the valley. That is why the coordinate is
+ * `dot(worldPosition, beddingNormal)` and nothing else — no UV, no
+ * object space, no per-mesh phase — and why every cliff should be
+ * given the same options.
+ *
+ * `tilt` is the whole point. Level beds read as a stripe texture; beds
+ * dipping a few degrees read as geology, because the bands then cut
+ * across the topography instead of following it. It is a dip in
+ * DEGREES, and the dip direction comes from `seed`.
+ *
+ * Three things keep it from being wallpaper. Bed THICKNESS varies, in
+ * two registers: a slow warp of the stack coordinate gives a run of
+ * thick beds and then a run of thin ones, and every bed floor carries
+ * its own offset on top of that, so a 0.8 m stack measures anywhere
+ * from 0.13 m to 1.5 m bed to bed. The bedding surfaces UNDULATE, by
+ * `jitter` of a bed over ~30 m of ground, so no boundary is a ruled
+ * line. And every so often a contact carries a thin dark PARTING —
+ * drawn with `astraStroke`, which fades a stroke out once a pixel spans
+ * more than it, so the seams thin away with distance instead of
+ * aliasing into moire. Past a pixel per bed the whole stack dissolves
+ * into its own mean tone, for the same reason.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` beds every mesh
+ * wearing it, so clone it first if that is not what you want.
+ * @param {object} [opts] `spacing` metres of an average bed (default
+ * 0.8; thickness varies about it); `tilt` dip of the beds in degrees
+ * (default 7 — 0 is level and reads as texture, past ~25 it reads as
+ * folded); `colors` array of THREE.Color or hex, resampled to the
+ * four tones the beds ramp through (default a buff-to-mudstone run,
+ * authored WARM against this renderer's blue-sky fill — see BEDS; a
+ * palette that is merely "rock-coloured" comes back cyan in shade);
+ * `contrast` how far the albedo goes toward the bed tone, 0..1
+ * (default 0.7); `jitter` how far a bedding surface wanders, in beds
+ * (default 0.35); `seed` moves the tones, the wander and the dip
+ * direction (default 1).
+ * @returns {THREE.Material} The same material. Its uniforms stay live
+ * on `material.userData.uniforms`, so `uStrataUp` can be retuned for
+ * a whole scene at once.
+ */
+export function patchRockStrata(material, opts = {}) {
+ const spacing = opts.spacing === undefined ? 0.8 : opts.spacing;
+ const tilt = opts.tilt === undefined ? 7 : opts.tilt;
+ const contrast = opts.contrast === undefined ? 0.7 : opts.contrast;
+ const jitter = opts.jitter === undefined ? 0.35 : opts.jitter;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const beds = palette4(opts.colors);
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'strata:beds',
+ uniforms: {
+ uStrataUp: { value: beddingUp(tilt, seed) },
+ uStrataSpacing: { value: Math.max(1e-3, spacing) },
+ uStrataAmt: { value: unit(contrast) },
+ uStrataJit: { value: Math.max(0, jitter) },
+ uStrataSeed: { value: seedOffset(seed, 0) },
+ uStrataC0: { value: beds[0] },
+ uStrataC1: { value: beds[1] },
+ uStrataC2: { value: beds[2] },
+ uStrataC3: { value: beds[3] },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform vec3 uStrataUp;',
+ 'uniform float uStrataSpacing;',
+ 'uniform float uStrataAmt;',
+ 'uniform float uStrataJit;',
+ 'uniform vec3 uStrataSeed;',
+ 'uniform vec3 uStrataC0;',
+ 'uniform vec3 uStrataC1;',
+ 'uniform vec3 uStrataC2;',
+ 'uniform vec3 uStrataC3;',
+ // A ramp, not a set: neighbouring beds take unrelated points on
+ // it, so a sequence gets both near-twins and hard contacts.
+ 'vec3 astraStrataTone(float f) {',
+ ' float g = f * 3.0;',
+ ' vec3 c = mix(uStrataC0, uStrataC1, clamp(g, 0.0, 1.0));',
+ ' c = mix(c, uStrataC2, clamp(g - 1.0, 0.0, 1.0));',
+ ' return mix(c, uStrataC3, clamp(g - 2.0, 0.0, 1.0));',
+ '}',
+ // Which point of the ramp a bed takes. A uniform draw lands a
+ // quarter of the beds in the palest quarter and a quarter in the
+ // darkest, and consecutive beds then alternate near-white and
+ // near-black: a barcode, not a formation. This pulls the middle
+ // of the draw toward the middle of the ramp and leaves the two
+ // ends alone, so most beds are mid-tone and the pale marker bed
+ // and the dark parting bed stay rare enough to read as events.
+ // Monotone and continuous, so the contact antialiasing below is
+ // untouched.
+ 'float astraStrataPick(float h) {',
+ ' float e = abs(2.0 * h - 1.0);',
+ ' return 0.5 + (h - 0.5) * (0.45 + 0.55 * e * e);',
+ '}',
+ ].join('\n'),
+ fragmentBody: [
+ // Altitude across the beds, in beds. World, and anchored to
+ // nothing the mesh knows, so two cliffs cut one stack.
+ ' float stB = dot(vAstraWorld, normalize(uStrataUp))',
+ ' / uStrataSpacing;',
+ // The surfaces undulate over ~30 m of ground: no bed was ever
+ // laid down against a ruler.
+ ' stB += (astraStrataFbm(vAstraWorld.xz * 0.035',
+ ' + uStrataSeed.xz) - 0.5) * uStrataJit;',
+ // A slow stretch of the stack by a function of ITSELF: a run of
+ // thick beds, then a run of thin ones, the way a formation reads.
+ ' stB += (astraStrataFbm(vec2(stB * 0.16, uStrataSeed.y)) - 0.5)',
+ ' * 1.20;',
+ // ...and each bed floor carries its OWN offset on top of that, so
+ // one bed comes out several times another. A stripe of one width
+ // is wallpaper, and this is the line that stops it being one.
+ ' float stI = floor(stB);',
+ ' float stLo = astraStrataFloor(stI, uStrataSeed.z);',
+ ' if (stB < stLo) {',
+ ' stI -= 1.0;',
+ ' stLo = astraStrataFloor(stI, uStrataSeed.z);',
+ ' }',
+ ' float stHi = astraStrataFloor(stI + 1.0, uStrataSeed.z);',
+ ' if (stB >= stHi) {',
+ ' stI += 1.0; stLo = stHi;',
+ ' stHi = astraStrataFloor(stI + 1.0, uStrataSeed.z);',
+ ' }',
+ ' float stTh = max(stHi - stLo, 1e-3);',
+ ' float stF = (stB - stLo) / stTh;',
+ // Continuous across a contact where stF is not, so the seam's own
+ // antialiasing reads a gradient there instead of a jump.
+ ' float stP = stI + stF;',
+ ' float stAA = clamp(fwidth(stB) / stTh, 1e-4, 2.0);',
+ // astraHash21, not astraHash11: over consecutive integers the 1-D
+ // one lands 40% of the beds in its palest quarter and the cliff
+ // comes out bleached.
+ ' float stNb = stI + (stF < 0.5 ? -1.0 : 1.0);',
+ // A contact is sharp in the rock, and a sharp edge in a shader is
+ // what crawls — MSAA never sees one — so it is resolved over the
+ // pixel it actually covers.
+ ' vec3 stCol = mix(',
+ ' astraStrataTone(astraStrataPick(',
+ ' astraHash21(vec2(stI, uStrataSeed.z + 2.3)))),',
+ ' astraStrataTone(astraStrataPick(',
+ ' astraHash21(vec2(stNb, uStrataSeed.z + 2.3)))),',
+ ' 0.5 - 0.5 * smoothstep(0.0, stAA, min(stF, 1.0 - stF)));',
+ // Grain from world XZ only, so within a bed it streaks ALONG the
+ // bedding on any vertical face, and each bed gets its own.
+ ' float stG = astraStrataFbm(vAstraWorld.xz * 1.1 + stI * 4.7);',
+ // In HUE as well as value: one bed is not one colour across a
+ // face — it is warm where the iron collected and washed out where
+ // it did not — and a scalar multiply here leaves a whole bed
+ // flat, which is what makes a shader stack read as printed
+ // stripes. The far end of the grain is BLEACHED, barely cool: on
+ // a face already lit by a blue sky a cool multiply is what tips a
+ // bed past G/R = 1 and turns it green, and a green patch is not
+ // a mineral.
+ ' stCol *= mix(vec3(1.12, 1.02, 0.87), vec3(0.95, 0.97, 1.01),',
+ ' stG);',
+ // A finer mottle on top, so the metre-scale grain is not the
+ // smallest thing on the rock at arm's length.
+ ' float stG2 = astraStrataFbm(vAstraWorld.xz * 3.7 + stI * 9.1);',
+ ' stCol *= mix(0.93, 1.06, stG2);',
+ // Every bed is a little darker at its foot, which is the shadow
+ // of the ledge the harder bed above it makes — and warmer, since
+ // that is where the iron coming down the face stops.
+ ' stCol *= mix(vec3(1.0), vec3(1.0, 0.92, 0.80),',
+ ' 1.0 - smoothstep(0.0, 0.32, stF));',
+ ' stCol *= mix(0.93, 1.03, smoothstep(0.0, 0.30, stF));',
+ // The occasional thin dark parting at a contact, in fractions of
+ // the bed it belongs to; astraStroke fades it out rather than
+ // aliasing once a pixel spans more than the seam itself.
+ ' float stS = astraHash21(vec2(stI, uStrataSeed.z + 5.1));',
+ ' float stSeam = astraStroke(stP + 0.5, mix(0.02, 0.09, stS))',
+ ' * smoothstep(0.55, 0.75, stS)',
+ // ...and it fades in and out ALONG the bed, on that bed's own
+ // grain. A parting of one strength the whole way round is a
+ // scribed line, which is the tell that a shader drew the contact.
+ ' * mix(0.28, 1.0, stG);',
+ // A parting is a thin bed of clay, not a hole punched in the
+ // cliff: it goes to a dark, slightly cooler version of the rock
+ // above it and keeps a floor, so the seam never crushes to black
+ // and never loses its hue.
+ ' stCol = mix(stCol,',
+ ' stCol * vec3(0.50, 0.49, 0.54)',
+ ' + vec3(0.012, 0.011, 0.012), 0.66 * stSeam);',
+ // A pixel that spans a bed cannot show one, so the stack
+ // dissolves into its own mean tone there instead of into moire —
+ // and the far cliff keeps its rock colour rather than reverting.
+ ' vec3 stAvg = 0.25 * (uStrataC0 + uStrataC1 + uStrataC2',
+ ' + uStrataC3);',
+ ' stCol = mix(stCol, stAvg, smoothstep(0.30, 1.00, stAA));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, stCol, uStrataAmt);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Cut the runs the rain leaves down a face, along the FALL LINE.
+ *
+ * Rock does not weather evenly: water sheets off the ledges, gathers
+ * into threads and takes the dirt down the steepest path, which is
+ * straight down a vertical face and the fall line on anything shallower
+ * — never world Y on a slope, and never a UV direction. The fall line
+ * is `gravity - normal * dot(gravity, normal)`, and a run is that
+ * direction's SMEAR of the field: taps upslope of each fragment with
+ * decaying weight, so features come out long downslope, narrow across
+ * it, and bend as the surface turns. (Squashing the position along the
+ * fall line instead is cheaper and wrong — the lever arm is the whole
+ * world position, so a 1% turn of the normal moves the field a whole
+ * feature and the surface's own wrinkles get painted on it.)
+ *
+ * They must not be everywhere, and a fragment cannot look up the slope
+ * to find the ledge that fed it. What it CAN see is the way the surface
+ * bends under it, so the sources are read from curvature split into its
+ * two halves: concave ACROSS the flow is a gully and holds its thread
+ * the whole way down, convex ALONG the flow is a lip and pours what it
+ * catches over, and convex across is a rib that sheds sideways and
+ * stays clean. A source lowers the field's THRESHOLD rather than
+ * dimming it, so clean rock keeps a few strong runs and a gully floor
+ * darkens broadly. On flat-shaded geometry (`BoxGeometry`, anything
+ * unwelded) curvature reads zero and the field alone carries it.
+ *
+ * The fade downslope is the smear's own decay: each tap upslope arrives
+ * weaker than the last, so a run continues below where it started and
+ * tapers out, which is flow rather than stripes.
+ *
+ * Roughness is per MATERIAL, not per pixel (`<color_fragment>` runs
+ * before `<roughnessmap_fragment>`), so the wash takes a small polish
+ * off the whole surface through `composeRoughness` — a face with water
+ * tracks is a face that gets wet.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material streaks every mesh wearing it.
+ * @param {object} [opts] `strength` how far a run goes toward `color`,
+ * 0..1 (default 0.45); `color` THREE.Color or hex, the mineral the
+ * runs carry — the shader derives a rust and a darker varnish from it
+ * (default a dark iron brown; a NEUTRAL dark here renders as a
+ * slate-blue patch under a blue-sky fill, which is what the reference
+ * grey-brown did); `scale` metres across a run (default 0.8; its
+ * length is ~8x that, and the curvature the sources look for scales
+ * with it); `seed` moves them (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`.
+ */
+export function patchErosionStreaks(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.45 : opts.strength;
+ const scale = opts.scale === undefined ? 0.8 : opts.scale;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ composeRoughness(material, 'strata:erosion',
+ 1 - 0.10 * unit(strength));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'strata:erosion',
+ uniforms: {
+ uErosAmt: { value: unit(strength) },
+ uErosColor: { value: toColor(opts.color, 0x3e2615) },
+ uErosScale: { value: Math.max(1e-3, scale) },
+ uErosSeed: { value: seedOffset(seed, 3.7) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uErosAmt;',
+ 'uniform vec3 uErosColor;',
+ 'uniform float uErosScale;',
+ 'uniform vec3 uErosSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 erN = normalize(vAstraWorldN);',
+ // The fall line is gravity with the normal taken out, and its
+ // LENGTH is the sine of the slope — one expression gives the way
+ // the water goes and the gate that keeps it off level ground.
+ ' vec3 erG = vec3(0.0, -1.0, 0.0) + erN * erN.y;',
+ ' float erSin = length(erG);',
+ ' vec3 erD = erG / max(erSin, 1e-4);',
+ ' vec3 erP = vAstraWorld / uErosScale + uErosSeed;',
+ // Long: the smear is what makes a run a run, and at 5.5 it came
+ // out as round blotches on a face this size — a stain, not a
+ // track. Six taps over 7.5 run widths is an 8:1 feature before
+ // the threshold ever sees it.
+ ' float erA = astraStrataRun(erP, erD, 7.5, 6);',
+ // A finer smear ADDED before the threshold rather than multiplied
+ // after: it tears every run's edge into threads that run WITH it.
+ // Weighted hard enough to actually break the edge — at 0.26 the
+ // broad field won everywhere and the runs closed back into blobs.
+ ' float erFib = astraStrataRun(erP * 3.4, erD, 2.8, 4);',
+ ' float erF = erA + (erFib - 0.5) * 0.40;',
+ // Curvature in run widths, split by direction: a hollow ACROSS
+ // the flow holds water, a break ALONG it pours what it caught
+ // over, a rib across it sheds sideways and stays clean.
+ ' float erAl = astraStrataBend(erN, vAstraWorld, erD) * uErosScale;',
+ ' float erAc = astraStrataCurv(erN, vAstraWorld) * uErosScale',
+ ' - erAl;',
+ ' float erSrc = clamp(0.34 + 0.60 * astraStrataBand(-erAc)',
+ ' + 0.40 * astraStrataBand(erAl)',
+ ' - 0.32 * astraStrataBand(erAc), 0.0, 1.0);',
+ // A source lowers the BAR rather than dimming the run: clean rock
+ // keeps only the strongest few. The span is narrow because a
+ // screen-derivative gate is flat per TRIANGLE.
+ ' float erT = mix(0.72, 0.58, erSrc);',
+ ' float erAA = clamp(fwidth(erF), 0.0, 0.5);',
+ // Two levels on one field, kept APART rather than summed away: a
+ // broad wash and the darker core inside it are different
+ // minerals, and the pair is what makes a run read as a run and
+ // not as a smudge.
+ ' float erBroad = smoothstep(erT - 0.10 - erAA,',
+ ' erT + 0.04 + erAA, erF);',
+ ' float erCore = smoothstep(erT + 0.04 - erAA,',
+ ' erT + 0.15 + erAA, erF);',
+ ' float erK = 0.45 * erBroad + 0.55 * erCore;',
+ // A slope to run down, and not a soffit: what faces down drips
+ // clear of the rock instead of tracking across it.
+ ' float erFlow = smoothstep(0.10, 0.42, erSin)',
+ ' * (1.0 - smoothstep(0.15, 0.65, -erN.y));',
+ ' float erAmt = clamp(erK * erFlow * uErosAmt, 0.0, 1.0);',
+ // Which mineral this run carries, from a field far coarser than
+ // the run itself, so ONE run is one mineral the whole way down
+ // instead of speckling along its length: iron leaves a rust
+ // margin, manganese the near-black varnish of a desert face.
+ // Neither variant is allowed to go neutral: under a blue-sky fill
+ // a neutral dark stain renders as a slate-blue patch, which is
+ // how a grey-brown default reads on a cliff in its own shade.
+ ' float erMin = astraStrataN3(erP * 0.21 + 13.7);',
+ ' vec3 erIron = uErosColor * vec3(1.55, 1.15, 0.78);',
+ ' vec3 erMang = uErosColor * vec3(0.55, 0.58, 0.72);',
+ ' vec3 erTint = mix(erIron, erMang,',
+ ' erCore * mix(0.35, 0.95, erMin));',
+ // A wet track DARKENS the rock it runs over and keeps that
+ // rock\'s hue; replacing the albedo outright erases the bedding
+ // the runs are supposed to run ACROSS, which is what turns a
+ // face of runs into a face of grey cloud. So the stain is a
+ // darkening of what is underneath, tinted toward the mineral.
+ ' vec3 erWet = diffuseColor.rgb * mix(0.30, 0.78, erA);',
+ ' vec3 erCol = mix(erWet, erTint * mix(0.78, 1.22, erA), 0.56);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, erCol, erAmt);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/submerged.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/submerged.js
new file mode 100644
index 00000000..20750aa9
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/submerged.js
@@ -0,0 +1,674 @@
+/**
+ * Submerged: the water column over what is under it, the rings rain
+ * leaves on open water, and a sheet of thin ice over either.
+ *
+ * A waterline alone leaves a sunk rock as a rock with a line across
+ * it. What says UNDER is the column: contrast falls, the colour walks
+ * toward the water's own, and red goes first — over DEPTH and over the
+ * distance the eye looks through, so a deep floor far off is further
+ * gone than the same floor underfoot.
+ *
+ * The two patches go through `patchStandard`, so each material keeps
+ * its lighting, shadows, fog and depth chunks and they CHAIN with the
+ * waterline (`waterside.js`), the caustic net (`caustics.js`) and the
+ * rock projection (`terrain_shade.js`) the same surface already wears.
+ * `makeRainRings` is the open-water half of `rain.js`, whose splashes
+ * are for hard ground.
+ *
+ * NOT a second reflective surface: `water.js` owns the scene's one RTT
+ * plane. Everything here shades what is under that plane or lies on it.
+ */
+
+import * as THREE from 'three';
+import {
+ patchStandard, composeRoughness, makeShaderMaterial, instancedQuad,
+ keepOutOfDepthPasses,
+} from './shader.js';
+
+// Water absorbs red an order of magnitude faster than blue, and that
+// spectrum IS the effect. Pure water is 1 : 0.21 : 0.054; lifted a
+// little so a 3 m pool does not go pure cyan.
+const EXT_RATIO = new THREE.Vector3(1.0, 0.26, 0.10);
+
+// 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;
+
+// Named as caustics and waterside name them, so a submerged bank
+// wearing a waterline, a net and this declares ONE pair.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// One base for both patches. `transformed` is still object-space after
+// <begin_vertex>, so the instance transform is folded in by hand or
+// every scattered cobble takes its depth from the world origin.
+const BASE = {
+ name: 'submerged:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 subWp = vec4(transformed, 1.0);',
+ ' vec3 subWn = normal;',
+ '#ifdef USE_INSTANCING',
+ ' subWp = instanceMatrix * subWp;',
+ ' subWn = mat3(instanceMatrix) * subWn;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * subWp).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(subWn, 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** Deterministic 0..1 stream: a shipped factory owns its own RNG. */
+function rng(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);
+}
+
+/**
+ * A seed becomes a far-apart lattice offset, not a one-cell shift.
+ *
+ * Seeds 7 and 8 offsetting by 1 would TRANSLATE the field by one cell,
+ * which is the same pool twice.
+ */
+function seedOffset(seed) {
+ const s = Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973;
+ return new THREE.Vector2(((s * 16807) % 9973) * 0.091,
+ ((s * 48271) % 9973) * 0.067);
+}
+
+/**
+ * Per-channel extinction: a scalar on water's spectrum, or three
+ * coefficients given outright (THREE.Vector3 or [r, g, b], per metre).
+ */
+function extinctionVec(value) {
+ if (value && value.isVector3) return value.clone();
+ if (Array.isArray(value)) {
+ return new THREE.Vector3(value[0] || 0, value[1] || 0, value[2] || 0);
+ }
+ const k = value === undefined ? 0.35 : Math.max(0, value);
+ return EXT_RATIO.clone().multiplyScalar(k);
+}
+
+/**
+ * Apply the shared world-space base, then the patch itself.
+ *
+ * `patchStandard` replaces a patch of the SAME name in place, so the
+ * base costs one vertex body however many of these a material wears.
+ */
+function withBase(material, part) {
+ // A raw ShaderMaterial (the addon Water, anything from
+ // makeShaderMaterial) has neither hook, so the patch is a silent
+ // no-op — the one failure mode nothing else here would report.
+ if (material && material.isShaderMaterial) {
+ console.warn(
+ part.name + ': ' + (material.name || 'material') + ' is a raw ' +
+ 'ShaderMaterial with no <color_fragment> hook, so this patch ' +
+ 'does nothing. Patch a standard-material surface instead.');
+ }
+ patchStandard(material, BASE);
+ return patchStandard(material, part);
+}
+
+const UNDER_HEAD = [
+ 'uniform float uSubLevel;',
+ 'uniform vec3 uSubExt;',
+ 'uniform vec3 uSubColor;',
+ 'uniform float uSubMurk;',
+ 'uniform float uSubLight;',
+ 'uniform vec2 uSubSeed;',
+].join('\n');
+
+const UNDER_BODY = [
+ ' float subD = max(uSubLevel - vAstraWorld.y, 0.0);',
+ // The eye ray counts only where it runs UNDER the surface: this
+ // fragment's share of the climb to the camera, which is 0 at the
+ // line however far away the camera is.
+ ' float subRise = max(cameraPosition.y - vAstraWorld.y, 1e-4);',
+ ' float subWet = clamp(subD / subRise, 0.0, 1.0);',
+ ' float subView = length(cameraPosition - vAstraWorld) * subWet;',
+ // Silt drifts. A uniform column is glass, and a still one is a
+ // stain, so the path length rides a slow seeded field.
+ ' vec2 subQ = vAstraWorld.xz * 0.13 + uSubSeed',
+ ' + vec2(uTime * 0.011, uTime * -0.008);',
+ ' float subS = uSubMurk * (astraFbm2(subQ, 3) - 0.44);',
+ ' float subMk = 1.0 + subS;',
+ // Turbidity is not a dimmer, it is a HUE. Silt scatters green and
+ // drinks blue, so the cloudy reaches of one pool run green where the
+ // clear ones run blue — and ONE flat teal over a whole basin is the
+ // tell of a tint rather than a column. The swings are bounded: murk
+ // caps at 1 and the field at -0.44, so no coefficient can go
+ // negative and amplify with depth.
+ ' vec3 subK = uSubExt',
+ ' * vec3(1.0, 1.0 - 0.30 * subS, 1.0 + 1.60 * subS);',
+ ' vec3 subT = exp(-subK * ((subD + subView) * subMk));',
+ // Beer-Lambert down and back out: what the surface returns is
+ // absorbed along both legs, and red is gone first.
+ ' diffuseColor.rgb *= subT;',
+ // The column scatters into the ray exactly what the ray lost, lit
+ // by the blue that got this deep — so contrast dies into the
+ // water's own colour rather than into black. (Filtering the veil per
+ // CHANNEL here is the more literal physics and was measured to be
+ // worse: the red of a green-blue water colour is already near zero
+ // in linear, so the deep end clipped to one channel and came out a
+ // flat, hyper-saturated cyan — mean saturation 0.930 -> 0.941 with
+ // no visible gain.)
+ // ...and by how much light there is to scatter at all. The veil is
+ // LIGHT, and no fragment hook can see the scene's lamps — the head
+ // is injected above <lights_pars_begin> — so a column left at the
+ // daylight number glows the same green through a night scene, which
+ // is the one thing a still of a night pool never shows.
+ ' vec3 subVeil = uSubColor * uSubLight * (1.0 - subT)',
+ ' * exp(-uSubExt.b * subD);',
+ // The same silt that swung the path swings the COLOUR: a turbid
+ // reach scatters green where a clear one runs blue, so one pool is
+ // never one teal. This is where the murk becomes visible — inside
+ // the exponent it only moves an already-saturated exponential.
+ ' subVeil = astraHueBreak(subVeil, subQ, 1.0, 0.30 + 0.9 * uSubMurk);',
+ // A basin is a hundred-pixel ramp of a smooth exponential, which is
+ // exactly where 8-bit output lays down contour bands (measured: the
+ // longest constant run across the deep water fell from 31 px to 7).
+ ' subVeil *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.07;',
+ ' totalEmissiveRadiance += subVeil;',
+].join('\n');
+
+/**
+ * Sink a surface into a water column: contrast out, water colour in.
+ *
+ * Nothing above `level` is touched — the depth is clamped at the line
+ * and the eye ray's underwater share goes to zero there too, so the
+ * transmittance is exactly 1 and the veil exactly 0 above it, with no
+ * step at the line. Below it the loss runs on the TOTAL path: the
+ * depth the light fell through plus the underwater length of the ray
+ * back to the camera. That second leg is what makes the far end of a
+ * pool floor read as further away rather than merely darker, and it is
+ * why a bank photographs bluer across a bay than at your feet.
+ *
+ * Extinction is per channel, which is the whole point: red is gone in
+ * a couple of metres where blue runs for tens, so the albedo walks to
+ * the water's colour red-first while the veil the column scatters back
+ * fills in what was lost. Contrast between two neighbouring albedos
+ * falls by exactly the transmittance, because both take the same veil.
+ *
+ * Turbidity is a HUE, not a second dimmer. The silt field that swings
+ * the path length also swings the SPECTRUM — silt scatters green and
+ * drinks blue — and it swings the veil's own colour with it, so the
+ * cloudy reaches of one pool run green where the clear ones run blue.
+ * One flat teal over a whole basin is the tell of a tint rather than a
+ * column, and it costs one field that was already being sampled. The
+ * veil then carries a per-pixel dither, because a basin is a hundred
+ * pixels of a smooth exponential and that is where 8-bit output lays
+ * contours (measured here: the longest constant run across the deep
+ * water fell from 31 px to 7).
+ *
+ * WITH `caustics.js`: they are two halves of one surface and belong on
+ * the same material at the same `level`. `patchCaustics` ADDS its net
+ * to `totalEmissiveRadiance` tinted by `diffuseColor`; this MULTIPLIES
+ * `diffuseColor` by the transmittance and adds the column's veil to
+ * that same term. Patches run in CALL ORDER, so call this one FIRST
+ * and the net is tinted by the already-extinguished albedo instead of
+ * burning white over water that has eaten every other red in frame.
+ * The net's own `depthFade` is its extinction: keep it near
+ * `1 / extinction` or the net will outlive the floor it lands on. Both
+ * share `vAstraWorld`/`vAstraWorldN` by name, so the pair costs one.
+ *
+ * `level` is a world plane, so EVERYTHING under it is under water,
+ * including the dry outside of a pool wall and the far side of a dam.
+ * Give those their own material, exactly as `caustics.js` needs.
+ *
+ * Needs a LIT material — MeshStandard / MeshPhysical: the veil lands
+ * on the emissive term, which MeshBasicMaterial does not have. Drive
+ * it with `tickShaders(scene, t)`; an un-advanced uTime freezes the
+ * silt, which is a stain rather than a column.
+ *
+ * AT NIGHT, set `light`. The veil is scattered LIGHT and it lands on
+ * the emissive term, so nothing in the scene dims it: a column left at
+ * the daylight number glows the same green under a night sky, which is
+ * the one thing a photograph of a night pool never shows (measured
+ * here: the night basin's water sat at mean luminance 0.42 against a
+ * 0.25 frame until this was turned down). No fragment hook can read
+ * the scene's lamps — patchStandard injects its head ABOVE
+ * `<lights_pars_begin>` — so this is the one number that has to be
+ * told rather than found.
+ *
+ * @param {THREE.Material} material A built-in lit material, patched in
+ * place.
+ * @param {object} [opts] `level` world Y of the water surface (default
+ * 0); `color` THREE.Color or hex the water goes toward (default a
+ * green-blue); `extinction` per-metre loss — a scalar on water's own
+ * spectrum (default 0.35) or a THREE.Vector3 / [r, g, b] of
+ * coefficients outright; `murk` how far drifting silt swings the
+ * path length AND its colour, 0..1 (default 0.5); `light` how much
+ * light there is for the column to scatter, 1 = open daylight
+ * (default 1; 0.15..0.3 under a night sky, more under a lamp);
+ * `seed` moves that silt, so two pools are not one pool twice
+ * (default 1).
+ * @returns {THREE.Material} The same material, its uniforms live on
+ * `material.userData.uniforms` so `uSubLevel` can follow a tide.
+ */
+export function patchUnderwater(material, opts = {}) {
+ const level = opts.level === undefined ? 0 : opts.level;
+ const murk = opts.murk === undefined ? 0.5 : opts.murk;
+ // The one silent failure here: no emissive term means either a raw
+ // ShaderMaterial (no hook at all) or a Basic (no such variable).
+ if (material && material.emissive === undefined) {
+ console.warn(
+ 'patchUnderwater: ' + (material.name || material.type) + ' has '
+ + 'no emissive term — the column scatters LIGHT back into the '
+ + 'ray and that lands on totalEmissiveRadiance, which a '
+ + 'MeshBasicMaterial and a raw ShaderMaterial do not have. '
+ + 'Patch a lit material instead.');
+ }
+ return withBase(material, {
+ name: 'submerged:underwater',
+ uniforms: {
+ uSubLevel: { value: level },
+ uSubExt: { value: extinctionVec(opts.extinction) },
+ uSubColor: { value: toColor(opts.color, 0x1a5b63) },
+ uSubMurk: { value: unit(murk) },
+ // A negative here would subtract light and punch black holes in
+ // the water; there is no upper clamp because a lit pool is a
+ // real case.
+ uSubLight: {
+ value: Math.max(0, opts.light === undefined ? 1 : opts.light),
+ },
+ uSubSeed: { value: seedOffset(opts.seed) },
+ },
+ fragmentHead: UNDER_HEAD,
+ fragmentBody: UNDER_BODY,
+ });
+}
+
+const RING_VERTEX_HEAD = [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 iOff;',
+ 'attribute vec3 iExtra;',
+ 'uniform float uRingRate;',
+ 'uniform float uRingSize;',
+ 'uniform float uRingJit;',
+].join('\n');
+
+const RING_VERTEX = [
+ ' vUv = uv;',
+ ' float rgP = iExtra.x + uTime * uRingRate;',
+ ' float rgCyc = floor(rgP);',
+ ' vAge = fract(rgP);',
+ // Each cycle the drop lands somewhere new: a ring that re-forms on
+ // the same spot forever is a sprinkler, not rain.
+ ' vec2 rgJ = vec2(astraHash21(vec2(iExtra.z, rgCyc)),',
+ ' astraHash21(vec2(rgCyc, iExtra.z + 7.1))) - 0.5;',
+ // Every impact catches its own patch of sky: one crest colour over a
+ // whole field of rings is the tell of a sheet of decals.
+ ' vRgT = astraHash21(vec2(iExtra.z + 2.7, rgCyc)) - 0.5;',
+ ' vec3 rgC = iOff + vec3(rgJ.x, 0.0, rgJ.y) * uRingJit;',
+ // The quad lies FLAT and keeps its size; the wavefront travels
+ // inside it, so the ring is a place on a surface, not a sprite that
+ // scales up.
+ ' transformed = rgC + vec3(aCorner.x, 0.0, aCorner.y)',
+ ' * (uRingSize * iExtra.y);',
+].join('\n');
+
+const RING_FRAGMENT_HEAD = [
+ 'uniform vec3 uRingColor;',
+ 'uniform vec3 uRingTrough;',
+ 'uniform float uRingWidth;',
+ 'uniform float uRingOpacity;',
+].join('\n');
+
+const RING_FRAGMENT = [
+ ' float rgR = length(vUv * 2.0 - 1.0);',
+ ' if (rgR > 1.0) discard;',
+ // Where the wave IS, not how faded a sprite is: the front runs out
+ // and DECELERATES, so a still frame catches rings bunched near the
+ // rim and wide apart near the impact.
+ ' float rgFront = 0.90 * pow(vAge, 0.62);',
+ ' float rgAA = max(fwidth(rgR), 0.002);',
+ ' float rgW = max(uRingWidth * (1.0 + rgFront), rgAA * 1.6);',
+ ' float rgA = (rgR - rgFront) / rgW;',
+ ' float rgCrest = exp(-rgA * rgA);',
+ // The capillary train behind the front, and the trough between the
+ // two. A lone bright circle is a decal; a crest with a dark
+ // shoulder is a wave on a surface.
+ ' float rgB = (rgR - rgFront * 0.62) / (rgW * 1.7);',
+ ' float rgTrain = 0.40 * exp(-rgB * rgB);',
+ ' float rgD = (rgR - rgFront * 0.84) / (rgW * 1.5);',
+ ' float rgDip = 0.30 * exp(-rgD * rgD);',
+ // Amplitude falls as the same water spreads over a longer front,
+ // then the whole ring dies with age; born soft so it cannot pop.
+ ' float rgFade = (1.0 - vAge) * smoothstep(0.0, 0.07, vAge)',
+ ' / (1.0 + 2.2 * rgFront);',
+ ' rgFade *= 1.0 - smoothstep(0.86, 1.0, rgR);',
+ // A ring narrower than a couple of pixels can only alias into a
+ // hard little square, so it does not draw until it has spread.
+ ' rgFade *= smoothstep(rgAA * 1.2, rgAA * 3.5, rgFront);',
+ ' float rgUp = rgCrest + rgTrain;',
+ ' float a = (rgUp + rgDip) * rgFade * uRingOpacity;',
+ ' if (a < 0.004) discard;',
+ ' vec3 rgCol = mix(uRingTrough, uRingColor,',
+ ' rgUp / max(rgUp + rgDip, 1e-4));',
+ // Warm one drop, cool the next, about the crest colour the caller
+ // gave: a field of identical rings reads as printed, and the swing
+ // is per IMPACT rather than per pixel so a single ring stays one
+ // wave rather than turning speckled.
+ ' rgCol *= 1.0 + vRgT * vec3(0.34, 0.14, -0.24);',
+ ' gl_FragColor = vec4(rgCol, clamp(a, 0.0, 1.0));',
+].join('\n');
+
+/**
+ * The expanding rings rain makes on open water.
+ *
+ * `rain.js`'s `makeSplashes` is the hard-ground half of this — crowns
+ * of spray thrown up off a road. On water there is no crown to speak
+ * of: what you see is a ring of surface travelling out from the
+ * impact, and the three things that make it read as a surface rather
+ * than a sprite are all here. The quad is FLAT and a fixed size, so
+ * the wavefront moves across a patch of water instead of the whole
+ * card scaling up. The front DECELERATES and its amplitude falls as it
+ * spreads, so a frozen frame shows rings bunched and faint at the rim
+ * and wide and sharp near the drop. And each ring is a crest, a
+ * trailing capillary crest and a DARK trough between them, so it
+ * bends the water rather than painting a white circle on it.
+ *
+ * Impacts relocate every cycle, hashed on the cycle index, so the
+ * field is rain and not a fixed row of drippers. Add the mesh at the
+ * scene ROOT (it is world-space, like `rain.js`) and drive it from
+ * `tick`: `obj.userData.update(t)`, or one `tickShaders(scene, t)`.
+ *
+ * It lies `0.012` above `y` to clear a coplanar water plane, and it is
+ * kept out of the depth passes: a transparent card is a solid wall to
+ * the ambient-occlusion override material, and this is a field of them.
+ *
+ * @param {object} [opts]
+ * `area` (default `{x: 0, z: 0, w: 24, d: 24}`, or a number for a
+ * square) the water rect the rings land on;
+ * `rate` (default 1.6) impacts per second per site;
+ * `size` (default 0.55) metres across a fully spread ring;
+ * `y` (default 0) world Y of the water surface;
+ * `seed` (default 7) placement and phase seed;
+ * `count` (default 320) impact sites — one draw call regardless;
+ * `color` (default 0xdfeaf0) the crest, which catches the sky;
+ * `trough` (default 0x2a3a44) the dark shoulder between the crests;
+ * `width` (default 0.055) crest thickness as a fraction of `size`;
+ * `opacity` (default 0.42) peak alpha.
+ * @returns {THREE.Mesh} Mesh named 'RainRings' with
+ * `userData.update(t)` advancing the rings.
+ */
+export function makeRainRings(opts = {}) {
+ // A number is truthy, so `area: 12` would read w/d as undefined and
+ // put every ring at NaN — measured in rain.js, same trap.
+ const area = typeof opts.area === 'number'
+ ? { x: 0, z: 0, w: opts.area, d: opts.area }
+ : (opts.area || { x: 0, z: 0, w: 24, d: 24 });
+ const rate = opts.rate === undefined ? 1.6 : opts.rate;
+ const size = opts.size === undefined ? 0.55 : opts.size;
+ const y = opts.y === undefined ? 0 : opts.y;
+ const count = Math.max(1, opts.count === undefined ? 320 : opts.count);
+ const width = opts.width === undefined ? 0.055 : opts.width;
+ const opacity = opts.opacity === undefined ? 0.42 : opts.opacity;
+ const rand = rng(opts.seed === undefined ? 7 : opts.seed);
+
+ const off = new Float32Array(count * 3);
+ const ext = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ off[i * 3] = area.x + (rand() - 0.5) * area.w;
+ off[i * 3 + 1] = y + LIFT;
+ off[i * 3 + 2] = area.z + (rand() - 0.5) * area.d;
+ ext[i * 3] = rand(); // phase: a still shows all radii
+ ext[i * 3 + 1] = 0.7 + rand() * 0.6; // size of this drop's ring
+ ext[i * 3 + 2] = rand() * 97.0; // identity, for the relocation
+ }
+ // Culling reads the geometry's SPHERE and `position` is all zeros,
+ // so a real radius here is what stops three dropping the whole field
+ // the moment the origin leaves frame.
+ const reach = Math.hypot(Math.abs(area.x) + area.w * 0.5 + size,
+ Math.abs(area.z) + area.d * 0.5 + size);
+ const geo = instancedQuad(count, 1, 1,
+ Math.hypot(reach, Math.abs(y) + size));
+ geo.setAttribute('iOff', new THREE.InstancedBufferAttribute(off, 3));
+ geo.setAttribute('iExtra', new THREE.InstancedBufferAttribute(ext, 3));
+
+ const mat = makeShaderMaterial({
+ name: 'RainRings',
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ uniforms: {
+ uRingRate: { value: rate },
+ uRingSize: { value: Math.max(size, 1e-3) },
+ // Relocate inside this site's own share of the rect, so the
+ // drops cover the water instead of clumping.
+ uRingJit: {
+ value: Math.sqrt(Math.max(area.w * area.d, 0) / count),
+ },
+ uRingColor: { value: toColor(opts.color, 0xdfeaf0) },
+ uRingTrough: { value: toColor(opts.trough, 0x2a3a44) },
+ uRingWidth: { value: Math.max(width, 1e-3) },
+ uRingOpacity: { value: unit(opacity) },
+ },
+ varyings: 'varying vec2 vUv;\nvarying float vAge;\n'
+ + 'varying float vRgT;',
+ vertexHead: RING_VERTEX_HEAD,
+ vertexMain: RING_VERTEX,
+ fragmentHead: RING_FRAGMENT_HEAD,
+ fragmentMain: RING_FRAGMENT,
+ });
+
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.name = 'RainRings';
+ mesh.renderOrder = 2;
+ mesh.userData.update = (t) => { mat.uniforms.uTime.value = t; };
+ return keepOutOfDepthPasses(mesh);
+}
+
+const ICE_VARYING = 'varying vec2 vAstraIceUv;';
+
+const ICE_HEAD = [
+ 'uniform float uIceThick;',
+ 'uniform float uIceDens;',
+ 'uniform float uIceFrost;',
+ 'uniform float uIceRim;',
+ 'uniform vec3 uIceColor;',
+ 'uniform vec2 uIceSeed;',
+ // Arc length to the nearest of `n` rays from the cell's origin, and
+ // WHICH ray (mod n, so an arm survives atan's seam). Scaling the
+ // phase by n makes 2n keep every ray of n and add one between.
+ 'vec2 astraIceRay(vec2 d, float n, float j) {',
+ ' float x = (atan(d.y, d.x) * 0.15915494 + j) * n;',
+ ' float k = floor(x + 0.5);',
+ ' float g = abs(x - k) / n * 6.2831853 * max(length(d), 0.18);',
+ ' return vec2(g, mod(k, n));',
+ '}',
+ // A crack BRANCHES: the ray count doubles every step out and the two
+ // levels cross-fade, so an old crack runs on while a new one grows
+ // from it. Each arm runs its OWN length, or the fan is a snowflake.
+ 'float astraIceCracks(vec2 p, float w) {',
+ ' vec2 id = floor(p);',
+ ' vec2 o = vec2(astraHash21(id), astraHash21(id + 19.7)) - 0.5;',
+ ' vec2 d = fract(p) - 0.5 - o * 0.6 + 1e-4;',
+ ' float r = length(d);',
+ ' float lv = floor(r * 3.0);',
+ ' float j = astraHash21(id + 3.1);',
+ ' float n = 3.0 * exp2(lv);',
+ ' vec2 ra = astraIceRay(d, n, j);',
+ ' vec2 rb = astraIceRay(d, n * 2.0, j);',
+ ' float f = fract(r * 3.0);',
+ ' float g = mix(ra.x, rb.x, f);',
+ ' float reach = mix(astraHash21(id + ra.y * 0.37 + 5.0),',
+ ' astraHash21(id + rb.y * 0.37 + 5.0), f);',
+ ' reach = 0.30 + 0.55 * reach;',
+ ' return (1.0 - smoothstep(w * 0.35, w, g))',
+ ' * (1.0 - smoothstep(reach * 0.55, reach, r));',
+ '}',
+].join('\n');
+
+const ICE_BODY = [
+ // Refract at the surface and run the ray down by the thickness: the
+ // interior then SLIDES against the surface as the eye moves, which
+ // is the parallax that reads as looking through something.
+ ' vec3 iceV = normalize(vAstraWorld - cameraPosition);',
+ ' vec3 iceN = normalize(vAstraWorldN);',
+ ' iceN = faceforward(iceN, iceV, iceN);',
+ // Air into ice is eta < 1, so refract() can never return the zero
+ // vector here and there is no total-internal-reflection case.
+ ' vec3 iceRf = refract(iceV, iceN, 0.763);',
+ ' vec2 icePar = vAstraWorld.xz',
+ ' + iceRf.xz * (uIceThick / max(abs(iceRf.y), 0.25));',
+ // Thickness is a column like the water's: what is under the sheet
+ // dims and takes the ice's colour the further down it sits. Ice is
+ // CLEAR — a hand's width of it is nearly nothing — so the
+ // coefficient is 1.6 per metre. At the 3.0 this shipped with, a
+ // 10 cm sheet mixed a quarter of a pale mint over the dark water and
+ // landed at an albedo of 0.25 linear, which on a sunlit horizontal
+ // plane is 200/255 before a single crack is drawn: a milk plate.
+ ' float iceK = 1.0 - exp(-uIceThick * 1.6);',
+ ' vec3 iceC = mix(diffuseColor.rgb, uIceColor, iceK);',
+ ' float iceB = astraFbm2(icePar * 2.6 + uIceSeed, 3);',
+ ' iceC *= 0.78 + 0.52 * iceB;',
+ ' iceC = mix(iceC, uIceColor + 0.22,',
+ ' smoothstep(0.52, 0.86, iceB) * iceK * 0.7);',
+ // Frozen-in air is not one colour: the bubble clouds scatter warm
+ // where the light reaches them and the clear ice between runs blue.
+ ' iceC = astraHueBreak(iceC, icePar * 1.4, 1.0, 0.30);',
+ // FRESNEL. Everything above came from INSIDE the sheet, and only
+ // what the surface let in ever got there — at a grazing angle almost
+ // nothing does, which is why a frozen pond across a bay is a sheet
+ // of sky and its cracks appear as you walk out onto it. The renderer
+ // already adds that reflection as specular, so without this term the
+ // sheet is paid for the sky twice and lands on a white card
+ // (measured here: 200/255 flat at an 11 deg view, cracks invisible).
+ ' float iceFz = astraFresnel(iceN, -iceV, 5.0);',
+ ' iceC *= 1.0 - 0.78 * iceFz;',
+ // The cracks live on the SURFACE, so they take the unrefracted
+ // point and they are NOT behind that fresnel: crack over bubble is
+ // what fixes the two at their depths.
+ ' vec2 iceP = vAstraWorld.xz * uIceDens + uIceSeed;',
+ ' iceP += (astraNoise2(iceP * 0.9 + 5.7) - 0.5) * 0.35;',
+ // A crack is 2 cm of ice wherever it is, so its width is stated in
+ // METRES and converted by the density — a width in cell units would
+ // be 5 cm on a dense sheet and 20 cm on a sparse one.
+ ' float iceW = max(uIceDens * 0.022,',
+ ' max(fwidth(iceP.x), fwidth(iceP.y)) * 1.3);',
+ // The second layer is COARSER and turned: a few long masters over
+ // the finer network, where a finer second layer is only speckle.
+ ' vec2 iceQ = vec2(iceP.x * 0.6 - iceP.y * 0.8,',
+ ' iceP.x * 0.8 + iceP.y * 0.6) * 0.55 + 31.7;',
+ ' float iceCr = max(astraIceCracks(iceP, iceW),',
+ ' astraIceCracks(iceQ, iceW * 0.55));',
+ // A fissure is TWO things at once: the fracture planes scatter white
+ // and the gap between them is a slot of the dark water below. Drawn
+ // as one bright line it is a chalk mark on a plate, so the core of
+ // the same field — free, it is already computed — darkens back.
+ ' float iceCore = smoothstep(0.55, 0.98, iceCr);',
+ ' iceC = mix(iceC, vec3(0.87, 0.93, 0.96) * (0.84 + 0.30 * iceB),',
+ ' clamp(iceCr, 0.0, 1.0) * 0.80);',
+ ' iceC *= 1.0 - 0.55 * iceCore;',
+ // The rim is the sheet's own UV border — cut the sheet to the bank
+ // and that border IS the bank — torn by noise, because a bank does
+ // not rule a straight line.
+ ' float iceE = min(min(vAstraIceUv.x, 1.0 - vAstraIceUv.x),',
+ ' min(vAstraIceUv.y, 1.0 - vAstraIceUv.y));',
+ ' iceE += (astraFbm2(vAstraWorld.xz * 1.7 + uIceSeed, 3) - 0.44)',
+ ' * uIceRim * 0.9;',
+ ' float iceFr = astraContact(iceE, uIceRim) * uIceFrost;',
+ ' float iceFn = astraFbm2(vAstraWorld.xz * 9.0 + uIceSeed, 3);',
+ ' iceFr *= 0.45 + 0.75 * iceFn;',
+ // Frost is crystal, not paint. It sits ABOVE the surface, so it does
+ // not pay the fresnel either, and it is never one white: each patch
+ // takes its own light and its own warm/cool cast.
+ ' vec3 iceFc = astraHueBreak(',
+ ' vec3(0.90, 0.94, 0.97) * (0.84 + 0.28 * iceFn),',
+ ' vAstraWorld.xz, 0.8, 0.22);',
+ ' iceC = mix(iceC, iceFc, clamp(iceFr, 0.0, 1.0));',
+ // A sheet is a wide smooth ramp of thickness, bubble and frost, and
+ // a smooth ramp is where 8-bit output lays down contour bands.
+ ' iceC *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.03;',
+ ' diffuseColor.rgb = clamp(iceC, 0.0, 1.0);',
+].join('\n');
+
+/**
+ * A sheet of thin ice over water or stone: depth, cracks, frosted rim.
+ *
+ * Patch the SHEET, and give it the colour of what is UNDER it — the
+ * dark water or the stone — because that is what the shader takes as
+ * the thing seen through the ice. Three layers at three depths are
+ * what makes it a slab rather than a white plane. The interior is
+ * sampled at the point the eye ray reaches after REFRACTING at the
+ * surface and running down by `thickness`, so bubbles and murk slide
+ * against the surface as the camera moves and the sheet acquires a
+ * near and a far face. The cracks are sampled unrefracted, so they sit
+ * ON the surface above that interior. The frost sits on top of both.
+ *
+ * The interior is behind a FRESNEL and the two surface layers are not.
+ * Only what the air-ice interface let in ever reached the bubbles, so
+ * at a grazing angle the interior all but vanishes and what remains is
+ * the sky the renderer reflects off the sheet as specular: a frozen
+ * pond across a bay IS a sheet of sky, and its cracks appear as you
+ * walk out onto it. Without that term the sheet is paid for the sky
+ * twice and every grazing angle lands on a white card.
+ *
+ * The cracks radiate and BRANCH: rays leave a jittered origin per
+ * cell, and the ray count doubles every step outward with the phase
+ * scaled to match, which keeps every existing ray and grows a new one
+ * between them. That is a fork; one noise call is a smear, and it is
+ * the difference between ice and cracked paint. Two rotated layers are
+ * maxed together so the cell grid does not read as a grid.
+ *
+ * The frosted rim is found from the sheet's own UV border, wandered by
+ * noise: cut the sheet to fit the bank and that border IS the bank.
+ * A geometry with no uv has no border, and frosts everywhere — give
+ * the sheet a PlaneGeometry's uv or pass `frost: 0`.
+ *
+ * Gloss goes through `composeRoughness`, the only route to it: the one
+ * fragment hook runs before `<roughnessmap_fragment>`, so roughness is
+ * a material value, and frostier ice is duller.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place.
+ * @param {object} [opts] `thickness` metres of ice, driving the
+ * parallax and the tint (default 0.08); `crackDensity` crack cells
+ * per metre (default 0.7 — an origin every metre and a half);
+ * `frost` how heavy the rim, 0..1 (default 0.8); `rim` width of that
+ * band in UV, so 0.12 is a tenth of the sheet (default 0.12);
+ * `color` THREE.Color or hex of the ice itself (default a cold
+ * green-white); `seed` moves cracks and bubbles (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`.
+ */
+export function patchThinIce(material, opts = {}) {
+ const thick = opts.thickness === undefined ? 0.08 : opts.thickness;
+ const dens = opts.crackDensity === undefined ? 0.7
+ : opts.crackDensity;
+ const frost = opts.frost === undefined ? 0.8 : opts.frost;
+ const rim = opts.rim === undefined ? 0.12 : opts.rim;
+ // Ice is glossy and frost is not, so the sheet's roughness is the
+ // one thing here that cannot be a uniform.
+ composeRoughness(material, 'submerged:thinIce',
+ 0.18 + 0.62 * unit(frost));
+ return withBase(material, {
+ name: 'submerged:thinIce',
+ uniforms: {
+ uIceThick: { value: Math.max(thick, 1e-3) },
+ uIceDens: { value: Math.max(dens, 1e-3) },
+ uIceFrost: { value: unit(frost) },
+ uIceRim: { value: Math.max(rim, 1e-3) },
+ uIceColor: { value: toColor(opts.color, 0x9fc4c6) },
+ uIceSeed: { value: seedOffset(opts.seed) },
+ },
+ vertexHead: ICE_VARYING,
+ vertexBody: ' vAstraIceUv = uv;',
+ fragmentHead: [ICE_VARYING, ICE_HEAD].join('\n'),
+ fragmentBody: ICE_BODY,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/surface_wear.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/surface_wear.js
new file mode 100644
index 00000000..3524b0ea
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/surface_wear.js
@@ -0,0 +1,344 @@
+/**
+ * Surface wear: the two passes that land on EVERY material in a scene.
+ *
+ * The rest of this library shades one KIND of thing — a cliff, a leaf,
+ * a waterline. These two shade whatever they are handed, which is why
+ * they are the cheapest realism here: a scene reads as CG largely
+ * because every material paints one exact colour at one exact gloss
+ * over a whole object, and no photographed surface does either. Both go
+ * through `patchStandard`, so lighting, shadows, fog and the depth
+ * chunks survive; both shade from world position and world normal, so
+ * neither needs a UV; and both CHAIN with each other and with
+ * `terrain_shade` / `waterside` on one material.
+ *
+ * Gloss is the one thing neither can do per pixel: the only fragment
+ * hook runs after `<color_fragment>`, which is BEFORE
+ * `<roughnessmap_fragment>`, so both retune `material.roughness`
+ * instead and compose their factors through `composeRoughness`.
+ *
+ * PORT NOTES (2026-09-01, measured on our host — no post chain, ACES in
+ * the fragment tail, a bright baked environment as the specular source):
+ *
+ * 1. The breakup's hue jitter was `astraHueShift`, a rotation about the
+ * grey axis, and that rotation returns a NEUTRAL unchanged — exactly
+ * zero on a grey, 0.0014 peak channel move on our stone albedo
+ * 0x8d8577 at the default 0.03. Stone, plaster, concrete and dirt
+ * are most of what this patch ever lands on, so the one line meant
+ * to make it "a change of MATERIAL rather than a brightness dial"
+ * was a no-op on them. It is a warm/cool break now — the swing
+ * daylight actually makes, and the same transfer `astraHueBreak`
+ * uses — so `hue` is a fraction of the albedo, not radians.
+ * 2. Edge wear degenerated into a barber pole on anything thin. Past
+ * ~3x the onset curvature the ramp is saturated, so on a 6 cm rail
+ * post the ONLY structure left was one 14 cm blotch field on a 12 cm
+ * object: alternating solid bands of flat bone white. The break-up
+ * is two octaves now, both scaled to the width asked for, and the
+ * worn tone is thinned paint before it is bare substrate.
+ * 3. The worn tone was one flat colour over every material wearing it.
+ * It carries its own value and warm/cool variance now, and the
+ * default substrate came down from 0xe8e2d6 (0.816 linear — over
+ * the top of the sane albedo range before the value break, and it
+ * read as white primer under our sun) to 0xd2cabb, which leaves the
+ * break room to peak at 0.79.
+ * 4. Edge gloss was an area-weighted error: a whole material polished
+ * by 0.35 * strength for wear that covers a fraction of it. 0.12.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade and waterside name them, so a material wearing
+// a splat, a waterline and wear declares ONE pair (patchStandard
+// dedupes varyings); the locals are prefixed wr because those two
+// vertex bodies already own astraWp and wsP.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// Both patches read the same two fields, so they are built once. A
+// planar UV would smear either of them into vertical streaks on a wall,
+// and these patches land on walls.
+const WEAR_HEAD = [
+ 'vec3 astraWearAxes(vec3 n) {',
+ ' vec3 w = abs(n * n * n);',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+ 'float astraWearNoise(vec3 p, vec3 w) {',
+ ' return astraNoise2(p.yz + 13.7) * w.x',
+ ' + astraNoise2(p.zx + 41.3) * w.y',
+ ' + astraNoise2(p.xy + 71.9) * w.z;',
+ '}',
+].join('\n');
+
+const BASE = {
+ name: 'wear:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 wrP = vec4(transformed, 1.0);',
+ ' vec3 wrN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' wrP = instanceMatrix * wrP;',
+ ' wrN = mat3(instanceMatrix) * wrN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * wrP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(wrN, 0.0)).xyz);',
+ ].join('\n'),
+ fragmentHead: [WORLD_VARYINGS, WEAR_HEAD].join('\n'),
+};
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** 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 materials differ.
+ *
+ * An offset is a UNIFORM: the seed must not reach the GLSL, or the
+ * first material to compile the shared cache key would fix its own
+ * seed for every other material wearing the same patch.
+ */
+function seedOffset(seed) {
+ return new THREE.Vector3(
+ hash11(seed + 0.17), hash11(seed + 3.71), hash11(seed + 7.13))
+ .multiplyScalar(64);
+}
+
+/**
+ * Break up the flat, even surface that reads as moulded plastic.
+ *
+ * A built-in material paints one exact colour over a whole object and
+ * nothing photographed is one exact colour — that evenness is most of
+ * what "CG" means, and it costs one patch on every material to lose.
+ * This lays a faint world-space variation over the albedo: a slow
+ * blotch at `scale`, a mid field at half of it, a grain at a quarter,
+ * and a warm/cool break so it is a change of MATERIAL rather than a
+ * brightness dial. Every field is projected on the three world axes and
+ * blended by the world normal, so a wall gets grain instead of vertical
+ * streaks and two objects sharing a scale share a surface.
+ *
+ * Keep it under the threshold of "what is that": the test of a good
+ * breakup is that it cannot be named in a still, only missed when it is
+ * taken away. Past ~0.2 `strength` it stops being texture and reads as
+ * dirt, and the grain fades itself out once a pixel spans a cycle of it
+ * — beyond that it is no longer texture but static, which is the one
+ * way this reads as an effect rather than as a surface.
+ *
+ * Roughness varies per MATERIAL, not per pixel (see `composeRoughness`):
+ * `seed` detunes the material's own roughness by a few percent, which
+ * is what stops every surface in a scene from carrying one identical
+ * highlight.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material from `materials.js` patches every mesh
+ * wearing it, so clone it first if that is not what you want.
+ * @param {object} [opts] `scale` metres per cycle of the blotch
+ * (default 0.6); `strength` peak albedo swing either way, 0..1
+ * (default 0.10); `hue` the warm/cool break, as a fraction of the
+ * albedo either way (default 0.15 — NOT radians, see the port note;
+ * it is the peak, and the field reaches about 0.6 of it, which puts
+ * the typical swing on `astraHueBreak`'s own calibrated stone number);
+ * `seed` decorrelates two materials and picks the roughness detune
+ * (default 1).
+ * @returns {THREE.Material} The same material. Its uniforms stay live
+ * on `material.userData.uniforms` for a scene that wants to retune
+ * them.
+ */
+export function patchMicroBreakup(material, opts = {}) {
+ const scale = opts.scale === undefined ? 0.6 : opts.scale;
+ const strength = opts.strength === undefined ? 0.10 : opts.strength;
+ const hue = opts.hue === undefined ? 0.15 : opts.hue;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ composeRoughness(material, 'micro',
+ 1 + (hash11(seed + 1.9) - 0.5) * unit(strength) * 2);
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'wear:micro',
+ uniforms: {
+ uMicroScale: { value: Math.max(1e-3, scale) },
+ uMicroAmt: { value: unit(strength) },
+ uMicroHue: { value: hue },
+ uMicroSeed: { value: seedOffset(seed) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uMicroScale;',
+ 'uniform float uMicroAmt;',
+ 'uniform float uMicroHue;',
+ 'uniform vec3 uMicroSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 mbW = astraWearAxes(normalize(vAstraWorldN));',
+ ' vec3 mbP = vAstraWorld / uMicroScale + uMicroSeed;',
+ ' float mbLo = astraWearNoise(mbP, mbW);',
+ ' float mbMi = astraWearNoise(mbP * 2.03, mbW);',
+ ' float mbHi = astraWearNoise(mbP * 4.1, mbW);',
+ // Each field is dropped once a pixel spans most of a cycle of it:
+ // past that it is no longer texture, it is static, and static is
+ // the one way this reads as an effect. Two octaves need two
+ // fades, or the mid one aliases across a floor at grazing angle
+ // while the fine one is already gone.
+ ' float mbFw = length(fwidth(mbP));',
+ ' float mbGm = 1.0 - smoothstep(0.35, 1.00, mbFw * 2.03);',
+ ' float mbG = 1.0 - smoothstep(0.35, 1.00, mbFw * 4.1);',
+ // Value noise clusters around 0.5, so it is centred and stretched
+ // to reach the strength asked for; three octaves rather than two
+ // because a surface with one blotch size and one grain size is
+ // still a pattern, and the clamp keeps `strength` a hard bound
+ // however they stack.
+ ' float mbV = clamp((mbLo - 0.5) * 2.4',
+ ' + (mbMi - 0.5) * 1.5 * mbGm',
+ ' + (mbHi - 0.5) * 1.6 * mbG, -1.0, 1.0);',
+ // WARM/COOL, not a hue rotation: rotating about the grey axis
+ // leaves a neutral exactly unchanged, and stone, plaster and
+ // concrete are most of what this rides on. Warm where the sun has
+ // dried and bleached it, cool where only the sky reaches. It
+ // rides the DIFFERENCE of two fields, which is not the brightness
+ // field again.
+ ' float mbT = clamp((mbLo - mbHi) * 2.2, -1.0, 1.0) * uMicroHue;',
+ ' diffuseColor.rgb *= vec3(1.0 + mbT, 1.0 + mbT * 0.15,',
+ ' 1.0 - mbT);',
+ // The dark half of the field is dust and grime, and dust is
+ // greyer than what it settles on: saturation varies with it, so
+ // the patch is a change of material and not one brightness dial.
+ ' float mbL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, vec3(mbL),',
+ ' max(-mbV, 0.0) * uMicroAmt * 0.6);',
+ ' diffuseColor.rgb *= 1.0 + mbV * uMicroAmt;',
+ ].join('\n'),
+ });
+}
+
+/**
+ * Lighten the convex edges, where hands and weather take the finish off.
+ *
+ * Paint wears off what sticks out. An object whose edges match its
+ * faces exactly has never been touched, and giving the edges back their
+ * lighter, harder-worn tone is the second thing (after breaking the
+ * flat colour) that moves a surface from moulded to used.
+ *
+ * EDGE ROUTE — the world normal's screen-space DERIVATIVE divided by
+ * the world-space length of that same pixel step. The ratio is the
+ * surface's curvature in 1/m, which is the one edge estimate a fragment
+ * can compute: it holds still under distance and resolution (a raw
+ * `fwidth(normal)` would draw a fixed-pixel-width line that thickens as
+ * the camera pulls back), and it is SIGNED, so a concave corner — where
+ * dirt collects rather than wear — is left alone.
+ *
+ * It reads ZERO across a hard, unwelded edge (`BoxGeometry`'s corners,
+ * anything flat-shaded): derivatives never cross a primitive, so both
+ * faces see a constant normal right up to the seam. That is also why
+ * this can never flicker into a wireframe. Bevel or smooth-shade the
+ * edges you want worn; rounded geometry wears where it curves tightest.
+ *
+ * Gloss moves per MATERIAL, not per pixel (see `composeRoughness`): a
+ * worn edge is polished, and the small drop in the material's own
+ * roughness is the reachable half of that.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place — a shared material patches every mesh wearing it.
+ * The worn area is not one flat colour. Light wear is the paint itself
+ * rubbed thin — the surface's OWN tone, lightened and desaturated,
+ * which is what keeps the wear belonging to the object it is on — and
+ * only the hardest-hit part goes through to `color`, which is itself
+ * broken up in value and in warm/cool. A single flat tone painted over
+ * every material in a scene is the thing this patch exists to undo.
+ *
+ * @param {object} [opts] `strength` how far the edge goes toward
+ * `color`, 0..1 (default 0.35); `color` THREE.Color or hex, the bare
+ * substrate under the finish (default a warm bone); `width` the
+ * feature RADIUS in metres
+ * where wear BEGINS, reaching full at a third of it (default 0.35 —
+ * a 12 cm rim wears through, a 2 m barrel is untouched); `seed`
+ * moves the patchy break-up (default 1).
+ * @returns {THREE.Material} The same material, with its uniforms live
+ * on `material.userData.uniforms`.
+ */
+export function patchEdgeWear(material, opts = {}) {
+ const strength = opts.strength === undefined ? 0.35 : opts.strength;
+ const width = opts.width === undefined ? 0.35 : opts.width;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ // Area-weighted: the gloss move is the MATERIAL's, and wear covers a
+ // fraction of it. Spending the worn patch's full polish on the whole
+ // surface is how a painted rail becomes a sky mirror on a renderer
+ // with no post chain and a bright environment.
+ composeRoughness(material, 'edge', 1 - 0.12 * unit(strength));
+ patchStandard(material, BASE);
+ return patchStandard(material, {
+ name: 'wear:edge',
+ uniforms: {
+ uEdgeAmt: { value: unit(strength) },
+ uEdgeColor: { value: toColor(opts.color, 0xd2cabb) },
+ uEdgeWidth: { value: Math.max(1e-3, width) },
+ uEdgeSeed: { value: seedOffset(seed + 0.5) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [
+ 'uniform float uEdgeAmt;',
+ 'uniform vec3 uEdgeColor;',
+ 'uniform float uEdgeWidth;',
+ 'uniform vec3 uEdgeSeed;',
+ ].join('\n'),
+ fragmentBody: [
+ ' vec3 ewN = normalize(vAstraWorldN);',
+ ' vec3 ewPx = dFdx(vAstraWorld);',
+ ' vec3 ewPy = dFdy(vAstraWorld);',
+ ' vec3 ewNx = dFdx(ewN);',
+ ' vec3 ewNy = dFdy(ewN);',
+ // Curvature in 1/m: how far the normal turns per metre the
+ // surface travels under one pixel. Positive is convex, and only
+ // the convex half wears.
+ ' float ewD = dot(ewPx, ewPx) + dot(ewPy, ewPy);',
+ ' float ewC = (dot(ewNx, ewPx) + dot(ewNy, ewPy))',
+ ' / max(ewD, 1e-12);',
+ ' float ewR = 1.0 / uEdgeWidth;',
+ ' float ewK = smoothstep(ewR, ewR * 3.0, ewC);',
+ // Rubbing is patchy and FINE, at TWO scales. The ramp above is
+ // saturated everywhere on anything much tighter than `width` — a
+ // 6 cm rail post is 1.0 over every pixel — so a single blotch
+ // field is the only structure left there, and a 14 cm blotch on a
+ // 12 cm object is a barber pole, not wear. The second octave is
+ // the chipping inside each patch; both are tied to the width
+ // asked for, so the pattern scales with the feature and a
+ // re-render at another distance is the same surface.
+ ' vec3 ewAx = astraWearAxes(ewN);',
+ ' vec3 ewQ = vAstraWorld * (ewR * 3.4) + uEdgeSeed;',
+ ' float ewP = astraWearNoise(ewQ, ewAx);',
+ ' float ewF = astraWearNoise(ewQ * 3.3 + 11.3, ewAx);',
+ ' float ewG = 1.0 - smoothstep(0.35, 1.00,',
+ ' length(fwidth(ewQ)) * 3.3);',
+ ' ewK *= smoothstep(0.36, 0.72, ewP + (ewF - 0.5) * ewG);',
+ // Thinned finish first, bare substrate only where it is worn
+ // through: the light half keeps the object's OWN hue (lightened
+ // and desaturated), and the substrate carries its own value and
+ // warm/cool spread, so no two worn patches are the same colour.
+ ' float ewL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));',
+ ' vec3 ewThin = mix(diffuseColor.rgb, vec3(ewL), 0.45) * 1.16;',
+ ' float ewT = (ewF - 0.5) * 0.24;',
+ ' vec3 ewBare = uEdgeColor * (0.86 + 0.24 * ewP)',
+ ' * vec3(1.0 + ewT, 1.0 + ewT * 0.15, 1.0 - ewT);',
+ ' vec3 ewTone = mix(ewThin, ewBare, smoothstep(0.35, 0.90, ewK));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, ewTone,',
+ ' clamp(ewK * uEdgeAmt, 0.0, 1.0));',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain.js
new file mode 100644
index 00000000..213b46d5
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain.js
@@ -0,0 +1,257 @@
+/**
+ * The ground, textured and seatable, in one call (the model takes CODE
+ * and ignores prose, so the ground ships as a function). `ground()`
+ * returns the SAME height function it displaced the mesh with — place
+ * every asset at `h(x, z)`; floating assets are the most-flagged defect.
+ */
+
+import * as THREE from 'three';
+import * as MAT from './materials.js';
+
+/**
+ * Build a displaced, textured ground plane and its height function.
+ *
+ * @param {object} opts
+ * `size` metres across (default 400), `segments` grid resolution
+ * (default 128, the performance ceiling), `rand` a seeded PRNG
+ * (REQUIRED — no Math.random), `material` a THREE material (defaults
+ * to `MAT.soil()`), `relief` peak-to-trough metres (default 6),
+ * `scale` feature size in metres (default 90), `flat` a function
+ * (x, z) => 0..1 that damps relief to 0 where the scene needs level
+ * ground (a plaza, a quay, a street grid), `name` (default 'Ground').
+ * @returns {{mesh: THREE.Mesh, height: (x: number, z: number) => number}}
+ * The mesh to add, and the height function EVERY placement must use.
+ */
+export function ground(opts = {}) {
+ const size = opts.size || 400;
+ const segs = Math.min(opts.segments || 128, 128);
+ const rand = opts.rand || (() => 0.5);
+ const relief = opts.relief === undefined ? 6 : opts.relief;
+ const scale = opts.scale || 90;
+
+ // A small seeded lattice, bilinearly sampled: the same field drives the
+ // mesh and the height function, so they cannot drift apart.
+ const N = 32;
+ const lat = new Float32Array(N * N);
+ for (let i = 0; i < N * N; i++) lat[i] = rand();
+ const sample = (x, z) => {
+ const u = (x / scale) % N, v = (z / scale) % N;
+ const uu = u < 0 ? u + N : u, vv = v < 0 ? v + N : v;
+ const i0 = Math.floor(uu), j0 = Math.floor(vv);
+ const fx = uu - i0, fz = vv - j0;
+ const i1 = (i0 + 1) % N, j1 = (j0 + 1) % N;
+ const a = lat[j0 * N + i0], b = lat[j0 * N + i1];
+ const c = lat[j1 * N + i0], d = lat[j1 * N + i1];
+ return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
+ };
+
+ const height = (x, z) => {
+ let n = sample(x, z) * 0.65 + sample(x * 2.9, z * 2.9) * 0.35;
+ n = (n - 0.5) * 2 * relief;
+ return opts.flat ? n * (1 - Math.min(1, Math.max(0, opts.flat(x, z)))) : n;
+ };
+
+ const geo = new THREE.PlaneGeometry(size, size, segs, segs);
+ geo.rotateX(-Math.PI / 2);
+ const pos = geo.attributes.position;
+ for (let i = 0; i < pos.count; i++) {
+ pos.setY(i, height(pos.getX(i), pos.getZ(i)));
+ }
+ geo.computeVertexNormals();
+
+ // TEXTURED by default, and tiled to the ground's real size so the
+ // pattern reads at metres rather than smearing across 400 m.
+ //
+ // On a COPY, always. `MAT.soil()` (and every other factory) returns a
+ // CACHED material whose maps are shared with every other caller of that
+ // look, so retiling in place reached back through the cache: measured
+ // 2026-09-01, a wall built with `MAT.soil()` before a 480 m `ground()`
+ // came out at repeat 40x40, and two grounds of different sizes fought
+ // over one texture. A Texture clone shares its `.source`, so the copy
+ // is a few bytes of state, not a second upload.
+ let material = opts.material || MAT.soil();
+ if (material.userData && material.userData.shared) {
+ material = material.clone();
+ material.userData = {};
+ }
+ const retiled = new Map();
+ for (const key of ['map', 'roughnessMap', 'bumpMap', 'normalMap']) {
+ const tex = material[key];
+ if (!tex || !tex.repeat) continue;
+ // bumpMap is usually the SAME texture object as map: clone it once,
+ // or the two slots tile independently and the bump slides off the
+ // colour it is supposed to emboss.
+ let copy = retiled.get(tex);
+ if (!copy) {
+ copy = tex.clone();
+ copy.wrapS = copy.wrapT = THREE.RepeatWrapping;
+ copy.repeat.set(size / 12, size / 12);
+ copy.needsUpdate = true;
+ retiled.set(tex, copy);
+ }
+ material[key] = copy;
+ }
+
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.name = opts.name || 'Ground';
+ mesh.receiveShadow = true;
+ return { mesh, height };
+}
+
+/*
+ * A cliff face is ONE connected ribbon, never a pile of slabs (slab
+ * piles read as buildings). Strata are VERTEX-COLOUR bands sampled on
+ * the displaced surface so a band cannot detach; the same field backs
+ * `faceAt(s, y)` so props seat ON the measured rock.
+ */
+
+/**
+ * Build one connected, displaced cliff ribbon and its face function.
+ * Spans x in [-length/2, length/2], base on y = 0, FACES +Z; parent
+ * face-seated props to the mesh.
+ *
+ * @param {object} opts
+ * `length` metres along the wall (default 200), `height` metres
+ * (default 40), `rand` a seeded PRNG (REQUIRED — no Math.random),
+ * `strata` band count OR an array of hex band colours (default 6
+ * seeded variations of `color`), `color` base rock hex (default
+ * 0x8a7a66), `relief` ledge/gully depth in metres (default
+ * height * 0.15, clamped 2..8), `name` (default 'Cliff').
+ * @returns {{mesh: THREE.Mesh, faceAt: (s: number, y: number) =>
+ * THREE.Vector3}}
+ * ONE mesh (zero children — nothing to float), and `faceAt(s, y)` —
+ * `s` metres along the wall from its left end (0..length), `y`
+ * metres up from the base — returning the point ON the displaced
+ * face in the mesh's local space. Offset ~0.2 m along +Z to keep a
+ * seated prop clear of the rock.
+ */
+export function cliff(opts = {}) {
+ const length = opts.length || 200;
+ const height = opts.height || 40;
+ const rand = opts.rand || (() => 0.5);
+ const relief = opts.relief === undefined
+ ? Math.min(8, Math.max(2, height * 0.15)) : opts.relief;
+
+ // Strata band colours: authored hexes, or seeded variations of the
+ // base rock colour.
+ let bandColors;
+ if (Array.isArray(opts.strata) && opts.strata.length) {
+ bandColors = opts.strata.map((c) => new THREE.Color(c));
+ } else {
+ const n = (typeof opts.strata === 'number' && opts.strata > 0)
+ ? Math.round(opts.strata) : 6;
+ const base = new THREE.Color(
+ opts.color === undefined ? 0x8a7a66 : opts.color);
+ bandColors = [];
+ for (let i = 0; i < n; i++) {
+ const c = base.clone();
+ c.offsetHSL((rand() - 0.5) * 0.04, (rand() - 0.5) * 0.1,
+ (rand() - 0.5) * 0.2);
+ bandColors.push(c);
+ }
+ }
+ const bands = bandColors.length;
+ const bandH = height / bands;
+
+ // One seeded lattice drives the mesh, the band edges AND faceAt, so
+ // none of them can drift apart (the same trick ground() uses).
+ const N = 32;
+ const lat = new Float32Array(N * N);
+ for (let i = 0; i < N * N; i++) lat[i] = rand();
+ const sample = (u, v) => {
+ const uu = ((u % N) + N) % N, vv = ((v % N) + N) % N;
+ const i0 = Math.floor(uu), j0 = Math.floor(vv);
+ const fx = uu - i0, fz = vv - j0;
+ const i1 = (i0 + 1) % N, j1 = (j0 + 1) % N;
+ const a = lat[j0 * N + i0], b = lat[j0 * N + i1];
+ const c = lat[j1 * N + i0], d = lat[j1 * N + i1];
+ return (a * (1 - fx) + b * fx) * (1 - fz) + (c * (1 - fx) + d * fx) * fz;
+ };
+
+ // Per-band ledge offsets and a few meandering gullies, all seeded up
+ // front so faceAt closes over the exact numbers the mesh used.
+ const bandStep = [];
+ for (let i = 0; i < bands; i++) bandStep.push((rand() - 0.5) * 2);
+ const gullies = [];
+ const nGullies = Math.max(2, Math.round(length / 70));
+ for (let k = 0; k < nGullies; k++) {
+ gullies.push({
+ x: (rand() - 0.5) * length * 0.9,
+ w: 3 + rand() * 7,
+ d: 0.5 + rand() * 0.6,
+ drift: (rand() - 0.5) * 14,
+ phase: rand() * Math.PI * 2,
+ });
+ }
+
+ const bandOf = (x, y) => {
+ // Band edges undulate with the rock instead of ruler lines;
+ // sampled per-vertex on the same geometry, so they cannot detach.
+ const wob = (sample(x / 26 + 5.5, 7.7) - 0.5) * bandH * 0.7;
+ const i = Math.floor((y + wob) / bandH);
+ return Math.min(bands - 1, Math.max(0, i));
+ };
+
+ const depth = (x, y) => {
+ const n = sample(x / 16, y / 16) * 0.6 + sample(x / 4, y / 4) * 0.4;
+ let z = (n - 0.5) * relief; // rough rock
+ z += bandStep[bandOf(x, y)] * relief * 0.3; // stratum ledge
+ for (const g of gullies) { // carved gullies
+ const gx = g.x + Math.sin(g.phase + (y / height) * 4) * g.drift;
+ const t = (x - gx) / g.w;
+ z -= Math.exp(-t * t) * g.d * relief;
+ }
+ return z;
+ };
+
+ const segX = Math.min(240, Math.max(24, Math.round(length / 1.25)));
+ const segY = Math.min(64, Math.max(8, Math.round(height / 1.25)));
+ const geo = new THREE.PlaneGeometry(length, height, segX, segY);
+ geo.translate(0, height / 2, 0); // base rests on y = 0
+ const pos = geo.attributes.position;
+ const col = new Float32Array(pos.count * 3);
+ const tone = new THREE.Color();
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), y = pos.getY(i);
+ const z = depth(x, y);
+ pos.setZ(i, z);
+ tone.copy(bandColors[bandOf(x, y)]);
+ // Cheap AO: recessed rock reads darker, ledges catch the light.
+ tone.offsetHSL(0, 0, Math.max(-1, Math.min(1, z / relief)) * 0.09);
+ col[i * 3] = tone.r;
+ col[i * 3 + 1] = tone.g;
+ col[i * 3 + 2] = tone.b;
+ }
+ geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ geo.computeVertexNormals();
+
+ // Cloned so setting repeat cannot leak into the shared texture cache.
+ const map = MAT.noiseTexture({ scale: 20, seed: 9, contrast: 0.4 }).clone();
+ const rough = MAT.noiseTexture(
+ { scale: 34, seed: 50, contrast: 0.5, linear: true }).clone();
+ map.repeat.set(length / 20, height / 20);
+ rough.repeat.copy(map.repeat);
+ map.needsUpdate = true;
+ rough.needsUpdate = true;
+ const material = new THREE.MeshStandardMaterial({
+ vertexColors: true,
+ map,
+ roughnessMap: rough,
+ bumpMap: map,
+ bumpScale: 0.05,
+ roughness: 0.95,
+ });
+
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.name = opts.name || 'Cliff';
+ mesh.castShadow = true;
+ mesh.receiveShadow = true;
+
+ const faceAt = (s, y) => {
+ const x = Math.max(-length / 2, Math.min(length / 2, s - length / 2));
+ const yy = Math.max(0, Math.min(height, y));
+ return new THREE.Vector3(x, yy, depth(x, yy));
+ };
+
+ return { mesh, faceAt };
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain_shade.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain_shade.js
new file mode 100644
index 00000000..1a15c82a
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/terrain_shade.js
@@ -0,0 +1,364 @@
+/**
+ * Terrain surfaces that read as rock, not as stretched wallpaper.
+ *
+ * Both patches here shade from the SURFACE — world position and world
+ * normal — so neither needs a UV and the ground and the cliff from
+ * `terrain.js` can wear one look at any angle. Each is a `patchStandard`
+ * on a material you already built, so the built-in's lighting, shadows,
+ * fog and depth chunks stay exactly as they were.
+ */
+
+import * as THREE from 'three';
+import { patchStandard } from './shader.js';
+
+// The whole interface between the stages. `transformed` is still
+// object-space at <begin_vertex>, so the instance transform has to be
+// folded in here or every scattered rock projects from the origin.
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+const WORLD_BODY = [
+ ' vec4 astraWp = vec4(transformed, 1.0);',
+ ' vec3 astraWn = normal;',
+ '#ifdef USE_INSTANCING',
+ ' astraWp = instanceMatrix * astraWp;',
+ ' astraWn = mat3(instanceMatrix) * astraWn;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * astraWp).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(astraWn, 0.0)).xyz);',
+].join('\n');
+
+// astraFbm2 sums 0.5, 0.25, ... so its top end moves with the octave
+// count; rescaled to 0..1, one mix factor means the same at any count.
+const FBM_UNIT = [
+ '#ifndef ASTRA_FBM_UNIT',
+ '#define ASTRA_FBM_UNIT',
+ 'float astraFbmUnit(vec2 p, int oct) {',
+ ' float d = max(1.0 - pow(0.5, float(oct)), 0.25);',
+ ' return clamp(astraFbm2(p, oct) / d, 0.0, 1.0);',
+ '}',
+ '#endif',
+].join('\n');
+
+// MINERAL colour, and the reason both patches stopped looking like
+// putty.
+//
+// `astraHueBreak` at one scale is a TINT, not a grain: its field is a
+// 2-octave fbm, so at the ~3 m wavelength the two bodies below used to
+// ask for, anything boulder-sized lands whole inside a single lobe.
+// Measured on this library's showcase before this block: a 1 m boulder
+// came out R-B = -32 (cold slate) against the unpatched dirt beside it
+// at +21, saturation 0.06-0.09, and a hue spread of 0.02-0.03 across a
+// whole region — one flat cold value, which is the exact defect the
+// palette probe names.
+//
+// So: TWO scales — patch-sized over hand-sized — and a mean pulled
+// warm. Rock in daylight is never cooler than the ground beside it;
+// the cool half of the swing only happens where the sky alone reaches,
+// and the LIGHT does that for free. The ochre term rides the same
+// world field the mesh does, so the warm patches sit on the surface
+// rather than on a screen grid.
+const GRAIN = [
+ '#ifndef ASTRA_TERRAIN_GRAIN',
+ '#define ASTRA_TERRAIN_GRAIN',
+ 'vec3 astraTerrainGrain(vec3 c, vec3 wp, float swing) {',
+ // astraHueBreak's own swing is a HALF-amplitude of 0.375 * swing, so
+ // splitting one 0.34 call into two smaller ones lost amplitude
+ // instead of gaining structure: the first attempt moved rendered
+ // saturation by 0.00-0.03 and was invisible. Both scales run at or
+ // above the original swing; the two fields are decorrelated, so they
+ // stack to mineral movement rather than to one louder tint.
+ ' vec3 g = astraHueBreak(c, wp.xz + wp.y * 0.55, 0.40, swing * 0.80);',
+ ' g = astraHueBreak(g, wp.zx + wp.y * 0.9 + 27.3, 2.4, swing * 1.15);',
+ ' float w = clamp(astraFbmUnit(wp.xz * 0.85 + wp.y * 0.35 + 5.1, 3)',
+ ' * 1.25 - 0.12, 0.0, 1.0);',
+ ' return g * mix(vec3(0.92, 0.96, 1.04), vec3(1.21, 1.05, 0.84), w);',
+ '}',
+ '#endif',
+].join('\n');
+
+const TRI_HEAD = [
+ 'uniform vec3 uTriA;',
+ 'uniform vec3 uTriB;',
+ 'uniform float uTriScale;',
+ 'uniform float uTriSharp;',
+ 'uniform int uTriOct;',
+ 'vec3 astraTriWeights(vec3 n, float sharp) {',
+ ' vec3 w = pow(abs(n), vec3(sharp));',
+ ' return w / max(w.x + w.y + w.z, 1e-4);',
+ '}',
+].join('\n');
+
+const TRI_BODY = [
+ ' vec3 tpW = astraTriWeights(normalize(vAstraWorldN), uTriSharp);',
+ ' vec3 tpP = vAstraWorld / uTriScale;',
+ // One noise read on three planes mirrors itself across the diagonals
+ // and the seam shows as a crease; the offsets decorrelate them.
+ ' float tpN = astraFbmUnit(tpP.yz + 11.3, uTriOct) * tpW.x',
+ ' + astraFbmUnit(tpP.zx + 41.7, uTriOct) * tpW.y',
+ ' + astraFbmUnit(tpP.xy + 71.1, uTriOct) * tpW.z;',
+ // Kept in a local the SPLAT can read: patch bodies are
+ // concatenated into one main(), and a splat that simply
+ // assigned over this erased the whole triplanar.
+ ' vec3 tpC = mix(uTriA, uTriB, clamp(tpN, 0.0, 1.0));',
+ // MASS-scale value, and the up-face wash. A cliff is light and dark
+ // ROCK; rain bleaches the ledges pale and leaves the sheltered
+ // undersides dark. Without these two the whole wall is one tone
+ // dithered — measured at luminance sigma 0.023 across a 13 m face.
+ // Kept in `tpV` so a SPLAT landing on top can carry the same
+ // structure instead of flattening it back out.
+ ' float tpM = astraFbmUnit(tpP.xz * 0.21 + 3.3, 3);',
+ ' float tpU = normalize(vAstraWorldN).y * 0.5 + 0.5;',
+ ' float tpV = mix(0.80, 1.15, tpM) * mix(0.84, 1.10, tpU);',
+ ' tpC *= tpV;',
+ // Rock is never one colour at arm's length: a granite face runs pink,
+ // grey and near-black across a metre, and the palette probe named
+ // exactly this surface "one flat hue".
+ ' tpC = astraTerrainGrain(tpC, vAstraWorld, 0.42);',
+ ' diffuseColor.rgb = tpC;',
+].join('\n');
+
+const SPLAT_HEAD = [
+ 'uniform vec3 uSplatGrass;',
+ 'uniform vec3 uSplatScree;',
+ 'uniform vec3 uSplatRock;',
+ 'uniform vec3 uSplatSnow;',
+ 'uniform float uSplatLow;',
+ 'uniform float uSplatHigh;',
+ 'uniform float uSplatBlend;',
+ 'uniform float uSplatSnowY;',
+ 'uniform float uSplatSnowBand;',
+].join('\n');
+
+const SPLAT_CORE = [
+ ' vec3 spN = normalize(vAstraWorldN);',
+ // A threshold on normal.y alone draws a contour line no hillside has;
+ // ~12 m of noise wanders it onto the rock itself.
+ ' float spJit = (astraFbmUnit(vAstraWorld.xz * 0.08, 3) - 0.5) * 0.16;',
+ // 12 m of wander still draws a SMOOTH edge across anything
+ // boulder-sized: the grass cap on a 1 m rock came out a lime sticker
+ // with a clean rim (measured saturation 0.39 against 0.06 for the
+ // rock under it). A hand-scale term breaks that rim into speckle.
+ ' float spFine = (astraFbmUnit(vAstraWorld.xz * 1.6',
+ ' + vAstraWorld.y * 0.9 + 4.7, 4) - 0.5) * 0.11;',
+ ' float spUp = clamp(spN.y + spJit + spFine, 0.0, 1.0);',
+ ' float spB = max(uSplatBlend, 1e-3);',
+ ' float spG = smoothstep(uSplatLow - spB, uSplatLow + spB, spUp);',
+ ' float spR = 1.0 - smoothstep(uSplatHigh - spB, uSplatHigh + spB, spUp);',
+ ' vec3 spC = mix(mix(uSplatScree, uSplatRock, spR), uSplatGrass, spG);',
+ // The zone tones are three near-neutral greys and a green; three
+ // greys blended by a slope ramp is a flat card whatever the ramp.
+ // BEFORE the snow, so a partly covered slope still shows the rock's
+ // own mineral colour through the drifts.
+ ' spC = astraTerrainGrain(spC, vAstraWorld, 0.45);',
+ // MASS scale, ~4.5 m: a hillside is light and dark ground before it
+ // is any of these zones, and without it the only value variation was
+ // a 1.6 m dither that averages out at any distance (measured modal
+ // luminance 0.93 over a whole crag, down to 0.86 with this line).
+ ' float spMass = astraFbmUnit(vAstraWorld.xz * 0.22',
+ ' + vAstraWorld.y * 0.09 + 17.9, 3);',
+ ' spC *= mix(0.80, 1.18, spMass);',
+ // Snow lies only where the slope can hold it, so the same two knobs
+ // gate it and the steepest faces stay bare rock above the line.
+ ' float spHold = smoothstep(uSplatHigh, uSplatLow, spUp);',
+ ' float spSnow = smoothstep(uSplatSnowY - uSplatSnowBand,',
+ ' uSplatSnowY + uSplatSnowBand,',
+ ' vAstraWorld.y + spJit * uSplatSnowBand * 2.8);',
+ // Snow is not a white card. Wind packs it into drifts and SCOURS
+ // bare patches, so the same field has to move the COVERAGE, not just
+ // tint the white: a smooth ramp painted the whole cap one value
+ // (measured hue spread 0.003 and luminance sigma 0.018 over an entire
+ // peak, a dead frozen frame). Tinting the snow alone did not shift
+ // either number; letting rock show through does.
+ // The hue break is a TENTH of the rock's — snow that swings hue looks
+ // like ice cream — because the cold-shade / warm-sun split of real
+ // snow is the LIGHT's job, not the albedo's.
+ ' float spDrift = astraFbmUnit(vAstraWorld.xz * 1.15',
+ ' + vAstraWorld.y * 0.5 + 8.3, 4);',
+ ' vec3 spSnowC = astraHueBreak(uSplatSnow * mix(0.84, 1.06, spDrift),',
+ ' vAstraWorld.xz, 1.4, 0.09);',
+ ' float spCov = clamp(spSnow * spHold * mix(0.45, 1.45, spDrift),',
+ ' 0.0, 1.0);',
+ ' spC = mix(spC, spSnowC, spCov);',
+ ' float spVar = astraFbmUnit(vAstraWorld.xz * 0.6, 3);',
+].join('\n');
+
+// The last line, and its only variant. A `.replace` on the assembled
+// body was silent when it missed — and a missed replace here is
+// exactly the bug the composition comment below describes.
+const SPLAT_TAIL = ' diffuseColor.rgb = spC * mix(0.86, 1.14, spVar);';
+
+// Applied over a triplanar, the zone colour must carry that grain
+// rather than replace it: the two are a colour and a variation, not
+// two colours. `tpV` brings the triplanar's mass-scale value and
+// up-face wash through as well, at half strength — without it the
+// splat flattened the cliff structure the triplanar had just built.
+const SPLAT_TAIL_OVER_TRI =
+ ' diffuseColor.rgb = spC * mix(0.86, 1.14, spVar)'
+ + ' * mix(0.88, 1.12, clamp(tpN, 0.0, 1.0)) * mix(1.0, tpV, 0.5);';
+
+const SPLAT_BODY = [SPLAT_CORE, SPLAT_TAIL].join('\n');
+const SPLAT_BODY_OVER_TRI = [SPLAT_CORE, SPLAT_TAIL_OVER_TRI].join('\n');
+
+// Metres. Far above any authored terrain, yet small enough that the
+// +/-5 m snow band survives float32 (at 1e9 it would collapse to NaN).
+const SNOW_OFF = 1e6;
+
+/** 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);
+}
+
+/** Clamp to the 1..6 astraFbm2 actually loops over. */
+function toOctaves(value) {
+ return Math.max(1, Math.min(6, Math.round(value)));
+}
+
+/**
+ * The world position and normal both patches shade from, applied once.
+ *
+ * Named, so a material wearing both patches gets one copy: two copies
+ * declared the same locals and redefined the same helper, and the
+ * material was dead — verified on the GPU by a sibling library that
+ * landed on the same bank material.
+ */
+function withWorld(material) {
+ return patchStandard(material, {
+ name: 'terrain:world',
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: WORLD_VARYINGS,
+ vertexBody: WORLD_BODY,
+ util: true,
+ });
+}
+
+
+/**
+ * Project a procedural rock surface on the world axes — no UVs at all.
+ *
+ * A planar UV smears every steep face (the ground's own UV stretches to
+ * a vertical streak on a cliff), so this blends three world-axis noise
+ * projections by the world normal instead: a face at ANY angle gets the
+ * projection it faces most, and geometry that shares a scale shares a
+ * look with no UV to author. Replaces the base colour, so pass the two
+ * tones you want; the material's lighting and maps are untouched.
+ *
+ * @param {THREE.Material} material A built-in material, patched in place.
+ * @param {object} [opts] `scale` world metres per repeat (default 2);
+ * `sharpness` blend exponent, higher = harder plane transitions
+ * (default 4); `colorA`/`colorB` THREE.Color or hex, the low and high
+ * ends of the noise; `noiseOctaves` detail levels 1..6 (default 4);
+ * `name` the program cache key (default 'terrain:triplanar' — every
+ * patch KIND needs its own, or three's per-type program cache serves
+ * one compiled program to both and the second never runs).
+ * @returns {THREE.Material} The same material. Its uniforms stay live on
+ * `material.userData.uniforms` for a scene that wants to retune them.
+ */
+export function patchTriplanar(material, opts = {}) {
+ const scale = opts.scale === undefined ? 2 : opts.scale;
+ const sharpness = opts.sharpness === undefined ? 4 : opts.sharpness;
+ const oct = opts.noiseOctaves === undefined ? 4 : opts.noiseOctaves;
+ withWorld(material);
+ material.userData.astraTriplanar = true;
+ return patchStandard(material, {
+ name: opts.name || 'terrain:triplanar',
+ uniforms: {
+ // HUE-SEPARATED, not two values of one hue. The old pair sat at
+ // 33 and 37 degrees, so the three-plane noise produced a value
+ // ramp and nothing else — the grain had no colour to move
+ // between. A shaded grey-pink at 12 degrees under a buff ochre
+ // at 42 gives the mix 30 degrees to travel, which is what a
+ // weathered rock face actually does.
+ uTriA: { value: toColor(opts.colorA, 0x6d5952) },
+ uTriB: { value: toColor(opts.colorB, 0xab9670) },
+ uTriScale: { value: Math.max(1e-3, scale) },
+ uTriSharp: { value: Math.max(1, sharpness) },
+ uTriOct: { value: toOctaves(oct) },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [FBM_UNIT, GRAIN, TRI_HEAD].join('\n'),
+ fragmentBody: TRI_BODY,
+ });
+}
+
+/**
+ * Choose the surface by SLOPE first and height second.
+ *
+ * Colouring terrain by height alone paints a cliff the same as the
+ * meadow beside it at the same altitude; what the eye reads is that
+ * nothing grows on a steep face. So grass takes the flats, scree the
+ * mid slopes, bare rock the steepest, and snow lands above `snowLine`
+ * ONLY where the slope can hold it — the steep faces stay bare rock
+ * through the snow line, which is what makes a peak read as a peak.
+ * Every boundary is noise-wandered, since a clean contour reads as a
+ * decal.
+ *
+ * @param {THREE.Material} material A built-in material, patched in place.
+ * @param {object} [opts] `grass`/`scree`/`rock`/`snow` THREE.Color or
+ * hex; `snowLine` metres of world Y (default Infinity = no snow);
+ * `snowBand` half-width of the snow transition in metres (default 5 —
+ * right for a mountain, and far too wide for anything smaller: at the
+ * default a 9 m spire is snow-hazed from base to tip instead of
+ * capped, so a boulder field or a 10 m crag wants 1..2);
+ * `slopeLow`/`slopeHigh` the normal.y that ends the flats and begins
+ * the bare rock (default 0.75/0.45 — slopeLow is the GENTLER slope, so
+ * it is the LARGER normal.y, and the pair is ordered here because a
+ * GLSL smoothstep with its edges inverted is undefined); `blend`
+ * half-width of both slope transitions in normal.y (default 0.08);
+ * `name` the program cache key (default 'terrain:slopeSplat').
+ * @returns {THREE.Material} The same material. Its uniforms stay live on
+ * `material.userData.uniforms`, so `uSplatSnowY` can be animated.
+ */
+export function patchSlopeSplat(material, opts = {}) {
+ const low = opts.slopeLow === undefined ? 0.75 : opts.slopeLow;
+ const high = opts.slopeHigh === undefined ? 0.45 : opts.slopeHigh;
+ const blend = opts.blend === undefined ? 0.08 : opts.blend;
+ const line = opts.snowLine;
+ const band = opts.snowBand === undefined ? 5 : opts.snowBand;
+ withWorld(material);
+ // The two are a colour and a variation. Whichever lands second
+ // used to assign straight over the first, so on the terrain the
+ // prompts recommend — both — one of them was always invisible.
+ // A MARK, not a name: patchTriplanar invites a custom `name`, and
+ // detecting by name sent the splat straight back to assigning over
+ // it the moment anyone used that option.
+ const overTri = material.userData.astraTriplanar === true;
+ return patchStandard(material, {
+ name: opts.name || (overTri ? 'terrain:slopeSplat+tri'
+ : 'terrain:slopeSplat'),
+ uniforms: {
+ // The zones read as MATERIALS, not as one grey at four
+ // brightnesses: bare rock is the darkest AND the most saturated
+ // (fresh, wet, lichened), scree is pale and dusty and nearly
+ // neutral, grass is a dry olive rather than the lime the old
+ // 0x55703a made of a boulder cap (saturation 0.48 -> 0.38).
+ uSplatGrass: { value: toColor(opts.grass, 0x5f6b42) },
+ uSplatScree: { value: toColor(opts.scree, 0xa08e73) },
+ uSplatRock: { value: toColor(opts.rock, 0x6e5844) },
+ // Snow albedo, not snow LIGHT: 0xeef2f6 is 0.93-0.97 linear, over
+ // the 0.8 an unlit dielectric may hold, and it left the cap a
+ // dead flat card (hue spread 0.005 across a whole peak). The sun
+ // is what makes snow white; a neutral 0.79 keeps the highlight
+ // room ACES needs and lets the drift break show.
+ uSplatSnow: { value: toColor(opts.snow, 0xcbc9c4) },
+ uSplatLow: { value: Math.max(low, high) },
+ uSplatHigh: { value: Math.min(low, high) },
+ uSplatBlend: { value: Math.max(1e-3, blend) },
+ uSplatSnowY: { value: Number.isFinite(line) ? line : SNOW_OFF },
+ // A band that cannot RESOLVE against the off-sentinel makes a
+ // smoothstep with equal edges: 0/0, NaN, and a black terrain.
+ // float32 steps by 0.125 m at 1e6, so the OFF case floors the
+ // band at a metre; with a real snow line any positive band works.
+ uSplatSnowBand: {
+ value: Number.isFinite(line)
+ ? Math.max(1e-2, band) : Math.max(1, band),
+ },
+ },
+ vertexHead: WORLD_VARYINGS,
+ fragmentHead: [FBM_UNIT, GRAIN, SPLAT_HEAD].join('\n'),
+ fragmentBody: overTri ? SPLAT_BODY_OVER_TRI : SPLAT_BODY,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js
new file mode 100644
index 00000000..766971db
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/urban.js
@@ -0,0 +1,1114 @@
+/**
+ * The three things that say CITY rather than a row of boxes: a glazed
+ * facade, the cables strung over the street, and the hoarding on the
+ * gable end.
+ *
+ * Each replaces a specific cheat. A curtain wall drawn as one shiny
+ * material is one mirror sheet — real glazing is a grid of separately
+ * hung panels, each at its own angle and tint, and what it shows
+ * depends on where you stand: the sky at grazing angles, the room
+ * head-on. Power lines drawn as straight tubes are a truss; a hanging
+ * cable is a CATENARY and the eye knows the difference. And a
+ * 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.
+ */
+
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+
+import { patchNeonSpill } from './neon.js';
+import { fbm2, mulberry32, noiseDataTexture } from './noise.js';
+import {
+ composeRoughness, keepOutOfDepthPasses, makeShaderMaterial, patchStandard,
+ tickShaders,
+} from './shader.js';
+
+const _UP = new THREE.Vector3(0, 1, 0);
+
+/** 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/** A point in any accepted spelling as its own Vector3. */
+function toVec(p) {
+ if (p && p.isVector3) return p.clone();
+ if (Array.isArray(p)) return new THREE.Vector3(p[0], p[1], p[2] || 0);
+ return new THREE.Vector3(p.x || 0, p.y || 0, p.z || 0);
+}
+
+/**
+ * A seed becomes a far-apart lattice offset, not a one-cell shift.
+ *
+ * Seeds 7 and 8 offsetting a hash lattice by 1 would merely TRANSLATE
+ * the pattern by one panel, which reads as the same tower twice.
+ */
+function seedOffset(seed) {
+ const s = Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973;
+ return ((s * 16807) % 9973) * 0.0517;
+}
+
+/** Read a `[w, h]`, `{w, h}` or single number as a metric pair. */
+function toPair(value, dw, dh) {
+ if (value === undefined || value === null) return [dw, dh];
+ if (Array.isArray(value)) {
+ return [Math.max(1e-3, value[0] || dw),
+ Math.max(1e-3, value[1] === undefined ? dh : value[1])];
+ }
+ if (typeof value === 'number') return [Math.max(1e-3, value), value];
+ return [Math.max(1e-3, value.w === undefined ? dw : value.w),
+ Math.max(1e-3, value.h === undefined ? dh : value.h)];
+}
+
+
+// ---------------------------------------------------------------- glass
+
+const CW_VARYINGS = [
+ 'varying vec3 vCwW;',
+ 'varying vec3 vCwN;',
+].join('\n');
+
+// `transformed` is still object-space at <begin_vertex>, so an
+// instanced skyline needs instanceMatrix folded in by hand.
+const CW_VERTEX = [
+ ' vec4 cwP = vec4(transformed, 1.0);',
+ ' vec3 cwNo = normal;',
+ '#ifdef USE_INSTANCING',
+ ' cwP = instanceMatrix * cwP;',
+ ' cwNo = mat3(instanceMatrix) * cwNo;',
+ '#endif',
+ ' vCwW = (modelMatrix * cwP).xyz;',
+ ' vCwN = normalize((modelMatrix * vec4(cwNo, 0.0)).xyz);',
+].join('\n');
+
+const CW_HEAD = [
+ 'uniform vec2 uCwPanel;',
+ 'uniform vec3 uCwTint;',
+ 'uniform vec3 uCwMetal;',
+ 'uniform vec3 uCwSky;',
+ 'uniform vec3 uCwHaze;',
+ 'uniform vec3 uCwGround;',
+ 'uniform vec3 uCwBlindCol;',
+ 'uniform float uCwMullion;',
+ 'uniform float uCwReflect;',
+ 'uniform float uCwBow;',
+ 'uniform float uCwBlinds;',
+ 'uniform float uCwCurve;',
+ 'uniform float uCwSeed;',
+ 'uniform float uCwGain;',
+ 'uniform float uCwCoat;',
+ // Schlick, with the head-on term the COATING sets rather than glass's
+ // own 4% — untinted glass at 4% renders as a black hole, and the
+ // grazing limit is 1 for any coating, which is the whole effect.
+ 'float astraCwFresnel(float ndv, float f0) {',
+ ' float c = clamp(1.0 - clamp(ndv, 0.0, 1.0), 0.0, 1.0);',
+ ' float c2 = c * c;',
+ ' return f0 + (1.0 - f0) * c2 * c2 * c;',
+ '}',
+ // One key per panel, built from astraHash11 of a linear combination
+ // so the same numbers can be read on the CPU.
+ 'float astraCwKey(float ix, float iy) {',
+ ' return astraHash11(ix * 1.0731 + iy * 7.3313 + 0.317);',
+ '}',
+ 'float astraCwJit(float key, float k) {',
+ ' return astraHash11(key * 19.73 + k * 3.117 + 0.611);',
+ '}',
+].join('\n');
+
+const CW_BODY = [
+ ' vec3 cwN = normalize(vCwN);',
+ ' vec3 cwV = normalize(cameraPosition - vCwW);',
+ // dot(p.xz, t) is EXACT arc length along a flat face at any
+ // orientation and 0 round a tower, where the azimuth term carries it
+ // instead; a facade needs a METRIC grid, never a UV one.
+ ' vec2 cwTz = vec2(-cwN.z, cwN.x);',
+ ' float cwTl = length(cwTz);',
+ ' float cwFace = smoothstep(0.20, 0.55, cwTl);',
+ ' vec2 cwT = cwTl > 1e-4 ? cwTz / cwTl : vec2(1.0, 0.0);',
+ ' float cwU = dot(vCwW.xz, cwT) + uCwCurve * atan(cwN.z, cwN.x);',
+ ' vec2 cwG = vec2(cwU, vCwW.y) / uCwPanel;',
+ ' vec2 cwAa = fwidth(cwG);',
+ ' vec2 cwId = floor(cwG);',
+ ' float cwKey = astraCwKey(cwId.x + uCwSeed, cwId.y - uCwSeed);',
+ // Per-panel detail is texture until a pixel spans a panel and static
+ // after it, so every panel-scale term fades to its mean exactly there.
+ ' float cwSharp = 1.0 - smoothstep(0.30, 0.85, max(cwAa.x, cwAa.y));',
+ ' float cwMull = max(astraStroke(cwG.x, uCwMullion * 0.5 / uCwPanel.x),',
+ ' astraStroke(cwG.y, uCwMullion * 0.5 / uCwPanel.y));',
+ ' cwMull *= cwFace;',
+ // Every panel hangs at its own angle. Without this the whole wall
+ // shares one reflected ray and reads as a single mirror sheet.
+ ' vec3 cwTan = vec3(cwT.x, 0.0, cwT.y);',
+ ' vec3 cwBi = cross(cwN, cwTan);',
+ ' float cwB1 = (astraCwJit(cwKey, 1.0) - 0.5) * 2.0 * uCwBow * cwSharp;',
+ ' float cwB2 = (astraCwJit(cwKey, 2.0) - 0.5) * 2.0 * uCwBow * cwSharp;',
+ ' vec3 cwPn = normalize(cwN + cwTan * cwB1 + cwBi * cwB2);',
+ ' float cwF0 = uCwReflect * mix(0.82, 1.18,',
+ ' astraCwJit(cwKey, 3.0) * cwSharp + 0.5 * (1.0 - cwSharp));',
+ ' float cwFr = astraCwFresnel(dot(cwPn, cwV), clamp(cwF0, 0.0, 1.0));',
+ ' vec3 cwRay = reflect(-cwV, cwPn);',
+ ' vec3 cwRefl = mix(uCwGround, uCwHaze,',
+ ' smoothstep(-0.30, 0.01, cwRay.y));',
+ ' cwRefl = mix(cwRefl, uCwSky, smoothstep(0.0, 0.55, cwRay.y));',
+ // Glass FILTERS what is behind it — the room patchWindowInteriors put
+ // in diffuseColor — and never replaces it; the tint is a hue, so a
+ // dark green glass does not black the interior out.
+ ' float cwTm = max(max(uCwTint.r, uCwTint.g), max(uCwTint.b, 1e-3));',
+ ' vec3 cwFilt = mix(vec3(1.0), uCwTint / cwTm, 0.85);',
+ // A coating reflects a TINTED image. Left untinted, a tower under a
+ // hazy sky returns the haze and reads as one grey sheet whatever the
+ // glass is — which is why real glazing reads green, bronze or blue
+ // from across the street and this did not.
+ ' cwRefl *= mix(vec3(1.0), uCwTint / cwTm, uCwCoat);',
+ // Coating batch varies unit to unit: brightness AND a warm/cool tilt,
+ // both fading to their mean when a pixel spans a panel. This is what
+ // stops a hundred panels sharing one colour.
+ ' float cwJb = astraCwJit(cwKey, 7.0) - 0.5;',
+ ' float cwJh = (astraCwJit(cwKey, 8.0) - 0.5) * cwSharp;',
+ ' cwRefl *= (1.0 + 0.26 * cwJb * cwSharp)',
+ ' * vec3(1.0 + 0.17 * cwJh, 1.0, 1.0 - 0.17 * cwJh);',
+ ' vec3 cwGl = diffuseColor.rgb * cwFilt;',
+ // A few panels have the blind down: the one thing that DOES hide the
+ // room, and the cheapest proof the panels are not one surface. It is
+ // an interior surface, so it is filtered by the same glass.
+ ' float cwBl = step(astraCwJit(cwKey, 4.0), uCwBlinds * cwSharp);',
+ ' float cwDrop = 0.30 + 0.50 * astraCwJit(cwKey, 5.0);',
+ ' float cwEdge = max(cwAa.y, 0.01);',
+ ' cwBl *= smoothstep(1.0 - cwDrop - cwEdge, 1.0 - cwDrop + cwEdge,',
+ ' fract(cwG.y));',
+ ' cwGl = mix(cwGl, uCwBlindCol * cwFilt',
+ ' * (0.26 + 0.22 * astraCwJit(cwKey, 6.0)), cwBl);',
+ ' float cwGlass = cwFace * (1.0 - cwMull);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, cwGl, cwGlass);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, uCwMetal, cwMull);',
+ // What the mirror TAKES out of the transmitted image, and what it
+ // returns: reflected radiance, which no albedo term can carry — a
+ // facade in shadow still mirrors the sky.
+ ' float cwRw = cwFr * cwGlass;',
+ ' diffuseColor.rgb *= 1.0 - 0.85 * cwRw;',
+ ' totalEmissiveRadiance += cwRefl * (cwRw * uCwGain);',
+].join('\n');
+
+/**
+ * Glaze a facade: mullion grid, fresnel sky, and panels that differ.
+ *
+ * A curtain wall shaded as one smooth material is one MIRROR SHEET, and
+ * that is the tell however good the reflection is. Real glazing is a
+ * grid of separately hung units: each panel sits at a slightly
+ * different angle, carries a slightly different tint and coating batch,
+ * and every fifth one has the blind down. This lays that grid on in
+ * world METRES (never UV — a facade merged from boxes carries a full
+ * 0..1 UV per box), varies it per panel, and reflects the sky through a
+ * Schlick fresnel so the tower shows the sky at grazing angles and its
+ * own interior head-on.
+ *
+ * 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
+ * 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.
+ * Pair it with an `envMap` when you want that; three's IBL runs
+ * underneath this untouched.
+ *
+ * COMPOSE, do not duplicate: apply `patchWindowInteriors` FIRST and
+ * this second. It never assigns over `diffuseColor.rgb` — it FILTERS
+ * what is already there by the glass tint, dims it by what the mirror
+ * takes, and adds the reflection through `totalEmissiveRadiance`. So
+ * the rooms that patch shades stay visible head-on and are progressively
+ * replaced by sky toward grazing, which is what the eye reads as glass.
+ * It chains with `patchMicroBreakup` the same way.
+ *
+ * @param {THREE.Material} material A lit built-in material (MeshStandard
+ * / MeshPhysical — the reflection needs `totalEmissiveRadiance`),
+ * patched in place. Clone a shared `materials.js` instance first.
+ * @param {object} [opts] `mullion` width of the aluminium member in
+ * metres (default 0.07); `panel` glazing unit size in metres, `[w, h]`
+ * / `{w, h}` / one number (default 1.5 x 3.6 — a floor-height unit);
+ * `tint` glass colour, used as a HUE the glass filters by (default
+ * 0x33556b); `reflect` head-on reflectance 0..1, the coating (default
+ * 0.22; 0.04 is uncoated glass, 0.45 a mirror-glass tower — the
+ * grazing limit is 1 whatever this is); `sky` / `haze` / `ground` what
+ * the reflected ray finds looking up, along the horizon and down
+ * (defaults a daylight sky; pass a night sky and the same glass reads
+ * as night); `bow` radians each panel may be off true (default 0.020,
+ * about a degree — 0 gives back the mirror sheet); `blinds` fraction
+ * of panels with the blind down (default 0.16); `curve` radius in
+ * `coat` how much of the glass tint the REFLECTED image carries, 0
+ * an uncoated pane that returns the sky's own colour to 1 a fully
+ * tinted mirror (default 0.45 — at 0 a tower under a hazy sky reads
+ * as one grey sheet whatever `tint` says); `curve` radius in
+ * metres of a ROUND tower, so the mullion pitch follows the arc
+ * instead of the chord (default 0, flat; the azimuth seam falls at
+ * -X); `metal` mullion colour (default 0x8d949a); `blindCol` (default
+ * 0xcfc7b6); `gain` reflection brightness (default 1); `seed` moves
+ * which panels differ how (default 1); `name` the program cache key
+ * (default 'urban:curtain' — every option here is a UNIFORM, so one
+ * name is correct and two differently tuned towers share one compiled
+ * program).
+ * @returns {THREE.Material} The same material, its uniforms live on
+ * `material.userData.uniforms` so a scene can swing `uCwSky` from day
+ * to dusk without rebuilding anything.
+ */
+export function patchCurtainWall(material, opts = {}) {
+ const panel = toPair(opts.panel, 1.5, 3.6);
+ const mullion = opts.mullion === undefined ? 0.07 : opts.mullion;
+ const sky = toColor(opts.sky, 0x7ba6d8);
+ const haze = opts.haze === undefined
+ ? sky.clone().lerp(new THREE.Color(0xffffff), 0.62)
+ : toColor(opts.haze, 0xdfe7ee);
+ const reflect = opts.reflect === undefined ? 0.22 : unit(opts.reflect);
+ // Glass is the smoothest thing on a street; roughness is a MATERIAL
+ // property here (no patch can reach the per-pixel one).
+ const base = material.userData.astraRoughness
+ ? material.userData.astraRoughness.base : material.roughness;
+ composeRoughness(material, 'urban:curtain',
+ base > 0 ? Math.max(0.05, 0.10 / base) : 1);
+ return patchStandard(material, {
+ name: opts.name || 'urban:curtain',
+ uniforms: {
+ uCwPanel: { value: new THREE.Vector2(panel[0], panel[1]) },
+ uCwTint: { value: toColor(opts.tint, 0x33556b) },
+ uCwMetal: { value: toColor(opts.metal, 0x8d949a) },
+ uCwSky: { value: sky },
+ uCwHaze: { value: haze },
+ uCwGround: { value: toColor(opts.ground, 0x4b4740) },
+ uCwBlindCol: { value: toColor(opts.blindCol, 0xcfc7b6) },
+ // Clamped under half the panel: a mullion wider than that is a
+ // wall with slots in it, and astraStroke only vanishes cleanly
+ // for a THIN stroke.
+ uCwMullion: { value: Math.max(
+ 0, Math.min(mullion, Math.min(panel[0], panel[1]) * 0.25)) },
+ uCwReflect: { value: reflect },
+ uCwBow: { value: Math.max(0, opts.bow === undefined ? 0.020
+ : opts.bow) },
+ uCwBlinds: { value: unit(opts.blinds === undefined ? 0.16
+ : opts.blinds) },
+ uCwCurve: { value: Math.max(0, opts.curve || 0) },
+ uCwSeed: { value: seedOffset(opts.seed) },
+ uCwGain: { value: Math.max(0, opts.gain === undefined ? 1
+ : opts.gain) },
+ uCwCoat: { value: unit(opts.coat === undefined ? 0.45 : opts.coat) },
+ },
+ vertexHead: CW_VARYINGS,
+ vertexBody: CW_VERTEX,
+ fragmentHead: [CW_VARYINGS, CW_HEAD].join('\n'),
+ fragmentBody: CW_BODY,
+ });
+}
+
+
+// ---------------------------------------------------------------- cable
+
+/**
+ * The catenary parameter `a` for a span that sags `sag` at midspan.
+ *
+ * sag = a * (cosh(L / 2a) - 1) has no closed form, so it is bisected on
+ * u = L / 2a, where the left side rises monotonically from 0.
+ *
+ * @param {number} span Horizontal distance between the ends, metres.
+ * @param {number} sag Midspan dip below the chord, metres.
+ * @returns {number} `a` in metres; Infinity for a straight cable.
+ */
+function catenaryA(span, sag) {
+ if (!(sag > 1e-6) || !(span > 1e-6)) return Infinity;
+ let lo = 1e-6;
+ let hi = 1;
+ while (span / (2 * hi) * (Math.cosh(hi) - 1) < sag && hi < 1e4) hi *= 2;
+ for (let i = 0; i < 80; i++) {
+ const mid = 0.5 * (lo + hi);
+ if (span / (2 * mid) * (Math.cosh(mid) - 1) < sag) lo = mid;
+ else hi = mid;
+ }
+ return span / (2 * (0.5 * (lo + hi)));
+}
+
+/**
+ * Sample the true hanging curve between two points.
+ *
+ * A parabola is the giveaway: it is the small-sag limit of this, and it
+ * gets the CURVATURE wrong — constant along the span where a catenary's
+ * grows as cosh, so the cable leaves the insulator at the wrong angle.
+ *
+ * @param {THREE.Vector3} a One attachment point.
+ * @param {THREE.Vector3} b The other, at any height.
+ * @param {number} sag Midspan dip in metres.
+ * @param {number} n Segments.
+ * @returns {THREE.Vector3[]} n + 1 points from `a` to `b`.
+ */
+function catenaryPoints(a, b, sag, n) {
+ const span = Math.hypot(b.x - a.x, b.z - a.z);
+ const par = catenaryA(span, sag);
+ const out = [];
+ if (!Number.isFinite(par)) {
+ for (let i = 0; i <= n; i++) {
+ out.push(a.clone().lerp(b, i / n));
+ }
+ return out;
+ }
+ // Fit the SAME curve to unequal end heights by sliding its low point,
+ // which is what a cable on a slope does.
+ const k = Math.asinh((b.y - a.y)
+ / (2 * par * Math.sinh(span / (2 * par))));
+ const p = span / 2 - par * k;
+ const q = a.y - par * Math.cosh(p / par);
+ for (let i = 0; i <= n; i++) {
+ const s = (i / n) * span;
+ out.push(new THREE.Vector3(
+ a.x + (b.x - a.x) * (i / n),
+ par * Math.cosh((s - p) / par) + q,
+ a.z + (b.z - a.z) * (i / n)));
+ }
+ return out;
+}
+
+const CABLE_VARYINGS = [
+ 'varying float vCbSide;',
+ 'varying float vCbUp;',
+ 'varying float vCbFade;',
+].join('\n');
+
+const CABLE_VHEAD = [
+ 'attribute vec3 aCbTan;',
+ 'attribute vec3 aCbRide;',
+ 'uniform float uCbRadius;',
+ 'uniform float uCbMinPx;',
+ 'uniform float uCbViewH;',
+ 'uniform float uCbSway;',
+ // A conductor is ~1 cm across and a pixel at 80 m is 10, so a
+ // world-width cable breaks into dashes exactly where a skyline needs
+ // it. Widen it to a floor of `minPx` and pay for it in alpha.
+ 'float astraCbHalf(float depth, float perPx, float radius,',
+ ' float minPx) {',
+ ' return max(radius, minPx * perPx * depth);',
+ '}',
+].join('\n');
+
+const CABLE_VERTEX = [
+ ' vec3 cbW = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' mat3 cbM = mat3(modelMatrix);',
+ ' float cbSc = max(length(cbM[0]), 1e-6);',
+ ' vec3 cbT = normalize(cbM * aCbTan);',
+ // Wind: the span swings about its ends, so the envelope rides in on
+ // the attribute and the phase decorrelates neighbouring conductors.
+ ' vec3 cbLat = normalize(cross(cbT, vec3(0.0, 1.0, 0.0)) + 1e-6);',
+ ' float cbSw = sin(uTime * 0.63 + aCbRide.x) * uCbSway * aCbRide.y;',
+ ' vec3 cbOff = cbLat * cbSw',
+ ' + vec3(0.0, cos(uTime * 0.41 + aCbRide.x) * uCbSway * 0.35',
+ ' * aCbRide.y, 0.0);',
+ ' cbW += cbOff;',
+ ' vec3 cbV = normalize(cameraPosition - cbW);',
+ ' vec3 cbSd = cross(cbT, cbV);',
+ ' float cbSl = length(cbSd);',
+ ' cbSd = cbSl > 1e-5 ? cbSd / cbSl : vec3(1.0, 0.0, 0.0);',
+ ' float cbDepth = max(-(viewMatrix * vec4(cbW, 1.0)).z, 1e-3);',
+ // Metres per pixel comes from the camera's OWN projection, so a wide
+ // lens and a long lens both get the same on-screen thickness.
+ ' float cbPerPx = 2.0 / (max(projectionMatrix[1][1], 1e-4) * uCbViewH);',
+ ' float cbHalf = astraCbHalf(cbDepth, cbPerPx, uCbRadius, uCbMinPx);',
+ ' vCbFade = clamp(uCbRadius / cbHalf, 0.35, 1.0);',
+ ' vCbSide = aCbRide.z;',
+ ' vCbUp = aCbRide.z * cbSd.y;',
+ ' cbOff += cbSd * (aCbRide.z * cbHalf);',
+ // Back to object space: exact for the rigid-plus-uniform-scale
+ // placement a group gets, which is every placement in this engine.
+ ' transformed += (transpose(cbM) * cbOff) / (cbSc * cbSc);',
+].join('\n');
+
+const CABLE_FRAGMENT = [
+ // The edge feather is capped and then DIVIDED OUT of the alpha: at a
+ // 1.5 px ribbon the feather spans the whole width, and left
+ // uncompensated it threw away three quarters of the ink the cable is
+ // owed — a line that is present and invisible is still a dashed line.
+ ' float cbAa = clamp(fwidth(vCbSide) * 1.5, 0.02, 0.7);',
+ ' float cbA = (1.0 - smoothstep(1.0 - cbAa, 1.0, abs(vCbSide)))',
+ ' / (1.0 - 0.5 * cbAa);',
+ ' cbA = min(cbA * vCbFade, 1.0);',
+ ' if (cbA < 0.004) discard;',
+ // A round wire: the near side of the cylinder catches the sky and the
+ // far side is its own silhouette.
+ ' float cbRound = sqrt(max(1.0 - vCbSide * vCbSide, 0.0));',
+ ' vec3 cbCol = uCbColor * (0.62 + 0.38 * vCbUp)',
+ ' * (0.72 + 0.28 * cbRound);',
+ ' gl_FragColor = vec4(cbCol, cbA);',
+].join('\n');
+
+/**
+ * Build the ribbon: one strip per strand, position on the CENTRELINE.
+ *
+ * Both sides of the strip share the centreline and the vertex shader
+ * spreads them, so the GTAO override pass — which draws raw `position`
+ * — sees a zero-area strip instead of a wall, and the bounding box
+ * measures the cable rather than its widened silhouette.
+ */
+function cableGeometry(strands) {
+ const pos = [], tan = [], ride = [], idx = [];
+ let base = 0;
+ for (const s of strands) {
+ const n = s.pts.length;
+ for (let i = 0; i < n; i++) {
+ const p = s.pts[i];
+ const a = s.pts[Math.max(0, i - 1)];
+ const b = s.pts[Math.min(n - 1, i + 1)];
+ const t = new THREE.Vector3().subVectors(b, a);
+ if (t.lengthSq() < 1e-12) t.set(1, 0, 0);
+ t.normalize();
+ const env = Math.sin(Math.PI * (i / (n - 1)));
+ for (let k = 0; k < 2; k++) {
+ pos.push(p.x, p.y, p.z);
+ tan.push(t.x, t.y, t.z);
+ ride.push(s.phase, env, k === 0 ? -1 : 1);
+ }
+ if (i < n - 1) {
+ const a0 = base + i * 2;
+ idx.push(a0, a0 + 1, a0 + 2, a0 + 1, a0 + 3, a0 + 2);
+ }
+ }
+ base += n * 2;
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('aCbTan', new THREE.Float32BufferAttribute(tan, 3));
+ g.setAttribute('aCbRide', new THREE.Float32BufferAttribute(ride, 3));
+ g.setIndex(idx);
+ g.computeBoundingSphere();
+ return g;
+}
+
+/**
+ * Weathering in a vertex colour: damp at the foot, sun-silvered up.
+ *
+ * A run of poles merged into one mesh is ONE flat brown, and that is
+ * what says "the same prop, twenty times" from across the street. Real
+ * timber differs pole to pole (creosote batch, how long it has stood)
+ * and along its own length (the bottom metre stays wet, the top bleaches
+ * grey). This is the whole of that fix and it costs nothing: no extra
+ * draw call, no texture, and `mergeGeometries` needs the attribute on
+ * every piece anyway. It only ever DARKENS — the tone runs down from 1
+ * and the warm/cool tilt is normalised — so `color` stays the material's
+ * true albedo instead of quietly becoming a floor under a brighter one.
+ *
+ * @param {THREE.BufferGeometry} geo Already translated into place.
+ * @param {() => number} rand The run's seeded stream.
+ * @param {number} foot World y the piece rises from.
+ * @param {object} [opts] `spread` piece-to-piece tone range, `tilt`
+ * warm/cool range, `damp` metres the wet foot reaches.
+ * @returns {THREE.BufferGeometry} The same geometry.
+ */
+function paintPiece(geo, rand, foot, opts = {}) {
+ const pos = geo.attributes.position;
+ const col = new Float32Array(pos.count * 3);
+ const tone = 1 - rand()
+ * (opts.spread === undefined ? 0.24 : opts.spread);
+ const tilt = (rand() - 0.5) * (opts.tilt === undefined ? 0.10 : opts.tilt);
+ const damp = Math.max(0.05, opts.damp === undefined ? 1.6 : opts.damp);
+ // The tilt is a HUE, not a gain: normalised, so the warm channel
+ // reaches 1 and the cool one falls, and neither lifts the albedo.
+ const norm = 1 / (1 + Math.abs(tilt));
+ for (let i = 0; i < pos.count; i++) {
+ const h = unit((pos.getY(i) - foot) / damp);
+ const v = tone * (0.78 + 0.22 * h);
+ col[i * 3] = v * (1 + tilt) * norm;
+ col[i * 3 + 1] = v * norm * (1 + Math.abs(tilt) * 0.5);
+ col[i * 3 + 2] = v * (1 - tilt) * norm;
+ }
+ geo.setAttribute('color', new THREE.Float32BufferAttribute(col, 3));
+ return geo;
+}
+
+/** A box as geometry, yawed about Y and positioned by its centre. */
+function _box(w, h, d, x, y, z, yaw) {
+ const g = new THREE.BoxGeometry(w, h, d);
+ if (yaw) g.rotateY(yaw);
+ g.translate(x, y, z);
+ return g;
+}
+
+/** Resample a route into `spans` equal-length legs, ends included. */
+function resample(points, spans) {
+ const seg = [];
+ let total = 0;
+ for (let i = 1; i < points.length; i++) {
+ const d = points[i].distanceTo(points[i - 1]);
+ seg.push(d);
+ total += d;
+ }
+ if (!(total > 0)) return points.map((p) => p.clone());
+ const out = [];
+ for (let k = 0; k <= spans; k++) {
+ let want = (k / spans) * total;
+ let i = 0;
+ while (i < seg.length - 1 && want > seg[i]) { want -= seg[i]; i++; }
+ out.push(points[i].clone().lerp(
+ points[i + 1], Math.min(1, want / Math.max(seg[i], 1e-9))));
+ }
+ return out;
+}
+
+/**
+ * Cables between poles, hanging in a true CATENARY.
+ *
+ * Two things carry this and neither is the geometry of a tube. The
+ * curve is the catenary a hanging chain actually makes, not the
+ * parabola that is its small-sag limit — the parabola's curvature is
+ * constant along the span, so its cable leaves the insulator at the
+ * wrong angle and the eye reads a drawn arc. And the cable is drawn as
+ * a CAMERA-FACING ribbon whose half-width has a floor in PIXELS: a real
+ * conductor is about a centimetre across, a pixel at 80 m is ten, and a
+ * world-width tube therefore breaks into dashes exactly where a skyline
+ * needs it. The ribbon widens to that floor and gives back the extra
+ * width in alpha, so the line stays continuous and simply gets fainter.
+ *
+ * The poles come with it: tapered shafts, crossarms square to the run,
+ * and a ceramic insulator under every conductor.
+ *
+ * @param {object} [opts] `points` the route as pole bases, `[[x,y,z],
+ * ...]` or Vector3s — y is the GROUND there (default a 44 m run);
+ * `spans` resample the route into this many equal legs, so two points
+ * and `spans: 4` give five poles (default: a pole per point); `sag`
+ * midspan dip in metres (default 4% of the mean span — a slack line
+ * is 8%, a taut transmission line 2%); `thickness` cable DIAMETER in
+ * metres (default 0.04); `minPixels` the width the cable never falls
+ * below on screen (default 1.5 — this is what stops the aliasing, set
+ * 0 for the honest sub-pixel cable and its dashes); `viewportHeight`
+ * the frame height in px that width is measured against (default 576,
+ * the renderer's; `userData.setViewport(px)` retunes it);
+ * `poles` false for bare cables, or `{height, arms, wires, spread,
+ * radius, color}` (default 8.5 m, 2 arms, 3 wires an arm, 2.4 m
+ * spread — the poles are still what SPACES the cables when this is
+ * false; the pole `color` is the timber's albedo, which per-pole
+ * weathering DARKENS in a vertex colour so a run of them is never one
+ * flat brown); `color` conductor colour (default 0x15181c); `sway` metres of
+ * wind swing at midspan, driven by `tick` (default 0.05); `seed`
+ * detunes each conductor's sag and swing (default 1).
+ * @returns {THREE.Group} Named `PowerLines`, resting on the y of its
+ * points, with `userData.tick(t)` (the sway), `userData.setViewport(px)`
+ * and `userData.spans` — the measured span lengths. The cable mesh is
+ * guarded by `keepOutOfDepthPasses`: a transparent ribbon is a solid
+ * wall to the GTAO override pass.
+ */
+export function makePowerLines(opts = {}) {
+ const raw = (Array.isArray(opts.points) && opts.points.length >= 2
+ ? opts.points : [[-22, 0, 0], [22, 0, 0]]).map(toVec);
+ const poleAt = opts.spans > 0 ? resample(raw, Math.round(opts.spans))
+ : raw;
+ const spec = Object.assign(
+ { height: 8.5, arms: 2, spread: 2.4, radius: 0.15, color: 0x6d6255 },
+ (opts.poles && typeof opts.poles === 'object') ? opts.poles : {});
+ const rand = mulberry32(Math.round(opts.seed === undefined ? 1
+ : opts.seed));
+ const arms = Math.max(1, Math.round(spec.arms));
+ const perArm = Math.max(1, Math.round(
+ spec.wires === undefined ? 3 : spec.wires));
+ const radius = Math.max(1e-3,
+ (opts.thickness === undefined ? 0.04 : opts.thickness) * 0.5);
+
+ const g = new THREE.Group();
+ g.name = 'PowerLines';
+
+ // Crossarm direction at each pole: square to the run, bisected at a
+ // corner so a turning line does not tear its own arms apart.
+ const side = [];
+ for (let i = 0; i < poleAt.length; i++) {
+ const a = poleAt[Math.max(0, i - 1)];
+ const b = poleAt[Math.min(poleAt.length - 1, i + 1)];
+ const d = new THREE.Vector3().subVectors(b, a);
+ d.y = 0;
+ if (d.lengthSq() < 1e-9) d.set(1, 0, 0);
+ d.normalize();
+ side.push(new THREE.Vector3().crossVectors(_UP, d).normalize());
+ }
+
+ // Where every conductor lands, pole by pole.
+ const hooks = poleAt.map((p, i) => {
+ const out = [];
+ for (let a = 0; a < arms; a++) {
+ const y = p.y + spec.height - 0.55 - a * 1.15;
+ for (let k = 0; k < perArm; k++) {
+ const off = perArm < 2 ? 0
+ : (k / (perArm - 1) - 0.5) * spec.spread;
+ out.push(new THREE.Vector3(
+ p.x + side[i].x * off, y + 0.18, p.z + side[i].z * off));
+ }
+ }
+ return out;
+ });
+
+ const spans = [];
+ for (let i = 1; i < poleAt.length; i++) {
+ spans.push(Math.hypot(poleAt[i].x - poleAt[i - 1].x,
+ poleAt[i].z - poleAt[i - 1].z));
+ }
+ const mean = spans.reduce((a, b) => a + b, 0) / Math.max(1, spans.length);
+ const sag0 = opts.sag === undefined ? mean * 0.04 : opts.sag;
+
+ const strands = [];
+ for (let c = 0; c < hooks[0].length; c++) {
+ // A lower arm hangs slacker than the one above it, and no two
+ // conductors on a line are tensioned identically.
+ const slack = (1 + 0.10 * Math.floor(c / perArm))
+ * (0.92 + 0.16 * rand());
+ for (let i = 1; i < hooks.length; i++) {
+ strands.push({
+ pts: catenaryPoints(hooks[i - 1][c], hooks[i][c], sag0 * slack,
+ Math.max(8, Math.round(spans[i - 1] * 1.2))),
+ phase: rand() * Math.PI * 2,
+ });
+ }
+ }
+
+ const viewH = Math.max(64, opts.viewportHeight === undefined
+ ? 576 : opts.viewportHeight);
+ const cableMat = makeShaderMaterial({
+ name: 'PowerCable',
+ uniforms: {
+ uCbColor: { value: toColor(opts.color, 0x15181c) },
+ uCbRadius: { value: radius },
+ uCbMinPx: { value: Math.max(0, opts.minPixels === undefined
+ ? 1.5 : opts.minPixels) * 0.5 },
+ uCbViewH: { value: viewH },
+ uCbSway: { value: Math.max(0, opts.sway === undefined ? 0.05
+ : opts.sway) },
+ },
+ varyings: CABLE_VARYINGS,
+ vertexHead: CABLE_VHEAD,
+ vertexMain: CABLE_VERTEX,
+ fragmentHead: 'uniform vec3 uCbColor;',
+ fragmentMain: CABLE_FRAGMENT,
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+ const cables = new THREE.Mesh(cableGeometry(strands), cableMat);
+ cables.name = 'Cables';
+ cables.renderOrder = 2;
+ g.add(keepOutOfDepthPasses(cables));
+
+ if (opts.poles !== false) {
+ const wood = [];
+ const ceramic = [];
+ for (let i = 0; i < poleAt.length; i++) {
+ const p = poleAt[i];
+ const yaw = Math.atan2(side[i].x, side[i].z);
+ const shaft = new THREE.CylinderGeometry(
+ spec.radius * 0.72, spec.radius, spec.height, 8);
+ shaft.translate(p.x, p.y + spec.height / 2, p.z);
+ wood.push(paintPiece(shaft, rand, p.y));
+ for (let a = 0; a < arms; a++) {
+ const y = p.y + spec.height - 0.55 - a * 1.15;
+ wood.push(paintPiece(_box(0.11, 0.16, spec.spread + 0.5,
+ p.x, y, p.z, yaw), rand, y - 0.4));
+ // The knee braces: without them the arm is a stick balanced on
+ // a pole, which is the one thing a crossarm never is.
+ for (const s of [-1, 1]) {
+ const kn = new THREE.BoxGeometry(0.07, 0.93, 0.07);
+ kn.rotateX(s * 0.632);
+ kn.translate(0, y - 0.38, s * 0.28);
+ kn.rotateY(yaw);
+ kn.translate(p.x, 0, p.z);
+ wood.push(paintPiece(kn, rand, y - 0.9));
+ }
+ }
+ for (const h of hooks[i]) {
+ const ins = new THREE.CylinderGeometry(0.075, 0.055, 0.20, 6);
+ ins.translate(h.x, h.y - 0.10, h.z);
+ // Porcelain weathers too, just far less; the ramp reads as the
+ // grime that collects on the skirt of every insulator.
+ ceramic.push(paintPiece(ins, rand, h.y - 0.22,
+ { spread: 0.12, tilt: 0.05, damp: 0.22 }));
+ }
+ }
+ const poleMesh = new THREE.Mesh(
+ mergeGeometries(wood, false),
+ new THREE.MeshStandardMaterial({
+ color: spec.color, roughness: 0.92, metalness: 0.02,
+ vertexColors: true,
+ }));
+ poleMesh.name = 'Poles';
+ poleMesh.castShadow = true;
+ poleMesh.receiveShadow = true;
+ g.add(poleMesh);
+ const insMesh = new THREE.Mesh(
+ mergeGeometries(ceramic, false),
+ new THREE.MeshStandardMaterial({
+ color: 0x6f7a6a, roughness: 0.35, metalness: 0.0,
+ vertexColors: true,
+ }));
+ insMesh.name = 'Insulators';
+ insMesh.castShadow = true;
+ g.add(insMesh);
+ }
+
+ g.userData.spans = spans;
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.setViewport = (px) => {
+ cableMat.uniforms.uCbViewH.value = Math.max(64, px);
+ return g;
+ };
+ return g;
+}
+
+
+// ------------------------------------------------------------ billboard
+
+const GLOW_FRAGMENT = [
+ ' vec2 bbD = abs(vBbUv - 0.5) * 2.0;',
+ ' float bbA = (1.0 - smoothstep(0.18, 1.0, bbD.x))',
+ ' * (1.0 - smoothstep(0.18, 1.0, bbD.y));',
+ // A halo is glow in the AIR round the sign, and the board is opaque:
+ // the card must not veil the artwork it sits in front of. Left solid
+ // through the middle it clipped the top band of the poster to 1.0 in
+ // daylight AND at night — an additive sheet over the face flattens
+ // the print and buys nothing without a bloom pass. So it is hollowed
+ // out over the board's own outline (`uBbInner`, the face as a
+ // fraction of this card) down to `uBbCore`, which only a light box —
+ // whose face really does emit — keeps above zero.
+ ' float bbOut = max(bbD.x / uBbInner.x, bbD.y / uBbInner.y);',
+ ' bbA *= mix(uBbCore, 1.0, smoothstep(0.60, 1.04, bbOut));',
+ // Lit from within it is even; lit by lamps on the top rail it is
+ // brightest under them and gone at the hoarding's feet.
+ ' bbA *= mix(1.0, smoothstep(-0.35, 0.95, vBbUv.y), uBbBias);',
+ // Rolled off, not clamped: a saturating halo draws a flat slab with a
+ // hard rim, which is the card again.
+ ' bbA = 1.0 - exp(-bbA * bbA * uBbGain * 3.4);',
+ ' if (bbA < 0.004) discard;',
+ // The gradient is metres wide and 8 bits deep, which is exactly where
+ // banding rings; a sub-LSB dither costs one hash and removes it.
+ ' bbA *= 1.0 + (astraHash21(gl_FragCoord.xy) - 0.5) * 0.06;',
+ ' gl_FragColor = vec4(uBbColor, bbA);',
+].join('\n');
+
+/**
+ * The pasted-up sheet: bold blocks, a headline band, paper grain.
+ *
+ * Three things this refuses, each one measured on a rendered board.
+ * The grain was `sin(u * 91.7 + v * 47.3) * 43758.5 % 1`, which is not
+ * a hash at those frequencies — it is a low-order beat, and it printed
+ * as DIAGONAL STRIPES across the whole poster. It is fBm now. The ink
+ * peaked at L 0.92, i.e. an albedo of ~0.9: a sheet of paper is not a
+ * light source, and under the gooseneck lamps that white clipped
+ * before the grade could touch it, so every colour is held inside the
+ * 0.02..0.80 band. And one flat ink over the sheet is the flat-decal
+ * tell, so the paper carries ink-density mottle, a bill-poster's PASTE
+ * SEAMS (a sheet this size is hung in strips) and sun bleach up the
+ * face — hue variance the eye reads as printing rather than as fill.
+ *
+ * The band is stated in sRGB because that is what a colour texture
+ * holds: 0.155..0.80 here is 0.02..0.60 linear, i.e. the albedo band
+ * with the top left clear for the lamps to work in.
+ */
+function posterTexture(color, seed, lit) {
+ const key = Math.round(seed);
+ const rand = mulberry32(key * 977 + 13);
+ const base = toColor(color, 0xc8352f);
+ const hsl = { h: 0, s: 0, l: 0 };
+ base.getHSL(hsl);
+ // Paper white is a WARM off-white, never 1.0 — the ceiling is the top
+ // of the albedo band, and `lit` only decides where inside it we sit.
+ const CEIL = lit ? 0.80 : 0.74;
+ const FLOOR = 0.155;
+ const paper = new THREE.Color().setHSL(
+ (hsl.h + 0.47) % 1, Math.min(0.16, hsl.s * 0.22 + 0.04), CEIL * 0.94);
+ const accent = new THREE.Color().setHSL(
+ (hsl.h + 0.47) % 1, Math.min(1, hsl.s * 0.8 + 0.15), CEIL * 0.68);
+ const dark = new THREE.Color().setHSL(
+ (hsl.h + 0.02) % 1, hsl.s * 0.9, Math.max(0.09, hsl.l * 0.34));
+ // Round-robin, not a roll per bar: a poster printed in three inks uses
+ // all three. Rolling independently gave sheets that came out as four
+ // near-black bars on red — one hue, which is the flat-decal look this
+ // is here to avoid.
+ const inks = [paper, dark, accent, dark];
+ const bars = [];
+ for (let i = 0; i < 4; i++) {
+ bars.push({ y: 0.10 + rand() * 0.72, h: 0.05 + rand() * 0.13,
+ x: 0.04 + rand() * 0.30, w: 0.30 + rand() * 0.60,
+ c: inks[(i + Math.round(seed)) % inks.length] });
+ }
+ // Where the billposter's strips butt up, and how each strip was inked.
+ const strips = 2 + Math.round(rand());
+ const stripTone = [];
+ for (let i = 0; i <= strips; i++) stripTone.push(0.955 + rand() * 0.09);
+ const ox = seedOffset(key) * 0.37;
+ const tex = noiseDataTexture(128, (u, v) => {
+ const c = base.clone();
+ for (const b of bars) {
+ if (v > b.y && v < b.y + b.h && u > b.x && u < Math.min(1, b.x + b.w)) {
+ c.copy(b.c);
+ }
+ }
+ const s = Math.min(strips - 1, Math.floor(u * strips));
+ const su = u * strips - s;
+ // The seam itself: a hairline of shadow where one sheet laps the next.
+ const seam = 1 - 0.14 * (1 - Math.min(1, Math.min(su, 1 - su) * 26));
+ // Ink density (broad) and paper grain (fine), both real fBm so the
+ // sheet cannot beat against its own sampling.
+ const mottle = fbm2(u * 3.3 + ox, v * 3.3, { seed: key + 5 });
+ const grain = fbm2(u * 96, v * 96, { octaves: 2, seed: key + 31 });
+ const n = stripTone[s] * seam * (1 + 0.16 * mottle + 0.10 * grain);
+ // Sun bleach: the top of a hoarding fades first, and it fades WARM.
+ const bleach = 0.13 * v * v;
+ const tilt = 0.05 * mottle;
+ const out = [
+ unit(c.r * n * (1 + tilt) + bleach * CEIL * 0.30),
+ unit(c.g * n + bleach * CEIL * 0.27),
+ unit(c.b * n * (1 - tilt) + bleach * CEIL * 0.22),
+ ];
+ // The floor is held on LUMINANCE, not per channel: clamping each
+ // channel to it turns a dark red ink into a pink-grey, and the point
+ // of the floor is that nothing on the sheet is a hole.
+ const lum = 0.2126 * out[0] + 0.7152 * out[1] + 0.0722 * out[2];
+ const k = lum < FLOOR ? FLOOR / Math.max(lum, 1e-4) : 1;
+ return out.map((x) => Math.min(CEIL, x * k));
+ });
+ tex.colorSpace = THREE.SRGBColorSpace;
+ return tex;
+}
+
+/**
+ * A hoarding or a lit sign panel, on the structure that holds it up.
+ *
+ * A billboard without its frame is a decal floating in the air, so the
+ * legs, the back bracing and the rim come with the face. `kind` picks
+ * which of the two real things this is, and they light differently
+ * because they ARE lit differently: a `'hoarding'` is a pasted sheet
+ * lit from OUTSIDE by gooseneck lamps on the top rail, so the poster is
+ * brightest under each lamp and falls off toward its feet; a `'panel'`
+ * is a light box lit from WITHIN, so the face is even and the structure
+ * around it catches the spill.
+ *
+ * The light itself is `lib/neon.js`: `patchNeonSpill` already owns
+ * windowed falloff, the wrapped terminator a broad source needs, and
+ * the reflection through the receiving surface's own albedo, so this
+ * hands its sources to that patch instead of growing a second copy. It
+ * patches its OWN structure that way at build time and hands the same
+ * sources out through `userData.spillSources(n)` — give them to a
+ * `patchNeonSpill` on the wall behind or the pavement below, which is
+ * the difference between a lit sign and a lit street.
+ *
+ * @param {object} [opts] `width` / `height` of the face in metres
+ * (default 6 x 3); `kind` `'hoarding'` (default) or `'panel'`;
+ * `color` the poster's dominant ink, which is also what the sign
+ * throws (default 0xc8352f); `lit` (default false) turns on the
+ * lamps or the light box, the halo and the spill; `lift` metres from
+ * the ground to the bottom of the face (default the greater of 2.4
+ * and half the height); `frameColor` (default 0x4a4c4f); `glow` halo
+ * brightness (default 1); `ambient` how bright the surroundings are,
+ * 0 an unlit street to 1 open daylight, passed straight to
+ * `patchNeonSpill` (default 0.15); `seed` the poster and the lamp
+ * spacing (default 1).
+ * @returns {THREE.Group} Named `Billboard`, resting at y = 0 and facing
+ * +Z (`userData.forward`), with `userData.spillSources(n)` (world
+ * points, read through the group's CURRENT matrix),
+ * `userData.relight()` — call it after MOVING a lit sign, since the
+ * spill on its own structure was aimed where it was built — and
+ * `userData.tick(t)`. The halo is guarded by `keepOutOfDepthPasses`.
+ */
+export function makeBillboard(opts = {}) {
+ const w = Math.max(0.5, opts.width === undefined ? 6 : opts.width);
+ const h = Math.max(0.4, opts.height === undefined ? 3 : opts.height);
+ const panelKind = opts.kind === 'panel' ? 'panel' : 'hoarding';
+ const lit = !!opts.lit;
+ const lift = opts.lift === undefined ? Math.max(2.4, h * 0.5) : opts.lift;
+ const color = toColor(opts.color, 0xc8352f);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const rand = mulberry32(Math.round(seed) * 131 + 7);
+ const ambient = unit(opts.ambient === undefined ? 0.15 : opts.ambient);
+ const y0 = lift + h / 2;
+
+ const g = new THREE.Group();
+ g.name = 'Billboard';
+
+ const frameMat = new THREE.MeshStandardMaterial({
+ color: opts.frameColor === undefined ? 0x4a4c4f : opts.frameColor,
+ roughness: 0.62, metalness: 0.55,
+ });
+ const boardMat = new THREE.MeshStandardMaterial({
+ color: 0x2b2c2e, roughness: 0.85, metalness: 0.1,
+ });
+ const faceMat = new THREE.MeshStandardMaterial({
+ map: posterTexture(color, seed, lit),
+ roughness: panelKind === 'panel' ? 0.28 : 0.78,
+ metalness: 0,
+ });
+ if (lit && panelKind === 'panel') {
+ // A light box is lit from within: emissive is the only term that
+ // survives an unlit street, and the map keeps the artwork in it.
+ faceMat.emissive = new THREE.Color(0xffffff);
+ faceMat.emissiveMap = faceMat.map;
+ faceMat.emissiveIntensity = 1.5 * (1 - 0.7 * ambient);
+ }
+
+ const board = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.14), boardMat);
+ board.position.set(0, y0, -0.02);
+ board.name = 'Board';
+ board.castShadow = true;
+ board.receiveShadow = true;
+ g.add(board);
+
+ const face = new THREE.Mesh(
+ new THREE.PlaneGeometry(w - 0.18, h - 0.18), faceMat);
+ face.position.set(0, y0, 0.06);
+ face.name = 'Face';
+ face.receiveShadow = true;
+ g.add(face);
+
+ // Legs, rim and back bracing in one mesh: a billboard is a steel
+ // frame with a sheet on it, and the frame is most of the silhouette.
+ const steel = [];
+ const legX = w * 0.3;
+ for (const sx of [-legX, legX]) {
+ steel.push(_box(0.18, y0 + h / 2, 0.18, sx, (y0 + h / 2) / 2, -0.16));
+ // The raking strut every real hoarding has behind it, lifted by
+ // its own half-thickness so the foot rests ON the ground.
+ const ang = Math.atan2(lift * 0.75, lift);
+ const rake = new THREE.BoxGeometry(0.12, Math.hypot(lift, lift * 0.75),
+ 0.12);
+ rake.rotateX(-ang);
+ rake.translate(sx, lift * 0.5 + 0.06 * Math.sin(ang),
+ -0.16 - lift * 0.375);
+ steel.push(rake);
+ }
+ steel.push(_box(w + 0.24, 0.16, 0.16, 0, y0 + h / 2 + 0.08, 0));
+ steel.push(_box(w + 0.24, 0.16, 0.16, 0, y0 - h / 2 - 0.08, 0));
+ steel.push(_box(0.16, h, 0.16, -w / 2 - 0.08, y0, 0));
+ steel.push(_box(0.16, h, 0.16, w / 2 + 0.08, y0, 0));
+
+ const lamps = [];
+ const sources = [];
+ if (lit && panelKind === 'hoarding') {
+ const n = Math.max(2, Math.round(w / 3));
+ for (let i = 0; i < n; i++) {
+ const x = (i + 0.5) / n * w - w / 2 + (rand() - 0.5) * 0.1;
+ const ly = y0 + h / 2 + 0.62;
+ steel.push(_box(0.09, 0.09, 0.9, x, ly, 0.42));
+ steel.push(_box(0.09, 0.7, 0.09, x, ly - 0.35, 0.86));
+ const head = new THREE.CylinderGeometry(0.17, 0.11, 0.2, 10);
+ head.rotateX(Math.PI * 0.42);
+ head.translate(x, ly - 0.62, 0.84);
+ lamps.push(head);
+ sources.push({ position: new THREE.Vector3(x, ly - 0.72, 0.78),
+ color: new THREE.Color(0xfff0cf) });
+ }
+ }
+
+ const frame = new THREE.Mesh(mergeGeometries(steel, false), frameMat);
+ frame.name = 'Frame';
+ frame.castShadow = true;
+ frame.receiveShadow = true;
+ g.add(frame);
+
+ if (lamps.length) {
+ const lampMat = new THREE.MeshStandardMaterial({
+ color: 0xd8d2c4, roughness: 0.4, metalness: 0.6,
+ emissive: new THREE.Color(0xfff0cf),
+ emissiveIntensity: 2.2 * (1 - 0.7 * ambient),
+ });
+ const lampMesh = new THREE.Mesh(mergeGeometries(lamps, false), lampMat);
+ lampMesh.name = 'Lamps';
+ g.add(lampMesh);
+ }
+ if (lit && panelKind === 'panel') {
+ for (let i = 0; i < 4; i++) {
+ sources.push({
+ position: new THREE.Vector3(
+ (i / 3 - 0.5) * w * 0.8, y0 + (rand() - 0.5) * h * 0.5, 0.1),
+ color: color.clone(),
+ });
+ }
+ }
+
+ if (lit) {
+ // The card carries the halo OUTSIDE the board now, so it has to be
+ // big enough to hold one: at 1.5 x 1.7 the aureole was a bright rim
+ // a few pixels wide instead of light standing in the air.
+ const CARD = [2.0, 2.2];
+ const glow = new THREE.Mesh(
+ new THREE.PlaneGeometry(w * CARD[0], h * CARD[1]),
+ makeShaderMaterial({
+ name: 'BillboardGlow',
+ uniforms: {
+ uBbColor: { value: panelKind === 'panel'
+ ? color.clone().lerp(new THREE.Color(0xffffff), 0.35)
+ : new THREE.Color(0xffe9c4) },
+ // A halo is light scattered in the AIR, so it is only ever
+ // visible against a darker frame: linear in `ambient` it
+ // still clipped the sky round a hoarding at midday
+ // (blown_frac 0.033 in the day close view), and the curve is
+ // what makes one card read at night and vanish by noon.
+ uBbGain: { value: Math.max(0, opts.glow === undefined ? 1
+ : opts.glow)
+ * Math.pow(Math.max(0, 1 - ambient), 1.7) },
+ uBbBias: { value: panelKind === 'panel' ? 0 : 1 },
+ // Where the board's own outline falls on this card.
+ uBbInner: { value: new THREE.Vector2(1 / CARD[0], 1 / CARD[1]) },
+ uBbCore: { value: panelKind === 'panel' ? 0.30 : 0.0 },
+ },
+ varyings: 'varying vec2 vBbUv;',
+ vertexMain: ' vBbUv = uv;',
+ fragmentHead: 'uniform vec3 uBbColor;\nuniform float uBbGain;\n'
+ + 'uniform float uBbBias;\nuniform vec2 uBbInner;\n'
+ + 'uniform float uBbCore;',
+ fragmentMain: GLOW_FRAGMENT,
+ additive: true,
+ }));
+ glow.position.set(0, y0, 0.09);
+ glow.name = 'Glow';
+ glow.renderOrder = 3;
+ g.add(keepOutOfDepthPasses(glow));
+ }
+
+ // Sources are read through the CURRENT world matrix, so placing the
+ // sign moves the light it throws.
+ g.userData.spillSources = (n) => {
+ g.updateWorldMatrix(true, false);
+ const want = Math.min(8, Math.max(1, Math.round(
+ n === undefined ? sources.length || 1 : n)));
+ const pick = want >= sources.length
+ ? sources
+ : sources.filter((_, i) => i % Math.ceil(sources.length / want) === 0)
+ .slice(0, want);
+ return pick.map((s) => ({
+ position: s.position.clone().applyMatrix4(g.matrixWorld),
+ color: s.color.clone(),
+ }));
+ };
+ // The sign lights its OWN structure through neon.js rather than
+ // growing a second spill; the face too, when lamps light it.
+ g.userData.relight = () => {
+ if (!sources.length) return g;
+ const list = g.userData.spillSources(sources.length);
+ const reach = Math.max(w, h) * 1.4;
+ // Measured at night: a strength of 1.1 on the steel and 1.5 on the
+ // poster clipped both — the frame went to a white silhouette and the
+ // top third of the artwork disappeared into the wash. A gooseneck
+ // makes POOLS on a sheet, so the spill has to stay under the ink it
+ // is lighting.
+ patchNeonSpill(frameMat, { sources: list, radius: reach,
+ strength: 0.72, ambient });
+ if (panelKind === 'hoarding') {
+ patchNeonSpill(faceMat, { sources: list, radius: reach,
+ strength: 0.85, ambient });
+ }
+ return g;
+ };
+ g.userData.relight();
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.forward = '+Z';
+ return g;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/veils.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/veils.js
new file mode 100644
index 00000000..89d27128
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/veils.js
@@ -0,0 +1,842 @@
+/**
+ * Weather seen AT DISTANCE: the veils, not the drops.
+ *
+ * `rain.js` gives the drops near the camera — a wrap box a few metres
+ * wide, streaks measured in centimetres. A rainy valley needs the other
+ * thing entirely: the pale sheets of rain crossing the far hillside,
+ * tens of metres tall, slanted with the wind, that tell you the weather
+ * is out THERE. Same for snow, and for the dust and pollen that say
+ * this air has something in it. None of the three is a bigger copy of
+ * the near-field version, and the differences are the point:
+ *
+ * `makeRainVeil` is a handful of huge slanted curtains, not thousands
+ * of streaks. A curtain is legible only if it never shows an edge and
+ * never reads as a rectangle, so each one billboards about its OWN
+ * fall axis and carries filaments that travel down its face.
+ *
+ * `makeSnowfall` is not rain that is white. A snowflake falls at
+ * under a metre a second and WANDERS — its horizontal path is a curve
+ * with no preferred direction — and that wander is the whole
+ * difference. Flakes near the camera are drawn bigger and softer,
+ * because a real lens focussed on the valley cannot hold them.
+ *
+ * `makeMotes` is the air itself: specks that hang, barely drift, and
+ * flash as they turn their faces to the light.
+ *
+ * BLENDING — all three blend NORMALLY, none of them additively.
+ * `godrays.js` measures what added light does to a bright frame: 12.8%
+ * of it past 0.97, and 3.6x less gain still left 11.3%, because 0.94
+ * plus anything visible clips. Every effect here is pale and every one
+ * of them can appear in daylight, so additive blending would turn each
+ * into a solid white slab at any strength worth having. Rain and snow
+ * SCATTER — they lower the contrast of what is behind them, which is
+ * the opposite of adding — and a mote is a speck of matter, not a lamp;
+ * its glint is carried to near-white through ALPHA, which is the
+ * brightest an element that does not add is allowed to be.
+ *
+ * LIGHT — none of the three is a lit material, and all three read the
+ * scene anyway: each field probes the lights around it every few frames
+ * and multiplies its colour by that irradiance, normalised so the
+ * library's own day rig is 1.0. Daylight is therefore unchanged and a
+ * moonlit valley no longer carries a glowing white curtain. A lamp is
+ * included with its falloff at the field's own origin, which is what
+ * puts a mote volume standing in a lamp's pool into that pool.
+ *
+ * All three 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.
+ */
+
+import * as THREE from 'three';
+
+import { instancedQuad, keepOutOfDepthPasses, makeShaderMaterial, tickShaders }
+ from './shader.js';
+
+// Terminal fall of medium rain. Written once because the slant, the
+// sheet length and the streak rate must all read the same number.
+const _RAIN_FALL = 9.0;
+
+/** 16807 LCG: same seed, same field, on every machine. */
+function prng(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);
+}
+
+/** Horizontal velocity in xz from a number, an array or a vector. */
+function toWind(v, dx, dz) {
+ if (typeof v === 'number') return new THREE.Vector2(v, 0);
+ if (Array.isArray(v)) {
+ return new THREE.Vector2(v[0] || 0,
+ (v.length > 2 ? v[2] : v[1]) || 0);
+ }
+ if (v && v.isVector3) return new THREE.Vector2(v.x, v.z);
+ if (v && v.isVector2) return new THREE.Vector2(v.x, v.y);
+ return new THREE.Vector2(dx, dz);
+}
+
+// Two octaves with a fixed envelope, so the swing is bounded by 1 and
+// the field's stated volume is exactly the volume it occupies.
+function _wobX(f, p, t) {
+ return Math.sin(f * t + p) * 0.75
+ + Math.sin(f * 1.9 * t + p * 2.1) * 0.25;
+}
+
+function _wobZ(f, p, t) {
+ return Math.cos(f * t + p) * 0.75
+ + Math.cos(f * 2.3 * t + p * 1.6) * 0.25;
+}
+
+const _WOB_GLSL = [
+ 'float astraVeilWobX(float f, float p, float t) {',
+ ' return sin(f * t + p) * 0.75 + sin(f * 1.9 * t + p * 2.1) * 0.25;',
+ '}',
+ 'float astraVeilWobZ(float f, float p, float t) {',
+ ' return cos(f * t + p) * 0.75 + cos(f * 2.3 * t + p * 1.6) * 0.25;',
+ '}',
+].join('\n');
+
+/** Wrap v into [-half, half), the CPU mirror of GLSL mod(). */
+function _wrap(v, extent, half) {
+ return v - Math.floor((v + half) / extent) * extent;
+}
+
+/*
+ * LIGHT. None of the three materials is lit — they are billboards with
+ * a colour and an alpha — and an unlit pale card is the brightest thing
+ * in any frame that is not daylight. Measured on the moonlit rig
+ * (elevation -20): the rain curtain came back at 0.62 luminance over a
+ * 0.12 scene, a glowing sheet hanging in front of a night sky, and the
+ * motes stayed white inside a shadow. Nothing here can be lit properly
+ * — a veil is a volume, not a surface — but what it SCATTERS is the
+ * irradiance where it hangs, and that is one vec3 the scene can be
+ * asked for. So each field probes its own scene once every few frames
+ * and multiplies its colour by the answer, normalised so the library's
+ * own day rig lands on 1.0 and every veil in daylight looks exactly as
+ * it did. `uLight` stays (1,1,1) in a scene with no lights at all,
+ * which is what an asset preview and the shader check build.
+ */
+
+// Weights per light type: a veil sees the whole sky and only a slice of
+// a directional beam (forward scatter), so the hemisphere dominates.
+const _W_HEMI_SKY = 0.62;
+const _W_HEMI_GROUND = 0.18;
+const _W_DIR = 0.12;
+// Irradiance the library's `sunRig()` day preset puts on a veil, so the
+// probe is a no-op at noon and a real dimming everywhere else.
+const _LIGHT_REF = 1.02;
+
+const _PROBE = new WeakMap();
+const _TMP_AT = new THREE.Vector3();
+const _TMP_LP = new THREE.Vector3();
+
+/** The distant (position-free) part of a scene's light, cached per frame. */
+function _probeScene(scene, frame) {
+ const hit = _PROBE.get(scene);
+ if (hit && frame - hit.frame < 15) return hit;
+ const distant = { r: 0, g: 0, b: 0 };
+ const punctual = [];
+ let found = 0;
+ scene.traverse((o) => {
+ if (!o.isLight || o.visible === false || !(o.intensity > 0)) return;
+ found++;
+ const c = o.color;
+ const i = o.intensity;
+ if (o.isAmbientLight) {
+ distant.r += c.r * i; distant.g += c.g * i; distant.b += c.b * i;
+ } else if (o.isHemisphereLight) {
+ const g = o.groundColor;
+ distant.r += (c.r * _W_HEMI_SKY + g.r * _W_HEMI_GROUND) * i;
+ distant.g += (c.g * _W_HEMI_SKY + g.g * _W_HEMI_GROUND) * i;
+ distant.b += (c.b * _W_HEMI_SKY + g.b * _W_HEMI_GROUND) * i;
+ } else if (o.isDirectionalLight) {
+ distant.r += c.r * i * _W_DIR;
+ distant.g += c.g * i * _W_DIR;
+ distant.b += c.b * i * _W_DIR;
+ } else if (o.isPointLight || o.isSpotLight) {
+ punctual.push(o);
+ }
+ });
+ const out = { frame, distant, punctual, found, fog: scene.fog || null };
+ _PROBE.set(scene, out);
+ return out;
+}
+
+/**
+ * Drive `uLight` (and, when the caller left the colour alone, the hue of
+ * `uColor`) from the scene the mesh is being drawn in.
+ *
+ * A lamp is included with its own inverse-square falloff at the FIELD's
+ * origin, which is what gives a mote volume standing in a lamp's pool a
+ * warm lift and leaves the 70 m rain field untouched by it.
+ *
+ * @param {THREE.Mesh} mesh Carries a `makeShaderMaterial` with `uLight`.
+ * @param {THREE.Color} [autoTint] The default colour to pull into the
+ * scene's fog hue — omitted when the caller passed a colour of its own.
+ */
+function _litByScene(mesh, autoTint) {
+ const prev = mesh.onBeforeRender;
+ const uni = mesh.material.uniforms;
+ const base = autoTint ? autoTint.clone() : null;
+ const hsl = { h: 0, s: 0, l: 0 };
+ const own = { h: 0, s: 0, l: 0 };
+ mesh.onBeforeRender = (r, scene, cam, geo, mat, grp) => {
+ if (prev) prev(r, scene, cam, geo, mat, grp);
+ const p = _probeScene(scene, r.info.render.frame);
+ if (!p.found) return;
+ let { r: er, g: eg, b: eb } = p.distant;
+ if (p.punctual.length) {
+ mesh.getWorldPosition(_TMP_AT);
+ for (const l of p.punctual) {
+ l.getWorldPosition(_TMP_LP);
+ const d2 = Math.max(0.25, _TMP_LP.distanceToSquared(_TMP_AT));
+ if (l.distance > 0 && d2 > l.distance * l.distance) continue;
+ const a = (l.intensity / d2) * _W_DIR;
+ er += l.color.r * a; eg += l.color.g * a; eb += l.color.b * a;
+ }
+ }
+ // The floor keeps a veil legible in a scene lit by one dim lamp;
+ // the ceiling stops a lamp two metres away turning it into a
+ // white slab, which is the failure ordinary blending exists to
+ // avoid in the first place.
+ // ADAPTATION, not physics. A straight ratio is right for the
+ // hue and too steep for the value: a moonlit curtain at 0.15 of
+ // daylight is a curtain nobody can see, while the eye watching
+ // that valley has opened up. The 0.82 exponent is the whole of
+ // the fudge — it is 1.0 at daylight, so noon is untouched, and
+ // it lifts the moonlit field to 0.21 of it.
+ const k = 1 / _LIGHT_REF;
+ const adapt = (e) => Math.min(1.7,
+ Math.max(0.05, Math.pow(Math.max(0, e * k), 0.82)));
+ uni.uLight.value.setRGB(adapt(er), adapt(eg), adapt(eb));
+ // FOG HUE. A veil the scene's own haze does not agree with reads
+ // as a card in front of the weather rather than part of it — so
+ // an untouched default takes the fog's HUE and keeps its own
+ // lightness. Taking the fog's value as well would send the veil
+ // to black in a night scene the light probe has already dimmed.
+ if (base && p.fog) {
+ p.fog.color.getHSL(hsl);
+ base.getHSL(own);
+ uni.uColor.value.setHSL(hsl.h,
+ Math.min(0.30, hsl.s * 0.75 + own.s * 0.25), own.l);
+ }
+ };
+}
+
+/**
+ * Sheets of rain crossing the middle and far distance.
+ *
+ * A few very large curtains, not a cloud of streaks: at 80 m a drop is
+ * far under a pixel, so what the eye is given is the SHEET — leaning
+ * with the wind, thickest at its foot, ragged at its edges, with
+ * filaments running down its face. Two constraints keep it from reading
+ * as flat cards, which is the one way this effect fails. Each sheet
+ * billboards about its own fall axis, so it turns its face to every
+ * camera and never shows an edge or a rectangle; and the per-sheet
+ * alpha is solved from how many sheets a ray across the field crosses,
+ * so `density` means the same veil however many of them there are and
+ * an overlap never stacks into a slab.
+ *
+ * BLENDING: ORDINARY. Rain scatters — it lowers the contrast of the
+ * ridge behind it — and a sheet this size added to a daylight sky
+ * would clip to a white slab at any strength worth having.
+ *
+ * @param {object} [opts]
+ * `extent` metres square the sheets are spread over (default 120 —
+ * this is landscape weather, so think valley, not garden);
+ * `height` metres from the cloud base to the ground (default 60 —
+ * a veil no taller than the ridge it crosses reads as ground haze,
+ * so give it half again the height of what it falls past);
+ * `direction` wind in m/s as a number (along +x), [dx, dz] or a
+ * THREE.Vector2/3 (default [3.5, 0]) — it sets the SLANT (against a
+ * 9 m/s fall) and the speed the sheets travel across the field;
+ * `density` how much the veil hides, 0 to 1 (default 0.6; 0.9 is a
+ * downpour that greys out the far ridge);
+ * `color` THREE.Color or hex — the veil's ALBEDO, which the scene's
+ * own light then multiplies (default a cool grey that takes the
+ * scene fog's HUE at its own lightness, so the sheets never stand in
+ * front of the weather; pass a colour to keep that from happening);
+ * `seed` PRNG seed (default 7).
+ * @returns {THREE.Group} Named `RainVeil`, centred on its own origin
+ * with the sheets' feet at y ~ 0, with `userData.tick(t)`,
+ * `userData.sample(i, t)` giving sheet i's foot and `userData.axis`
+ * the shared fall direction. Move the group to place the field.
+ */
+export function makeRainVeil(opts = {}) {
+ const extent = Math.max(6,
+ opts.extent === undefined ? 120 : opts.extent);
+ const height = Math.max(3,
+ opts.height === undefined ? 60 : opts.height);
+ const wind = toWind(opts.direction, 3.5, 0);
+ const density = Math.min(0.97, Math.max(0.02,
+ opts.density === undefined ? 0.6 : opts.density));
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xb9c6d4 : opts.color);
+ const autoTint = opts.color === undefined ? color : null;
+ const rnd = prng(opts.seed === undefined ? 7 : opts.seed);
+
+ const axis = new THREE.Vector3(wind.x, -_RAIN_FALL, wind.y).normalize();
+ // Length ALONG the slanted axis that spans `height` vertically, so
+ // the cloud base stays level however hard the wind blows.
+ const len = height / Math.max(0.2, -axis.y);
+ const half = extent * 0.5;
+ const sink = height * 0.05;
+
+ const count = Math.round(Math.min(9, Math.max(4, extent / 25)));
+ const sheet = new Float32Array(count * 4);
+ const veil = new Float32Array(count * 2);
+ const footR = Math.hypot(half * Math.SQRT2, sink);
+ const topR = Math.hypot(half * Math.SQRT2 + len * Math.hypot(axis.x,
+ axis.z), len * -axis.y - sink);
+ let widths = 0;
+ let radius = 0;
+ for (let i = 0; i < count; i++) {
+ // Stratified around a ring, never a uniform draw: a uniform one
+ // puts two sheets on top of each other and leaves a third of
+ // the valley with no weather in it at all.
+ const a = ((i + rnd()) / count) * Math.PI * 2;
+ const r = half * (0.22 + 0.74 * rnd());
+ const hw = extent * (0.09 + 0.09 * rnd());
+ sheet[i * 4] = Math.cos(a) * r;
+ sheet[i * 4 + 1] = Math.sin(a) * r;
+ sheet[i * 4 + 2] = hw;
+ sheet[i * 4 + 3] = rnd() * 40;
+ veil[i * 2] = 0.62 + 0.58 * rnd();
+ veil[i * 2 + 1] = rnd() * 9;
+ widths += hw * 2;
+ radius = Math.max(radius, Math.max(footR, topR) + hw);
+ }
+ // Sheets a ray across the field crosses. Solving the per-sheet
+ // alpha from it keeps `density` the depth of the VEIL at any count,
+ // and the 2.6 pays back what the profile and the holes take.
+ const hits = Math.max(0.8, widths / extent);
+ const alpha = Math.min(0.70, Math.max(0.01,
+ 2.6 * (1 - Math.pow(1 - density, 1 / hits))));
+
+ const geom = instancedQuad(count, 1, 1, radius * 1.02);
+ geom.setAttribute('aSheet', new THREE.InstancedBufferAttribute(sheet, 4));
+ geom.setAttribute('aVeil', new THREE.InstancedBufferAttribute(veil, 2));
+
+ const mesh = new THREE.Mesh(geom, veilMaterial({
+ color, alpha, axis, wind, extent, half, len, sink,
+ wisp: Math.max(1.2, extent * 0.05),
+ near: Math.max(4, extent * 0.08),
+ }));
+ mesh.name = 'RainSheets';
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = 'RainVeil';
+ g.add(mesh);
+ // A curtain of rain is not a wall to the ambient-occlusion pass and
+ // does not cast a shadow; every other veil in this library says so.
+ keepOutOfDepthPasses(g);
+ _litByScene(mesh, autoTint);
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.axis = axis.clone();
+ g.userData.length = len;
+ g.userData.sample = (i, t) => {
+ const k = Math.min(count - 1, Math.max(0, i | 0));
+ return new THREE.Vector3(
+ _wrap(sheet[k * 4] + wind.x * t, extent, half), -sink,
+ _wrap(sheet[k * 4 + 1] + wind.y * t, extent, half));
+ };
+ return g;
+}
+
+/** One curtain per instance, rolled about its own fall axis. */
+function veilMaterial(cfg) {
+ return makeShaderMaterial({
+ name: 'RainVeilSheets',
+ uniforms: {
+ uTime: { value: 0 },
+ uColor: { value: cfg.color },
+ uLight: { value: new THREE.Color(1, 1, 1) },
+ uAlpha: { value: cfg.alpha },
+ uAxis: { value: cfg.axis },
+ uWind: { value: cfg.wind },
+ uExtent: { value: cfg.extent },
+ uHalf: { value: cfg.half },
+ uLen: { value: cfg.len },
+ uSink: { value: cfg.sink },
+ uWisp: { value: cfg.wisp },
+ uNear: { value: cfg.near },
+ uFall: { value: _RAIN_FALL },
+ // Metres between filaments across the sheet and between
+ // their heads down it.
+ uSpacing: { value: 0.55 },
+ uSeg: { value: 6.0 },
+ },
+ varyings: 'varying vec2 vUv; varying vec3 vP;'
+ + ' varying float vBright; varying float vSeed;'
+ + ' varying float vHalfW; varying float vFade;',
+ // `uniform float uTime;` rides on a long line on purpose: the
+ // GLSL audit only reads quoted strings long enough to look like
+ // shader source, so alone it is skipped and this file reads as
+ // using uTime without ever declaring it (shader.js injects the
+ // declaration, and the duplicate here is deduped away).
+ vertexHead: 'attribute vec3 aCorner; attribute vec4 aSheet;'
+ + ' uniform float uTime;'
+ + ' attribute vec2 aVeil; uniform vec3 uAxis;'
+ + ' uniform vec2 uWind; uniform float uExtent;'
+ + ' uniform float uHalf; uniform float uLen;'
+ + ' uniform float uSink;',
+ vertexMain: [
+ ' vUv = uv;',
+ ' vBright = aVeil.x;',
+ ' vSeed = aVeil.y + aSheet.w;',
+ ' vHalfW = aSheet.z;',
+ // The whole curtain travels with the wind and wraps in the
+ // field; the edge fade below hides the wrap.
+ ' vec2 fxz = mod(aSheet.xy + uWind * uTime + uHalf, uExtent)',
+ ' - uHalf;',
+ ' vec3 foot = vec3(fxz.x, -uSink, fxz.y);',
+ ' vec3 up = -uAxis;',
+ ' vec3 mid = foot + up * (uLen * 0.5);',
+ // Rolled about its OWN fall axis: the slant stays true from
+ // every camera and the sheet never turns edge-on, which is
+ // the moment a curtain would betray itself as a card.
+ ' vec3 side = cross(uAxis, mid - cameraPosition);',
+ ' float sl = length(side);',
+ ' side = sl > 1e-4 ? side / sl : vec3(1.0, 0.0, 0.0);',
+ ' transformed = foot + up * ((aCorner.y + 0.5) * uLen)',
+ ' + side * (aCorner.x * 2.0 * aSheet.z);',
+ ' vP = transformed;',
+ ' vFade = 1.0 - smoothstep(0.85, 1.20,',
+ ' length(fxz) / uHalf);',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'
+ + ' uniform float uAlpha;'
+ + ' uniform float uLen; uniform float uWisp;'
+ + ' uniform float uNear; uniform float uFall;'
+ + ' uniform float uSpacing; uniform float uSeg;',
+ fragmentMain: [
+ ' vec2 e = abs(vUv * 2.0 - 1.0);',
+ // Denser at the foot and gone into the cloud at the top —
+ // and soft on both flanks, because a rim IS the card.
+ ' float prof = mix(1.0, 0.45, vUv.y)',
+ ' * (1.0 - smoothstep(0.80, 1.02, vUv.y))',
+ ' * (1.0 - smoothstep(0.30, 1.0, e.x));',
+ ' float near = smoothstep(uNear * 0.3, uNear,',
+ ' length(vP - cameraPosition));',
+ ' float cap = uAlpha * vBright * vFade * prof * near;',
+ ' if (cap < 0.002) discard;',
+ ' float wx = (vUv.x - 0.5) * 2.0 * vHalfW;',
+ ' float wy = vUv.y * uLen + uTime * uFall;',
+ // Stretched 8x along the fall. Round blotches are what
+ // makes a pale mass read as steam; rain is drawn out into
+ // bands that run the whole way down the shaft.
+ ' vec2 q = vec2(wx / uWisp, wy / (uWisp * 8.0)) + vSeed;',
+ ' float band = astraFbm2(q, 3) * 0.72',
+ ' + astraNoise2(q * 3.1 + vec2(0.0, 4.0)) * 0.28;',
+ // GUSTS, metres across, under the centimetre bands: a real
+ // curtain is thick in patches and thin between them, and
+ // without that the sheet is flat everywhere the filaments
+ // are not, which is what makes the filaments read as
+ // scratches on the ridge instead of rain in front of it.
+ // Centred on 1.0, so `density` still means what it says.
+ ' float gust = astraFbm2(q * 0.21 + vec2(5.3, 1.7), 2);',
+ ' float body = mix(0.42, 1.0, smoothstep(0.20, 0.78, band))',
+ ' * mix(0.68, 1.28, smoothstep(0.14, 0.64, gust));',
+ // Filaments travelling down the face: without them a sheet
+ // this size is a painted gradient and reads as a backdrop.
+ // Thin (0.10 of the spacing, not 0.16) so `astraStroke`'s
+ // own kill can still retire them at distance, never fully
+ // off between heads, and coupled to `body` — a filament in
+ // a thin part of the curtain has nothing to be made of.
+ ' float ux = wx / uSpacing;',
+ ' float d = fract(wy / uSeg + astraStagger(floor(ux) + vSeed));',
+ ' float fil = astraStroke(ux, 0.12)',
+ ' * (0.34 + 0.66 * exp(-d * 2.1)) * sqrt(body);',
+ ' float a = cap * body * (1.0 + 0.66 * fil);',
+ // Hue variance inside one curtain: broad warm/cool patches
+ // across its face, plus a per-sheet offset, so a stack of
+ // them is weather rather than one flat grey wash.
+ ' vec3 c = astraHueBreak(uColor, q, 0.34, 0.32);',
+ ' float hue = astraHash11(vSeed * 0.37) * 2.0 - 1.0;',
+ ' c *= 1.0 + hue * vec3(0.06, 0.012, -0.065);',
+ // Dither: a curtain is a wide, shallow alpha ramp over a
+ // smooth sky, which is exactly where 8-bit output bands.
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ ' if (a < 0.003) discard;',
+ ' gl_FragColor = vec4(c * uLight * (0.96 + 0.11 * fil),',
+ ' clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
+
+/**
+ * Snow: flakes that fall slowly and WANDER, not white rain.
+ *
+ * A raindrop falls at 9 m/s down a straight line; a flake falls at well
+ * under one and its horizontal path is a curve that goes nowhere in
+ * particular. That wander is the entire difference between snow and
+ * white rain, so it is not decoration here — every flake carries its
+ * own two swing frequencies and phases, and the CPU mirror runs the
+ * same curve the vertex shader does. The second half is the lens:
+ * flakes nearer than the focus distance are drawn BIGGER and softer,
+ * with their alpha divided by the same factor, because a camera
+ * focussed on the valley cannot hold a flake at arm's length and a
+ * field of uniformly crisp dots reads as a particle system.
+ *
+ * BLENDING: ORDINARY, for the same reason as the rain — snow scatters,
+ * and white added to a bright winter frame has nowhere to go.
+ *
+ * @param {object} [opts]
+ * `extent` metres square the field covers (default 40); `height`
+ * metres it stands (default 18); `rate` flakes reaching the ground
+ * per second across the whole field (default 260 — the count is
+ * solved from it and the fall time, so there is no particle budget to
+ * guess); `size` flake diameter in metres (default 0.035, which also
+ * sets how fast they fall and how far they swing); `drift` wind in
+ * m/s, a number (along +x), [dx, dz] or a THREE.Vector2/3 (default
+ * [0.35, 0] — snow drifts, it does not race); `color` THREE.Color or
+ * hex, the flake albedo the scene's light multiplies (default a cold
+ * white that takes the fog's hue); `seed` PRNG seed (default 9).
+ * @returns {THREE.Group} Named `Snowfall`, its foot on y = 0, with
+ * `userData.tick(t)` and `userData.sample(i, t)` returning flake i's
+ * group-local position — the CPU mirror of the vertex shader.
+ */
+export function makeSnowfall(opts = {}) {
+ const extent = Math.max(2, opts.extent === undefined ? 40 : opts.extent);
+ const height = Math.max(1, opts.height === undefined ? 18 : opts.height);
+ const rate = Math.max(1, opts.rate === undefined ? 260 : opts.rate);
+ const size = Math.max(0.002,
+ opts.size === undefined ? 0.035 : opts.size);
+ const drift = toWind(opts.drift, 0.35, 0);
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xf2f7ff : opts.color);
+ const rnd = prng(opts.seed === undefined ? 9 : opts.seed);
+ const autoTint = opts.color === undefined ? color : null;
+
+ // A bigger flake carries more mass per unit drag, so it falls
+ // faster and swings wider; both are read off `size`.
+ const fall = 0.45 + 6 * size;
+ const wob = 0.22 + 4.5 * size;
+ const half = extent * 0.5;
+ const count = Math.round(Math.min(9000,
+ Math.max(120, rate * (height / fall))));
+
+ const pos = new Float32Array(count * 3);
+ const flake = new Float32Array(count * 4);
+ const swing = new Float32Array(count * 4);
+ let scale = 0;
+ for (let i = 0; i < count; i++) {
+ pos[i * 3] = (rnd() - 0.5) * extent;
+ pos[i * 3 + 1] = rnd() * height;
+ pos[i * 3 + 2] = (rnd() - 0.5) * extent;
+ flake[i * 4] = 0.6 + 0.9 * rnd();
+ flake[i * 4 + 1] = 0.65 + 0.8 * rnd();
+ flake[i * 4 + 2] = 0.55 + 0.6 * rnd();
+ flake[i * 4 + 3] = rnd();
+ swing[i * 4] = 0.35 + 0.95 * rnd();
+ swing[i * 4 + 1] = rnd() * 6.283;
+ swing[i * 4 + 2] = 0.35 + 0.95 * rnd();
+ swing[i * 4 + 3] = rnd() * 6.283;
+ scale = Math.max(scale, flake[i * 4]);
+ }
+ const focus = Math.max(2, extent * 0.10);
+ const bokeh = 2.4;
+ // The wrap keeps every flake inside the box, so the only thing the
+ // sphere has to add is the widest a quad can be drawn.
+ const radius = Math.hypot(half * Math.SQRT2, height)
+ + size * scale * (1 + bokeh) * Math.SQRT1_2;
+
+ const geom = instancedQuad(count, 1, 1, radius * 1.02);
+ geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));
+ geom.setAttribute('aFlake', new THREE.InstancedBufferAttribute(flake, 4));
+ geom.setAttribute('aSwing', new THREE.InstancedBufferAttribute(swing, 4));
+
+ const mesh = new THREE.Mesh(geom, snowMaterial({
+ color, size, fall, wob, drift, extent, half, height, focus, bokeh,
+ }));
+ mesh.name = 'Snowflakes';
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = 'Snowfall';
+ g.add(mesh);
+ keepOutOfDepthPasses(g);
+ _litByScene(mesh, autoTint);
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.sample = (i, t) => {
+ const k = Math.min(count - 1, Math.max(0, i | 0));
+ const y = pos[k * 3 + 1] - fall * flake[k * 4 + 1] * t;
+ return new THREE.Vector3(
+ _wrap(pos[k * 3] + drift.x * t
+ + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),
+ extent, half),
+ y - Math.floor(y / height) * height,
+ _wrap(pos[k * 3 + 2] + drift.y * t
+ + wob * _wobZ(swing[k * 4 + 2], swing[k * 4 + 3], t),
+ extent, half));
+ };
+ return g;
+}
+
+/** Slow fall, wandering path, and a lens that cannot hold the near ones. */
+function snowMaterial(cfg) {
+ return makeShaderMaterial({
+ name: 'SnowflakeField',
+ uniforms: {
+ uTime: { value: 0 },
+ uColor: { value: cfg.color },
+ uLight: { value: new THREE.Color(1, 1, 1) },
+ uAlpha: { value: 0.85 },
+ uSize: { value: cfg.size },
+ uFall: { value: cfg.fall },
+ uWob: { value: cfg.wob },
+ uDrift: { value: cfg.drift },
+ uExtent: { value: cfg.extent },
+ uHalf: { value: cfg.half },
+ uHeight: { value: cfg.height },
+ uFocus: { value: cfg.focus },
+ uBokeh: { value: cfg.bokeh },
+ },
+ varyings: 'varying vec2 vUv; varying float vBright;'
+ + ' varying float vBlur; varying float vFade;'
+ + ' varying float vHue; varying float vTumble;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'
+ + ' uniform float uTime;'
+ + ' attribute vec4 aFlake; attribute vec4 aSwing;'
+ + ' uniform float uSize; uniform float uFall;'
+ + ' uniform float uWob; uniform vec2 uDrift;'
+ + ' uniform float uExtent; uniform float uHalf;'
+ + ' uniform float uHeight; uniform float uFocus;'
+ + ' uniform float uBokeh;\n' + _WOB_GLSL,
+ vertexMain: [
+ ' vUv = uv;',
+ ' vBright = aFlake.z;',
+ // aFlake.w was spare. A field of flakes at ONE white is the
+ // give-away that they came out of a loop: real ones catch
+ // the sun or only the sky, and they TUMBLE — face, edge,
+ // face — which is a slow breath of brightness, not a
+ // sparkle. Both ride this one per-flake number.
+ ' vHue = aFlake.w * 2.0 - 1.0;',
+ ' vTumble = 0.74 + 0.26 * abs(sin(uTime * (0.7 + aFlake.w)',
+ ' + aFlake.w * 6.283));',
+ // Its own fall speed, so the field never descends as a
+ // sheet, and its own two swings, which is the wander.
+ ' float y = mod(aPos.y - uFall * aFlake.y * uTime, uHeight);',
+ ' vec2 w = vec2(astraVeilWobX(aSwing.x, aSwing.y, uTime),',
+ ' astraVeilWobZ(aSwing.z, aSwing.w, uTime));',
+ ' vec2 xz = mod(aPos.xz + uDrift * uTime + uWob * w + uHalf,',
+ ' uExtent) - uHalf;',
+ ' vec3 p = vec3(xz.x, y, xz.y);',
+ // Nearer than the focus distance: bigger and blurrier, the
+ // way a lens focussed on the valley renders arm's length.
+ ' vBlur = 1.0 - smoothstep(0.0, uFocus,',
+ ' length(p - cameraPosition));',
+ ' float s = uSize * aFlake.x * (1.0 + uBokeh * vBlur);',
+ ' vec3 camR = vec3(viewMatrix[0][0], viewMatrix[1][0],',
+ ' viewMatrix[2][0]);',
+ ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',
+ ' viewMatrix[2][1]);',
+ ' transformed = p + camR * (aCorner.x * s)',
+ ' + camU * (aCorner.y * s);',
+ ' float vy = y / uHeight;',
+ ' vFade = smoothstep(0.0, 0.05, vy)',
+ ' * (1.0 - smoothstep(0.86, 1.0, vy))',
+ ' * (1.0 - smoothstep(0.74, 1.02, length(xz) / uHalf));',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'
+ + ' uniform float uAlpha;',
+ fragmentMain: [
+ ' float d = length(vUv - 0.5) * 2.0;',
+ ' if (d > 1.0) discard;',
+ // In focus it is a disc with a soft rim; out of focus it is
+ // a smear, and the same factor takes its alpha away.
+ ' float core = 1.0 - smoothstep(mix(0.42, 0.0, vBlur),',
+ ' 1.0, d);',
+ ' float a = uAlpha * vBright * vFade * core * vTumble',
+ ' / (1.0 + 2.4 * vBlur);',
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ ' if (a < 0.004) discard;',
+ // Snow is white the way paper is white: the ones the sun
+ // reaches are warm, the ones only the sky reaches are blue.
+ ' vec3 c = uColor * (1.0 + vHue * vec3(0.055, 0.008, -0.06));',
+ ' gl_FragColor = vec4(c * uLight, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
+
+/**
+ * Dust or pollen hanging in a shaft of light.
+ *
+ * What this buys is the statement that the air is not empty — the thing
+ * a light shaft, a barn interior or a summer meadow has and a rendered
+ * one never does. The constraint is that motes must not read as
+ * particles: they hang almost still (a few centimetres a second of
+ * settle, a bounded wander that never leaves the stated volume) and
+ * they TWINKLE, because a speck of matter is a flake with faces, and
+ * what the eye actually catches is the flash as one comes round to the
+ * light. A speck at constant brightness reads as a dot on the lens.
+ *
+ * BLENDING: ORDINARY, though a mote is the one of the three that is
+ * arguably light. It is a speck of MATTER, and additive specks over a
+ * sunlit wall clip; the glint rides alpha up to a near-white instead.
+ *
+ * @param {object} [opts]
+ * `extent` metres square the volume covers (default 6); `height`
+ * metres it stands (default 4); `count` specks (default 320 — a
+ * shaft of light holds surprisingly few, and a fog of them reads as
+ * noise); `size` speck diameter in metres (default 0.024 — it is the
+ * glint that has to be visible, not the grain); `color` THREE.Color
+ * or hex (default a warm near-white — the dust's own colour, spread
+ * ochre to grey per speck and then multiplied by the light actually
+ * reaching the volume, lamps included); `seed` PRNG seed
+ * (default 13).
+ * @returns {THREE.Group} Named `Motes`, its foot on y = 0, with
+ * `userData.tick(t)`, `userData.sample(i, t)` giving speck i's
+ * group-local position and `userData.volume` the box it stays in.
+ */
+export function makeMotes(opts = {}) {
+ const extent = Math.max(0.5, opts.extent === undefined ? 6 : opts.extent);
+ const height = Math.max(0.3, opts.height === undefined ? 4 : opts.height);
+ const count = Math.round(Math.min(4000,
+ Math.max(8, opts.count === undefined ? 320 : opts.count)));
+ const size = Math.max(0.001,
+ opts.size === undefined ? 0.024 : opts.size);
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xfff2d8 : opts.color);
+ const rnd = prng(opts.seed === undefined ? 13 : opts.seed);
+
+ const half = extent * 0.5;
+ // Dust does not fall so much as fail to stay up.
+ const settle = 0.035;
+ const wob = Math.min(0.35, extent * 0.12);
+ // Start inside the volume by the whole swing, so the wander can
+ // never carry a speck out of the box the caller was promised.
+ const inner = Math.max(0, half - wob);
+
+ const pos = new Float32Array(count * 3);
+ const mote = new Float32Array(count * 4);
+ const swing = new Float32Array(count * 4);
+ let scale = 0;
+ for (let i = 0; i < count; i++) {
+ pos[i * 3] = (rnd() * 2 - 1) * inner;
+ pos[i * 3 + 1] = rnd() * height;
+ pos[i * 3 + 2] = (rnd() * 2 - 1) * inner;
+ mote[i * 4] = 0.5 + 1.5 * rnd();
+ mote[i * 4 + 1] = 0.5 + 1.3 * rnd();
+ mote[i * 4 + 2] = rnd() * 6.283;
+ mote[i * 4 + 3] = 0.55 + 0.6 * rnd();
+ swing[i * 4] = 0.12 + 0.34 * rnd();
+ swing[i * 4 + 1] = rnd() * 6.283;
+ swing[i * 4 + 2] = 0.12 + 0.34 * rnd();
+ swing[i * 4 + 3] = rnd() * 6.283;
+ scale = Math.max(scale, mote[i * 4]);
+ }
+ const radius = Math.hypot(half * Math.SQRT2, height)
+ + size * scale * 1.2 * Math.SQRT1_2;
+
+ const geom = instancedQuad(count, 1, 1, radius * 1.02);
+ geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(pos, 3));
+ geom.setAttribute('aMote', new THREE.InstancedBufferAttribute(mote, 4));
+ geom.setAttribute('aSwing', new THREE.InstancedBufferAttribute(swing, 4));
+
+ const mesh = new THREE.Mesh(geom, moteMaterial({
+ color, size, settle, wob, height,
+ }));
+ mesh.name = 'DustMotes';
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = 'Motes';
+ g.add(mesh);
+ keepOutOfDepthPasses(g);
+ // No fog tint for dust: motes are LIT matter close to the camera,
+ // not haze at distance, and the colour is the caller's statement
+ // about the light they hang in.
+ _litByScene(mesh, null);
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.volume = { extent, height };
+ g.userData.sample = (i, t) => {
+ const k = Math.min(count - 1, Math.max(0, i | 0));
+ const y = pos[k * 3 + 1] - settle * t;
+ return new THREE.Vector3(
+ pos[k * 3] + wob * _wobX(swing[k * 4], swing[k * 4 + 1], t),
+ y - Math.floor(y / height) * height,
+ pos[k * 3 + 2] + wob * _wobZ(swing[k * 4 + 2],
+ swing[k * 4 + 3], t));
+ };
+ return g;
+}
+
+/** Near-still specks that flash as their faces come round. */
+function moteMaterial(cfg) {
+ return makeShaderMaterial({
+ name: 'DustMotes',
+ uniforms: {
+ uTime: { value: 0 },
+ uColor: { value: cfg.color },
+ uLight: { value: new THREE.Color(1, 1, 1) },
+ uAlpha: { value: 0.95 },
+ uSize: { value: cfg.size },
+ uSettle: { value: cfg.settle },
+ uWob: { value: cfg.wob },
+ uHeight: { value: cfg.height },
+ uSpin: { value: 1.6 },
+ },
+ varyings: 'varying vec2 vUv; varying float vBright;'
+ + ' varying float vTw; varying float vFade;'
+ + ' varying float vHue;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec3 aPos;'
+ + ' uniform float uTime;'
+ + ' attribute vec4 aMote; attribute vec4 aSwing;'
+ + ' uniform float uSize; uniform float uSettle;'
+ + ' uniform float uWob; uniform float uHeight;'
+ + ' uniform float uSpin;\n' + _WOB_GLSL,
+ vertexMain: [
+ ' vUv = uv;',
+ ' vBright = aMote.w;',
+ // Dust is not white. A shaft holds grain, pollen, ash and
+ // fibre at once, and their spread runs ochre to cool grey —
+ // one flat tint is the tell that this is a particle system.
+ ' vHue = astraHash11(aMote.z * 4.7 + aMote.y) * 2.0 - 1.0;',
+ ' float y = mod(aPos.y - uSettle * uTime, uHeight);',
+ ' vec3 p = vec3(',
+ ' aPos.x + uWob * astraVeilWobX(aSwing.x, aSwing.y, uTime),',
+ ' y,',
+ ' aPos.z + uWob * astraVeilWobZ(aSwing.z, aSwing.w,',
+ ' uTime));',
+ // A mote is a flake with faces: it flashes when one comes
+ // round to the light and all but vanishes edge-on.
+ ' vTw = pow(abs(sin(uTime * uSpin * aMote.y + aMote.z)), 5.0);',
+ ' float s = uSize * aMote.x * (0.45 + 0.75 * vTw);',
+ ' vec3 camR = vec3(viewMatrix[0][0], viewMatrix[1][0],',
+ ' viewMatrix[2][0]);',
+ ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',
+ ' viewMatrix[2][1]);',
+ ' transformed = p + camR * (aCorner.x * s)',
+ ' + camU * (aCorner.y * s);',
+ ' float vy = y / uHeight;',
+ ' vFade = smoothstep(0.0, 0.06, vy)',
+ ' * (1.0 - smoothstep(0.90, 1.0, vy));',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform vec3 uLight;'
+ + ' uniform float uAlpha;',
+ fragmentMain: [
+ ' float d = length(vUv - 0.5) * 2.0;',
+ ' if (d > 1.0) discard;',
+ // A bright centre inside a wide soft skirt, not a disc with
+ // an edge: a speck at this size is a point spread, and a
+ // hard rim is what makes a field of them read as a dot
+ // screen printed on the lens.
+ ' float core = (1.0 - smoothstep(0.16, 1.0, d))',
+ ' * (0.55 + 0.45 * (1.0 - smoothstep(0.0, 0.42, d)));',
+ ' float a = uAlpha * vBright * vFade * core',
+ ' * (0.18 + 0.82 * vTw);',
+ ' a += (astraHash21(gl_FragCoord.xy) - 0.5) * 0.006;',
+ ' if (a < 0.004) discard;',
+ ' vec3 c = uColor * (1.0 + vHue * vec3(0.10, 0.015, -0.14));',
+ ' gl_FragColor = vec4(c * uLight * (0.78 + 0.44 * vTw),',
+ ' clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/water.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/water.js
new file mode 100644
index 00000000..f1f9b9ff
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/water.js
@@ -0,0 +1,407 @@
+/**
+ * Reflective water plane: the addon Water shader with a procedural
+ * wave-normal map (npm three ships no waternormals.jpg, so
+ * `makeWaterNormals()` synthesizes a deterministic tiling one).
+ * Every Water instance re-renders the WHOLE scene per frame:
+ * contract is ONE water plane, never alongside a Reflector floor.
+ * Stills freeze `uniforms.time`; animate via `mesh.userData.update(t)`.
+ *
+ * The addon's fragment shader is REGRADED here (see `_regrade`): its
+ * stock look is a 30%-reflective milk with a flat +0.1 veil, which on
+ * our pipeline (ACES, exposure 1.0, no post chain) renders a pool as
+ * pale plastic — measured 2026-09-01, a still pool read mean_lum 0.73
+ * at BOTH a steep and a grazing view, i.e. no Fresnel at all. Pass
+ * `legacyShader: true` to get the addon's own tail back.
+ */
+
+import * as THREE from 'three';
+import { Water } from 'three/addons/objects/Water.js';
+
+// Battery-graded freeze point: mid-phase, waves clearly formed.
+const FROZEN_TIME = 7.3;
+
+// Default sun matches the day rig in lib/environment.js (azimuth 35,
+// elevation 48, same axis convention), so a scene that forgot to pass
+// sunDir still gets specular broadly agreeing with the shipped light.
+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 _oceans = 0;
+
+/**
+ * Synthesize the tiling wave-normal DataTexture the Water shader
+ * needs (npm three ships no waternormals.jpg). A sum of integer-
+ * frequency sines guarantees a seamless wrap; finite differences at
+ * strength 2.2 turn the heightfield into tangent-space normals.
+ *
+ * @param {number} [size] Texture width and height in px (default 256).
+ * @returns {THREE.DataTexture} RGBA, RepeatWrapping, needsUpdate set.
+ */
+export function makeWaterNormals(size = 256, opts = {}) {
+ // Tiling heightfield: sum of integer-frequency sines.
+ const h = new Float32Array(size * size);
+ // Eight pure tones read as CORDUROY at a grazing angle — it is
+ // the periodicity of the SET that shows, not any one wave. The
+ // broadband set spreads 28 directions at 1/f^2 and kills it, at
+ // the cost of a calmer surface; only wide water needs it.
+ const waves = opts.broadband ? [
+ [1, 1, 1.3000, 5.34], [0, -5, 0.1040, 3.33],
+ [1, -1, 1.3000, 3.01], [4, -1, 0.1529, 4.21],
+ [2, -4, 0.1300, 1.12], [-3, -1, 0.2600, 2.37],
+ [1, -5, 0.1000, 3.75], [4, 4, 0.0812, 4.83],
+ [-2, 2, 0.3250, 1.58], [-6, 3, 0.0578, 6.14],
+ [-3, -5, 0.0765, 4.67], [-2, 1, 0.5200, 3.62],
+ [4, -5, 0.0634, 5.34], [-6, -6, 0.0361, 5.28],
+ [-3, 0, 0.2889, 4.61], [-5, 2, 0.0897, 0.28],
+ [-1, 2, 0.5200, 6.18], [-1, 0, 2.6000, 2.22],
+ [-1, 3, 0.2600, 1.89], [1, -2, 0.5200, 5.29],
+ [-4, -5, 0.0634, 3.96], [2, -5, 0.0897, 2.32],
+ [-2, 6, 0.0650, 5.36], [2, -1, 0.5200, 5.77],
+ [-2, 0, 0.6500, 0.05], [5, -3, 0.0765, 2.56],
+ [-5, -5, 0.0520, 4.68], [1, 0, 2.6000, 0.65]
+ ] : [
+ [3, 1, 1.0, 0.0], [5, 2, 0.7, 1.3], [2, 4, 0.55, 2.1],
+ [7, 3, 0.4, 4.2], [4, 6, 0.35, 0.7], [9, 5, 0.25, 3.3],
+ [11, 8, 0.18, 5.1], [6, 10, 0.15, 2.6],
+ ];
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const u = (x / size) * Math.PI * 2;
+ const v = (y / size) * Math.PI * 2;
+ let s = 0;
+ for (const [fx, fy, a, p] of waves) {
+ s += a * Math.sin(fx * u + fy * v + p);
+ }
+ h[y * size + x] = s;
+ }
+ }
+ // Finite-difference normals -> RGB.
+ const data = new Uint8Array(size * size * 4);
+ const amp = 2.2; // normal strength (the battery-graded value)
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const xm = (x - 1 + size) % size, xp = (x + 1) % size;
+ const ym = (y - 1 + size) % size, yp = (y + 1) % size;
+ const dx = (h[y * size + xp] - h[y * size + xm]) * amp;
+ const dy = (h[yp * size + x] - h[ym * size + x]) * amp;
+ const inv = 1 / Math.hypot(dx, dy, 1);
+ const i = (y * size + x) * 4;
+ data[i] = (-dx * inv * 0.5 + 0.5) * 255;
+ data[i + 1] = (-dy * inv * 0.5 + 0.5) * 255;
+ data[i + 2] = (inv * 0.5 + 0.5) * 255;
+ data[i + 3] = 255;
+ }
+ }
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ // DataTexture defaults to NearestFilter with no mipmaps, which prints
+ // a fine dither over water seen from any distance. Only visible once
+ // the wave size stopped moireing over the top of it.
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true;
+ tex.anisotropy = 16;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+// The regraded tail of the addon's fragment shader, spliced in over the
+// range `vec2 distortion = ...` .. `gl_FragColor = ...` (see `_regrade`).
+const _TAIL = /* glsl */`
+ // ---- 3dcv regrade ------------------------------------------------
+ // The addon scales its screen-space reflection offset by 1/distance
+ // with no ceiling, so water 3 m from the eye samples the mirror ONE
+ // FULL FRAME away (0.33 * distortionScale) and prints slivers of sky
+ // through the near surface. Cap the offset at the value the far half
+ // already uses; beyond ~1/maxDistort metres nothing changes at all.
+ vec2 distortion = surfaceNormal.xz
+ * min( maxDistort, 0.001 + 1.0 / distance ) * distortionScale;
+ vec3 reflectionSample = vec3( texture2D( mirrorSampler,
+ mirrorCoord.xy / mirrorCoord.w + distortion ) );
+
+ // Fresnel: the addon hardcodes rf0 = 0.3, so its water is 30%
+ // mirror even looked straight down into — the single reason a stock
+ // Water pool reads as pale milk. Dielectric water is F0 = 0.02 and
+ // only turns mirror at grazing, which is what gives a body of water
+ // its dark near half and bright far half.
+ float theta = max( dot( eyeDirection, surfaceNormal ), 0.0 );
+ float reflectance = rf0 + ( 1.0 - rf0 ) * pow( 1.0 - theta, 5.0 );
+
+ // A body colour with a HUE FIELD, not one flat value: a slow read of
+ // the same wave map drifts the mix between the deep tone and a
+ // shallower, greener one. The period is turbScale METRES (set from
+ // the plane's extent), not a constant — pinned to one, a pond samples
+ // a single texel of the field and the whole basin comes out one
+ // colour, which is the flatness this term exists to break.
+ vec3 turbSample = texture2D( normalSampler,
+ worldPosition.xz / turbScale
+ + vec2( time / 190.0, time / 230.0 ) ).rgb;
+ float turbid = clamp( 0.5 + ( turbSample.x - 0.5 ) * 1.3, 0.0, 1.0 );
+ float wMag = max( max( waterColor.r, waterColor.g ), waterColor.b );
+ // The deep tone gets a dark NEUTRAL floor. The graded 0x0e3f5c has a
+ // red channel of 0.0045 linear — 4% of its blue — and a body with one
+ // dead channel reads electric rather than deep (measured at night:
+ // mean RGB 0.034/0.140/0.276, saturation 0.85). Real water always
+ // carries some neutral scatter, and the floor is still under the
+ // 0.02 the aesthetic brief calls the bottom of a sane albedo.
+ vec3 body = mix( max( waterColor * 0.62, vec3( 0.015, 0.022, 0.030 ) ),
+ waterColor * 1.9 + vec3( 0.05, 0.30, 0.16 ) * wMag, turbid );
+
+ // Lit as the dielectric it is: sky ambient so water in shadow is
+ // never black, plus the key light's real irradiance, shadowed by the
+ // scene. Both come from the scene itself (see makeOcean's sniff).
+ float shade = getShadowMask();
+ float lambert = max( dot( sunDirection, surfaceNormal ), 0.0 );
+ vec3 bodyLit = body * ( ambientColor + keyColor * lambert * shade );
+ // Backlit crests glow — the one cue that reads as TRANSLUCENT, and
+ // it only fires when the eye is looking into the key light.
+ float back = pow( max( 0.0, dot( eyeDirection, -sunDirection ) ), 3.0 );
+ bodyLit += body * keyColor * back * 0.55 * shade;
+
+ // Glitter is ADDITIVE. The addon gates its whole specular behind
+ // the mirror sample, so a sun track can only appear where the
+ // mirror was already bright — i.e. never on dark water, which is
+ // exactly where a sun track is the brightest thing in a frame.
+ // Two lobes: a tight glint on the crests, a broad sheen holding them
+ // together. Peak ~2.6, inside the 1.5-4 a bloom pass takes cleanly.
+ vec3 sunReflect = normalize( reflect( -sunDirection, surfaceNormal ) );
+ float glint = max( 0.0, dot( eyeDirection, sunReflect ) );
+ vec3 glitter = sunColor * glitterScale * shade
+ * ( 0.3 + 0.7 * reflectance )
+ * ( pow( glint, 420.0 ) * 2.6 + pow( glint, 28.0 ) * 0.22 );
+
+ vec3 outgoingLight =
+ mix( bodyLit, reflectionSample, reflectance ) + glitter;
+ // A mirror this smooth bands in 8 bits; a sub-LSB of hash noise in
+ // linear costs one mad and removes it.
+ float dth = fract( sin( dot( gl_FragCoord.xy,
+ vec2( 12.9898, 78.233 ) ) ) * 43758.5453 );
+ outgoingLight += ( dth - 0.5 ) * 0.0022;
+ gl_FragColor = vec4( outgoingLight, alpha );`;
+
+/**
+ * Splice `_TAIL` over the addon shader's own shading tail and declare the
+ * uniforms it adds. Version-tolerant: if either anchor is missing (a
+ * three release rewrote Water.js) the material is left exactly as the
+ * addon built it and the caller gets a warning, never a broken shader.
+ *
+ * @param {THREE.ShaderMaterial} material The Water material.
+ * @returns {boolean} true when the regrade was applied.
+ */
+function _regrade(material) {
+ const src = material.fragmentShader;
+ const END = 'gl_FragColor = vec4( outgoingLight, alpha );';
+ const a = src.indexOf('vec2 distortion =');
+ const b = src.indexOf(END);
+ if (a < 0 || b < 0 || b < a) {
+ console.warn(
+ 'makeOcean: this three build\'s Water shader does not carry the '
+ + 'anchors the 3dcv regrade splices over — shipping the addon '
+ + 'look unchanged (pale, no Fresnel).');
+ return false;
+ }
+ material.fragmentShader =
+ src.slice(0, a).replace(
+ 'uniform vec3 waterColor;',
+ 'uniform vec3 waterColor;\n\t\t\t\tuniform vec3 ambientColor;'
+ + '\n\t\t\t\tuniform vec3 keyColor;\n\t\t\t\tuniform float rf0;'
+ + '\n\t\t\t\tuniform float glitterScale;'
+ + '\n\t\t\t\tuniform float maxDistort;'
+ + '\n\t\t\t\tuniform float turbScale;')
+ + _TAIL + src.slice(b + END.length);
+ return true;
+}
+
+/**
+ * Read the scene's own lighting once, at the first render, and point the
+ * water's key light at it. Water is built before the scene exists, so
+ * without this a night pool glitters for a noon sun in a colour nothing
+ * else in the frame is lit by — the failure the aesthetic brief calls
+ * "hardcoded light colours".
+ *
+ * Only uniforms the caller did NOT pin are touched.
+ */
+const _V1 = new THREE.Vector3();
+const _V2 = new THREE.Vector3();
+
+function _readScene(scene, uniforms, pinned) {
+ let key = null, keyLum = -1, hemi = null, amb = null;
+ scene.traverse((o) => {
+ if (!o.visible) return;
+ if (o.isDirectionalLight) {
+ const c = o.color;
+ const l = o.intensity
+ * (c.r * 0.2126 + c.g * 0.7152 + c.b * 0.0722);
+ if (l > keyLum) { keyLum = l; key = o; }
+ } else if (o.isHemisphereLight) {
+ if (!hemi || o.intensity > hemi.intensity) hemi = o;
+ } else if (o.isAmbientLight) {
+ if (!amb || o.intensity > amb.intensity) amb = o;
+ }
+ });
+ // three's Lambert BRDF divides irradiance by PI; the water body is a
+ // Lambert term too, so the same 1/PI is what puts it on the same scale
+ // as every MeshStandardMaterial around it.
+ const INV_PI = 1 / Math.PI;
+ if (key) {
+ uniforms.keyColor.value.copy(key.color)
+ .multiplyScalar(Math.min(6, key.intensity) * INV_PI);
+ if (!pinned.sunColor) {
+ // HUE only: the glitter lobes are graded artistic values (a sun
+ // disc we do not model), so they must not be scaled by whatever
+ // watts the rig runs at — only tinted by its colour.
+ const c = key.color;
+ const peak = Math.max(c.r, c.g, c.b, 1e-4);
+ uniforms.sunColor.value.copy(c).multiplyScalar(1 / peak);
+ }
+ if (!pinned.sunDir) {
+ // A directional light aims from its world position at its TARGET,
+ // and a rig that moved the target (a low sun tracked onto a
+ // subject) would otherwise hand the glitter a direction the
+ // shadows do not use. An un-parented target sits at the origin,
+ // which is exactly what `position` alone assumes.
+ const p = _V1.setFromMatrixPosition(key.matrixWorld);
+ const q = key.target
+ ? _V2.setFromMatrixPosition(key.target.matrixWorld)
+ : _V2.set(0, 0, 0);
+ p.sub(q);
+ if (p.lengthSq() > 1e-12) uniforms.sunDirection.value.copy(p).normalize();
+ }
+ }
+ if (!pinned.ambient) {
+ const t = uniforms.ambientColor.value;
+ if (hemi) t.copy(hemi.color).multiplyScalar(hemi.intensity * INV_PI);
+ else if (amb) t.copy(amb.color).multiplyScalar(amb.intensity * INV_PI);
+ else if (scene.fog) t.copy(scene.fog.color).multiplyScalar(0.35);
+ t.r = Math.min(t.r, 1); t.g = Math.min(t.g, 1); t.b = Math.min(t.b, 1);
+ }
+}
+
+/**
+ * Build the scene's ONE reflective water plane (XZ, faces +Y).
+ * Returned mesh is at y = 0; set `position.y` to the water level.
+ * Defaults are graded values — keep them unless the brief says not to.
+ *
+ * @param {number} width X extent in metres.
+ * @param {number} depth Z extent in metres.
+ * @param {object} [opts]
+ * `sunDir` normalized THREE.Vector3 toward the sun — pass the SAME
+ * direction the key light uses so the glitter track agrees with the
+ * shadows (default: the day rig's axis);
+ * `waterColor` hex (default 0x0e3f5c);
+ * `sunColor` hex (default 0xffffff);
+ * `distortionScale` reflection wobble (default 2.8);
+ * `rttSize` reflection render-target px (default 256);
+ * `size` wave-pattern density uniform (default: scaled to the plane);
+ * `waterNormals` texture override (default `makeWaterNormals(256)`);
+ * `fog` fold scene fog into the shader (default true);
+ * `rf0` Fresnel reflectance head-on (default 0.02, real water);
+ * `glitter` sun-track strength, 0 kills it (default 1);
+ * `ambient` hex sky ambient for the water BODY (default: read off the
+ * scene's hemisphere/ambient light, else its fog);
+ * `hdrReflection` half-float mirror target (default true);
+ * `legacyShader` ship the addon's own tail instead (default false).
+ * @returns {THREE.Mesh} The Water mesh, rotated flat, named 'Ocean',
+ * with `userData.update(t)` driving the wave phase for `tick`.
+ */
+export function makeOcean(width, depth, opts = {}) {
+ _oceans++;
+ if (_oceans > 1) {
+ console.warn(
+ 'makeOcean: ' + _oceans + ' oceans in one scene — each one ' +
+ 're-renders the whole scene per frame. Contract is ONE RTT ' +
+ 'surface (one ocean, never alongside a Reflector).');
+ }
+ const sunDir =
+ (opts.sunDir ? opts.sunDir.clone() : _DAY_SUN.clone()).normalize();
+ // 512, not 256: a 256px mirror stretched across half a 1280x720 frame
+ // tears into stair-stepped blocks at grazing angles — 9 confirmed
+ // sightings across the 2026-08-04 gallery audit. Cost is one extra
+ // scene pass at 4x the pixels, still the cheapest thing in the frame.
+ const rtt = opts.rttSize || 512;
+ const _extent = Math.max(width, depth);
+ const water = new Water(new THREE.PlaneGeometry(width, depth), {
+ textureWidth: rtt,
+ textureHeight: rtt,
+ waterNormals: opts.waterNormals
+ || makeWaterNormals(256, { broadband: _extent > 1500 }),
+ sunDirection: sunDir,
+ sunColor: opts.sunColor === undefined ? 0xffffff : opts.sunColor,
+ waterColor:
+ opts.waterColor === undefined ? 0x0e3f5c : opts.waterColor,
+ distortionScale: opts.distortionScale === undefined ?
+ 2.8 : opts.distortionScale,
+ fog: opts.fog === undefined ? true : opts.fog,
+ });
+ water.rotation.x = -Math.PI / 2;
+ water.name = 'Ocean';
+ const uniforms = water.material.uniforms;
+ uniforms.time.value = FROZEN_TIME;
+ // The shader samples the normals at worldPosition.xz * size / 103, so
+ // one wave period is ~103/size metres. Hold that at a twelfth of the
+ // plane and the graded 6 falls out at 200 m while a 2800 m harbor gets
+ // 0.44 — measured as the largest value that does not moire into radial
+ // stripes at grazing angles (0.70 stripes, 1.2 is unusable).
+ //
+ // The law used to be capped at 6, which froze it for anything under
+ // 206 m and gave an 18 m pool ONE wave period across the whole basin —
+ // an ocean swell in a bathtub (measured 2026-09-01: ripple contrast
+ // 1.22 at size 6, 2.51 at 30). The cap is now 30, the largest value
+ // that stays clean at a 1024 px grazing close-up; 68 speckles the far
+ // band into per-pixel sparkle. Big water is untouched.
+ const _autoSize = Math.min(30, 1236 / Math.max(_extent, 1));
+ uniforms.size.value = opts.size === undefined ? _autoSize : opts.size;
+ water.userData.update = (t) => {
+ uniforms.time.value = FROZEN_TIME + t;
+ };
+
+ // ---- the regrade: our pipeline, and the scene's own light ---------
+ if (opts.legacyShader !== true && _regrade(water.material)) {
+ uniforms.rf0 = { value: opts.rf0 === undefined ? 0.02 : opts.rf0 };
+ uniforms.glitterScale =
+ { value: opts.glitter === undefined ? 1 : opts.glitter };
+ uniforms.maxDistort =
+ { value: opts.maxDistort === undefined ? 0.05 : opts.maxDistort };
+ // Two-and-a-bit patches of turbidity across the plane, never finer
+ // than 8 m: any tighter and the colour field starts competing with
+ // the waves instead of sitting under them.
+ uniforms.turbScale = { value: Math.max(8, _extent / 2.5) };
+ uniforms.keyColor = { value: new THREE.Color(1, 1, 1) };
+ // Fallback ambient ≈ the day rig's hemisphere at 1/PI, used only
+ // until `_readScene` finds the scene's real one on the first frame.
+ uniforms.ambientColor = {
+ value: opts.ambient === undefined
+ ? new THREE.Color(0.149, 0.215, 0.364)
+ : new THREE.Color(opts.ambient),
+ };
+ const pinned = {
+ sunColor: opts.sunColor !== undefined,
+ sunDir: opts.sunDir !== undefined,
+ ambient: opts.ambient !== undefined,
+ };
+ const base = water.onBeforeRender;
+ let first = true;
+ water.onBeforeRender = function (renderer, scene, camera) {
+ if (first) {
+ first = false;
+ _readScene(scene, uniforms, pinned);
+ // The mirror target is 8-bit LINEAR (three disables tone mapping
+ // and sRGB encoding when rendering to a non-sRGB target), so the
+ // bottom of its range quantises to a handful of steps: a night
+ // sky at ~0.002 linear reflects as two flat bands. Half-float
+ // costs 2 bytes a texel on ONE 512px target and removes it.
+ const mirror = uniforms.mirrorSampler.value;
+ if (opts.hdrReflection !== false
+ && (renderer.extensions.has('EXT_color_buffer_float')
+ || renderer.extensions.has('EXT_color_buffer_half_float'))) {
+ mirror.type = THREE.HalfFloatType;
+ }
+ }
+ base.call(this, renderer, scene, camera);
+ };
+ }
+ return water;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.js
new file mode 100644
index 00000000..bf9bb52f
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/waterfall.js
@@ -0,0 +1,568 @@
+/**
+ * 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.js
new file mode 100644
index 00000000..322f1b2e
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/watermist.js
@@ -0,0 +1,613 @@
+/**
+ * The air over moving water, and the droplets moving water throws.
+ *
+ * `makeWaterMist` is the veil that hangs over a river, a weir or a
+ * wake: thickest in the first hand's breadth above the surface, gone by
+ * a couple of metres, streaked ALONG the flow and scrolling downstream
+ * with it. `atmosphere.js` `makeHeightFog` is the same height profile
+ * in STILL air — evenly blotched, barely moving — and the two must not
+ * read alike, so everything here that costs anything goes into the
+ * motion: the streaks lie down the current, and the top of the bank
+ * runs ahead of its foot.
+ *
+ * `makeSpray` is the other half a wake or a waterfall foot needs and
+ * neither has today: the droplets thrown UP where water strikes, each
+ * on its own ballistic arc, stretched along its own motion so it reads
+ * as fast, and fading as it falls back.
+ *
+ * BLENDING — both are pale, both can appear in daylight, so both use
+ * ORDINARY blending. `makeShaderMaterial({ additive: true })` is for
+ * light that ADDS, and `godrays.js` measures what added light does to a
+ * bright frame: 12.8% of it blown past 0.97, and cutting the gain 3.6x
+ * still left 11.3%, because 0.94 plus anything visible clips. Mist does
+ * the opposite of adding — it SCATTERS, lowering the contrast behind
+ * it — and a droplet is an object, not a light.
+ *
+ * The mist is a field of soft cards, and the whole difficulty is that
+ * no card may be visible. Three things do that, and dropping any one
+ * of them puts the cards back in the frame. The structure a fragment
+ * shows comes from ONE noise field read at the fragment's own
+ * position, so overlapping cards agree and their sum along a view ray
+ * is a crude volume integral. Every card faces the camera squarely and
+ * is no wider than the bank is deep, so a ray crossing the bank meets
+ * a dozen of them rather than one — one card per pixel paints its own
+ * noise raw, and that ribbon IS the card. And their heights are packed
+ * 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.
+ */
+
+import * as THREE from 'three';
+
+import { instancedQuad, makeShaderMaterial, tickShaders, keepOutOfDepthPasses } from './shader.js';
+
+// Free fall. It is written twice on purpose — in the vertex shader and
+// in the CPU mirror `userData.sample` — so both read this one number.
+const _G = 9.81;
+
+/** 16807 LCG: same seed, same field, on every machine. */
+function prng(seed) {
+ let s = (seed >>> 0) || 1;
+ return () => ((s = (s * 16807) % 2147483647) / 2147483647);
+}
+
+/** A THREE.Vector3 from a vector, an [x,y,z] array or nothing. */
+function toVec3(v) {
+ if (Array.isArray(v)) {
+ return new THREE.Vector3(v[0] || 0, v[1] || 0, v[2] || 0);
+ }
+ if (v && v.isVector3) return v.clone();
+ return new THREE.Vector3();
+}
+
+/**
+ * The key light as a direction plus how much of it there is.
+ *
+ * Mist and spray are LIT things, not coloured ones: what they show is
+ * an albedo times what reaches them. The sun below the horizon delivers
+ * nothing, so the gain goes to zero there and the skylight term (the
+ * scene's own fog colour) is all that is left — which is what turns
+ * both of these dark at night without the caller saying so.
+ *
+ * @param {*} v A THREE.Vector3, an [x,y,z], or nothing.
+ * @returns {{dir: THREE.Vector3, gain: number}} Unit direction TOWARD
+ * the sun (default straight up, the neutral top-lit read for a
+ * caller with no rig to hand) and 0..1 for how far it has risen.
+ */
+function toSun(v) {
+ const d = toVec3(v);
+ if (d.lengthSq() < 1e-8) return { dir: new THREE.Vector3(0, 1, 0), gain: 1 };
+ d.normalize();
+ // 0 at the horizon, full by ten degrees up: the last of the sun
+ // reddens and dims the scene's own lights long before this matters.
+ const gain = Math.min(1, Math.max(0, (d.y - 0.005) / 0.175));
+ return { dir: d, gain };
+}
+
+/** Downstream velocity as a unit direction in xz plus a speed. */
+function toFlow(v) {
+ let x = 0.45;
+ let z = 0;
+ if (typeof v === 'number') {
+ x = v;
+ } else if (Array.isArray(v)) {
+ x = v[0] || 0;
+ z = (v.length > 2 ? v[2] : v[1]) || 0;
+ } else if (v && (v.isVector3 || v.isVector2)) {
+ x = v.x;
+ z = v.isVector3 ? v.z : v.y;
+ }
+ const speed = Math.hypot(x, z);
+ if (speed < 1e-5) return { dir: new THREE.Vector2(1, 0), speed: 0 };
+ return { dir: new THREE.Vector2(x / speed, z / speed), speed };
+}
+
+/**
+ * The mist that hangs over moving water — air, not a stack of cards.
+ *
+ * Density falls with height ABOVE THE WATER, not with camera distance,
+ * so a hull sits in it and a bank above it does not. Every card is
+ * faint; the per-card alpha is solved from how many of them a
+ * horizontal ray crosses, so `density` means the same thickness
+ * whatever `extent` and `height` make of the card count.
+ *
+ * @param {object} [opts]
+ * `extent` metres square the bank covers (default 14; full strength
+ * right across it and gone by its corners, so it draws no boundary
+ * of its own); `height` metres at which the mist is gone (default 2
+ * — mist over water is a low thing, and a tall one reads as
+ * weather); `density` how thick the bank is, 0 to 1 (default 0.5 a
+ * clear haze; 0.9 hides the far bank);
+ * `color` the medium's ALBEDO, THREE.Color or hex (default a pale
+ * blue-grey) — it is multiplied by the light that reaches the bank,
+ * never emitted, so keep it near white and let the scene colour it;
+ * `sunDir` THREE.Vector3 or [x,y,z] TOWARD the key light, from
+ * `sunRig().sunDir` (default +Y, top lit) — the bank scatters it
+ * FORWARD, so it burns looking into the sun and greys looking away,
+ * and it delivers nothing once the sun is down;
+ * `sunColor` THREE.Color or hex for that light (default a warm
+ * white); `drift` downstream velocity in m/s, a number (along +x), [dx, dz],
+ * [dx, dy, dz] or a THREE.Vector2/3 (default [0.45, 0]) — it sets
+ * both the direction the streaks lie in and how fast they travel;
+ * `heightAt` (x, z) => y water surface height, so the bank follows a
+ * sloping reach; `seed` PRNG seed (default 5).
+ * @returns {THREE.Group} Named `WaterMist`, its foot on y = 0 (or on
+ * `heightAt`), with `userData.tick(t)` driving the drift. Move the
+ * group to move the bank.
+ */
+export function makeWaterMist(opts = {}) {
+ const extent = Math.max(1, opts.extent === undefined ? 14 : opts.extent);
+ const top = Math.max(0.2, opts.height === undefined ? 2 : opts.height);
+ const density = Math.min(0.97, Math.max(0,
+ opts.density === undefined ? 0.5 : opts.density));
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xdfeaf2 : opts.color);
+ const sun = toSun(opts.sunDir);
+ const sunColor = new THREE.Color(
+ opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);
+ const flow = toFlow(opts.drift);
+ const heightAt = opts.heightAt || null;
+ const rnd = prng(opts.seed === undefined ? 5 : opts.seed);
+
+ // Cards no wider than the bank is deep. A ray that crosses the
+ // bank must meet SEVERAL of them or the one it meets paints its
+ // own noise raw, and a single card's pattern is a visible ribbon.
+ const cardW = Math.min(extent * 0.25,
+ Math.max(1, top * 1.1, extent / 22));
+ const cardH = top * 1.1;
+ const count = Math.round(Math.min(1200, Math.max(24,
+ 14 * (extent * extent) / (cardW * cardW))));
+ // Cards a horizontal ray crosses. Solving the per-card alpha from
+ // it keeps `density` the thickness of the BANK at any card count,
+ // and the constant pays back what the height profile, the wisps and
+ // the card envelope take. It rose from 9 to 16 when the card
+ // envelope was softened to kill the striping — a softer envelope
+ // spends more of every card, and `density` has to go on meaning the
+ // same thickness. Measured on the weir showcase against a
+ // mist-free control: the bank's own contribution over the wall came
+ // back to 5.3/255 where the hard-edged 9 gave 5.9.
+ const hits = Math.max(1, (count * cardW) / extent);
+ const alpha = Math.min(0.60, Math.max(0.004,
+ 16.0 * (1 - Math.pow(1 - density, 1 / hits))));
+ // Wisps scale with the bank's own height, not with the reach: a
+ // pattern stretched to the extent reads as one printed backdrop.
+ const wisp = Math.min(Math.max(top * 1.2, 0.8), extent * 0.28);
+
+ const puff = new Float32Array(count * 4);
+ const card = new Float32Array(count * 2);
+ const cols = Math.ceil(Math.sqrt(count));
+ let radius = 0;
+ for (let i = 0; i < count; i++) {
+ // A jittered grid, never a uniform draw: the clumps and holes a
+ // uniform draw leaves read as separate clouds, not one bank.
+ const gx = ((i % cols) + 0.5) / cols - 0.5;
+ const gz = (Math.floor(i / cols) + 0.5) / cols - 0.5;
+ const x = (gx + (rnd() - 0.5) / cols) * extent;
+ const z = (gz + (rnd() - 0.5) / cols) * extent;
+ const base = heightAt ? heightAt(x, z) : 0;
+ // Heights PACKED toward the water, because that is where the
+ // mist is: cards all at one height leave a view from above
+ // integrating a single slice of the profile.
+ const mid = base + top * 1.05 * Math.pow(rnd(), 1.6);
+ const s = 0.70 + 0.75 * rnd();
+ puff[i * 4] = x;
+ puff[i * 4 + 1] = z;
+ puff[i * 4 + 2] = base;
+ puff[i * 4 + 3] = mid;
+ card[i * 2] = s;
+ card[i * 2 + 1] = 0.80 + 0.5 * rnd();
+ radius = Math.max(radius, Math.hypot(x, mid, z)
+ + 0.5 * Math.hypot(cardW * s, cardH * card[i * 2 + 1]));
+ }
+ // position stays at zero for the AO pass, so the sphere is the only
+ // thing three can cull the field by; the margin covers the float32
+ // the attributes are read back at.
+ const geom = instancedQuad(count, 1, 1, radius * 1.02);
+ geom.setAttribute('aPuff', new THREE.InstancedBufferAttribute(puff, 4));
+ geom.setAttribute('aCard', new THREE.InstancedBufferAttribute(card, 2));
+
+ const mesh = new THREE.Mesh(geom, mistMaterial({
+ color, alpha, top, extent, flow, cardW, cardH, wisp,
+ sun, sunColor, hits,
+ offset: new THREE.Vector2(rnd() * 96, rnd() * 96),
+ }));
+ mesh.name = 'MistCards';
+ mesh.renderOrder = 2;
+ const g = new THREE.Group();
+ g.name = 'WaterMist';
+ g.add(mesh);
+ g.userData.tick = (t) => tickShaders(g, t);
+ return keepOutOfDepthPasses(g);
+}
+
+/** Camera-facing cards, all reading one scrolling field of air. */
+function mistMaterial(cfg) {
+ return makeShaderMaterial({
+ name: 'WaterMistCards',
+ uniforms: {
+ // Declared and bound HERE as well as by shader.js, because the
+ // static GLSL audit reads one FILE at a time: the dither line
+ // below carries `gl_FragCoord`, which is what makes the audit
+ // collect the string at all, and it then sees a file that reads
+ // uTime without ever declaring or binding it. godrays.js
+ // carries the same pair for the same reason.
+ uTime: { value: 0 },
+ uColor: { value: cfg.color },
+ uAlpha: { value: cfg.alpha },
+ uTop: { value: cfg.top },
+ // Under half the height is the e-fold, so the first hand's
+ // breadth over the water carries most of the extinction.
+ uScale: { value: cfg.top * 0.45 },
+ uFreq: { value: 1 / cfg.wisp },
+ uFlow: { value: cfg.flow.dir },
+ uSpeed: { value: cfg.flow.speed },
+ uSize: { value: new THREE.Vector2(cfg.cardW, cfg.cardH) },
+ uRadius: { value: cfg.extent * 0.5 },
+ // Metres downstream per metre of height.
+ uShear: { value: cfg.top * 0.9 },
+ uOffset: { value: cfg.offset },
+ uSunDir: { value: cfg.sun.dir },
+ uSunColor: { value: cfg.sunColor },
+ // Skylight is the scene's OWN fog colour, lifted: the fog
+ // is the sky seen through a kilometre of it and the bank is
+ // a metre away, so it arrives brighter than the horizon.
+ uSkyGain: { value: 1.28 },
+ // Forward-scattered sun at its peak, held UNDER the sky
+ // term: a bank that out-runs the sky reads as a lamp.
+ uSunGain: { value: 0.75 * cfg.sun.gain },
+ // Dither, PER CARD. A dozen independent draws of it sum as
+ // a random walk, so the amplitude has to be divided by the
+ // root of the stack depth or the veil comes out visibly
+ // grainy — measured: 0.004 flat put a coarse speckle right
+ // across the bank at 85 cards deep.
+ uDither: { value: 0.010 / Math.sqrt(Math.max(1, cfg.hits)) },
+ },
+ varyings: 'varying vec2 vUv; varying vec3 vP;'
+ + ' varying float vBase;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec4 aPuff;'
+ + ' attribute vec2 aCard; uniform vec2 uSize;',
+ vertexMain: [
+ ' vUv = uv;',
+ ' vBase = aPuff.z;',
+ // Square on to the camera from every elevation. An upright
+ // card seen from above shows the bank's thin foot as a
+ // ribbon; this one shows it spread across its face.
+ ' vec3 camR = vec3(viewMatrix[0][0], viewMatrix[1][0],',
+ ' viewMatrix[2][0]);',
+ ' vec3 camU = vec3(viewMatrix[0][1], viewMatrix[1][1],',
+ ' viewMatrix[2][1]);',
+ ' vec3 mid = vec3(aPuff.x, aPuff.w, aPuff.y);',
+ ' transformed = mid + camR * (aCorner.x * uSize.x * aCard.x)',
+ ' + camU * (aCorner.y * uSize.y * aCard.y);',
+ ' vP = transformed;',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform float uAlpha;'
+ + ' uniform float uTop; uniform float uScale;'
+ + ' uniform float uFreq; uniform vec2 uFlow;'
+ + ' uniform float uSpeed; uniform float uRadius;'
+ + ' uniform vec2 uOffset; uniform float uShear;'
+ + ' uniform vec3 uSunDir; uniform vec3 uSunColor;'
+ + ' uniform float uSkyGain; uniform float uSunGain;'
+ + ' uniform float uDither; uniform float uTime;',
+ fragmentMain: [
+ // Height above THIS card's water, so a sloping reach keeps
+ // its own surface, and zero before either card edge.
+ ' float h = vP.y - vBase;',
+ // Both axes: the height profile cannot fade a card the
+ // camera is looking down on, and its rim would be an edge.
+ // The VERTICAL fade starts almost at the middle: a camera
+ // near the top of the bank sees the cards' upper rims
+ // near edge-on and a late fade lands them all in one screen
+ // band, which is the horizontal striping a night frame
+ // showed across the whole veil.
+ ' vec2 e = abs(vUv * 2.0 - 1.0);',
+ ' float env = (1.0 - smoothstep(0.30, 1.0, e.x))',
+ ' * (1.0 - smoothstep(0.16, 1.0, e.y));',
+ // The profile at its thickest (lift = 1) bounds this
+ // fragment, so everything outside the bank leaves before
+ // paying for three noise fields — and the cards are stacked
+ // a dozen deep, which is most of what this effect costs.
+ ' float cap = uAlpha * env * exp(-h / uScale)',
+ ' * (1.0 - smoothstep(uTop * 0.35, uTop, h))',
+ ' * smoothstep(-uTop * 0.22, -uTop * 0.02, h);',
+ ' if (cap < 0.002) discard;',
+ ' float along = dot(vP.xz, uFlow) - uTime * uSpeed;',
+ ' float across = dot(vP.xz, vec2(-uFlow.y, uFlow.x));',
+ // Compressed along the current, so the wisps lie DOWN it
+ // instead of blotching like still air.
+ ' vec2 q0 = vec2(along * 0.70, across) * uFreq + uOffset;',
+ // How deep the bank is HERE, read at the surface: a
+ // constant top is a lid, and a lid is what reads as a slab.
+ // TWO scales, and the coarse one carries most of the swing.
+ // A ray crosses a dozen cards spread over metres of xz, so
+ // the integral averages any pattern shorter than the ray
+ // away to its mean — the wisp scale survives inside one
+ // card and vanishes from the sum, which is exactly how the
+ // first render came out with a flat top and no tongues.
+ // Only structure metres across lives through the integral.
+ ' float coarse = astraFbm2(q0 * 0.30 + vec2(11.3, 4.7), 2);',
+ ' float lift = 0.20 + 0.42 * astraFbm2(q0, 3) + 0.62 * coarse;',
+ ' float prof = exp(-h / (uScale * lift))',
+ ' * (1.0 - smoothstep(uTop * lift * 0.35, uTop * lift, h))',
+ ' * smoothstep(-uTop * 0.22, -uTop * 0.02, h);',
+ // Higher air has been carried further downstream. Without
+ // this shear a card paints one column of the xz field over
+ // its whole height, and the field reads as flat ribbons.
+ ' vec2 q = q0 + vec2(h * uShear * uFreq, 0.0);',
+ ' float n = astraFbm2(q, 4);',
+ ' float sh = -uTime * uSpeed * uFreq * 0.55;',
+ ' float n2 = astraFbm2(q * 2.6 + vec2(sh, h * 0.5), 3);',
+ ' float wisp = smoothstep(0.12, 0.80, mix(n, n2, 0.32));',
+ // Full strength across the whole square and gone by its
+ // corners: an inscribed fade leaves mist on a third of the
+ // reach the caller asked for.
+ ' float edge = 1.0 - smoothstep(1.0, 1.42,',
+ ' length(vP.xz) / uRadius);',
+ ' float a = uAlpha * prof * wisp * env * edge;',
+ // A ramp this smooth across this many pixels bands in 8
+ // bits, and a dozen cards stack the SAME ramp, so the steps
+ // land on top of each other instead of dissolving. Under
+ // half a code value, per pixel, moving.
+ ' a += (astraHash21(gl_FragCoord.xy + vec2(uTime * 60.0))',
+ ' - 0.5) * uDither;',
+ ' if (a < 0.002) discard;',
+ // LIGHT, not paint. What a scattering medium shows is its
+ // albedo times what reaches it, so `uColor` is multiplied
+ // by the scene's own light and never emitted: `fogColor` IS
+ // the skylight at ground level, and reading it is what
+ // makes this bank pale at noon and a dim blue-grey at
+ // night with nothing said by the caller. (It exists only
+ // when the scene has fog — hence the guard, and the white
+ // fallback that leaves a fogless scene looking as before.)
+ ' vec3 sky = vec3(1.0);',
+ ' #ifdef USE_FOG',
+ ' sky = fogColor;',
+ ' #endif',
+ // Forward scattering, as the Henyey-Greenstein lobe rather
+ // than a power of the cosine. Water droplets throw light ON
+ // rather than back, so a bank between the camera and the
+ // sun burns and the same bank with the sun behind is grey —
+ // the one read that separates mist from a grey card. The
+ // lobe matters because it is BROAD: `pow(mu, 3)` only fires
+ // within about 30 degrees of the sun, and the flip test
+ // below moved the veil 2% between mu = +0.64 and mu = -0.85,
+ // which is no coupling at all at the angles a camera
+ // actually stands at. Normalised so side-scatter (mu = 0)
+ // reads 0.20, the value the power form had as its floor.
+ ' vec3 V = normalize(vP - cameraPosition);',
+ ' float mu = dot(V, uSunDir);',
+ ' float den = 1.3025 - 1.10 * mu;',
+ ' float hg = clamp(0.2929 / max(pow(den, 1.5), 1e-3),',
+ ' 0.14, 2.0);',
+ // The foot of a bank stands in the shade of the bank above
+ // it, so the sun reaches the top of the profile first.
+ ' float open = mix(0.40, 1.0,',
+ ' smoothstep(0.0, uTop * 0.75, h));',
+ ' vec3 col = uColor * (sky * uSkyGain + uColor * 0.032',
+ ' + uSunColor * (uSunGain * hg * open));',
+ // Never one flat value: cool in the thick of it where only
+ // sky gets in, warm where the sun does, plus a slow break
+ // across the reach so no two tongues are the same grey.
+ ' float warm = clamp(hg * open, 0.0, 1.0);',
+ ' col *= mix(vec3(0.94, 0.98, 1.07), vec3(1.05, 1.00, 0.94),',
+ ' warm);',
+ ' col = astraHueBreak(col, vP.xz, uFreq * 0.5, 0.16);',
+ // One flat colour per fragment keeps the over-blend order
+ // independent, so overlapping cards need no sorting.
+ ' gl_FragColor = vec4(col, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
+
+/**
+ * Droplets thrown UP where water strikes — real arcs, not a puff.
+ *
+ * Every droplet is launched from the impact ring with its own speed and
+ * its own flight time, rises, slows, and falls back under gravity; the
+ * count is solved from `rate` times the longest flight, so the field is
+ * continuous without anyone guessing a particle count. They are
+ * stretched along their own motion in the view plane, because a round
+ * dot at this size reads as snow and the streak is what reads as water.
+ *
+ * @param {object} [opts]
+ * `origin` impact point, THREE.Vector3 or [x,y,z] (default 0,0,0 —
+ * the group is MOVED there, so the droplets stay local);
+ * `radius` metres the impacts are spread over (default 0.7);
+ * `rate` droplets launched per second (default 120);
+ * `speed` launch speed in m/s (default 4.5 — it decides the height:
+ * 4.5 m/s tops out near a metre); `size` droplet diameter in metres
+ * (default 0.055); `color` the droplet's ALBEDO, THREE.Color or hex
+ * (default pale water) — multiplied by the light that reaches it,
+ * never emitted; `sunDir` THREE.Vector3 or [x,y,z] TOWARD the key
+ * light, from `sunRig().sunDir` (default +Y) — a droplet is a lens,
+ * so the sun comes back off it as a hard glint and nothing at all
+ * once the sun is down; `sunColor` for that light (default a warm
+ * white); `seed` PRNG seed (default 3).
+ * @returns {THREE.Group} Named `Spray`, positioned at `origin`, with
+ * `userData.tick(t)` driving it and `userData.sample(i, t)` returning
+ * droplet i's group-local position — the CPU mirror of the ballistics
+ * the vertex shader runs.
+ */
+export function makeSpray(opts = {}) {
+ const origin = toVec3(opts.origin);
+ const radius = Math.max(0.01,
+ opts.radius === undefined ? 0.7 : opts.radius);
+ const rate = Math.max(1, opts.rate === undefined ? 120 : opts.rate);
+ const speed = Math.max(0.4, opts.speed === undefined ? 4.5 : opts.speed);
+ const size = Math.max(0.004,
+ opts.size === undefined ? 0.055 : opts.size);
+ const color = new THREE.Color(
+ opts.color === undefined ? 0xeaf4ff : opts.color);
+ const sun = toSun(opts.sunDir);
+ const sunColor = new THREE.Color(
+ opts.sunColor === undefined ? 0xfff2e0 : opts.sunColor);
+ const rnd = prng(opts.seed === undefined ? 3 : opts.seed);
+
+ // A droplet lives one whole arc, so the field is exactly the launch
+ // rate times the longest flight — no particle count to guess.
+ const count = Math.round(Math.min(900,
+ Math.max(8, (rate * 2 * speed) / _G)));
+ const org = new Float32Array(count * 3);
+ const vel = new Float32Array(count * 3);
+ const ph = new Float32Array(count * 2);
+ let reach = 0;
+ for (let i = 0; i < count; i++) {
+ const a = rnd() * Math.PI * 2;
+ const r = radius * Math.sqrt(rnd());
+ const vy = speed * (0.52 + 0.48 * rnd());
+ // Thrown OUTWARD from where it struck, and far slower sideways
+ // than up: a symmetric cone reads as a fountain, not an impact.
+ const ang = a + (rnd() - 0.5) * 1.1;
+ const vh = speed * (0.10 + 0.38 * rnd());
+ org[i * 3] = Math.cos(a) * r;
+ org[i * 3 + 1] = rnd() * 0.05;
+ org[i * 3 + 2] = Math.sin(a) * r;
+ vel[i * 3] = Math.cos(ang) * vh;
+ vel[i * 3 + 1] = vy;
+ vel[i * 3 + 2] = Math.sin(ang) * vh;
+ ph[i * 2] = rnd();
+ ph[i * 2 + 1] = 0.55 + 0.95 * rnd();
+ const t = (2 * vy) / _G;
+ const far = Math.hypot(org[i * 3] + vel[i * 3] * t,
+ org[i * 3 + 2] + vel[i * 3 + 2] * t);
+ const apex = org[i * 3 + 1] + (vy * vy) / (2 * _G);
+ reach = Math.max(reach,
+ Math.hypot(far, apex) + size * ph[i * 2 + 1] * 1.5);
+ }
+ const geom = instancedQuad(count, 1, 1, reach * 1.02);
+ geom.setAttribute('aOrg', new THREE.InstancedBufferAttribute(org, 3));
+ geom.setAttribute('aVel', new THREE.InstancedBufferAttribute(vel, 3));
+ geom.setAttribute('aPhase', new THREE.InstancedBufferAttribute(ph, 2));
+
+ const mesh = new THREE.Mesh(geom,
+ sprayMaterial(color, size, sun, sunColor));
+ mesh.name = 'SprayDroplets';
+ mesh.renderOrder = 3;
+ const g = new THREE.Group();
+ g.name = 'Spray';
+ g.position.copy(origin);
+ g.add(mesh);
+ g.userData.tick = (t) => tickShaders(g, t);
+ g.userData.sample = (i, t) => {
+ const k = Math.min(count - 1, Math.max(0, i | 0));
+ const vy = vel[k * 3 + 1];
+ const flight = (2 * vy) / _G;
+ const age = ((((ph[k * 2] + t / flight) % 1) + 1) % 1) * flight;
+ return new THREE.Vector3(
+ org[k * 3] + vel[k * 3] * age,
+ org[k * 3 + 1] + vy * age - 0.5 * _G * age * age,
+ org[k * 3 + 2] + vel[k * 3 + 2] * age);
+ };
+ return keepOutOfDepthPasses(g);
+}
+
+/** One arc per droplet, stretched along the way it is going. */
+function sprayMaterial(color, size, sun, sunColor) {
+ return makeShaderMaterial({
+ name: 'SprayDroplets',
+ uniforms: {
+ uColor: { value: color },
+ uAlpha: { value: 0.85 },
+ uSize: { value: size },
+ uG: { value: _G },
+ // Seconds of travel drawn into the streak: a droplet at
+ // launch runs ~2.5x its width, one at the apex is round.
+ uStreak: { value: 0.33 },
+ uSunDir: { value: sun.dir },
+ uSunColor: { value: sunColor },
+ // A droplet is close and sees the whole sky, so it takes
+ // more skylight than the mist does.
+ uSkyGain: { value: 1.5 },
+ // The glint. It peaks near 1.8 in linear — bright enough to
+ // survive a bloom threshold, nowhere near the 20 that turns
+ // a highlight into a white hole.
+ uSunGain: { value: 0.95 * sun.gain },
+ },
+ varyings: 'varying vec2 vUv; varying float vLife;'
+ + ' varying float vGlint; varying float vJit;',
+ vertexHead: 'attribute vec3 aCorner; attribute vec3 aOrg;'
+ + ' attribute vec3 aVel; attribute vec2 aPhase;'
+ + ' uniform float uSize; uniform float uG;'
+ + ' uniform float uStreak; uniform vec3 uSunDir;',
+ vertexMain: [
+ ' vUv = uv;',
+ // Its own flight time, so every droplet relaunches on its
+ // own beat and the field never pulses together.
+ ' float flight = 2.0 * aVel.y / uG;',
+ ' float age = fract(aPhase.x + uTime / flight) * flight;',
+ ' vLife = age / flight;',
+ ' vec3 c = aOrg + vec3(aVel.x, 0.0, aVel.z) * age;',
+ ' c.y += aVel.y * age - 0.5 * uG * age * age;',
+ ' vec3 v = vec3(aVel.x, aVel.y - uG * age, aVel.z);',
+ ' vec3 f = normalize(cameraPosition - c);',
+ ' vec3 d = v - f * dot(v, f);',
+ ' float dl = length(d);',
+ ' vec3 dir = dl > 1e-4 ? d / dl',
+ ' : vec3(viewMatrix[0][1], viewMatrix[1][1],',
+ ' viewMatrix[2][1]);',
+ ' vec3 sid = normalize(cross(f, dir));',
+ ' float w = uSize * aPhase.y;',
+ ' float st = 1.0 + uStreak * length(v);',
+ ' transformed = c + dir * (aCorner.y * w * st)',
+ ' + sid * (aCorner.x * w);',
+ // Per droplet, not per pixel: a sphere this small is one
+ // highlight, and the whole lighting is a function of where
+ // it sits between the camera and the sun.
+ ' vGlint = pow(max(dot(-f, uSunDir), 0.0), 2.0);',
+ // No two the same. aPhase.y already varies the SIZE; this
+ // decorrelates the brightness from it so the big ones are
+ // not also the bright ones.
+ ' vJit = fract(aPhase.y * 7.3 + aPhase.x * 3.1);',
+ ].join('\n'),
+ fragmentHead: 'uniform vec3 uColor; uniform float uAlpha;'
+ + ' uniform vec3 uSunColor; uniform float uSkyGain;'
+ + ' uniform float uSunGain;',
+ fragmentMain: [
+ ' float d = length(vUv - 0.5) * 2.0;',
+ ' if (d > 1.0) discard;',
+ // A solid core with a one-pixel rim: a droplet is water,
+ // not a glow, and a soft blob at this size reads as dust.
+ ' float core = 1.0 - smoothstep(0.45, 1.0, d);',
+ // Thrown clear, then spent: it thins on the way back down
+ // instead of winking out at the end of its arc.
+ ' float rise = smoothstep(0.0, 0.05, vLife);',
+ ' float fall = 1.0 - smoothstep(0.40, 1.0, vLife);',
+ ' float a = uAlpha * core * rise * fall;',
+ ' if (a < 0.004) discard;',
+ // Same law as the mist: albedo times what arrives. The
+ // scene's fog colour is the skylight a droplet swims in, so
+ // the field goes from white in the sun to a dim blue-grey
+ // at night with nothing said by the caller.
+ ' vec3 sky = vec3(1.0);',
+ ' #ifdef USE_FOG',
+ ' sky = fogColor;',
+ ' #endif',
+ // A droplet is a LENS, so the sun leaves it as a hard
+ // glint pointed at the camera rather than a diffuse wash —
+ // and there is always a little skylight in the shade of it.
+ ' vec3 col = uColor * (sky * uSkyGain + uColor * 0.05',
+ ' + uSunColor * uSunGain * (0.28 + 0.72 * vGlint));',
+ ' col *= 0.80 + 0.40 * vJit;',
+ // The rim of a sphere refracts, so it out-runs the body:
+ // this is what keeps it a droplet and not a flat disc.
+ ' col *= 0.88 + 0.30 * core;',
+ ' gl_FragColor = vec4(col, clamp(a, 0.0, 1.0));',
+ ].join('\n'),
+ transparent: true,
+ depthWrite: false,
+ side: THREE.DoubleSide,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/waterside.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/waterside.js
new file mode 100644
index 00000000..a9990c45
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/waterside.js
@@ -0,0 +1,412 @@
+/**
+ * Waterlines: the contact transitions where ground, rock and water meet.
+ *
+ * A bank that meets water at a flat cut reads as two slabs intersecting,
+ * and it is the cheapest realism there is to fix. All three patches here
+ * go through `patchStandard`, so each material keeps its lighting,
+ * shadows, fog and depth chunks, and they CHAIN — a shore ground
+ * normally wears `patchShoreWet` and `patchShoreFoam` at once. Every
+ * tunable is a uniform, so two materials wearing one patch share one
+ * compiled program while keeping their own values.
+ *
+ * They complement `water.js` instead of fighting it: the addon Water is
+ * the scene's ONE RTT surface and its raw ShaderMaterial has no
+ * `<color_fragment>` hook, so `patchShallowWater` belongs on a plain
+ * standard-material reach (a shallow bay, a river) beside it.
+ */
+
+import * as THREE from 'three';
+import { patchStandard, composeRoughness } from './shader.js';
+
+// Named as terrain_shade names them, so a bank wearing a splat and a
+// waterline declares ONE pair (patchStandard dedupes varyings).
+const WORLD_VARYINGS = [
+ 'varying vec3 vAstraWorld;',
+ 'varying vec3 vAstraWorldN;',
+].join('\n');
+
+// One base for all three. `transformed` is still object-space after
+// <begin_vertex>, so the instance transform is folded in by hand or
+// every scattered rock takes its waterline from the world origin.
+const BASE = {
+ name: 'waterside:base',
+ vertexHead: WORLD_VARYINGS,
+ vertexBody: [
+ ' vec4 wsP = vec4(transformed, 1.0);',
+ ' vec3 wsN = normal;',
+ '#ifdef USE_INSTANCING',
+ ' wsP = instanceMatrix * wsP;',
+ ' wsN = mat3(instanceMatrix) * wsN;',
+ '#endif',
+ ' vAstraWorld = (modelMatrix * wsP).xyz;',
+ ' vAstraWorldN = normalize((modelMatrix * vec4(wsN, 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);
+}
+
+/** Clamp to 0..1 without importing MathUtils for one call. */
+function unit(value) {
+ return Math.max(0, Math.min(1, value));
+}
+
+/**
+ * Apply the shared world-space base, then the patch itself.
+ *
+ * `patchStandard` replaces a patch of the SAME name in place, so the
+ * base costs one vertex body however many of these a material wears.
+ */
+function withBase(material, part) {
+ // A raw ShaderMaterial (the addon Water, anything from
+ // makeShaderMaterial) has neither hook, so the patch is a silent
+ // no-op — the one failure mode nothing else here would report.
+ if (material && material.isShaderMaterial) {
+ console.warn(
+ part.name + ': ' + (material.name || 'material') + ' is a raw ' +
+ 'ShaderMaterial with no <color_fragment> hook, so this patch ' +
+ 'does nothing. Patch a standard-material surface instead.');
+ }
+ patchStandard(material, BASE);
+ return patchStandard(material, part);
+}
+
+/**
+ * Darken and gloss the ground below a waterline, fading out above it.
+ *
+ * Wet ground is darker than dry ground — that is the whole cue, and
+ * without it a bank meets the water as a flat cut with no contact at
+ * all. The fade band above the line is what makes it a shore rather
+ * than a painted stripe, and the line itself is noise-wandered because
+ * a level contour is a ruled edge no bank has. Below the line the
+ * surface stays fully wet, so submerged ground reads as submerged.
+ *
+ * Wetting is not a grey multiply. A water film drops the albedo AND
+ * deepens the colour already there, then gleams at grazing angles — so
+ * the band carries all three: darken, saturate, and a fresnel sheen in
+ * the SKY's hue (`fogColor` where the scene is fogged, which is the one
+ * sky-family colour a `<color_fragment>` patch can reach), which is
+ * what separates wet sand from sand in shadow.
+ *
+ * `gloss` lands on the MATERIAL, not per pixel: `patchStandard`'s only
+ * fragment hook runs after `<color_fragment>` and therefore BEFORE
+ * `<roughnessmap_fragment>` declares `roughnessFactor`, so per-pixel
+ * roughness is out of reach. It therefore defaults to a LIGHT touch:
+ * a shore ground is mostly dry, and the reference default of 0.45 took
+ * `MAT.soil()` from roughness 0.95 to 0.43 over the whole beach —
+ * measured on this renderer (ACES, exposure 1.0, baked environment) it
+ * turned the dry sand into satin and pushed the frame to mean_lum 0.85.
+ * The per-pixel sheen above is what the wet band actually reads from;
+ * pass `gloss: 0.45` when the bank has a material of its own.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place.
+ * @param {object} [opts] `level` world Y of the water surface (default
+ * 0); `band` metres of fade ABOVE it (default 0.25); `darken` how far
+ * the albedo drops at full wet, 0..1 (default 0.45); `saturate` extra
+ * chroma at full wet (default 0.35); `sheen` grazing-angle lift in
+ * the sky's hue (default 0.22); `gloss` multiplier on the material's
+ * dry roughness (default 0.85).
+ * @returns {THREE.Material} The same material. Its uniforms stay live on
+ * `material.userData.uniforms`, so `uWetY` can follow a tide.
+ */
+export function patchShoreWet(material, opts = {}) {
+ const level = opts.level === undefined ? 0 : opts.level;
+ const band = opts.band === undefined ? 0.25 : opts.band;
+ const darken = opts.darken === undefined ? 0.45 : opts.darken;
+ const gloss = opts.gloss === undefined ? 0.85 : opts.gloss;
+ const sat = opts.saturate === undefined ? 0.35 : opts.saturate;
+ const sheen = opts.sheen === undefined ? 0.22 : opts.sheen;
+ composeRoughness(material, 'waterside:wet', Math.max(gloss, 0));
+ return withBase(material, {
+ name: 'waterside:shoreWet',
+ uniforms: {
+ uWetY: { value: level },
+ uWetBand: { value: Math.max(band, 1e-3) },
+ uWetDark: { value: unit(darken) },
+ uWetSat: { value: Math.max(sat, 0) },
+ uWetSheen: { value: Math.max(sheen, 0) },
+ },
+ fragmentHead: [
+ 'uniform float uWetY;',
+ 'uniform float uWetBand;',
+ 'uniform float uWetDark;',
+ 'uniform float uWetSat;',
+ 'uniform float uWetSheen;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float wtH = vAstraWorld.y - uWetY;',
+ // astraFbm2 over 3 octaves averages ~0.44; centred there, this
+ // wanders the tide mark by up to half a band either way.
+ ' wtH += (astraFbm2(vAstraWorld.xz * 0.7, 3) - 0.44) * uWetBand;',
+ ' float wtK = astraContact(wtH, uWetBand);',
+ ' vec3 wtDry = diffuseColor.rgb;',
+ ' float wtL = dot(wtDry, vec3(0.2126, 0.7152, 0.0722));',
+ ' vec3 wtWet = mix(vec3(wtL), wtDry, 1.0 + uWetSat)',
+ ' * (1.0 - uWetDark);',
+ ' diffuseColor.rgb = mix(wtDry, max(wtWet, vec3(0.0)), wtK);',
+ // The sheen the material-wide gloss cannot place: it belongs on
+ // the film, not on the dry beach behind it. cameraPosition is a
+ // three built-in in both stages, so no extra varying is needed.
+ ' vec3 wtSky = vec3(0.42, 0.50, 0.60);',
+ '#ifdef USE_FOG',
+ ' wtSky = fogColor;',
+ '#endif',
+ ' vec3 wtV = normalize(cameraPosition - vAstraWorld);',
+ ' float wtF = astraFresnel(vAstraWorldN, wtV, 4.0);',
+ ' diffuseColor.rgb += wtSky * (wtF * wtK * uWetSheen);',
+ ].join('\n'),
+ });
+}
+
+/**
+ * A broken white band where water meets anything, torn into streamers.
+ *
+ * Foam is the second contact cue and it works on ground, rock or a
+ * jetty leg alike. It is strongest AT the waterline and hands over to
+ * both neighbours — fading up the bank and down under the surface —
+ * rather than ending at an edge. The tear runs ALONG the shore because
+ * the waves run across it: the horizontal part of the world normal
+ * points up-slope, so its perpendicular is the shore direction, and the
+ * noise is stretched sevenfold along it into streamers instead of the
+ * bands-marching-at-the-viewer a ranked field would give. On a dead
+ * flat surface there is no shore direction to find and it falls back to
+ * the world X axis.
+ *
+ * The band breathes: two decorrelated swells move the LINE itself, so
+ * the foam runs up the bank and drains again. Drive it with
+ * `tickShaders(scene, t)` — an un-advanced uTime is a frozen band.
+ *
+ * Foam is bubbles, never poured paint, so the band is broken TWICE: the
+ * streamer field tears it along the shore and a fine lace field breaks
+ * the churn inside it. And it is not one flat white — the thin film at
+ * the tail keeps a good part of the wet colour under it while only the
+ * churn goes bright, and the whole band carries a hue break, because a
+ * single white is the giveaway of a painted waterline. The default
+ * white is graded to 0.74-0.79 linear so it lifts under bloom instead
+ * of clipping (a 0xeef4f5 foam runs 0.87 in blue and blows first).
+ *
+ * A band in world Y covers `band / slope` metres of GROUND, so the
+ * flatter the surface the wider it spreads — and on the one surface
+ * that is exactly level, a water plane, it spreads over the whole
+ * reach: measured here, a foam patch on a flat reach tinted every
+ * fragment of it (contact 0.59 at t = 1.5) and laid streamers out to
+ * the horizon. So the band fades out once its own footprint passes
+ * `reach` metres, which leaves the bank, the rocks and the piles
+ * untouched and takes the wash off the open water. A flat reach has no
+ * waterline of its own; the foam belongs on what the water MEETS.
+ *
+ * @param {THREE.Material} material A built-in material, patched in
+ * place.
+ * @param {object} [opts] `level` world Y of the water surface (default
+ * 0); `band` metres the foam reaches EITHER side of it (default
+ * 0.35); `color` THREE.Color or hex (default a cold white); `speed`
+ * swell rate in radians per second (default 0.6); `strength` peak
+ * coverage, 0..1 (default 0.85); `reach` metres of ground the band
+ * may cover before it fades out (default 3, gone by 2.5x that; pass
+ * a huge value to put the band back on level surfaces).
+ * @returns {THREE.Material} The same material, with its uniforms live on
+ * `material.userData.uniforms`.
+ */
+export function patchShoreFoam(material, opts = {}) {
+ const level = opts.level === undefined ? 0 : opts.level;
+ const band = opts.band === undefined ? 0.35 : opts.band;
+ const speed = opts.speed === undefined ? 0.6 : opts.speed;
+ const strength = opts.strength === undefined ? 0.85 : opts.strength;
+ const reach = opts.reach === undefined ? 3 : opts.reach;
+ return withBase(material, {
+ name: 'waterside:shoreFoam',
+ uniforms: {
+ uFoamY: { value: level },
+ uFoamBand: { value: Math.max(band, 1e-3) },
+ uFoamColor: { value: toColor(opts.color, 0xdfe6e4) },
+ uFoamSpeed: { value: speed },
+ uFoamAmt: { value: unit(strength) },
+ uFoamReach: { value: Math.max(reach, 1e-3) },
+ },
+ fragmentHead: [
+ 'uniform float uFoamY;',
+ 'uniform float uFoamBand;',
+ 'uniform vec3 uFoamColor;',
+ 'uniform float uFoamSpeed;',
+ 'uniform float uFoamAmt;',
+ 'uniform float uFoamReach;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float fmT = uTime * uFoamSpeed;',
+ // Two swells, not one: a single sine is a metronome, and it is
+ // the LINE that moves, so the band runs up and drains.
+ ' float fmS = sin(fmT) * 0.35 + sin(fmT * 0.63 + 1.7) * 0.22;',
+ ' float fmH = vAstraWorld.y - uFoamY - fmS * uFoamBand;',
+ // The shore frame: a bank tilts its normal up-slope, so the
+ // horizontal normal is ACROSS the shore and its perpendicular
+ // runs along it. Dead flat, there is no shore — use +X.
+ ' vec2 fmNx = vAstraWorldN.xz;',
+ ' float fmL = length(fmNx);',
+ ' vec2 fmA = fmL > 1e-3 ? fmNx / fmL : vec2(1.0, 0.0);',
+ ' vec2 fmB = vec2(-fmA.y, fmA.x);',
+ ' float fmU = dot(vAstraWorld.xz, fmB);',
+ ' float fmV = dot(vAstraWorld.xz, fmA);',
+ // Structure runs ACROSS the flow: waves run up the bank, so the
+ // tear varies slowly along the shore and fast across it.
+ ' float fmN = astraFbm2(vec2(fmU * 0.30 + fmT * 0.05,',
+ ' fmV * 2.10 - fmT * 0.35), 3);',
+ // The lace: a second, much finer field across the same frame,
+ // drifting faster. Without it the streamers read as one poured
+ // sheet with a torn outline instead of as bubbles.
+ ' float fmD = astraFbm2(vec2(fmU * 1.70,',
+ ' fmV * 6.40 - fmT * 0.60), 2);',
+ ' float fmK = astraContact(abs(fmH), uFoamBand);',
+ ' fmK *= smoothstep(0.24, 0.62, fmN);',
+ ' fmK *= 0.55 + 0.45 * smoothstep(0.18, 0.72, fmD);',
+ // How much GROUND this band covers: a rise of uFoamBand runs
+ // band * Ny / |Nxz| metres along a surface of that slope, and
+ // 1/0 on a level one — where the band would be the whole reach.
+ ' float fmSpan = uFoamBand * abs(vAstraWorldN.y) / max(fmL, 1e-4);',
+ ' fmK *= 1.0 - smoothstep(uFoamReach, uFoamReach * 2.5, fmSpan);',
+ // The tail is a thin film that still shows what is under it; only
+ // the churn goes bright. Then a hue break, so no two square
+ // metres of the band are the same white.
+ ' vec3 fmC = mix(uFoamColor * 0.70, uFoamColor,',
+ ' smoothstep(0.30, 0.88, fmN));',
+ ' fmC = astraHueBreak(fmC, vAstraWorld.xz, 1.7, 0.14);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, fmC,',
+ ' clamp(fmK * uFoamAmt, 0.0, 1.0));',
+ ].join('\n'),
+ });
+}
+
+// Odd, so the grid is symmetric about the centre of `bounds` and the
+// least-squares normal equations decouple into three sums.
+const BED_SAMPLES = 9;
+
+/**
+ * Fit `bed(x, z) = c0 + cx*x + cz*z` to `bedAt` over `bounds`.
+ *
+ * Least squares on a grid symmetric about its own centre, where the
+ * cross terms vanish, so no matrix solve is needed.
+ */
+function fitBedPlane(bedAt, bounds, level) {
+ const flat = new THREE.Vector3(level, 0, 0);
+ if (typeof bedAt !== 'function') return flat;
+ const [x0, z0, x1, z1] = bounds;
+ const xc = (x0 + x1) / 2;
+ const zc = (z0 + z1) / 2;
+ const n = BED_SAMPLES;
+ let sb = 0, sx = 0, sz = 0, sxx = 0, szz = 0;
+ for (let i = 0; i < n; i++) {
+ for (let j = 0; j < n; j++) {
+ const x = x0 + (x1 - x0) * (i / (n - 1));
+ const z = z0 + (z1 - z0) * (j / (n - 1));
+ const b = bedAt(x, z);
+ if (!Number.isFinite(b)) return flat;
+ sb += b;
+ sx += (x - xc) * b;
+ sz += (z - zc) * b;
+ sxx += (x - xc) * (x - xc);
+ szz += (z - zc) * (z - zc);
+ }
+ }
+ const cx = sxx > 1e-9 ? sx / sxx : 0;
+ const cz = szz > 1e-9 ? sz / szz : 0;
+ return new THREE.Vector3(sb / (n * n) - cx * xc - cz * zc, cx, cz);
+}
+
+/**
+ * Colour a water surface by how deep it runs, so a reach is not a slab.
+ *
+ * One flat colour over a whole reach is what makes water read as a
+ * sheet of plastic laid on the ground; real water goes pale and warm
+ * where it runs thin over the bank and saturates into the deep tone
+ * where the bed drops away, which is also what tells the eye where the
+ * bank IS. The shallow edge is noise-wandered so the isoline does not
+ * rule a contour across the surface.
+ *
+ * DEPTH ROUTE — the bed comes from world XZ through a tilted plane
+ * least-squares FITTED to `bedAt` on the CPU, and depth is this
+ * fragment's own world Y minus that plane. That is the one of the two
+ * that a fragment shader can actually run: world Y against a `bedLevel`
+ * is a single number over a flat water plane and would paint the whole
+ * reach one colour, while a true per-fragment `bedAt` needs the
+ * heightfield uploaded as a texture or a depth prepass, and this engine
+ * runs neither. A plane is exact for a bed that slopes, which is what a
+ * bank is; with no `bedAt` it degenerates to the constant `bedLevel`.
+ *
+ * Not for the addon Water from `water.js` — that is a raw
+ * ShaderMaterial with no `<color_fragment>` hook (and the scene's one
+ * RTT surface). Use this on a plain standard-material reach beside it.
+ *
+ * @param {THREE.Material} material The water surface's built-in
+ * material, patched in place.
+ * @param {object} [opts] `bedAt` function(x, z) returning the bed's
+ * world Y, sampled 9x9 over `bounds` and fitted; `bounds`
+ * [minX, minZ, maxX, maxZ] to fit over (default 120 m about the
+ * origin); `bedLevel` the constant bed used when there is no `bedAt`
+ * (default -2, two metres under a surface at y = 0); `deep` /
+ * `shallow` THREE.Color or hex — the deep end defaults to water.js's
+ * own `waterColor`, so a reach agrees with the scene's RTT ocean, and
+ * the shallow end to a muted jade (0x6fa392, ~0.27 linear; the pale
+ * sage it replaced ran 0.40-0.57 and came back off this renderer as
+ * white paint); `range` metres of depth over which shallow becomes
+ * deep (default 2); `edgeFade` how much of the material's own opacity
+ * survives in the shallows, so the bed shows through where the water
+ * runs thin (default 0.55 on a transparent material, 1 on an opaque
+ * one, where alpha is ignored anyway).
+ * @returns {THREE.Material} The same material, with its uniforms live on
+ * `material.userData.uniforms`.
+ */
+export function patchShallowWater(material, opts = {}) {
+ const bedLevel = opts.bedLevel === undefined ? -2 : opts.bedLevel;
+ const bounds = opts.bounds || [-60, -60, 60, 60];
+ const range = opts.range === undefined ? 2 : opts.range;
+ // A UNIFORM, never a second source variant: the cache key names the
+ // patch, so the first material to compile decides the GLSL for every
+ // material wearing this chain. Opaque materials get 1 — three
+ // discards alpha there, and a fade they cannot show is a lie in the
+ // uniform dump.
+ const fade = opts.edgeFade === undefined
+ ? (material && material.transparent ? 0.55 : 1)
+ : unit(opts.edgeFade);
+ return withBase(material, {
+ name: 'waterside:shallow',
+ uniforms: {
+ uShoalBed: { value: fitBedPlane(opts.bedAt, bounds, bedLevel) },
+ uShoalDeep: { value: toColor(opts.deep, 0x0e3f5c) },
+ uShoalShallow: { value: toColor(opts.shallow, 0x6fa392) },
+ uShoalRange: { value: Math.max(range, 1e-3) },
+ uShoalFade: { value: fade },
+ },
+ fragmentHead: [
+ 'uniform vec3 uShoalBed;',
+ 'uniform vec3 uShoalDeep;',
+ 'uniform vec3 uShoalShallow;',
+ 'uniform float uShoalRange;',
+ 'uniform float uShoalFade;',
+ ].join('\n'),
+ fragmentBody: [
+ ' float swBed = uShoalBed.x + uShoalBed.y * vAstraWorld.x',
+ ' + uShoalBed.z * vAstraWorld.z;',
+ ' float swD = vAstraWorld.y - swBed;',
+ // The shoal edge wanders by a third of the range, or the ramp
+ // draws a contour line across open water.
+ ' swD += (astraFbm2(vAstraWorld.xz * 0.35, 3) - 0.44)',
+ ' * uShoalRange * 0.7;',
+ ' float swK = smoothstep(0.0, uShoalRange, max(swD, 0.0));',
+ ' vec3 swC = mix(uShoalShallow, uShoalDeep, swK);',
+ // Silt, weed and bed patches move the hue at metre scale, and
+ // they do it in the SHALLOWS, where the bed shows through; the
+ // deep end is the colour of water and holds still. Without this
+ // the reach is one clean ramp — the tell of painted water.
+ ' swC = astraHueBreak(swC, vAstraWorld.xz, 0.09,',
+ ' 0.34 * (1.0 - swK * 0.8));',
+ ' diffuseColor.rgb = swC;',
+ // Thin water is see-through water: the bed under the shoal edge
+ // is the cue that says where the bank goes.
+ ' diffuseColor.a *= mix(uShoalFade, 1.0, swK);',
+ ].join('\n'),
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/wetground.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/wetground.js
new file mode 100644
index 00000000..41e3436f
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/wetground.js
@@ -0,0 +1,385 @@
+/**
+ * Mirror and rain-wet floors: a real planar reflection under a rough
+ * overlay. A bare Reflector is SHARP (reads as marble, never damp
+ * asphalt), so the overlay sets the finish. COST CONTRACT: the
+ * Reflector re-renders the WHOLE scene per frame — AT MOST ONE RTT
+ * surface per scene (mirror floor OR water plane, never both).
+ *
+ * PORT NOTE (2026-09-01, our renderer: ACES, exposure 1.0, no post
+ * chain). The shipped pair blends the two layers by a CONSTANT, and
+ * measured here that is the one thing that stops the effect reading as
+ * ground: at the mid camera a 30 x 22 m plaza came back as a milky
+ * sheet, mean luminance 0.687 and p95 0.884 over its near half — the
+ * sky, mirrored 1:1, brighter than the ground it lay in. Real water
+ * films obey Fresnel: a few per cent looking down at them, near-total
+ * at grazing. So the pair now works like a film over a substrate.
+ *
+ * - The OVERLAY carries the Fresnel, in its alpha, through
+ * `shader.js`'s patchStandard so a `patch*` module can still chain
+ * onto the same floor. Once, and only there: attenuating the mirror
+ * as well squares the falloff and puts the night plaza at dark_frac
+ * 0.14 — a black hole where lit wet asphalt belongs.
+ * - The MIRROR ships its own Reflector shader: a swell that slides the
+ * reflection, a short vertical smear (which also hides the 512 px
+ * RTT's stair-stepping on every reflected edge), and the scene's own
+ * fog and dithering, which a ShaderMaterial opts out of — so the
+ * stock mirror stayed crisp and banded while the world around it
+ * fogged.
+ * - Both read ONE ripple field, so the highlight rides the wobble that
+ * made it.
+ *
+ * Same fixture after: near half 0.523 mean / 0.647 p95, night
+ * dark_frac 0.001, and the pools read as water rather than smoke.
+ */
+
+import * as THREE from 'three';
+import { Reflector } from 'three/addons/objects/Reflector.js';
+import { fbm2, noiseDataTexture } from './noise.js';
+import { GLSL_UTIL, patchStandard } from './shader.js';
+
+/**
+ * The film's swell, shared verbatim by the mirror and the overlay.
+ *
+ * Both layers have to agree on it: the overlay's Fresnel decides HOW
+ * MUCH reflection a pixel shows and the mirror decides WHAT it shows,
+ * so two different noise fields would slide the highlight off the
+ * wobble that made it. One string, included in both shaders.
+ */
+const WET_RIPPLE_GLSL = /* glsl */`
+ // Slope of the film at a world XZ point. dist fades the amplitude
+ // with range: this is a per-pixel noise with no mip chain, so left
+ // at full strength across a 30 m floor the far half shimmers into
+ // salt-and-pepper. Fading it is the LOD this effect can afford.
+ vec2 wetRippleGrad(vec2 xz, float scale, float amp, float dist) {
+ vec2 p = xz * scale;
+ float h0 = astraFbm2(p, 2);
+ float a = amp / (1.0 + dist * 0.08);
+ return vec2(astraFbm2(p + vec2(0.3, 0.0), 2) - h0,
+ astraFbm2(p + vec2(0.0, 0.3), 2) - h0) * a;
+ }
+
+ // Schlick for a water film. The exponent is 3, not the textbook 5:
+ // a real film is a stack of slopes, not one plane, and every slope
+ // that faces you admits more — measured at 5 a 30 m floor is dry to
+ // its last two metres and the wet read is lost, at 4 the mid-ground
+ // is a flat grey card, and at 3 the reflection comes in as a
+ // gradient the way a photograph of wet ground does.
+ float wetFresnel(vec3 n, vec3 v, float strength) {
+ float ndv = clamp(dot(normalize(n), normalize(v)), 0.0, 1.0);
+ return mix(1.0, 0.03 + 0.97 * pow(1.0 - ndv, 3.0), strength);
+ }
+`;
+
+/**
+ * Reflector shader with a ripple, a smear, fog and dithering. It
+ * decides WHAT the film reflects; the overlay's Fresnel decides how
+ * much of it survives. Everything in here is the SCENE's own radiance
+ * — no authored water colour — so the floor re-grades itself with the
+ * sky, the hour and the lights above it.
+ */
+const WET_REFLECTOR_SHADER = {
+ name: 'WetReflectorShader',
+
+ uniforms: THREE.UniformsUtils.merge([
+ THREE.UniformsLib.fog,
+ {
+ color: { value: null },
+ tDiffuse: { value: null },
+ textureMatrix: { value: null },
+ uBlur: { value: 0.010 },
+ uRipple: { value: 1.0 },
+ uRippleScale: { value: 4.0 },
+ },
+ ]),
+
+ vertexShader: /* glsl */`
+ uniform mat4 textureMatrix;
+ varying vec4 vUv;
+ varying vec3 vWorldPos;
+ varying vec3 vWorldNormal;
+
+ #include <common>
+ #include <fog_pars_vertex>
+ #include <logdepthbuf_pars_vertex>
+
+ void main() {
+ vUv = textureMatrix * vec4(position, 1.0);
+ vec4 worldPosition = modelMatrix * vec4(position, 1.0);
+ vWorldPos = worldPosition.xyz;
+ vWorldNormal = normalize(mat3(modelMatrix) * normal);
+ vec4 mvPosition = viewMatrix * worldPosition;
+ gl_Position = projectionMatrix * mvPosition;
+ #include <logdepthbuf_vertex>
+ #include <fog_vertex>
+ }`,
+
+ fragmentShader: /* glsl */`
+ uniform vec3 color;
+ uniform sampler2D tDiffuse;
+ uniform float uBlur;
+ uniform float uRipple;
+ uniform float uRippleScale;
+ varying vec4 vUv;
+ varying vec3 vWorldPos;
+ varying vec3 vWorldNormal;
+
+ #include <common>
+ #include <logdepthbuf_pars_fragment>
+ #include <fog_pars_fragment>
+ #include <dithering_pars_fragment>
+` + GLSL_UTIL + WET_RIPPLE_GLSL + /* glsl */`
+
+ float wetBlendOverlay(float base, float blend) {
+ return base < 0.5 ? (2.0 * base * blend)
+ : (1.0 - 2.0 * (1.0 - base) * (1.0 - blend));
+ }
+
+ vec3 wetBlendOverlay(vec3 base, vec3 blend) {
+ return vec3(wetBlendOverlay(base.r, blend.r),
+ wetBlendOverlay(base.g, blend.g),
+ wetBlendOverlay(base.b, blend.b));
+ }
+
+ // texture2DProj divides by w, so an offset in normalised projected
+ // space has to be pre-multiplied by w or the smear length swings
+ // with depth across the plane.
+ vec3 wetTap(vec2 o) {
+ return texture2DProj(
+ tDiffuse, vUv + vec4(o * vUv.w, 0.0, 0.0)).rgb;
+ }
+
+ void main() {
+ #include <logdepthbuf_fragment>
+
+ vec3 V = normalize(cameraPosition - vWorldPos);
+ float ndv = clamp(dot(normalize(vWorldNormal), V), 0.0, 1.0);
+
+ // The film is never a plane, and its swell slides what it
+ // reflects. HOW MUCH of this layer survives is the overlay's job
+ // (Fresnel there composites once; doing it here as well squared
+ // it and put the night plaza at dark_frac 0.14) — this layer only
+ // decides what the reflection looks like.
+ vec2 grad = wetRippleGrad(vWorldPos.xz, uRippleScale, uRipple,
+ distance(cameraPosition, vWorldPos));
+ // A short vertical smear on top: a wet surface is never a clean
+ // mirror, and it is also what hides the 512 px RTT's
+ // stair-stepping on every reflected edge.
+ float smear = uBlur * (0.35 + 0.65 * (1.0 - ndv));
+ vec2 o = grad * 0.12;
+ vec3 refl = wetTap(o + vec2(0.0, -2.0 * smear)) * 0.12
+ + wetTap(o + vec2(0.0, -smear)) * 0.22
+ + wetTap(o) * 0.32
+ + wetTap(o + vec2(0.0, smear)) * 0.22
+ + wetTap(o + vec2(0.0, 2.0 * smear)) * 0.12;
+
+ gl_FragColor = vec4(wetBlendOverlay(refl, color), 1.0);
+
+ #include <tonemapping_fragment>
+ #include <colorspace_fragment>
+ #include <fog_fragment>
+ #include <dithering_fragment>
+ }`,
+};
+
+/**
+ * Make the overlay's cover view-dependent — the change that turns the
+ * pair into wet ground rather than a sheet of glass with grit on it.
+ *
+ * A water film is not a constant blend. Looking DOWN at it you see
+ * through to the substrate (3% reflected) and looking ALONG it you see
+ * nothing but reflection. So the authored `overlayOpacity` (times the
+ * puddle mask) is the GRAZING limit, and the cover rises towards fully
+ * dry as the view steepens: `a = 1 - F * (1 - a0)`.
+ *
+ * Two consequences worth stating, both measured on our host:
+ * - It composites ONCE. Attenuating the mirror layer as well squared
+ * the falloff and dropped the night plaza to dark_frac 0.14 — a
+ * black hole where the near floor should show lit wet asphalt.
+ * - `fresnel: 0` reproduces the pre-port constant blend exactly, which
+ * is what a polished indoor floor under its own lighting wants.
+ *
+ * `alphamap_fragment` runs after this hook and multiplies the mask in
+ * again, so the mask is divided back out here; that is why the patch
+ * samples the map itself instead of reading `diffuseColor.a`.
+ */
+function patchWetFilm(material, opts) {
+ return patchStandard(material, {
+ name: 'WetGroundFilm',
+ uniforms: {
+ uWgFresnel: { value: opts.fresnel },
+ uWgRipple: { value: opts.ripple },
+ uWgRippleScale: { value: opts.rippleScale },
+ },
+ vertexHead: 'varying vec3 vWgWorldPos;',
+ vertexBody: 'vWgWorldPos = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ fragmentHead: [
+ 'uniform float uWgFresnel;',
+ 'uniform float uWgRipple;',
+ 'uniform float uWgRippleScale;',
+ 'varying vec3 vWgWorldPos;',
+ WET_RIPPLE_GLSL,
+ ].join('\n'),
+ fragmentBody: [
+ 'float wgMask = 1.0;',
+ '#ifdef USE_ALPHAMAP',
+ ' wgMask = texture2D(alphaMap, vAlphaMapUv).g;',
+ '#endif',
+ // The factory lays this plane flat, so the film's normal is world
+ // up tilted by the swell — and the same swell the mirror slides
+ // its reflection by, so highlight and wobble stay married.
+ 'vec3 wgV = cameraPosition - vWgWorldPos;',
+ 'vec2 wgGrad = wetRippleGrad(vWgWorldPos.xz, uWgRippleScale,',
+ ' uWgRipple, length(wgV));',
+ 'vec3 wgN = normalize(vec3(-wgGrad.x, 1.0, -wgGrad.y));',
+ 'float wgF = wetFresnel(wgN, wgV, uWgFresnel);',
+ 'float wgA0 = diffuseColor.a * wgMask;',
+ 'diffuseColor.a = (1.0 - wgF * (1.0 - wgA0)) / max(wgMask, 0.001);',
+ ].join('\n'),
+ });
+}
+
+/** The damp field: one seeded fBm all three overlay maps read, so a
+ * pool is darker, smoother AND more mirror in the same place. 0 dry,
+ * 1 pooled. */
+function dampField(u, v, seed) {
+ const n = fbm2(u * 4, v * 4, { seed: seed });
+ // The shipped band was 0.24 wide, which over a 30 m floor put the
+ // whole shoreline in a 6 m gradient: the pools read as smoke, not
+ // water. 0.11 still leaves 2-3 texels of softness at 256 px.
+ const t = (n + 0.02) / 0.11;
+ const k = Math.min(1, Math.max(0, t));
+ return 1 - k * k * (3 - 2 * k);
+}
+
+/**
+ * A mirror-reflective floor with a rough overlay that sets its finish:
+ * low overlay opacity reads as polished marble, 0.7+ with `puddleMask`
+ * as damp asphalt where only puddles hold the mirror.
+ *
+ * @param {number} w Floor width (X) in metres.
+ * @param {number} d Floor depth (Z) in metres.
+ * @param {object} [opts] `rttSize` (default 512) reflection target
+ * resolution; `color` (default 0x6f767c) tints/darkens the mirror
+ * like damp ground — an overlay blend, so a value under 0.5 grey
+ * darkens and one over it brightens; `overlayOpacity` (default 0.65,
+ * use 0.7-0.8 for asphalt, 0.4-0.55 for gloss marble); `overlayColor`
+ * (default 0x4a4642, the graded wet-asphalt tone); `puddleMask`
+ * (default false) breaks the overlay with a seeded fBm alpha mask so
+ * the mirror shows only in puddle pools; `seed` (default 1) shapes
+ * the puddles; `fresnel` (default 1, 0..1) how view-dependent the
+ * film is — the authored opacity becomes the GRAZING limit and the
+ * cover closes up as you look straight down, and 0 restores the flat
+ * blend a polished indoor floor wants; `ripple` (default 1.0) slope
+ * of the film's swell, which both slides the reflection and tilts
+ * the Fresnel that admits it — 0 for still water; `rippleScale`
+ * (default 4.0) ripples per metre; `detail` (default 1) scales the
+ * overlay's colour, damp and roughness break-up, 0 for a flat sheet.
+ * @returns {THREE.Group} Group named `MirrorFloor`, resting at y = 0.
+ */
+export function makeMirrorFloor(w, d, opts = {}) {
+ const rttSize = opts.rttSize === undefined ? 512 : opts.rttSize;
+ // 0x889199 shipped as the default and it is 0.53 grey: blendOverlay
+ // BRIGHTENS with it, so "tints/darkens like damp ground" did the
+ // opposite. 0x6f767c is the same cool damp hue below the 0.5 pivot.
+ const color = opts.color === undefined ? 0x6f767c : opts.color;
+ const overlayOpacity =
+ opts.overlayOpacity === undefined ? 0.65 : opts.overlayOpacity;
+ const overlayColor =
+ opts.overlayColor === undefined ? 0x4a4642 : opts.overlayColor;
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const fresnel = opts.fresnel === undefined ? 1 : opts.fresnel;
+ const ripple = opts.ripple === undefined ? 1.0 : opts.ripple;
+ const rippleScale =
+ opts.rippleScale === undefined ? 4.0 : opts.rippleScale;
+ const detail = opts.detail === undefined ? 1 : opts.detail;
+
+ const group = new THREE.Group();
+ group.name = 'MirrorFloor';
+
+ const mirror = new Reflector(new THREE.PlaneGeometry(w, d), {
+ clipBias: 0.003,
+ // MSAA on a 512 px reflection under a rough overlay is
+ // invisible and measured 39 ms a frame on software GL.
+ multisample: 0,
+ textureWidth: rttSize,
+ textureHeight: rttSize,
+ color: color,
+ shader: WET_REFLECTOR_SHADER,
+ });
+ mirror.rotation.x = -Math.PI / 2;
+ mirror.name = 'MirrorSurface';
+ // BOTH uniforms, or the mirror's swell and the overlay's Fresnel
+ // stop describing the same water.
+ mirror.material.uniforms.uRipple.value = ripple;
+ mirror.material.uniforms.uRippleScale.value = rippleScale;
+ // A ShaderMaterial opts OUT of both by default: without these the
+ // mirror is the one surface in the scene that neither fogs nor
+ // dithers, and a 20 m sky reflection is exactly the smooth gradient
+ // that bands in 8 bits.
+ mirror.material.fog = true;
+ mirror.material.dithering = true;
+ group.add(mirror);
+
+ const overlayMat = new THREE.MeshStandardMaterial({
+ color: overlayColor,
+ roughness: 1,
+ metalness: 0,
+ transparent: true,
+ opacity: overlayOpacity,
+ });
+ if (opts.puddleMask) {
+ // alphaMap: bright = dry overlay, dark = puddle showing the mirror.
+ // Smoothstep gives pooled shapes with soft shorelines; the 0.15
+ // floor keeps a thin damp film even inside puddles.
+ overlayMat.alphaMap = noiseDataTexture(256, (u, v) => (
+ 0.15 + 0.85 * (1 - dampField(u, v, seed))
+ ));
+ }
+ if (detail > 0) {
+ // One flat albedo over 600 m2 is the tell of a fake floor. Ground
+ // carries broad warm/cool patches (grit, oil, old repairs) and the
+ // damp field darkens what it wets, so the map is the two together.
+ overlayMat.map = noiseDataTexture(256, (u, v) => {
+ const h = fbm2(u * 3 + 17, v * 3 - 9, { seed: seed + 11 }) * detail;
+ const b = fbm2(u * 1.7 - 5, v * 1.7 + 3, { seed: seed + 41 }) * detail;
+ const g = fbm2(u * 13, v * 13, { seed: seed + 29 }) * detail;
+ const wet = dampField(u, v, seed) * detail;
+ // Water fills the pores and traps the light: a wet patch of any
+ // ground is about half the albedo of the dry patch beside it.
+ // Looking straight DOWN that darkening is the only thing that
+ // says "puddle" — Fresnel has admitted almost no reflection at
+ // that angle, so an albedo field this strong is not decoration,
+ // it is the whole near-field read. The 1.22 divides the peak
+ // back to 1, which makes `overlayColor` the driest crest rather
+ // than the average.
+ const l = (1 - 0.50 * wet) * (1 + 0.24 * b) * (1 + 0.18 * g) / 1.22;
+ // Warm where it is dry, cool where the water sits — the swing a
+ // photograph of wet asphalt actually carries, and the reason
+ // this floor does not read as one die-cut grey. Not a hue
+ // rotation: red up and blue down about a fixed green, so the
+ // tone stays put while the cast moves.
+ const c = 0.55 * h - 0.30 * (wet - 0.5);
+ return [l * (1 + c), l * (1 + 0.05 * c), l * (1 - c)];
+ });
+ // Base roughness stays 1 (the material contract); the map only
+ // takes it DOWN, and only a little. The SMOOTH thing here is the
+ // water surface, which is the mirror layer — dropping the
+ // substrate to 0.45 as well double-counts the film's specular and
+ // measured +20/255 of flat sky sheen over the whole plaza, which
+ // is what turned it into a light grey card.
+ overlayMat.roughnessMap = noiseDataTexture(256, (u, v) => {
+ const wet = dampField(u, v, seed) * detail;
+ const g = fbm2(u * 13, v * 13, { seed: seed + 29 }) * detail;
+ return Math.max(0.05, 0.97 - 0.18 * wet + 0.06 * g);
+ });
+ }
+ patchWetFilm(overlayMat, { fresnel, ripple, rippleScale });
+ const overlay = new THREE.Mesh(new THREE.PlaneGeometry(w, d), overlayMat);
+ overlay.rotation.x = -Math.PI / 2;
+ overlay.position.y = 0.002;
+ overlay.receiveShadow = true;
+ overlay.name = 'GroundOverlay';
+ group.add(overlay);
+
+ return group;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/windows.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/windows.js
new file mode 100644
index 00000000..db7076a0
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/windows.js
@@ -0,0 +1,396 @@
+/**
+ * Night windows that are ROOMS, not glowing rectangles.
+ *
+ * A lit window is the strongest habitation cue a night city has, and an
+ * emissive rectangle is the flattest way to draw one: it has no inside,
+ * so a whole facade reads as a decal. This shades the INTERIOR instead —
+ * from the surface UV and the view direction it intersects a shallow box
+ * behind the glass and shades the wall the ray lands on, so every window
+ * has a back wall, side walls, a floor and a ceiling that slide with the
+ * camera. No extra geometry and no second draw call: it is a
+ * `patchStandard` on the facade material the mesh already has.
+ */
+
+import * as THREE from 'three';
+import { patchStandard } from './shader.js';
+
+const WIN_VARYINGS = [
+ 'varying vec2 vWinUv;',
+ 'varying vec3 vWinW;',
+ 'varying vec3 vWinN;',
+ 'varying vec3 vWinKey;',
+].join('\n');
+
+// `transformed` is still object-space at <begin_vertex>, so an instanced
+// facade needs instanceMatrix folded in by hand.
+const WIN_VERTEX = [
+ ' vec4 winP = vec4(transformed, 1.0);',
+ ' vec3 winNo = normal;',
+ ' vec4 winO = vec4(0.0, 0.0, 0.0, 1.0);',
+ '#ifdef USE_INSTANCING',
+ ' winP = instanceMatrix * winP;',
+ ' winNo = mat3(instanceMatrix) * winNo;',
+ ' winO = instanceMatrix * winO;',
+ '#endif',
+ ' vWinUv = uv;',
+ ' vWinW = (modelMatrix * winP).xyz;',
+ ' vWinN = normalize((modelMatrix * vec4(winNo, 0.0)).xyz);',
+ // The draw's own origin, constant across the mesh: it keys the lit
+ // pattern per BUILDING even where a whole city shares one material.
+ ' vWinKey = (modelMatrix * winO).xyz;',
+].join('\n');
+
+const WIN_HEAD = [
+ 'uniform vec3 uWinWarm;',
+ 'uniform vec3 uWinCool;',
+ 'uniform vec2 uWinGrid;',
+ 'uniform float uWinDepth;',
+ 'uniform float uWinLit;',
+ 'uniform float uWinSeed;',
+ 'uniform float uWinEmissive;',
+ // The pane inside its cell; the rest of the cell stays facade, which
+ // is what makes a grid of glass read as openings in a wall.
+ 'const vec2 ASTRA_WIN_EDGE = vec2(0.18, 0.22);',
+ // A facade is any box face at any orientation and carries no tangent
+ // attribute, so the frame comes from the screen-space derivatives.
+ 'mat3 astraWinFrame(vec3 p, vec2 st, vec3 n, out vec2 mpu) {',
+ ' vec3 dp1 = dFdx(p), dp2 = dFdy(p);',
+ ' vec2 du1 = dFdx(st), du2 = dFdy(st);',
+ ' vec3 a = cross(dp2, n), b = cross(n, dp1);',
+ ' vec3 t = a * du1.x + b * du2.x;',
+ ' vec3 c = a * du1.y + b * du2.y;',
+ ' float k = inversesqrt(max(max(dot(t, t), dot(c, c)), 1e-12));',
+ // Metres per unit of UV: the only way a shader can tell a wall panel
+ // from a mullion box carrying its own full 0..1 UV.
+ ' float det = max(abs(du1.x * du2.y - du2.x * du1.y), 1e-12);',
+ ' mpu = vec2(length(dp1 * du2.y - dp2 * du1.y),',
+ ' length(dp2 * du1.x - dp1 * du2.x)) / det;',
+ ' return mat3(t * k, c * k, n);',
+ '}',
+ // Interior mapping: the nearest wall of a room one cell wide whose
+ // back sits `depth` behind the glass. z runs 0 (glass) to -depth, and
+ // `face` comes back as the weight of the axis that was hit.
+ 'vec3 astraWinRoom(vec3 o, vec3 d, float depth, out vec3 face) {',
+ ' vec3 ds = max(abs(d), vec3(1e-4)) * sign(d + 1e-9);',
+ ' vec3 tHi = (vec3(1.0, 1.0, 0.0) - o) / ds;',
+ ' vec3 tLo = (vec3(0.0, 0.0, -depth) - o) / ds;',
+ ' vec3 tm = max(tLo, tHi);',
+ ' float t = min(min(tm.x, tm.y), tm.z);',
+ ' face = step(tm, vec3(t));',
+ ' face /= max(face.x + face.y + face.z, 1.0);',
+ ' return o + d * t;',
+ '}',
+].join('\n');
+
+const WIN_BODY = [
+ ' vec2 winG = vWinUv * uWinGrid;',
+ ' vec2 winF = fract(winG);',
+ ' vec2 winAa = fwidth(winG) + 1e-4;',
+ // Derivatives are undefined under divergent control flow, so the pane
+ // is a mask mixed in at the end, never an early return.
+ ' vec2 winE = smoothstep(ASTRA_WIN_EDGE - winAa,',
+ ' ASTRA_WIN_EDGE + winAa, winF)',
+ ' * (1.0 - smoothstep(1.0 - ASTRA_WIN_EDGE - winAa,',
+ ' 1.0 - ASTRA_WIN_EDGE + winAa, winF));',
+ ' float winPane = winE.x * winE.y;',
+ ' vec3 winNn = normalize(vWinN);',
+ ' vec3 winV = normalize(cameraPosition - vWinW);',
+ ' vec2 winMpu;',
+ ' mat3 winTbn = astraWinFrame(vWinW, vWinUv, winNn, winMpu);',
+ // A cell under a metre across is a mullion or a spandrel band wearing
+ // its own 0..1 UV, never a window; that member keeps its own surface.
+ ' winPane *= smoothstep(0.55, 1.0, min(winMpu.x / uWinGrid.x,',
+ ' winMpu.y / uWinGrid.y));',
+ // And once a pixel spans a third of a cell the room can only alias
+ // into sparkle, so the facade is handed back instead.
+ ' winPane *= 1.0 - smoothstep(0.3, 0.8, max(winAa.x, winAa.y));',
+ ' vec3 winD = -vec3(dot(winV, winTbn[0]), dot(winV, winTbn[1]),',
+ ' dot(winV, winTbn[2]));',
+ // Edge-on and back-facing fragments would otherwise divide by ~0 and
+ // smear one room across the whole wall.
+ ' winD = normalize(vec3(winD.xy, min(winD.z, -0.02)));',
+ // Quantised normal + draw origin: one key per face per building, so
+ // four facades of one box are not the same lit pattern four times.
+ //
+ // EVERY term here is rounded to a whole number, and that is the whole
+ // reason the pattern holds still. `vWinKey` is one constant handed to
+ // every vertex, but a perspective-correct varying is (sum w/q)/(sum 1/q)
+ // and comes back a few ULPs apart per pixel; astraHash21 amplifies an
+ // input wobble by about a thousand (measured: 1 ULP at coordinate 120
+ // moves it 0.008), so hashing the raw key and then hashing THAT into
+ // the cell id chains two amplifications and turns `winOn` into a
+ // per-pixel coin flip — a facade of static, which is what this
+ // rendered before the floor()s went in. On an integer lattice inside
+ // +-700 the same hash is bit-exact per cell and still well spread
+ // (mean 0.504, sigma 0.291, adjacent |dh| 0.333).
+ ' vec3 winKq = floor(vWinKey * 16.0 + 0.5);',
+ ' float winFace = dot(floor(winNn * 4.0 + 0.5), vec3(11.0, 29.0, 53.0));',
+ ' float winB = floor(astraHash21(winKq.xz + winKq.y) * 29.0) + winFace;',
+ ' vec2 winId = floor(winG)',
+ ' + vec2(uWinSeed + winB, floor(uWinSeed * 1.7) - winB);',
+ ' float winOn = step(astraHash21(winId), uWinLit);',
+ // Three independent draws per room. A facade whose only variable is
+ // on/off reads as a stencil; what a night city actually has is a wide
+ // spread of BRIGHTNESS and a wide spread of HUE, and the fittings.
+ ' float winHt = astraHash21(winId + 3.3);',
+ ' float winHf = astraHash21(winId + 19.7);',
+ ' float winHl = astraHash21(winId + 41.1);',
+ ' vec2 winQ = clamp((winF - ASTRA_WIN_EDGE)',
+ ' / max(1.0 - 2.0 * ASTRA_WIN_EDGE, vec2(1e-3)), 0.0, 1.0);',
+ ' vec3 winHitFace;',
+ ' vec3 winHit = astraWinRoom(vec3(winQ, 0.0), winD,',
+ ' max(uWinDepth, 0.02), winHitFace);',
+ // The back wall carries the room, the ceiling catches the fitting and
+ // the floor stays dark; side walls fall off with how deep they are hit.
+ ' float winShade = winHitFace.z + winHitFace.x * 0.45',
+ ' + winHitFace.y * mix(0.22, 0.8, step(0.5, winHit.y));',
+ ' winShade *= mix(1.0, 0.5,',
+ ' clamp(-winHit.z / max(uWinDepth, 0.02), 0.0, 1.0));',
+ // The fitting is on the CEILING, so a room falls off downward: without
+ // this the back wall is one flat card and the box reads as a printed
+ // panel however well the ray traced it.
+ ' winShade *= mix(0.58, 1.14, smoothstep(0.0, 1.0, winHit.y));',
+ // A room is never an empty box: furniture against the back wall. The
+ // noise lattice is entered through the cell hash, not through winId
+ // itself, so the coordinate stays small enough to interpolate.
+ ' vec2 winNz = winHit.xy * 3.0 + vec2(winHt, winHl) * 37.0;',
+ ' winShade *= mix(0.55, 1.0, astraNoise2(winNz));',
+ // A blind pulled down over the top of a slice of the windows. The old
+ // hard step() cut a razor line across the pane at exactly one height on
+ // every floor of the building, which is the tell of a decal; this is a
+ // soft hem, and it slides with the room because it rides winQ.
+ ' winShade *= mix(1.0, 0.24, step(0.74, winHf)',
+ ' * smoothstep(0.46, 0.64, winQ.y));',
+ // And a curtain drawn across another slice: cloth SCATTERS, so that
+ // room stops being a box and becomes an even glowing panel, brightest
+ // where the fitting sits behind it. A facade of nothing but open rooms
+ // is as uniform as a facade of nothing but rectangles.
+ ' float winCurt = step(winHf, 0.30) * 0.85;',
+ ' winShade = mix(winShade, 0.52 + 0.34 * (1.0 - winQ.y), winCurt);',
+ // COLOUR. A two-tone warm/cool lerp gives a facade exactly two bulbs;
+ // the rotation and the saturation draw spread those into a hundred,
+ // which is the difference between a lit block and a printed one. The
+ // rotation is small (+-5 degrees) because a night window that leaves
+ // the tungsten-to-daylight axis stops reading as a window.
+ ' vec3 winTint = mix(uWinWarm, uWinCool, smoothstep(0.45, 0.75, winHt));',
+ ' winTint = astraHueShift(winTint, (winHl - 0.5) * 0.18);',
+ ' float winGry = dot(winTint, vec3(0.2126, 0.7152, 0.0722));',
+ ' winTint = max(mix(vec3(winGry), winTint,',
+ ' mix(0.72, 1.24, astraHash21(winId + 7.9))), 0.0);',
+ // Cloth washes the bulb toward its own pale, never toward white: a
+ // curtain over a tungsten room is still a warm curtain.
+ ' winTint = mix(winTint, mix(winTint, vec3(winGry * 1.25), 0.3), winCurt);',
+ // Brightness spread. Squared, so most rooms sit low and a few carry
+ // the facade — the shape a photograph of a lit block actually has.
+ ' float winLevel = mix(0.30, 1.15, winHl * winHl * (3.0 - 2.0 * winHl));',
+ ' vec3 winRoom = winTint * (winShade * winLevel);',
+ // Unlit cells keep the same room at a trickle and add the sky the
+ // glass reflects: a black rectangle reads as a hole in the wall. The
+ // sky it reflects is the SCENE's, not a constant — fog carries the
+ // horizon's own hue, so the same facade goes pale blue at noon and
+ // deep blue at midnight with no per-scene tuning. uWinCool stays in as
+ // the floor, so a face-on pane in a scene with no fog is dark glass
+ // rather than a hole.
+ ' vec3 winSky = uWinCool;',
+ '#ifdef USE_FOG',
+ ' winSky = mix(uWinCool, fogColor, 0.7);',
+ '#endif',
+ // Glass mirrors the GROUND as well as the sky, and the line between
+ // the two sweeping across a facade is most of what a curtain wall
+ // looks like from the street. The split rides the reflected ray, so it
+ // moves with the camera and bends round a corner instead of sitting on
+ // the surface; the per-pane term is the batch spread real glazing has.
+ ' vec3 winRefl = reflect(-winV, winNn);',
+ ' winSky *= mix(0.34, 1.0, smoothstep(-0.30, 0.30, winRefl.y))',
+ ' * mix(0.8, 1.25, winHt);',
+ ' float winFr = astraFresnel(winNn, winV, 3.0);',
+ ' vec3 winDark = winRoom * 0.06 + uWinCool * 0.015',
+ ' + winSky * (0.05 + 0.6 * winFr);',
+ // Every gradient above is a shallow ramp over a dark room, which is
+ // where 8-bit banding lives. One LSB of hash grain kills the contours
+ // and is under the noise floor of every display it will be seen on.
+ ' vec3 winGrain = vec3((astraHash21(gl_FragCoord.xy) - 0.5) * 0.004);',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb,',
+ ' max(mix(winDark, winRoom * 0.35, winOn) + winGrain * 0.25, 0.0),',
+ ' winPane);',
+ // diffuseColor is ALBEDO: without lifting the emissive term as well, a
+ // lit room can only ever be a pale wall.
+ ' totalEmissiveRadiance += max(winRoom + winGrain, 0.0)',
+ ' * (uWinEmissive * winOn * winPane);',
+ // And the SAME argument decides the unlit pane, which is the half of
+ // this effect that a night scene actually shows most of. A reflection
+ // is radiance, not albedo: written to diffuseColor alone it is
+ // multiplied by the light landing on the wall, and at night that is
+ // nothing — so every dark pane collapses to the black hole in the
+ // facade that `winDark` exists to prevent. A whisper of the room
+ // behind it rides along, so an unlit window still parallaxes.
+ ' totalEmissiveRadiance += (winSky * (0.06 + 0.9 * winFr)',
+ ' + max(winRoom + winGrain, 0.0) * 0.05)',
+ ' * ((1.0 - winOn) * winPane);',
+].join('\n');
+
+/** 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);
+}
+
+/**
+ * A seed becomes a far-apart WHOLE-NUMBER lattice offset.
+ *
+ * Seeds 7 and 8 offsetting the hash lattice by 1 would merely TRANSLATE
+ * the pattern by one window, which reads as the same building twice —
+ * hence the multiplier. It is an integer, and stays under a few hundred,
+ * because the shader hashes `uWinSeed + <integers>` as a lattice
+ * coordinate: a fractional offset would put every cell id between two
+ * lattice points, where the hash is a thousand times more sensitive to
+ * the last bit of the inputs than it is to the cell.
+ */
+function seedOffset(seed) {
+ const s = Math.abs(Math.round(seed === undefined ? 1 : seed)) % 9973;
+ return (s * 16807) % 257;
+}
+
+/**
+ * Shade the ROOM behind each window instead of the window itself.
+ *
+ * From the surface UV and the view direction this intersects a shallow
+ * box behind every cell of the facade and shades the wall the ray hits,
+ * so a lit window slides and parallaxes like an opening rather than
+ * sitting flat like a sticker — at ONE draw call for the whole facade,
+ * with no added geometry. Unlit cells keep the same interior at a
+ * trickle plus a fresnel sky reflection, because a black rectangle reads
+ * as a hole punched in the wall.
+ *
+ * No two rooms are the same room. `warm`/`cool` set the ends of the
+ * tungsten-to-daylight axis, and each cell then draws its own small hue
+ * rotation, its own saturation and its own BRIGHTNESS off that axis, so
+ * a facade carries a spread of bulbs rather than two. About a third of
+ * them are dressed: a blind hung over the top of the pane, or a curtain
+ * drawn right across, which stops being a box and becomes an even
+ * glowing panel. The sky an unlit pane mirrors is the SCENE's — it is
+ * read from the fog colour where the scene has fog, split at the
+ * reflected horizon so glass takes the ground below and the sky above —
+ * and it is added as RADIANCE, not albedo, so a dark pane still reads as
+ * glass in a night scene where nothing is lighting the wall.
+ *
+ * Two constraints it encodes. The grid is measured in UV, and three's
+ * BoxGeometry gives EVERY box face a full 0..1 UV whatever its size, so
+ * a facade merged from many boxes (`building.js` `block()`) would repeat
+ * the whole grid on every mullion; cells that work out under a metre
+ * across therefore fade out, and such a member keeps its own surface.
+ * Best on a wall whose UV spans it — a shell, a slab, a plane. And the
+ * lift is applied to `totalEmissiveRadiance` as well as `diffuseColor`,
+ * which needs a lit material — MeshStandard/MeshPhysical, not Basic.
+ *
+ * @param {THREE.Material} material A built-in material, patched in place.
+ * @param {object} [opts] `rows`/`cols` window cells per unit of UV,
+ * rounded so the grid closes at the seam (default 8/6); `depth` how far
+ * the back wall sits behind the glass, in cell widths (default 0.6);
+ * `lit` fraction of windows lit (default 0.35); `warm`/`cool`
+ * THREE.Color or hex room tints, mostly warm with the odd cool room —
+ * `cool` also floors the sky an unlit pane reflects where the scene
+ * carries no fog; `seed` the lit pattern (default 1); `emissive` the
+ * radiance of a lit room, which peaks around 1.3x this (default 1.6,
+ * so ~2.1 — keep it in 1.5..4 to bloom instead of clipping white);
+ * `name` the program cache key (default 'windows:interior' —
+ * every option here is a UNIFORM, so one name is correct and two
+ * differently tuned facades still share one compiled program).
+ * @returns {THREE.Material} The same material, its uniforms live on
+ * `material.userData.uniforms` for a scene that dims the city at dawn.
+ */
+export function patchWindowInteriors(material, opts = {}) {
+ const rows = opts.rows === undefined ? 8 : opts.rows;
+ const cols = opts.cols === undefined ? 6 : opts.cols;
+ const depth = opts.depth === undefined ? 0.6 : opts.depth;
+ const lit = opts.lit === undefined ? 0.35 : opts.lit;
+ const emissive = opts.emissive === undefined ? 1.6 : opts.emissive;
+ return patchStandard(material, {
+ name: opts.name || 'windows:interior',
+ uniforms: {
+ uWinWarm: { value: toColor(opts.warm, 0xffc98a) },
+ uWinCool: { value: toColor(opts.cool, 0x9fc0e8) },
+ uWinGrid: { value: new THREE.Vector2(
+ Math.max(1, Math.round(cols)), Math.max(1, Math.round(rows))) },
+ uWinDepth: { value: Math.max(0.02, depth) },
+ uWinLit: { value: Math.min(1, Math.max(0, lit)) },
+ uWinSeed: { value: seedOffset(opts.seed) },
+ uWinEmissive: { value: Math.max(0, emissive) },
+ },
+ vertexHead: WIN_VARYINGS,
+ vertexBody: WIN_VERTEX,
+ fragmentHead: [WIN_VARYINGS, WIN_HEAD].join('\n'),
+ fragmentBody: WIN_BODY,
+ });
+}
+
+// What a facade is called across this library: block() names its wall
+// mesh 'Walls', and a curtain wall or a shell is the same surface.
+const FACADE_RE = /facade|wall|shell|curtain/i;
+
+/** Bounding-box area: the facade is the biggest surface a building has. */
+function boxArea(geometry) {
+ if (!geometry) return 0;
+ if (!geometry.boundingBox) geometry.computeBoundingBox();
+ const b = geometry.boundingBox;
+ if (!b) return 0;
+ const x = b.max.x - b.min.x;
+ const y = b.max.y - b.min.y;
+ const z = b.max.z - b.min.z;
+ return x * y + y * z + z * x;
+}
+
+/** The meshes carrying the facade: by name where there is one, else size. */
+function facadeMeshes(root) {
+ const all = [];
+ root.traverse((o) => { if (o.isMesh && o.material) all.push(o); });
+ const named = all.filter(
+ (o) => FACADE_RE.test(o.name)
+ || [].concat(o.material).some((m) => m && FACADE_RE.test(m.name)));
+ if (named.length) return named;
+ if (all.length < 2) return all;
+ return [all.reduce(
+ (a, b) => (boxArea(b.geometry) > boxArea(a.geometry) ? b : a))];
+}
+
+/**
+ * Give a building night windows without knowing how it is built.
+ *
+ * `block()` and `tower()` return a GROUP of merged meshes — walls, trim,
+ * glazing, reveals — and only one of them is the facade, so a caller
+ * that reached for `mesh.material` would window the cornice or miss
+ * entirely. This finds the facade slot (by name, falling back to the
+ * largest surface), patches every slot it found once, and hands the
+ * object back. It also CLONES a material `materials.js` marked shared:
+ * that library returns one instance to every caller that asked for the
+ * same look, so patching in place would put windows on the whole city.
+ * On a `block()` that facade is merged mullions and spandrel bands, so
+ * the size gate stands the patch down and `block({ lit })` — which
+ * models those openings — still owns the look. It earns its keep on the
+ * plain shells and slabs a skyline is mostly made of.
+ *
+ * @param {THREE.Object3D} mesh A building mesh or group (a `block()`, a
+ * `tower()`, a whole `cityFabric()` group, or one InstancedMesh).
+ * @param {object} [opts] Passed straight to `patchWindowInteriors`.
+ * @returns {THREE.Object3D} The same object, so it can be added inline.
+ */
+export function makeNightWindows(mesh, opts = {}) {
+ if (!mesh || !mesh.traverse) return mesh;
+ const done = new Map();
+ for (const target of facadeMeshes(mesh)) {
+ const slots = [].concat(target.material);
+ const next = slots.map((m) => {
+ if (!m) return m;
+ if (done.has(m.uuid)) return done.get(m.uuid);
+ const out = (m.userData && m.userData.shared) ? m.clone() : m;
+ // clone() JSON-copies userData, which would carry a dead patch
+ // chain into the cache key of a material that no longer runs it.
+ if (out !== m) out.userData = {};
+ patchWindowInteriors(out, opts);
+ done.set(m.uuid, out);
+ return out;
+ });
+ target.material = Array.isArray(target.material) ? next : next[0];
+ }
+ return mesh;
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/lib/woodland.js b/harness/codeverse/languages/scene_threejs/starter/src/lib/woodland.js
new file mode 100644
index 00000000..099b6679
--- /dev/null
+++ b/harness/codeverse/languages/scene_threejs/starter/src/lib/woodland.js
@@ -0,0 +1,843 @@
+/**
+ * The two halves of a forest: the trunk the camera walks up to, and the
+ * stand-ins for everything too far away to be worth geometry.
+ *
+ * `patchBark` shades a trunk. Bark is the one surface in a scene the
+ * viewer has touched, so a flat brown cylinder is read instantly as a
+ * placeholder — and the cue is not roughness, it is DIRECTION: a trunk's
+ * fissures are long and narrow and they run UP. Isotropic noise on a
+ * trunk reads as stone. The field here is sampled with its along-trunk
+ * axis divided by `aniso`, so every feature is stretched that many times
+ * up the trunk before anything else happens to it.
+ *
+ * `makeImposters` puts a silhouette on a card. A hundred real trees is a
+ * budget; a hundred cards is one draw call, and past ~35 m nobody can
+ * tell (measured — see the function's own note). Cards carry the cost of
+ * a forest, a crowd or a distant town in the only place it is affordable.
+ *
+ * Both go through `lib/shader.js`, so both keep the depth and fog chunks
+ * that decide whether an effect is in the frame at all.
+ */
+
+import * as THREE from 'three';
+
+import { mulberry32 } from './noise.js';
+import { windOf } from './grass.js';
+import {
+ composeRoughness, instancedQuad, keepOutOfDepthPasses, makeShaderMaterial,
+ patchStandard, tickShaders,
+} from './shader.js';
+
+const _TAU = Math.PI * 2;
+
+/**
+ * The four barks, as UNIFORM values over one shared program.
+ *
+ * `aniso` is how many times longer a fissure is than it is wide;
+ * `crack` is its half-width and its contrast; `node` is the metres
+ * between a birch's peel seams or a bamboo's nodes.
+ */
+// `tint` is an ALBEDO: nothing here goes over 0.80 on a channel, or the
+// bark clips before the tone map can shape it. Birch was 0xd8d4c8
+// (0.85) and rendered as a white pole on this pipeline — measured 0.746
+// mean luminance with a p95 of 0.833, the brightest thing in a daylight
+// frame including the sky's own gradient.
+const BARK_KINDS = {
+ pine: { id: 0, tint: 0x8f5a33, scale: 0.075, aniso: 5.5,
+ crack: [0.25, 0.85], plate: [0.55, 1.00], node: 0, rough: 1.22 },
+ birch: { id: 1, tint: 0xc2beb1, scale: 0.110, aniso: 6.0,
+ crack: [0.13, 0.55], plate: [0, 0], node: 0.55, rough: 1.08 },
+ oak: { id: 2, tint: 0x6f5940, scale: 0.085, aniso: 10.5,
+ crack: [0.24, 1.00], plate: [0, 0], node: 0, rough: 1.30 },
+ bamboo: { id: 3, tint: 0x9aa858, scale: 0.160, aniso: 12.0,
+ crack: [0.07, 0.35], plate: [0, 0], node: 0.34, rough: 0.72 },
+};
+
+/** 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 four 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));
+}
+
+/**
+ * A seed as a noise-space offset, because the seed is a UNIFORM.
+ *
+ * The first material to compile the shared cache key fixes the GLSL for
+ * every other material wearing this patch, so a seed baked into the
+ * source would be every trunk's seed.
+ */
+function seedOffset(seed) {
+ return new THREE.Vector3(
+ hash11(seed + 0.29), hash11(seed + 4.13), hash11(seed + 9.67))
+ .multiplyScalar(48);
+}
+
+const BARK_VARYINGS = [
+ 'varying vec3 vAstraBarkP;',
+ 'varying vec3 vAstraBarkN;',
+ 'varying vec3 vAstraBarkS;',
+].join('\n');
+
+// The grain lives in the TRUNK's own frame, so the sun has to come down
+// into it; three applies instanceMatrix after this hook, hence the
+// branch. Projection, not inverse: compose() leaves the columns
+// orthogonal.
+const BARK_VERTEX_HEAD = [
+ BARK_VARYINGS,
+ 'uniform vec3 uBarkSun;',
+ 'vec3 astraBarkLocalDir(vec3 w) {',
+ ' mat3 m = mat3(modelMatrix);',
+ '#ifdef USE_INSTANCING',
+ ' m = m * mat3(instanceMatrix);',
+ '#endif',
+ ' return vec3(dot(w, m[0]) / max(dot(m[0], m[0]), 1e-6),',
+ ' dot(w, m[1]) / max(dot(m[1], m[1]), 1e-6),',
+ ' dot(w, m[2]) / max(dot(m[2], m[2]), 1e-6));',
+ '}',
+].join('\n');
+
+const BARK_FRAGMENT_HEAD = [
+ BARK_VARYINGS,
+ 'uniform float uBarkKind;',
+ 'uniform float uBarkScale;',
+ 'uniform float uBarkAniso;',
+ 'uniform float uBarkDepth;',
+ 'uniform float uBarkMoss;',
+ 'uniform vec2 uBarkCrack;',
+ 'uniform vec2 uBarkPlate;',
+ 'uniform float uBarkNode;',
+ 'uniform vec3 uBarkAxis;',
+ 'uniform vec3 uBarkTint;',
+ 'uniform vec3 uBarkMossColor;',
+ 'uniform vec3 uBarkSeed;',
+ 'vec3 astraBarkPerp(vec3 ax) {',
+ ' vec3 g = abs(ax.y) > 0.9 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 1.0, 0.0);',
+ ' return normalize(cross(ax, g));',
+ '}',
+ // Two 2D slices that SHARE the along-trunk coordinate: one divide by
+ // uBarkAniso then stretches every feature up the trunk at once, which
+ // is the whole difference between bark and gravel.
+ 'float astraBarkFbm(vec2 q, float h) {',
+ ' return 0.5 * (astraFbm2(vec2(q.x, h), 3)',
+ ' + astraFbm2(vec2(q.y, h) + 31.7, 3));',
+ '}',
+ // 0 ON a fissure line, 1 in the middle of a ridge: a fissure is where
+ // the field crosses its own median, which is a CURVE, not a blob.
+ // The gain sets how fast the ridge saturates, and it is what decides
+ // whether the cut reads as a LINE or as a cloud: at 4.8 the sub-1 band
+ // was wide enough that the kind's own cut width turned it into
+ // camouflage blotches on our render. 6.4 keeps the same curves and
+ // makes the dark part of them narrow.
+ 'float astraBarkRidge(vec2 q, float h) {',
+ ' return clamp(abs(astraBarkFbm(q, h) - 0.4375) * 6.4, 0.0, 1.0);',
+ '}',
+].join('\n');
+
+const BARK_FRAGMENT_BODY = [
+ ' vec3 bkAx = normalize(uBarkAxis);',
+ ' vec3 bkT1 = astraBarkPerp(bkAx);',
+ ' vec3 bkT2 = cross(bkAx, bkT1);',
+ ' float bkSc = max(uBarkScale, 1e-3);',
+ // ALONG is divided by aniso and ACROSS is not. This one asymmetry is
+ // the claim the whole patch makes.
+ ' float bkH = dot(vAstraBarkP, bkAx) / (bkSc * max(uBarkAniso, 1.0))',
+ ' + uBarkSeed.z;',
+ ' vec2 bkQ = vec2(dot(vAstraBarkP, bkT1), dot(vAstraBarkP, bkT2))',
+ ' / bkSc + uBarkSeed.xy;',
+ ' float bkV = astraBarkRidge(bkQ, bkH);',
+ ' float bkCut = 1.0 - smoothstep(0.0, uBarkCrack.x, bkV);',
+ // The second, finer set of cracks is scaled 3.1x ACROSS the trunk and
+ // only 1.35x along it: scaling both (it was 2.7 and 2.7) kept the
+ // aspect and so produced short strokes, which is the speckle that read
+ // as camouflage rather than as grain. Narrow and LONG is the whole
+ // point of the module.
+ ' float bkV2 = astraBarkRidge(bkQ * 3.1 + 9.3, bkH * 1.35);',
+ ' float bkFine = 1.0 - smoothstep(0.0, uBarkCrack.x * 0.5, bkV2);',
+ ' bkCut = clamp(bkCut + 0.40 * bkFine * (1.0 - bkCut), 0.0, 1.0);',
+ // HUE VARIANCE, before the kind's own structure. A trunk is never one
+ // colour — sapwood, weathering and the side the rain runs down move it
+ // warm and cool over half a metre — and a flat tint is what makes a
+ // shaded trunk read as a brown cylinder however good the fissures are.
+ // The same field, read very coarsely, so the drift follows the GRAIN
+ // instead of spotting the trunk.
+ ' float bkDr = astraBarkFbm(bkQ * 0.16, bkH * 0.16 + 5.3) - 0.4375;',
+ ' vec3 bkTint = uBarkTint * vec3(1.0 + bkDr * 1.10,',
+ ' 1.0 + bkDr * 0.26, 1.0 - bkDr * 0.85);',
+ ' float bkFlat = 0.0;',
+ ' if (uBarkKind < 0.5) {',
+ // PINE sheds in plates the size of a hand: a second field, coarse and
+ // barely stretched, cut at its own median into cells.
+ ' float bkPl = astraBarkRidge(bkQ * uBarkPlate.x,',
+ ' bkH * uBarkPlate.y + 4.7);',
+ ' float bkGap = 1.0 - smoothstep(0.0, 0.18, bkPl);',
+ ' bkCut = clamp(max(bkCut * 0.45, bkGap * 0.9), 0.0, 1.0);',
+ ' bkTint = mix(bkTint, bkTint * vec3(1.35, 0.95, 0.70), bkPl);',
+ ' } else if (uBarkKind < 1.5) {',
+ // BIRCH is the one bark whose marks run ACROSS: lenticel dashes over
+ // a papery skin the vertical grain barely scores.
+ ' float bkLn = astraBarkRidge(bkQ * 1.1 + 3.1, bkH * 11.0);',
+ ' float bkDash = 1.0 - smoothstep(0.0, 0.12, bkLn);',
+ ' float bkPeel = 1.0 - smoothstep(0.0, 0.10,',
+ ' astraBarkRidge(bkQ * 0.12 + 7.7, bkH * uBarkNode));',
+ ' bkCut = clamp(bkCut * 0.22 + bkDash * 0.65 + bkPeel * 0.55,',
+ ' 0.0, 1.0);',
+ ' } else if (uBarkKind < 2.5) {',
+ // OAK: the deepest fissures, and the flats between them are the
+ // ridge TOPS, which catch the light rather than only losing it.
+ ' bkCut = clamp(bkCut * 1.2, 0.0, 1.0);',
+ ' bkFlat = smoothstep(0.55, 0.95, bkV);',
+ ' } else {',
+ // BAMBOO: smooth culm, hard node. The ring is the only strong mark
+ // and the collar above it is paler.
+ ' float bkNd = abs(fract(bkH * uBarkNode) - 0.5) * 2.0;',
+ ' float bkRing = 1.0 - smoothstep(0.0, 0.10, bkNd);',
+ ' bkCut = clamp(bkCut * 0.35 + bkRing, 0.0, 1.0);',
+ ' bkTint = mix(bkTint * vec3(1.10, 1.14, 0.86), bkTint,',
+ ' smoothstep(0.08, 0.40, bkNd));',
+ ' }',
+ // Relief, not paint: the object-space gradient of the fissure depth
+ // tilts the normal this patch cannot reach, and the sun answers.
+ ' vec3 bkPx = dFdx(vAstraBarkP), bkPy = dFdy(vAstraBarkP);',
+ ' vec3 bkGr = (bkPx * dFdx(bkCut) + bkPy * dFdy(bkCut))',
+ ' / max(dot(bkPx, bkPx) + dot(bkPy, bkPy), 1e-12);',
+ ' vec3 bkNr = normalize(vAstraBarkN);',
+ ' vec3 bkSun = normalize(vAstraBarkS);',
+ ' float bkRel = dot(normalize(bkNr + bkGr * uBarkDepth * bkSc), bkSun)',
+ ' - dot(bkNr, bkSun);',
+ // The floor is 0.58, not 0.45: nothing outdoors is lit by the sun
+ // alone, and a relief that can take a facet to 45% of its own albedo
+ // paints black holes where a fissure turns away.
+ ' float bkLit = clamp(1.0 + bkRel * 0.9 + bkFlat * 0.10, 0.58, 1.6);',
+ // The albedo underneath is kept as LUMINANCE — a trunk you coloured
+ // dark stays dark, and every patch already on this material shows
+ // through. Never an assignment.
+ ' float bkLum = dot(diffuseColor.rgb, vec3(0.3333));',
+ ' vec3 bkBase = bkTint * (0.75 + 0.55 * smoothstep(0.02, 0.35, bkLum));',
+ ' diffuseColor.rgb = mix(diffuseColor.rgb, bkBase, 0.72);',
+ // The ridge is lifted as far as the fissure is cut, or a barked trunk
+ // is simply a darker trunk than the one it replaced. The FLOOR is
+ // 0.72 of the depth asked for and never zero: a fissure still sees
+ // the sky, and a black one is the one thing that reads as paint
+ // rather than as relief.
+ ' diffuseColor.rgb *= mix(1.0 + 0.30 * uBarkDepth,',
+ ' 1.0 - 0.72 * uBarkDepth, bkCut);',
+ // And what reaches the bottom of a fissure is SKY, not sun: the cut
+ // is cooler than the ridge beside it, which is the depth cue that
+ // survives being resolved down to four pixels.
+ ' diffuseColor.rgb *= mix(vec3(1.0), vec3(0.88, 0.95, 1.10),',
+ ' bkCut * 0.65);',
+ ' diffuseColor.rgb *= bkLit;',
+ ' float bkMs = uBarkMoss * bkCut * smoothstep(0.30, 0.75,',
+ ' astraBarkFbm(bkQ * 0.30, bkH * 0.30 + 2.9));',
+ // Moss takes the trunk's own drift: one flat green cushion is the
+ // giveaway that a bark is a texture and not a place things grow.
+ ' diffuseColor.rgb = mix(diffuseColor.rgb,',
+ ' uBarkMossColor * (1.0 + bkDr * 0.90), clamp(bkMs, 0.0, 1.0));',
+].join('\n');
+
+/**
+ * Give a trunk bark that runs UP it — the cue a flat brown cylinder
+ * misses.
+ *
+ * A trunk is the one surface in an outdoor scene a camera gets close
+ * enough to read, and what it reads is direction: fissures many times
+ * longer than they are wide, running along the grain. This samples its
+ * field with the along-axis coordinate divided by `aniso` (5.5 to 12,
+ * by kind), so the features are stretched up the trunk before the kind's
+ * own structure is cut into them — plates for pine, papery lenticel
+ * bands for birch, deep ridges for oak, smooth nodes for bamboo. All
+ * four are ONE program: the kind is a uniform, so a stand of four
+ * species costs one compile.
+ *
+ * The field is shaded from the trunk's OWN frame (object space, `axis`
+ * default +Y), so it wraps a cylinder correctly wherever the tree is
+ * placed and does not swim when the tree moves. A fallen log or a branch
+ * needs its own `axis`.
+ *
+ * It BLENDS over the albedo: the kind's tint is mixed 0.72 over what is
+ * there, weighted by that albedo's own luminance, then the fissures
+ * multiply it down — so a dark trunk stays dark and any patch already on
+ * the material shows through. It never assigns `diffuseColor.rgb`.
+ * Roughness is per MATERIAL, not per pixel (`composeRoughness`): bark is
+ * matte, bamboo is not.
+ *
+ * The one thing a fragment patch cannot reach is the normal, so the
+ * relief is baked into the albedo instead — the object-space gradient of
+ * the fissure depth against `sun`. It fades out on its own once a pixel
+ * spans a fissure, which is why the trunk does not sparkle at distance.
+ *
+ * @param {THREE.Material} material Trunk material, patched in place — a
+ * shared material from `materials.js` barks every mesh wearing it, so
+ * clone it first (and clone BEFORE patching).
+ * @param {object} [opts] `kind` 'pine' | 'birch' | 'oak' (default) |
+ * 'bamboo'; `scale` metres across one fissure (default by kind,
+ * 0.075..0.16 — this is the width of a crack, not the trunk);
+ * `depth` 0..1 how far the fissures cut, in shade and in relief
+ * (default 0.55); `mossy` 0..1 green held in the fissures (default
+ * 0.12 — `damp.js`'s `patchMoss` grows the cushion on the shaded
+ * side, this is only what lodges in the cracks); `axis` the trunk's
+ * own axis in OBJECT space, THREE.Vector3 or [x, y, z] (default +Y);
+ * `tint` THREE.Color or hex, the bark colour (default by kind);
+ * `sun` world direction TOWARD the sun, for the relief (default a day
+ * sun); `seed` moves the field (default 1).
+ * @returns {THREE.Material} The same material, uniforms live on
+ * `material.userData.uniforms`.
+ */
+export function patchBark(material, opts = {}) {
+ const kind = BARK_KINDS[opts.kind] || BARK_KINDS.oak;
+ const scale = Math.max(1e-3,
+ opts.scale === undefined ? kind.scale : opts.scale);
+ const depth = unit(opts.depth === undefined ? 0.55 : opts.depth);
+ const mossy = unit(opts.mossy === undefined ? 0.12 : opts.mossy);
+ const seed = opts.seed === undefined ? 1 : opts.seed;
+ const axis = toVec(opts.axis, 0, 1, 0);
+ if (axis.lengthSq() < 1e-9) axis.set(0, 1, 0);
+ // A node count in FIELD units: the along-axis coordinate is already
+ // divided by scale * aniso, so a spacing in metres has to come back
+ // through the same divide or `scale` would move the nodes.
+ const node = kind.node > 0
+ ? (scale * kind.aniso) / kind.node : 0;
+ composeRoughness(material, 'woodland:bark',
+ 1 + (kind.rough - 1) * (0.4 + 0.6 * depth));
+ return patchStandard(material, {
+ name: 'woodland:bark',
+ uniforms: {
+ uBarkKind: { value: kind.id },
+ uBarkScale: { value: scale },
+ uBarkAniso: { value: kind.aniso },
+ uBarkDepth: { value: depth },
+ uBarkMoss: { value: mossy },
+ uBarkCrack: { value: new THREE.Vector2(kind.crack[0], kind.crack[1]) },
+ uBarkPlate: { value: new THREE.Vector2(kind.plate[0], kind.plate[1]) },
+ uBarkNode: { value: node },
+ uBarkAxis: { value: axis.normalize() },
+ uBarkTint: { value: toColor(opts.tint, kind.tint) },
+ uBarkMossColor: { value: toColor(opts.mossColor, 0x46551f) },
+ uBarkSun: { value: toVec(opts.sun, 0.45, 0.78, 0.35).normalize() },
+ uBarkSeed: { value: seedOffset(seed) },
+ },
+ vertexHead: BARK_VERTEX_HEAD,
+ vertexBody: [
+ ' vAstraBarkP = transformed;',
+ ' vAstraBarkN = normal;',
+ ' vAstraBarkS = astraBarkLocalDir(uBarkSun);',
+ ].join('\n'),
+ fragmentHead: BARK_FRAGMENT_HEAD,
+ fragmentBody: BARK_FRAGMENT_BODY,
+ });
+}
+
+/**
+ * The four silhouettes, and what each is worth as a card.
+ *
+ * `cross` is whether the stand-in gets two fixed quads at right angles
+ * (which hold still while the camera moves) or one that turns to face
+ * it. A tree is watched from a moving camera; a distant figure is not.
+ */
+const IMPOSTER_KINDS = {
+ tree: { id: 0, cross: true, height: 9, aspect: 0.92, hue: 0.13,
+ color: 0x4a5c26, second: 0x8a7050, sway: 0.020,
+ bow: [1.9, 1.6, 0.20, 0.15], mid: 0.66 },
+ conifer: { id: 1, cross: true, height: 14, aspect: 0.52, hue: 0.10,
+ color: 0x2f4429, second: 0x7a6244, sway: 0.012,
+ bow: [1.3, 1.0, 0.25, 0.32], mid: 0.50 },
+ person: { id: 2, cross: false, height: 1.75, aspect: 0.46, hue: 0.55,
+ color: 0x9c6a55, second: 0x40465a, sway: 0,
+ bow: [1.1, 0.2, 0.90, 0.30], mid: 0.55 },
+ building: { id: 3, cross: true, height: 11, aspect: 1.35, hue: 0.06,
+ color: 0xa89880, second: 0x3a3630, sway: 0,
+ bow: [0.5, 0.1, 1.40, 0.20], mid: 0.50 },
+};
+
+// The fallback irradiance, matched to THIS renderer's own daylight rig
+// (`environment.js` sunRig 'day': a 0xfff0d8 sun at 5.4 and a 1.4
+// hemisphere, at exposure 1.0 with no post chain). The reference's
+// 3.0 / 0.85 was graded for a different exposure and a bloom pass, and
+// it lands a card field visibly under the geometry standing in it.
+// Pass `rig` and none of this is guesswork.
+// Measured off sunRig('day') here: the hemisphere delivers (0.42, 0.50,
+// 0.71) of irradiance and the environment bake a further (1.25, 1.68,
+// 2.11). Linear working values, not a hex — an irradiance over 1 has no
+// hex to be written as.
+const DAY_SUN = new THREE.Color(0xfff0d8).multiplyScalar(5.4);
+const DAY_AMBIENT = new THREE.Color(1.67, 2.18, 2.82);
+
+/**
+ * The irradiance a diffuse surface takes from an equirect environment.
+ *
+ * `sunRig` bakes its environment as a linear half-float equirect of
+ * RADIANCE, and every lit material in the scene is receiving it through
+ * three's PMREM. A card is not, so without this the far field is lit by
+ * the hemisphere alone and lands under the geometry standing in it — by
+ * a factor that is not a constant, because the ratio of sky bake to
+ * hemisphere is completely different at noon and at midnight (measured
+ * here: a treeline tuned to match by day came out at 0.72 of the real
+ * crown beside it under the moon).
+ *
+ * Solid-angle weighted mean radiance over the sphere, times PI. Sampled
+ * on a 64 x 32 grid, which is 2 048 texels of a 256 x 128 bake.
+ *
+ * @returns {THREE.Color|null} null for a texture with no readable data
+ * (a PMREM render target, a loaded image), which is not an error —
+ * the caller falls back to the hemisphere alone.
+ */
+function envIrradiance(tex) {
+ const img = tex && tex.image;
+ const data = img && img.data;
+ if (!data || !img.width || !img.height) return null;
+ const w = img.width, h = img.height;
+ const half = tex.type === THREE.HalfFloatType;
+ const dy = Math.max(1, Math.round(h / 32));
+ const dx = Math.max(1, Math.round(w / 64));
+ let r = 0, g = 0, b = 0, sum = 0;
+ for (let y = 0; y < h; y += dy) {
+ // Row 0 is the nadir, as the bake writes it.
+ const cw = Math.cos(((y + 0.5) / h - 0.5) * Math.PI);
+ for (let x = 0; x < w; x += dx) {
+ const i = (y * w + x) * 4;
+ const f = half ? THREE.DataUtils.fromHalfFloat : (v) => v;
+ r += f(data[i]) * cw;
+ g += f(data[i + 1]) * cw;
+ b += f(data[i + 2]) * cw;
+ sum += cw;
+ }
+ }
+ if (sum <= 0) return null;
+ return new THREE.Color(r / sum, g / sum, b / sum)
+ .multiplyScalar(Math.PI);
+}
+
+/**
+ * Read a `sunRig()` package as the three numbers a card needs.
+ *
+ * A card does its own lighting — it has no normals three can light and
+ * no place in the shadow map — so the ONE thing that makes it belong is
+ * being handed the same irradiance the geometry beside it receives:
+ * the directional as irradiance (colour times intensity), and the
+ * indirect as hemisphere PLUS the baked environment, which is what
+ * three gives every lit mesh in the scene.
+ */
+function rigLight(rig) {
+ if (!rig || !rig.sun || !rig.fill) return null;
+ // The hemisphere at the mix a roughly upright surface sees.
+ const amb = rig.fill.color.clone()
+ .lerp(rig.fill.groundColor, 0.45)
+ .multiplyScalar(rig.fill.intensity);
+ const env = envIrradiance(rig.envTex);
+ if (env) amb.add(env);
+ return {
+ sunDir: (rig.sunDir ? rig.sunDir.clone()
+ : rig.sun.position.clone()).normalize(),
+ sunColor: rig.sun.color.clone().multiplyScalar(rig.sun.intensity),
+ ambient: amb,
+ };
+}
+
+/**
+ * Stand-ins on cards: a forest, a crowd or a town for one draw call.
+ *
+ * DO NOT USE THESE INSIDE ~35 m. Measured against the same stand built
+ * as real geometry (mean absolute pixel difference over the frame,
+ * 512 px, daylight): 15 m 12.6/255 and plainly flat — the crown's
+ * silhouette is right but it has no interior and the eye reads a
+ * cut-out; 40 m 4.1/255, which is the point where a still frame stops
+ * telling them apart; 90 m 1.4/255, indistinguishable. So put real
+ * geometry in the near field and hand the rest to this — and give the
+ * two the same species colours, because the join is where a mismatch
+ * shows.
+ *
+ * Every card is seated on `heightAt` with its BASE at the ground, is
+ * scaled and hue-shifted per instance (a field of identical cards is
+ * wallpaper at any distance), and — for `tree` and `conifer` — leans on
+ * `grass.js`'s `windOf`, so one `wind` option moves the meadow, the
+ * reeds and the far treeline together.
+ *
+ * The whole field 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 is the only
+ * thing three can cull the field by. It is computed from the real
+ * placements here. The mesh is guarded by `keepOutOfDepthPasses`,
+ * because an override material draws a transparent card as a solid wall
+ * — which also means these cards cast no shadow; their contact with the
+ * ground is the darkened foot in the silhouette itself.
+ *
+ * @param {object} [opts] `source` 'tree' (default) | 'conifer' |
+ * 'person' | 'building'; `count` stand-ins (default 120 — one draw
+ * call at any count); `extent` metres of the square field's side,
+ * centred on the group's origin (default 120); `height` metres of the
+ * average stand-in (default by source: 9 / 14 / 1.75 / 11);
+ * `heightAt` (x, z) => y, the ground the cards are seated on (default
+ * y = 0); `seed` PRNG seed (default 7); `cross` two fixed quads at
+ * right angles instead of one turning card (default true except for
+ * `person`); `color` the main albedo, `trunkColor` the second one
+ * (trunk, clothing, window); `rig` the `sunRig()` package the scene is
+ * lit by — PASS IT: a card does its own lighting, so this is the whole
+ * of what makes the far field belong to the near one, and it is what
+ * turns a treeline down at night; `sunDir`/`sunColor`/`ambient` the
+ * same three by hand, each overriding `rig` (defaults: this
+ * renderer's own daylight rig); `wind` as `grass.js`'s `windOf` reads
+ * it; `name` group name.
+ * @returns {THREE.Group} Named `Imposters`, resting on the ground,
+ * holding ONE mesh, with `userData.tick(t)` driving the lean. Add it
+ * at the scene ROOT: the cards billboard against WORLD axes.
+ */
+export function makeImposters(opts = {}) {
+ const kind = IMPOSTER_KINDS[opts.source] || IMPOSTER_KINDS.tree;
+ const count = Math.max(1, Math.round(
+ opts.count === undefined ? 120 : opts.count));
+ const extent = Math.max(1, opts.extent === undefined ? 120 : opts.extent);
+ const height = Math.max(0.05,
+ opts.height === undefined ? kind.height : opts.height);
+ const ground = typeof opts.heightAt === 'function' ? opts.heightAt : null;
+ const seed = opts.seed === undefined ? 7 : opts.seed;
+ const cross = opts.cross === undefined ? kind.cross : !!opts.cross;
+ const wind = windOf(opts.wind);
+
+ const field = plant(count, extent, seed, kind, ground);
+ const cards = cross ? count * 2 : count;
+ const width = height * kind.aspect;
+ const half = 0.5 * width * field.scale * (cross ? Math.SQRT2 : 1);
+ const box = new THREE.Box3(
+ new THREE.Vector3(-extent / 2 - half, field.low, -extent / 2 - half),
+ new THREE.Vector3(extent / 2 + half, field.high + height * field.scale,
+ extent / 2 + half));
+ const sphere = box.getBoundingSphere(new THREE.Sphere());
+
+ // The REAL radius: `position` is all zeros, so three has nothing else
+ // to cull by and the 10 km default would frame 10 km of empty air.
+ const geom = instancedQuad(cards, 1, 1, sphere.radius);
+ geom.setAttribute('aPos', new THREE.InstancedBufferAttribute(
+ cardArray(field.pos, cross, 3), 3));
+ geom.setAttribute('aCard', new THREE.InstancedBufferAttribute(
+ cardArray(field.card, cross, 4), 4));
+ if (cross) {
+ const yaw = geom.attributes.aCard.array;
+ for (let i = 0; i < count; i++) yaw[(i * 2 + 1) * 4] += Math.PI / 2;
+ }
+ geom.boundingBox = box;
+ // instancedQuad centres its sphere on the ORIGIN; this one is centred
+ // on the field, so it is tighter and it is what three culls by. The
+ // radius passed above is only the floor under it.
+ geom.boundingSphere = sphere;
+
+ const light = rigLight(opts.rig);
+ const mesh = new THREE.Mesh(geom, imposterMaterial({
+ kind, width, height, cross, wind,
+ color: toColor(opts.color, kind.color),
+ second: toColor(opts.trunkColor, kind.second),
+ sun: opts.sunDir === undefined && light
+ ? light.sunDir : toVec(opts.sunDir, 0.45, 0.78, 0.35).normalize(),
+ // Irradiance, not a screen colour.
+ sunColor: opts.sunColor === undefined
+ ? (light ? light.sunColor : DAY_SUN.clone())
+ : toColor(opts.sunColor, 0xffffff),
+ ambient: opts.ambient === undefined
+ ? (light ? light.ambient : DAY_AMBIENT.clone())
+ : toColor(opts.ambient, 0xffffff),
+ }));
+ mesh.name = 'ImposterCards';
+ const g = new THREE.Group();
+ g.name = opts.name || 'Imposters';
+ g.add(keepOutOfDepthPasses(mesh));
+ g.userData.tick = (t) => tickShaders(g, t);
+ return g;
+}
+
+/**
+ * Seat `count` stand-ins on a jittered grid over the field.
+ *
+ * The grid is shuffled before it is cut to `count`, or a field that does
+ * not fill its last row loses a rectangular corner of itself.
+ */
+function plant(count, extent, seed, kind, 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 pos = new Float32Array(count * 3);
+ const card = new Float32Array(count * 4);
+ let low = Infinity, high = -Infinity, scale = 0;
+ for (let i = 0; i < count; i++) {
+ const c = order[i % order.length];
+ const x = -extent / 2 + ((c % cells) + rand()) * step;
+ const z = -extent / 2 + (Math.floor(c / cells) + rand()) * step;
+ const y = ground ? ground(x, z) : 0;
+ pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z;
+ const s = 0.72 + 0.62 * rand() * rand();
+ card[i * 4] = rand() * _TAU;
+ card[i * 4 + 1] = s;
+ card[i * 4 + 2] = (rand() * 2 - 1) * kind.hue;
+ card[i * 4 + 3] = rand();
+ low = Math.min(low, y); high = Math.max(high, y);
+ scale = Math.max(scale, s);
+ }
+ return { pos, card, low, high, scale };
+}
+
+/** Repeat each stand-in's data once per card it gets. */
+function cardArray(src, cross, stride) {
+ if (!cross) return src;
+ const out = new Float32Array(src.length * 2);
+ for (let i = 0; i < src.length / stride; i++) {
+ for (let k = 0; k < stride; k++) {
+ out[i * 2 * stride + k] = src[i * stride + k];
+ out[(i * 2 + 1) * stride + k] = src[i * stride + k];
+ }
+ }
+ return out;
+}
+
+/** Card, silhouette and light — the whole stand-in, in one program. */
+function imposterMaterial(cfg) {
+ return makeShaderMaterial({
+ name: 'Imposters',
+ uniforms: {
+ uImpKind: { value: cfg.kind.id },
+ uImpSize: { value: new THREE.Vector2(cfg.width, cfg.height) },
+ uImpFace: { value: cfg.cross ? 0 : 1 },
+ uImpSway: { value: cfg.kind.sway * cfg.wind.amp * 2 },
+ uImpWind: { value: cfg.wind.dir.clone() },
+ uImpSpeed: { value: cfg.wind.speed },
+ uImpColor: { value: cfg.color },
+ uImpSecond: { value: cfg.second },
+ uImpSun: { value: cfg.sun },
+ uImpBow: { value: new THREE.Vector4(
+ cfg.kind.bow[0], cfg.kind.bow[1], cfg.kind.bow[2],
+ cfg.kind.bow[3]) },
+ uImpMid: { value: cfg.kind.mid },
+ uImpSunColor: { value: cfg.sunColor },
+ uImpAmbient: { value: cfg.ambient },
+ },
+ varyings: 'varying vec2 vImpUv; varying vec4 vImpVar;'
+ + ' varying vec3 vImpN;',
+ vertexHead: [
+ 'attribute vec3 aCorner;',
+ 'attribute vec3 aPos;',
+ 'attribute vec4 aCard;',
+ 'uniform vec2 uImpSize;',
+ 'uniform float uImpFace;',
+ 'uniform float uImpSway;',
+ 'uniform float uImpSpeed;',
+ 'uniform vec2 uImpWind;',
+ 'uniform vec4 uImpBow;',
+ 'uniform float uImpMid;',
+ // The sun vector is a FRAGMENT uniform in the reference; the
+ // front/back test below needs it here too, and dedupeUniforms
+ // keeps the two declarations from colliding.
+ 'uniform vec3 uImpSun;',
+ ].join('\n'),
+ vertexMain: [
+ ' vImpUv = uv;',
+ // Camera axes in LOCAL space (rows of modelViewMatrix), so a
+ // moved or rotated parent cannot tear the field 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 stand-in yaws, it never tips: a card that also pitches with
+ // the camera lifts a whole forest off the ground together.
+ ' vec3 faceR = normalize(camR - up * dot(camR, up)',
+ ' + vec3(1e-5, 0.0, 0.0));',
+ ' vec3 crossR = vec3(cos(aCard.x), 0.0, sin(aCard.x));',
+ ' vec3 right = normalize(mix(crossR, faceR, uImpFace));',
+ ' float hf = aCorner.y + 0.5;',
+ ' vec3 p = aPos + right * (aCorner.x * uImpSize.x * aCard.y)',
+ ' + up * (hf * uImpSize.y * aCard.y);',
+ // One wind for the whole scene (grass.js windOf), and only the
+ // top of the stand-in answers it.
+ ' float sw = uTime * uImpSpeed + astraStagger(aPos.x + aPos.z * 0.31);',
+ ' p.xz += uImpWind * (uImpSway * uImpSize.y * hf * hf * sin(sw));',
+ ' transformed = p;',
+ // A crown is round, and the two quads of a cross have to agree
+ // about that or the seam between them lights as a hard edge: the
+ // fake normal is RADIAL from the mass centre, not the card's own.
+ ' vec3 fwd = cross(right, up);',
+ ' vImpN = right * (aCorner.x * uImpBow.x)',
+ ' + up * ((hf - uImpMid) * uImpBow.y + uImpBow.w)',
+ ' + fwd * uImpBow.z;',
+ // The other quad of a cross is edge-on exactly when this one is
+ // square to the camera, and an edge-on card is a lit 1 px sliver
+ // down the middle of the crown. Fade it; nothing is lost.
+ ' vec3 camF = vec3(modelViewMatrix[0][2], modelViewMatrix[1][2],',
+ ' modelViewMatrix[2][2]);',
+ // WHICH SIDE OF THE MASS THE SUN IS ON, in world space, so it is
+ // the same answer for both quads of a cross and for a card that
+ // turns. +1 the sun is behind the camera (the visible half is the
+ // lit half); -1 the stand is between the camera and the sun and
+ // the visible half is in its own shadow, transmitting.
+ ' vec3 wPos = (modelMatrix * vec4(transformed, 1.0)).xyz;',
+ ' float sunSide = dot(uImpSun,',
+ ' normalize(cameraPosition - wPos));',
+ ' vImpVar = vec4(aCard.z, aCard.w,',
+ ' mix(smoothstep(0.10, 0.42, abs(dot(fwd, camF))), 1.0,',
+ ' uImpFace), sunSide);',
+ ].join('\n'),
+ fragmentHead: [
+ 'uniform float uImpKind;',
+ 'uniform vec3 uImpColor;',
+ 'uniform vec3 uImpSecond;',
+ 'uniform vec3 uImpSunColor;',
+ 'uniform vec3 uImpAmbient;',
+ 'uniform vec3 uImpSun;',
+ ].join('\n'),
+ fragmentMain: [
+ ' vec2 iq = vec2(vImpUv.x * 2.0 - 1.0, vImpUv.y);',
+ ' float iPh = vImpVar.y * 37.0;',
+ ' float iS = -1.0;',
+ ' vec3 iAlb = uImpColor;',
+ ' if (uImpKind < 0.5) {',
+ // A broadleaf is one ragged mass on a short stem, and the edge is
+ // where the eye decides tree or lollipop.
+ ' vec2 tD = vec2(iq.x / 0.88, (iq.y - 0.66) / 0.36);',
+ ' float tR = length(tD);',
+ ' tR += 0.34 * (astraFbm2(vec2(atan(tD.y, tD.x) * 1.7, iPh), 3)',
+ ' - 0.44);',
+ ' float tCrown = 0.92 - tR;',
+ ' iS = max(tCrown, min(0.038 - abs(iq.x), 0.70 - iq.y));',
+ ' iAlb = mix(uImpSecond, uImpColor * (0.66 + 0.60 * iq.y),',
+ ' smoothstep(-0.02, 0.10, tCrown));',
+ ' } else if (uImpKind < 1.5) {',
+ // A spire that steps out at every whorl is a conifer; a clean
+ // triangle is a traffic cone.
+ ' float cW = 0.80 * pow(max(1.0 - iq.y, 0.0), 0.80);',
+ ' cW *= 0.78 + 0.34 * abs(fract(iq.y * 6.0 + iPh) - 0.5) * 2.0;',
+ ' cW -= 0.10 * astraFbm2(vec2(iq.y * 22.0, iPh), 2);',
+ ' iS = max(cW - abs(iq.x), min(0.035 - abs(iq.x), 0.14 - iq.y));',
+ ' iAlb = mix(uImpSecond, uImpColor * (0.60 + 0.62 * iq.y),',
+ ' smoothstep(0.10, 0.20, iq.y));',
+ ' } else if (uImpKind < 2.5) {',
+ // Head, shoulders and the gap between the legs. iq.x spans HALF
+ // the card and iq.y the whole height, so a round head is an
+ // ellipse here.
+ ' float pW = 0.60 - 0.17 * smoothstep(0.80, 0.90, iq.y)',
+ ' - 0.17 * smoothstep(0.74, 0.52, iq.y)',
+ ' + 0.07 * smoothstep(0.52, 0.34, iq.y);',
+ ' float pBody = min(min(pW - abs(iq.x), 0.90 - iq.y), iq.y);',
+ ' iS = max(0.29 - length(vec2(iq.x, (iq.y - 0.915) * 4.8)),',
+ ' min(pBody, max(abs(iq.x) - 0.11, iq.y - 0.38)));',
+ ' iAlb = mix(uImpSecond, uImpColor,',
+ ' smoothstep(0.38, 0.46, iq.y));',
+ ' iAlb = mix(iAlb, uImpColor * 1.35,',
+ ' smoothstep(0.85, 0.90, iq.y));',
+ ' } else {',
+ // A roofline that steps per instance, and windows that vanish on
+ // their own once a pixel spans one (astraStroke).
+ ' float bTop = 0.60 + 0.36 * fract(iPh * 3.7);',
+ ' float bW = 0.34 + 0.16 * fract(iPh * 7.3);',
+ ' iS = min(bW - abs(iq.x), bTop - iq.y);',
+ ' float bWin = astraStroke(iq.x * 7.0 + 0.5, 0.26)',
+ ' * astraStroke(iq.y * 13.0, 0.24)',
+ ' * step(iq.y, bTop - 0.06);',
+ ' iAlb = mix(uImpColor * (0.80 + 0.30 * iq.y), uImpSecond,',
+ ' bWin * 0.85);',
+ ' }',
+ // A card is antialiased by its own gradient or a distant stand
+ // 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 || vImpVar.z < 0.5) discard;',
+ // LEAVES, NOT FELT. A crown is clumps with light between them,
+ // and one flat mass is what makes a card read as a cut-out at any
+ // distance. The field is in card space at the instance's own
+ // phase, so no two stand-ins clump alike.
+ ' float iLeaf = uImpKind < 1.5 ? 1.0 : 0.0;',
+ ' float iMass = astraFbm2(vec2(iq.x * 5.2, vImpUv.y * 5.2)',
+ ' + iPh, 3);',
+ ' iAlb *= 1.0 + iLeaf * (iMass - 0.375) * 1.15;',
+ ' float iFine = astraFbm2(vec2(iq.x * 17.0, vImpUv.y * 17.0)',
+ ' + iPh * 1.7, 2);',
+ ' iAlb *= 1.0 + iLeaf * (iFine - 0.375) * 0.45;',
+ // Hue VARIANCE inside one crown, not only between crowns: the
+ // sunlit leaves are yellow and the ones in the mass are
+ // blue-green, and a ball of one hue is a painted ball.
+ ' iAlb = astraHueBreak(iAlb, vec2(iq.x, vImpUv.y) + iPh, 3.3,',
+ ' mix(0.20, 0.62, iLeaf));',
+ ' iAlb = astraHueShift(iAlb, vImpVar.x);',
+ // The card is flat and the thing it stands for is not: the bowed
+ // normal is what puts a lit side and a shaded side on it.
+ ' vec3 iN = normalize(vImpN);',
+ ' float iNdL = max(dot(iN, uImpSun), 0.0);',
+ // A crown is a BALL, and the camera only ever sees one half of
+ // it. The bowed normal knows nothing about that, so on a BACKLIT
+ // stand it hands half of every card a full sun term the geometry
+ // beside it does not get — measured on this renderer at 1.41x the
+ // real crown's luminance, which is what a treeline pasted on with
+ // scissors looks like. Fold the sun down as the mass turns away.
+ ' iNdL *= mix(0.09, 1.0, smoothstep(-0.30, 0.45, vImpVar.w));',
+ // What a backlit crown DOES do is glow: the sun comes through the
+ // thin edge of the mass. Warm, weighted to the silhouette, and
+ // gone the moment the sun is on the camera's side.
+ ' float iEdge = 1.0 - smoothstep(0.0, 0.26, iS);',
+ ' float iBack = smoothstep(0.15, -0.70, vImpVar.w);',
+ // Broken by the same clump field, or the glow is a stroke drawn
+ // round the silhouette rather than light coming through leaves.
+ ' vec3 iTrans = uImpSunColor * vec3(1.0, 0.82, 0.44)',
+ ' * (0.34 * iLeaf * iEdge * iBack',
+ ' * (0.45 + 1.35 * iMass * iFine));',
+ // A CROWN OCCLUDES ITSELF. Nothing else here can supply that — a
+ // card has no ambient occlusion, no self-shadow and no place in
+ // the shadow map — and handed the TRUE environment irradiance
+ // (the one every lit mesh in the scene receives) an unoccluded
+ // mass reads as a pale green cloud: measured 1.57x the real crown
+ // standing in the same field. The deep interior of a crown sees a
+ // fraction of the sky its outer leaves do. Floored, because that
+ // fraction is not zero: what bounced off the ground and off the
+ // rest of the wood gets in whatever the leaves do.
+ ' float iDeep = smoothstep(0.0, 0.38, iS);',
+ ' float iAO = max(0.26,',
+ ' 1.0 - iLeaf * 0.86 * iDeep * (1.0 - 0.78 * iMass));',
+ // Irradiance over PI, the same arithmetic a built-in Lambert
+ // does, so a card sits at the brightness its geometry would.
+ // A crown's underside sees less sky than its top, and that
+ // gradient is most of what says "mass" rather than "cut-out".
+ ' vec3 iIrr = (uImpAmbient * iAO',
+ ' + uImpSunColor * iNdL * mix(1.0, iAO, 0.75) + iTrans)',
+ ' * mix(0.62, 1.06, smoothstep(0.0, 0.85, iq.y));',
+ ' gl_FragColor = vec4(iAlb * iIrr / PI, iA);',
+ ].join('\n'),
+ // OPAQUE with alpha-to-coverage, not blended. One draw call means
+ // the cards are NOT sorted against each other, so a blended card
+ // resolves its soft edge against whatever was already in the buffer
+ // — the sky — and then writes depth, leaving a pale halo traced
+ // around every silhouette that has another card behind it (measured
+ // 2.5 per mille of the treeline band). Coverage is decided per
+ // MSAA sample instead, which this renderer has (antialias: true),
+ // so the edge stays soft, the card behind fills the samples this
+ // one did not take, and the field joins the opaque queue where it
+ // is depth-sorted front to back for free.
+ transparent: false,
+ alphaToCoverage: true,
+ depthWrite: true,
+ side: THREE.DoubleSide,
+ });
+}
diff --git a/harness/codeverse/languages/scene_threejs/starter/src/scene.js b/harness/codeverse/languages/scene_threejs/starter/src/scene.js
index a0527361..628f4701 100644
--- a/harness/codeverse/languages/scene_threejs/starter/src/scene.js
+++ b/harness/codeverse/languages/scene_threejs/starter/src/scene.js
@@ -8,7 +8,11 @@
// • update(t, dt): t = seconds since start, dt = step; animate here (no requestAnimationFrame).
// • loaders.gltf is a GLTFLoader: loaders.gltf.loadAsync('/assets/<name>.glb') for Blender-built assets.
// • Imports allowed: 'three', 'three/addons/*', relative files. No CDN, no network, no DOM access.
-// • Raw three.js + GLSL only: never import any helper SDK.
+// • Raw three.js + GLSL only: never import a helper SDK or any npm package.
+// ./lib/ is the ONE exception and is not an SDK: 52 harness-owned effect modules
+// shipped INTO this workspace, already compiled and rendered on this renderer.
+// Import and call them (`import { makeGrass } from './lib/grass.js'`); do not
+// rewrite them — writes to src/lib/ are reverted. Table: prompts effects_catalog.
import * as THREE from 'three';
import { buildEnv, heightAt, SUN_AZIMUTH_DEG } from './env.js';
import { build as buildMeadow } from './zones/meadow.js';
diff --git a/harness/codeverse/prompts/scene_threejs/contract.md b/harness/codeverse/prompts/scene_threejs/contract.md
index ea0a3e3e..36aa4f76 100644
--- a/harness/codeverse/prompts/scene_threejs/contract.md
+++ b/harness/codeverse/prompts/scene_threejs/contract.md
@@ -8,6 +8,7 @@ src/env.js export const BOUNDS; export function heightAt(x, z); export
src/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
public/assets/<snake>.glb (optional) Blender-built assets, loaded via loaders.gltf.loadAsync('/assets/<snake>.glb')
```
The harness serves the workspace root over http (`public/assets/` is mounted at
@@ -35,10 +36,17 @@ content pixels (rest sky/ground) = content too small. Dusk/night = coloured, ne
## Imports (only these resolve)
`three`, `three/addons/*` (GLTFLoader, BufferGeometryUtils, Sky, Water, EffectComposer…).
-Relative imports between your own files. No CDN, no other packages, no `three/webgpu`,
-no `three/tsl`. Post-processing (EffectComposer) is optional and described in the
-cookbook; the default harness renders the scene directly, so lighting and emissives must
-look right WITHOUT bloom.
+Relative imports between your own files, and `src/lib/*.js`. No CDN, no other packages,
+no `three/webgpu`, no `three/tsl`.
+
+`src/lib/` is NOT a helper SDK and the "raw language only" law does not exclude it: it is
+harness-owned source shipped into this workspace, every module compiled and rendered on
+this renderer, and writes to it are reverted. Reach for it before writing your own
+version of the same effect — the want → call table ships with this brief.
+
+The harness renders scene pictures THROUGH a post chain (GTAO + a selective emissive
+bloom + a grade that is identity unless `scene.userData.grade` is set). So emissives DO
+bloom: author them at peak 1.5–4, not 20. `--no-post` / `CV3D_POST=0` turns it off.
## Forbidden
`document.*` / `window.*` except `window.innerWidth` — never create canvases or DOM;
diff --git a/harness/codeverse/prompts/scene_threejs/effects_catalog.md b/harness/codeverse/prompts/scene_threejs/effects_catalog.md
new file mode 100644
index 00000000..870e165e
--- /dev/null
+++ b/harness/codeverse/prompts/scene_threejs/effects_catalog.md
@@ -0,0 +1,141 @@
+# The shipped effect library — call these before writing your own
+
+`src/lib/` is in your workspace already: 52 modules, every one of them compiled
+and rendered on THIS renderer. They carry the depth and fog chunks a
+hand-written shader silently loses, and they are not an outside package — they
+are harness code shipped into the workspace, so importing them is allowed where
+"never import a helper SDK" still forbids everything else.
+
+Reach for one FIRST. Write your own only for something no entry here covers,
+and then build it with `makeShaderMaterial` / `patchStandard` from
+`lib/shader.js`.
+
+Import with a relative path from the file you are writing — `src/zones/x.js`
+says `import { makeGrass } from '../lib/grass.js';`, `src/scene.js` says
+`'./lib/grass.js'`.
+
+| Want | Call |
+| --- | --- |
+| a grassy surface | `makeGrass({ extent, density, height, heightAt, patchy })` — `lib/grass.js` |
+| A CROWN OF LEAVES — every broadleaf tree, hedge and bush | `makeCanopy({ crowns: [{position, radius, height}] — or [{position, size:[x,y,z]}] for a mass that is not a ball, which is how a HEDGE is built — color, hue, wind })` — `lib/canopy.js`. NEVER a displaced sphere: see the rule at the end. |
+| trees, bushes, leaves | `patchLeafSSS` · `patchWind` · `patchRootContact` — `lib/foliage_shade.js` |
+| bark, and a forest at distance | `patchBark` · `makeImposters` — `lib/woodland.js` |
+| light through a canopy | `patchDappledLight` · `patchCanopyShade` — `lib/dapple.js`; goes on the surface being LIT, not on the tree |
+| flowers, drifting petals or leaves | `makeFlowers` · `makeFalling` — `lib/flowers.js` |
+| 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` |
+| a cliff that reads as rock | `patchRockStrata` · `patchErosionStreaks` — `lib/strata.js`; bedding by world altitude, so every cliff in a scene shares one bedding plane |
+| the land between the content and the horizon | `makeOutskirts({ inner, baseY, heightAt, shellRadius, colors, seed })` — `lib/environment.js`; seam-matched relief, field patchwork and wooded clusters. A bare oversized ground plane measured as "a diorama on a vast, empty flat plane" |
+| the sun, the fill and the baked environment | `sunRig({ azimuth, elevation })` — `lib/environment.js`; returns `{ sun, fill, sunDisc, envTex, sunDir }`. Add the lights, assign `scene.environment = rig.envTex` |
+| the sky itself | `makeSky(scene, { rig })` — `lib/sky.js`; the dome IS the backdrop, so `scene.background` stays null |
+| cloud, cirrus | `makeClouds({ preset, sunDir })` · `makeCirrus()` — `lib/clouds.js` |
+| stars, the Milky Way, aurora, heat shimmer | `makeStars` · `makeAurora` · `makeHeatShimmer` — `lib/celestial.js` |
+| fog on the ground, distance haze | `makeHeightFog` · `patchAerialPerspective` — `lib/atmosphere.js` |
+| shafts of light | `makeGodRays({ count, height, sunDir, ambient })` — `lib/godrays.js`; the default is daylight — pass `ambient` BELOW 0.35 only for a genuinely unlit interior, where the shafts switch to adding light |
+| 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` |
+| a flag, a hanging banner, a wheat field | `makeFlag` · `makeBanner` · `makeWheatField` — `lib/cloth.js`; the wave TRAVELS |
+| 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` |
+| 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` |
+| your own shader, safely | `makeShaderMaterial` · `patchStandard` · `shadowLike` · `tickShaders` — `lib/shader.js` |
+
+## The four rules that apply to all of them
+
+**1. `patch*` entries CHAIN.** Apply as many as a surface deserves to one
+material, in any order — they are composed into one program. Two patches may
+not define the same GLSL helper name with different bodies; the library prefixes
+its own (`astra…`), so prefix yours.
+
+**2. `make*` entries return a Group resting on y = 0 with
+`userData.tick(t, dt)` — and OUR contract drives it from `update(t, dt)`, not
+from a `tick` of your own.** Fan out in `scene.js`:
+
+```js
+function update(t, dt) {
+ if (env.update) env.update(t, dt);
+ for (const z of zones) if (z.userData.update) z.userData.update(t, dt);
+}
+```
+
+and in a zone, call the effect's own tick from the group's `update`:
+
+```js
+const rain = makeRain({ extent: 40 });
+g.add(rain);
+g.userData.update = (t, dt) => { rain.userData.tick(t, dt); };
+```
+
+Anything built with `patchStandard` is driven instead by one
+`tickShaders(scene, t)` — call it once, in `scene.js`'s `update`. An effect
+whose tick is never called stands still.
+
+**3. Shadows.** Displaced vegetation casts REAL moving shadows: flags,
+banners, reeds and flowers by default; grass and wheat behind `shadows: true`
+(tens of thousands of instances in the shadow map is a cost you opt into). A
+displaced lattice of your own gets the same through `shadowLike` in
+`lib/shader.js` — without it the shadow is cast by the UNDISPLACED geometry.
+
+**4. Import only what you CALL.** Measured over the reference battery's first
+six scenes: 120 imported names were never used. A line that lists a module's
+exports gets pasted whole and the unused half becomes dead weight every later
+round has to read.
+
+## What differs on this renderer
+
+* **There IS a post chain** (`runtime_js/lib/browser/post.js`, on by default for
+ scene renders): GTAO, a SELECTIVE emissive bloom, and a grade that is identity
+ until the scene asks. So emissives bloom — author them at peak **1.5–4**, not
+ 20, and let the bloom do the rest. A material can opt in or out explicitly
+ with `material.userData.bloom = false | true | <colour>`.
+* Grading is per scene: set `scene.userData.grade = { exposure, contrast,
+ saturation, warmth, tint, … }`. Leave it unset for identity.
+* Tone mapping is ACES at exposure **1.0** and output is sRGB. Non-emissive
+ albedos belong in **0.02–0.8** linear; a pure black or a pure white albedo is
+ always wrong.
+* `logarithmicDepthBuffer` is OFF by default, so the library's log-depth chunks
+ compile to nothing here. They cost nothing and `--log-depth` is a host
+ option, so leave them alone.
+* Everything reads `scene.environment` and the sun direction. Do not hardcode a
+ light colour inside an effect; pass `sunDir` / the rig.
+
+## A crown is leaves, not a lumpy ball
+
+The single most common way a scene reads as plastic is a tree whose foliage is
+displaced Icosahedra. It is not for want of effort — a measured avenue stacked
+32 of them per tree with four octaves of noise and still shipped what the
+renderer flagged as "a single flat untextured material, an unreadable slab". A
+closed surface has no silhouette to read, lets no light through, and carries ONE
+hue however carefully that hue is picked. `makeCanopy` places a few thousand
+separate leaf cards as one draw call instead: on the same tree the hue spread
+across the crown went from 3.6° to 9.4° and the 5–95 range from 10 to 22 — a
+photograph carries 25–45. Use it for every broadleaf crown, hedge and bush near
+enough for a camera to resolve; `makeImposters` still owns the far treeline.
diff --git a/harness/codeverse/prompts/system/harness_contract.md b/harness/codeverse/prompts/system/harness_contract.md
index 82ddd8c2..69b59b24 100644
--- a/harness/codeverse/prompts/system/harness_contract.md
+++ b/harness/codeverse/prompts/system/harness_contract.md
@@ -19,6 +19,9 @@ artifacts/ harness output (object.glb, renders/, gates/, measurement.json). RE
imports are listed in the language contract (bpy/bmesh/mathutils/math/random/… ;
`cadquery` + stdlib ; `three` + `three/addons/*`). Nothing else. No network, no DOM,
no file I/O from generated code (except `src/robot.urdf` for the articulated track).
+ A language contract may ALSO ship harness-owned modules inside your own `src/` and tell
+ you to call them (`scene_threejs`: `src/lib/*.js`). Those are not an SDK import — they
+ are code the harness wrote into your workspace. Call them; never rewrite them.
## 2. Code is truth
diff --git a/harness/codeverse/prompts/tracks/scene_compose.j2 b/harness/codeverse/prompts/tracks/scene_compose.j2
index aad76a5a..b7ba488c 100644
--- a/harness/codeverse/prompts/tracks/scene_compose.j2
+++ b/harness/codeverse/prompts/tracks/scene_compose.j2
@@ -44,5 +44,10 @@ Animation: {{ animation }}
{{ tool_cards }}
{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+
## Output
{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_env.j2 b/harness/codeverse/prompts/tracks/scene_env.j2
index cba996a8..3fdfcb45 100644
--- a/harness/codeverse/prompts/tracks/scene_env.j2
+++ b/harness/codeverse/prompts/tracks/scene_env.j2
@@ -82,6 +82,10 @@ After editing run `build`, then `scene_views` and LOOK: is the horizon hazy, is
multi-coloured, is the shade coloured rather than black? Read the frame table it prints:
every authored camera needs mean luminance >= 0.15 with dark <= 35 %.
{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
{% if recipes is defined and recipes %}
# Recipes (from the scene cookbook — copy these numbers and snippets)
diff --git a/harness/codeverse/prompts/tracks/scene_refine.j2 b/harness/codeverse/prompts/tracks/scene_refine.j2
index 77f37dcd..745c5fb0 100644
--- a/harness/codeverse/prompts/tracks/scene_refine.j2
+++ b/harness/codeverse/prompts/tracks/scene_refine.j2
@@ -89,5 +89,10 @@ frame table and the MEASURED MOTION per camera — use those numbers, not your i
{{ recipes }}
{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
+
## Output
{{ output_format }}
diff --git a/harness/codeverse/prompts/tracks/scene_zone.j2 b/harness/codeverse/prompts/tracks/scene_zone.j2
index e193e925..782ad4e9 100644
--- a/harness/codeverse/prompts/tracks/scene_zone.j2
+++ b/harness/codeverse/prompts/tracks/scene_zone.j2
@@ -90,6 +90,10 @@ again, then `scene_views` and LOOK at the frames: count the silhouettes, look
for a flat colour under your props, and read the MEASURED MOTION line it prints — if your zone's
motion is under 0.4 % of the frame, double the amplitude and render again.
{% endif %}
+{% if effects_catalog is defined and effects_catalog %}
+
+{{ effects_catalog }}
+{% endif %}
{% if recipes is defined and recipes %}
# Recipes (from the scene cookbook — copy these numbers and snippets)
diff --git a/harness/codeverse/tracks/prompting.py b/harness/codeverse/tracks/prompting.py
index 665832e3..9ab6b893 100644
--- a/harness/codeverse/tracks/prompting.py
+++ b/harness/codeverse/tracks/prompting.py
@@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, Any
from codeverse.config import fewer_turns_enabled
from codeverse.contracts.chat import ImagePart
-from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track
+from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, Track, is_harness_owned
from codeverse.contracts.plan import Plan, StaticPlan
from codeverse.contracts.run import RoundRecord
from codeverse.conventions import LANGUAGE_FRAME, Frame, frame_doc, to_snake
@@ -285,6 +285,25 @@ def language_system_prompt(language: Language, *, role: str = "", tools: bool =
return base + "\n\n" + render(f"system/role_{role}.j2", language=language.value, **vars).strip()
+#: the want -> call table for the shipped effect library, per language. Only
+#: scene_threejs ships one (D51); everything else gets "" and its templates render
+#: byte-identically to before.
+EFFECTS_CATALOG_REL: dict[Language, str] = {
+ Language.SCENE_THREEJS: "scene_threejs/effects_catalog.md",
+}
+
+
+def effects_catalog_text(language: Language) -> str:
+ """``prompts/<lang>/effects_catalog.md`` — the library table, or "" for a
+ language that ships no library."""
+ rel = EFFECTS_CATALOG_REL.get(language)
+ if not rel:
+ return ""
+ from codeverse.tracks.common import load_prompt_or
+
+ return load_prompt_or(rel, "")
+
+
def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
"""Variables every tracks/*.j2 template may use (StrictUndefined → all present)."""
plan = ctx.plan
@@ -322,6 +341,10 @@ def base_prompt_context(ctx: RunContext, **extra: Any) -> dict[str, Any]:
# a string, "" when off: templates render it with one {% if %} and stay byte-identical
# for the control arm
"turn_discipline": TURN_DISCIPLINE if (fewer_turns_enabled() and not ctx.single_shot) else "",
+ # The want -> call table for the effect library that ships in every
+ # scene_threejs workspace (D51). "" for every other language, so the
+ # templates that carry it stay byte-identical elsewhere.
+ "effects_catalog": effects_catalog_text(ctx.language),
}
d.update(extra)
return d
@@ -513,7 +536,7 @@ def current_files(
total = 0
for rel in rels:
p = ctx.ws.root / rel
- if not p.is_file() or rel in owned:
+ if not p.is_file() or is_harness_owned(rel, owned):
continue
text = p.read_text(errors="replace")
room = max_chars - total
diff --git a/harness/tests/scene_runtime/test_skeleton.py b/harness/tests/scene_runtime/test_skeleton.py
index fb81e8e7..400596a9 100644
--- a/harness/tests/scene_runtime/test_skeleton.py
+++ b/harness/tests/scene_runtime/test_skeleton.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from codeverse.contracts.plan import AssetPlan, BBox, CameraPlan, ScenePlan, ZonePlan
from codeverse.languages.scene_threejs import STARTER_DIR, lint, write_example, write_skeleton
+from codeverse.workspace import Workspace
from tests.scene_runtime.conftest import needs_node
@@ -65,3 +66,113 @@ def test_plan_skeleton_writes_zone_and_asset_stubs_and_lints(ws):
# what catches an env stage that never ran); everything else must already be legal.
other = [(f.target, f.message) for f in rep.errors if "untouched skeleton" not in f.message]
assert not other, other
+
+
+# ------------------------------------------------------- the effect library (D51)
+
+
+def test_both_skeleton_paths_ship_the_effect_library(tmp_path):
+ """The library is only usable if it is IN the workspace, and plan mode is the
+ PRODUCTION path. It shipped `PATTERN_FILES` only, so a planned run would have
+ carried the effects catalog in its prompt with no `src/lib/` to import from —
+ every `from './lib/grass.js'` an agent wrote would have been a build error."""
+ from codeverse.languages.scene_threejs import lib_files
+
+ names = {p.name for p in lib_files()}
+ assert len(names) >= 50 and "grass.js" in names and "shader.js" in names
+
+ for label, plan in (("example", None), ("plan", make_plan())):
+ ws = Workspace(tmp_path / label)
+ written = write_skeleton(ws, plan)
+ got = {p.name for p in written if p.parent == ws.src / "lib"}
+ assert got == names, (label, sorted(names - got))
+ assert (ws.src / "lib" / "grass.js").is_file(), label
+
+
+def test_the_library_is_harness_owned_so_an_agent_cannot_rewrite_it():
+ """`src/lib/` is starter code the agent CALLS. Registering it in
+ HARNESS_OWNED_SRC is what makes `_enforce_scope` revert a session's write to
+ it — the same protection `src/recipes.glsl` has had since 2026-08-26, when a
+ seeded file the agent COULD rewrite was measured gone by the end of the run."""
+ from codeverse.contracts.common import HARNESS_OWNED_SRC, Language, is_harness_owned
+
+ owned = HARNESS_OWNED_SRC[Language.SCENE_THREEJS]
+ assert owned == ("src/lib/",)
+ assert is_harness_owned("src/lib/grass.js", owned)
+ assert is_harness_owned("src/lib/nested/x.js", owned)
+ # the agent's OWN files stay writable
+ for rel in ("src/scene.js", "src/env.js", "src/zones/meadow.js", "src/libx.js"):
+ assert not is_harness_owned(rel, owned), rel
+ # a plain entry is still an exact match, not a prefix
+ glsl = HARNESS_OWNED_SRC[Language.GLSL_SHADER]
+ assert is_harness_owned("src/recipes.glsl", glsl)
+ assert not is_harness_owned("src/recipes.glsl.bak", glsl)
+
+
+def test_the_lint_does_not_judge_the_library_as_agent_code(tmp_path):
+ """The workspace gate polices what the AGENT writes. Once the library shipped
+ inside `src/`, linting it as agent code was 3 hard ERRORs (signage.js's
+ node-only font fallback imports `node:module` / `node:fs/promises` / `node:url`,
+ which the browser half never reaches) plus 12 "large file" WARNs telling the
+ agent to split files it does not own — a red gate on every scene run."""
+ from codeverse.contracts.artifacts import Severity
+
+ ws = Workspace(tmp_path / "ws")
+ write_example(ws)
+ report = lint(ws)
+ assert report.passed, [f.message for f in report.findings if f.severity == Severity.ERROR]
+ assert not [f for f in report.findings if f.target.startswith("src/lib/")], \
+ [f.target for f in report.findings if f.target.startswith("src/lib/")]
+
+
+def test_the_effects_catalog_reaches_the_scene_prompts_and_only_those():
+ """A catalog the prompt never carries teaches nothing (the same failure the
+ inlined cookbook chapters exist for). It is keyed on LANGUAGE: a blender
+ asset session inside a scene run must not be told to import three.js modules."""
+ from codeverse.contracts.common import Language
+ from codeverse.prompts import PROMPTS_DIR
+ from codeverse.tracks.prompting import effects_catalog_text
+
+ text = effects_catalog_text(Language.SCENE_THREEJS)
+ assert "makeGrass" in text and "makeCanopy" in text and "lib/shader.js" in text
+ assert effects_catalog_text(Language.BLENDER) == ""
+ assert effects_catalog_text(Language.GLSL_SHADER) == ""
+
+ tpl = PROMPTS_DIR / "tracks"
+ for name in ("scene_env.j2", "scene_zone.j2", "scene_refine.j2", "scene_compose.j2"):
+ assert "effects_catalog" in (tpl / name).read_text(), name
+ # the asset session authors BLENDER bpy, so it must NOT carry the table
+ assert "effects_catalog" not in (tpl / "scene_asset.j2").read_text()
+
+
+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
+ session writes an import that cannot resolve — and the reference catalog this
+ was ported from already carried five (`makeFigure`, `makeCreature`, `place`,
+ `instanceAll`, `hash` are none of them exports here)."""
+ import re
+
+ from codeverse.languages.scene_threejs import lib_files
+ from codeverse.prompts import PROMPTS_DIR
+
+ exports: set[str] = set()
+ modules = {p.name for p in lib_files()}
+ for p in lib_files():
+ src = p.read_text()
+ exports |= set(re.findall(r"^export\s+(?:async\s+)?function\s+([A-Za-z0-9_]+)", src, re.M))
+ exports |= set(re.findall(r"^export\s+const\s+([A-Za-z0-9_]+)", src, re.M))
+
+ catalog = (PROMPTS_DIR / "scene_threejs" / "effects_catalog.md").read_text()
+ # option names and prose words that appear in backticks but name no export
+ prose = {"js", "true", "false", "material", "scene", "g", "t", "dt", "update", "tick",
+ "logarithmicDepthBuffer", "sunDir", "ambient", "elevation", "keyElevation", "color"}
+ unknown, named = [], set()
+ for row in catalog.splitlines():
+ if not row.startswith("|") or row.startswith(("| ---", "| Want")):
+ continue
+ named |= set(re.findall(r"`lib/([a-z_]+\.js)`", row))
+ for fn in re.findall(r"`([a-zA-Z][A-Za-z0-9_]*)(?:\(|`| )", row):
+ if fn not in prose and fn not in exports:
+ unknown.append(fn)
+ assert not unknown, sorted(set(unknown))
+ assert named == modules, sorted(modules - named)