USER RULES — APPLY TO THIS PROMPT AND ALL FOLLOW-UP WORK
1. Do not create, play, render, include, or mux any music. Use only nonmusical sound effects where useful. Narration may be used only when I request or supply it, without a musical backing.
2. Do not generate any anti-Islamic content or any content that goes against Islamic values. If my topic or a proposed scene might conflict with this rule, ask me to clarify or choose a compliant alternative before generating it.
END USER RULES

I want a short 3D motion graphic made with three.js in the "Low-Poly" style. Below is the complete source of a reference animation in this exact style, plus the small rendering kit and sound kit it runs on. Use them as your style guide and rebuild the animation around my content.

MY CONTENT:
[Describe your topic, or paste your script here. If this is left as is, ask me for it before building.]


STORYBOARD FIRST: before building the animation, make a VISUAL storyboard and wait for my OK.
- One HTML page (show it as an artifact if you can) with a grid of panels, one per beat (about 3-6). Each panel is a still of that beat's key frame, rendered with the STAGE kit from a block-out of the scene: simple forms in the reference's materials, lighting, camera angle and grade, so the panels already look like the finished piece. Render the stills one after another on one canvas with S.seek(time) at about 16 samples (enough for depth of field and soft shadows to read) and copy each into an image. Stills only, no animation or sound yet.
- Under each panel: the beat number, its start and end time, the exact on-screen text, what moves or changes to get there from the previous panel, what the camera does, and its key sounds.
- Below the grid, list any facts or numbers you had to assume.
When I approve it (or after my changes), build the full animation exactly as storyboarded, reusing the storyboard's scene code.

WHAT TO BUILD
One self-contained HTML file (show it as an artifact if you can):
- three.js 0.187.0 core only, loaded as an ES module from a CDN with an import map (no addons), then set window.THREE = THREE before running the kit and the style code.
- A 1920x1080 canvas scaled to fit the window, with a small control bar: play/pause, a scrub slider, the time, a sound toggle, loop on by default.
- A new style object, built the same way as the reference (content block first, then build(S) returning update(t)), that tells MY CONTENT in this style. 7-12 seconds unless my content needs more.
- Run it with the kit: const S = await K.run(canvas, style, { samples }). Use a low sample count (2-4) while playing live and the style's full count when rendering frames. Expose window.seek = (t) => S.seek(t) and window.DURATION.
- Play the style's sound(k) score in sync from the player: on play call stopSound = SOUND.live((k) => style.sound(k), currentT, { voiceover: false }), and call stopSound() on pause, on seek and when the sound toggle is turned off.
- Include the STAGE kit and the SOUND kit below unchanged.
- Load these Google Fonts before building (the kit awaits the specs in style.fonts): Oswald

HOW TO STAY IN THE STYLE
- The reference shows the look, not the story. Its objects, layout and beats belong to its own topic: do not reuse them unless my content calls for them. Work out what my content needs to show first, then build those things in this look.
- Tell my content as an explainer, not a title card: things happen to objects or characters over three or four beats that follow from each other, and the picture does the telling. Words are small captions and labels, never the subject of a shot. End on the result of the process or the end of the story, not on a headline, slogan or logo.
- Keep the reference's materials, lighting, camera language, grade and the way things move. Change the story, the objects and the words; do not change the look.
- update(t) must set the whole scene for time t and nothing may build up between calls: the kit calls it many times per frame to make motion blur, depth of field and soft shadows. No Math.random, Date or timers; use K.rng(seed).
- Build everything in code: no downloaded models, images, HDRIs or textures.
- Simple forms, beautifully lit and finished, beat complicated models that look wrong. Draw my subject accurately and double-check any facts or numbers you show.
- It is video, often watched on a phone: keep every word the story needs large, sharp and on screen long enough to read, keep the subject filling most of the frame, and keep everything that matters inside the frame for the whole camera move. The first frame should already be worth looking at, and the last second should hold.

FLOW BETWEEN BEATS
- A new beat does not automatically mean a new scene. When the next idea builds on the last, stay in the same world: the things that matter stay on screen and move, grow, re-arrange or transform, and the camera travels to the part of the scene where the next idea happens.
- When the story really moves on (a new place or time, a before/after contrast, a reveal), change scene the way this look would: a turn of the set, a page, a passing object that wipes the frame, a change of light. No hard cuts.
- The reference's scene count is not a template: fit the number of beats to my content.

SOUND (no voiceover: a fuller mix)
- A sound starts on the exact frame its event appears: drive picture and sound from the same schedule, as the reference does.
- Score the events that land (things arriving, labels, contacts, transitions, the key number, the result) with sounds this material would make: glass, plastic, paper, metal, motors.
- Use only sparse sound effects where they clarify visible events. Leave small silences around key moments.


If you are Claude Code with a shell: render an MP4 in headless Chrome with the GPU enabled. Load the page, call window.seek(i / 30) for every frame, capture the canvas and pipe the frames into ffmpeg; render the sound with SOUND.renderOffline((k) => style.sound(k), DURATION, 48000, { voiceover: false }) and mux it in at about -15 LUFS. Look at a few rendered frames and fix framing, lighting or legibility problems before you call it done.

STYLE CARD
Name: Low-Poly
Family: Filters over 3D
Use: explainer
Look: A miniature world of flat, faceted shapes, like folded paper or cut stone: every triangle is one tone, and neighbours differ slightly, inside a short palette of sand, coral and cream against teal water and sage greens.
Motion: Things grow by unfolding facet by facet from one point, or pop out of the ground with a bounce; water heaves so its facets keep catching the light, clouds drift, small cut-gem droplets rise and fall.
Light: One low, warm sun from the side with soft-edged shadows, a cool blue sky filling the shadow sides so every facet turns either warm or cool, and peach haze that swallows the distance.
Materials: Matte paper-like facets with no texture at all; only the water is slightly glossy. Colour comes per triangle from the palette, never from gradients.
Camera: One continuous crane move on a long lens with tilt-shift-shallow focus, so the landscape feels like a tabletop model: close on each stage in turn, then out to the whole scene.
Finish: True depth of field and motion blur, colours kept true (neutral tone curve), a gentle vignette and only enough grain to keep the sky from banding. No filter pass: the facets are real geometry.
Good for: Processes that happen in a place: cycles, journeys, supply chains, how a system of parts feeds itself. Each stage is a spot in the landscape with a paper flag, and the camera travels the route between them.

STAGE KIT (lib/stage.js)
```js
// STAGE: a small film-style rendering kit for three.js motion graphics. Classic script; needs a global THREE (core only,
// no addons). It gives every style the same pipeline:
//   - one clock: stage.seek(t) builds the whole frame for time t, so frames can be rendered alone and in any order
//   - accumulation rendering: each frame is the average of N sub-renders, which gives real motion blur, anti-aliasing,
//     true depth of field (the camera moves across a lens aperture) and soft area-light shadows (lights move across
//     their own surface), all without post-process tricks
//   - HDR bloom, tone mapping, vignette, grain, chromatic aberration and a crisp 2D overlay for captions
//   - code-built lighting environments (no HDRI files), a real mirror floor, canvas textures, text planes, easing,
//     seeded random and noise
// Globals: K (helpers) and registerStyle(). A style is { id, name, ..., render: {...}, build(S) -> { update(t), overlay? } }.
(function (root) {
  const THREE = root.THREE;
  const K = {};
  const STYLES = [];
  root.STYLES = STYLES;
  root.registerStyle = (s) => { STYLES.push(s); return s; };

  // ---------------------------------------------------------------- maths
  K.clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
  K.lerp = (a, b, t) => a + (b - a) * t;
  K.map = (x, a, b, c, d) => c + (d - c) * K.clamp((x - a) / (b - a));
  K.smooth = (a, b, x) => { const t = K.clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
  // progress of time t through the window [a, b], 0..1, optionally eased: K.seg(t, 1, 2.5, K.ease.out)
  K.seg = (t, a, b, ease) => { const u = K.clamp((t - a) / (b - a)); return ease ? ease(u) : u; };
  K.ease = {
    linear: (t) => t,
    in: (t) => t * t * t,
    out: (t) => 1 - Math.pow(1 - t, 3),
    inOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2),
    outQuint: (t) => 1 - Math.pow(1 - t, 5),
    inOutQuint: (t) => (t < 0.5 ? 16 * t * t * t * t * t : 1 - Math.pow(-2 * t + 2, 5) / 2),
    outExpo: (t) => (t >= 1 ? 1 : 1 - Math.pow(2, -10 * t)),
    inExpo: (t) => (t <= 0 ? 0 : Math.pow(2, 10 * t - 10)),
    outBack: (t, s = 1.70158) => 1 + (s + 1) * Math.pow(t - 1, 3) + s * Math.pow(t - 1, 2),
    inBack: (t, s = 1.70158) => (s + 1) * t * t * t - s * t * t,
    outElastic: (t) => (t <= 0 ? 0 : t >= 1 ? 1 : Math.pow(2, -10 * t) * Math.sin((t * 10 - 0.75) * (2 * Math.PI) / 3) + 1),
    outBounce: (t) => { const n = 7.5625, d = 2.75; if (t < 1 / d) return n * t * t; if (t < 2 / d) return n * (t -= 1.5 / d) * t + 0.75; if (t < 2.5 / d) return n * (t -= 2.25 / d) * t + 0.9375; return n * (t -= 2.625 / d) * t + 0.984375; },
  };
  // damped spring from 0 to 1 starting at time 0 (t in seconds). freq in Hz, damp 0..1 (1 = no overshoot)
  K.spring = (t, freq = 2.2, damp = 0.45) => {
    if (t <= 0) return 0;
    const w = 2 * Math.PI * freq;
    if (damp >= 1) return 1 - Math.exp(-w * t) * (1 + w * t);
    const wd = w * Math.sqrt(1 - damp * damp);
    return 1 - Math.exp(-damp * w * t) * (Math.cos(wd * t) + (damp * w / wd) * Math.sin(wd * t));
  };
  // keyframe track: K.track([[0, [0,2,8]], [3, [2,2,6], 'inOut'], [6, 5, K.ease.out]]) -> f(t). Values are numbers or
  // arrays; the ease on a key shapes the move INTO that key.
  K.track = (keys) => (t) => {
    if (t <= keys[0][0]) return keys[0][1];
    for (let i = 1; i < keys.length; i++) {
      if (t <= keys[i][0]) {
        const [t0, v0] = keys[i - 1], [t1, v1, e] = keys[i];
        const fn = typeof e === 'function' ? e : K.ease[e || 'inOut'];
        const u = fn((t - t0) / (t1 - t0));
        return Array.isArray(v0) ? v0.map((a, k) => a + (v1[k] - a) * u) : v0 + (v1 - v0) * u;
      }
    }
    return keys[keys.length - 1][1];
  };

  // like K.track, but the value flows smoothly THROUGH the middle keys without stopping at them (it only eases in at
  // the first key and out at the last). Use it for camera moves that should feel like one continuous shot.
  K.path = (keys) => {
    const n = keys.length, arr = Array.isArray(keys[0][1]), val = (i) => (arr ? keys[i][1] : [keys[i][1]]), dim = val(0).length;
    const m = keys.map((_, i) => (i === 0 || i === n - 1 ? new Array(dim).fill(0) : val(i).map((_, k) => (val(i + 1)[k] - val(i - 1)[k]) / (keys[i + 1][0] - keys[i - 1][0]))));
    return (t) => {
      if (t <= keys[0][0]) return keys[0][1];
      if (t >= keys[n - 1][0]) return keys[n - 1][1];
      let i = 1; while (keys[i][0] < t) i++;
      const t0 = keys[i - 1][0], h = keys[i][0] - t0, u = (t - t0) / h, u2 = u * u, u3 = u2 * u;
      const a = val(i - 1), b = val(i), out = a.map((_, k) => (2 * u3 - 3 * u2 + 1) * a[k] + (u3 - 2 * u2 + u) * h * m[i - 1][k] + (-2 * u3 + 3 * u2) * b[k] + (u3 - u2) * h * m[i][k]);
      return arr ? out : out[0];
    };
  };

  // ---------------------------------------------------------------- seeded random and noise
  K.rng = (seed) => {
    let a = (typeof seed === 'string' ? [...seed].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 16777619), 2166136261) : seed * 2654435761) >>> 0;
    const r = () => { 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; };
    r.range = (lo, hi) => lo + (hi - lo) * r();
    r.int = (lo, hi) => Math.floor(lo + (hi - lo + 1) * r());
    r.pick = (arr) => arr[Math.floor(r() * arr.length)];
    r.chance = (p) => r() < p;
    r.gauss = () => { let u = 0, v = 0; while (u === 0) u = r(); v = r(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); };
    r.sign = () => (r() < 0.5 ? -1 : 1);
    return r;
  };
  // a stable 0..1 hash of up to three numbers (handy for per-instance variation without storing arrays)
  K.hash = (x, y = 0, z = 0) => { let h = Math.sin(x * 127.1 + y * 311.7 + z * 74.7) * 43758.5453123; return h - Math.floor(h); };
  K.noise = (seed = 1) => {
    const r = K.rng(seed), p = new Uint8Array(512), perm = Array.from({ length: 256 }, (_, i) => i);
    for (let i = 255; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [perm[i], perm[j]] = [perm[j], perm[i]]; }
    for (let i = 0; i < 512; i++) p[i] = perm[i & 255];
    const fade = (t) => t * t * t * (t * (t * 6 - 15) + 10);
    const grad = (h, x, y, z) => { const u = (h & 15) < 8 ? x : y, v = (h & 15) < 4 ? y : (h & 15) === 12 || (h & 15) === 14 ? x : z; return ((h & 1) ? -u : u) + ((h & 2) ? -v : v); };
    const n3 = (x, y, z) => {
      const X = Math.floor(x) & 255, Y = Math.floor(y) & 255, Z = Math.floor(z) & 255;
      x -= Math.floor(x); y -= Math.floor(y); z -= Math.floor(z);
      const u = fade(x), v = fade(y), w = fade(z), A = p[X] + Y, AA = p[A] + Z, AB = p[A + 1] + Z, B = p[X + 1] + Y, BA = p[B] + Z, BB = p[B + 1] + Z;
      const L = K.lerp;
      return L(L(L(grad(p[AA], x, y, z), grad(p[BA], x - 1, y, z), u), L(grad(p[AB], x, y - 1, z), grad(p[BB], x - 1, y - 1, z), u), v),
        L(L(grad(p[AA + 1], x, y, z - 1), grad(p[BA + 1], x - 1, y, z - 1), u), L(grad(p[AB + 1], x, y - 1, z - 1), grad(p[BB + 1], x - 1, y - 1, z - 1), u), v), w);
    };
    const fbm = (x, y, z = 0, oct = 4) => { let s = 0, a = 0.5, f = 1; for (let i = 0; i < oct; i++) { s += a * n3(x * f, y * f, z * f); a *= 0.5; f *= 2; } return s; };
    return { n3, n2: (x, y) => n3(x, y, 0), fbm };
  };
  const halton = (i, b) => { let f = 1, r = 0; while (i > 0) { f /= b; r += f * (i % b); i = Math.floor(i / b); } return r; };
  K.halton = halton;

  // ---------------------------------------------------------------- textures, text, geometry
  // K.canvasTex(1024, 512, (ctx, w, h) => {...}) -> THREE.CanvasTexture (sRGB, mipmapped). Redraw with tex.redraw(fn).
  K.canvasTex = (w, h, draw, opts = {}) => {
    const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
    const ctx = cv.getContext('2d');
    if (draw) draw(ctx, w, h);
    const tex = new THREE.CanvasTexture(cv);
    tex.colorSpace = opts.data ? THREE.NoColorSpace : THREE.SRGBColorSpace;
    tex.anisotropy = 8; tex.generateMipmaps = true; tex.minFilter = THREE.LinearMipmapLinearFilter;
    if (opts.repeat) { tex.wrapS = tex.wrapT = THREE.RepeatWrapping; tex.repeat.set(opts.repeat[0], opts.repeat[1]); }
    tex.redraw = (fn) => { ctx.clearRect(0, 0, w, h); fn(ctx, w, h); tex.needsUpdate = true; };
    tex.canvas2d = cv; tex.ctx = ctx;
    return tex;
  };
  // A flat piece of text living in the 3D world. K.textPlane('Hello', { font: '800 160px "Inter"', color: '#fff',
  // height: 0.5 }) -> Mesh whose world height is `height` units per line. opts: align, lineHeight, glow (emissive
  // multiplier for bloom), lit (use a lit material so it takes shadows), maxWidthPx, letterSpacing (px), pad (px).
  K.textPlane = (text, o = {}) => {
    const font = o.font || '700 160px "Inter"', px = +(/(\d+(?:\.\d+)?)px/.exec(font) || [0, 160])[1];
    const lines = String(text).split('\n'), lh = (o.lineHeight || 1.12) * px, pad = o.pad == null ? Math.ceil(px * 0.25) : o.pad;
    const m = document.createElement('canvas').getContext('2d'); m.font = font;
    if (o.letterSpacing) m.letterSpacing = o.letterSpacing + 'px';
    const wpx = Math.ceil(Math.max(...lines.map((l) => m.measureText(l).width))) + pad * 2, hpx = Math.ceil(lh * lines.length) + pad * 2;
    const tex = K.canvasTex(wpx, hpx, (ctx) => {
      ctx.font = font; if (o.letterSpacing) ctx.letterSpacing = o.letterSpacing + 'px';
      ctx.textBaseline = 'middle'; ctx.textAlign = o.align || 'center'; ctx.fillStyle = o.color || '#ffffff';
      const x = o.align === 'left' ? pad : o.align === 'right' ? wpx - pad : wpx / 2;
      lines.forEach((l, i) => ctx.fillText(l, x, pad + lh * (i + 0.5)));
    });
    const unit = (o.height || 1) / px, hWorld = hpx * unit, wWorld = wpx * unit; // `height` = world size of the font's px size
    const mat = o.lit
      ? new THREE.MeshStandardMaterial({ map: tex, transparent: true, alphaTest: 0.02, roughness: o.roughness == null ? 0.8 : o.roughness, metalness: 0 })
      : new THREE.MeshBasicMaterial({ map: tex, transparent: true, depthWrite: false });
    if (o.glow && !o.lit) mat.color.setScalar(o.glow);
    const mesh = new THREE.Mesh(new THREE.PlaneGeometry(wWorld, hWorld), mat);
    mesh.userData.size = [wWorld, hWorld]; mesh.userData.tex = tex;
    return mesh;
  };
  // Box with rounded edges, centred on the origin. r = edge radius, seg = roundness.
  K.roundedBox = (w, h, d, r = 0.05, seg = 6) => {
    r = Math.max(1e-4, Math.min(r, w / 2, h / 2, d / 2));
    const N = 2 * seg + 1, g = new THREE.BoxGeometry(2, 2, 2, N, N, N), p = g.attributes.position, nrm = g.attributes.normal;
    const half = [w / 2 - r, h / 2 - r, d / 2 - r], v = new THREE.Vector3();
    for (let i = 0; i < p.count; i++) {
      const c = [p.getX(i), p.getY(i), p.getZ(i)], inner = [0, 0, 0], a = [0, 0, 0];
      for (let k = 0; k < 3; k++) {
        const idx = Math.round((c[k] + 1) * N / 2), side = idx <= seg ? -1 : 1;
        a[k] = idx <= seg ? -(1 - idx / seg) : (idx - seg - 1) / seg; inner[k] = side * half[k];
      }
      v.set(Math.tan(a[0] * Math.PI / 4), Math.tan(a[1] * Math.PI / 4), Math.tan(a[2] * Math.PI / 4)).normalize();
      p.setXYZ(i, inner[0] + v.x * r, inner[1] + v.y * r, inner[2] + v.z * r); nrm.setXYZ(i, v.x, v.y, v.z);
    }
    // UVs: each of the six sides is mapped flat, 0..1 across the whole side, so textures are not stretched at the corners
    const uv = g.attributes.uv, per = (N + 1) * (N + 1), sz = [w, h, d];
    const ax = [[2, 1, -1], [2, 1, 1], [0, 2, 1, -1], [0, 2, 1, 1], [0, 1, 1], [0, 1, -1]];   // [u axis, v axis, u sign, v sign] for +x -x +y -y +z -z
    for (let i = 0; i < p.count; i++) {
      const f = ax[Math.min(5, Math.floor(i / per))], c = [p.getX(i), p.getY(i), p.getZ(i)];
      uv.setXY(i, f[2] * c[f[0]] / sz[f[0]] + 0.5, (f[3] || 1) * c[f[1]] / sz[f[1]] + 0.5);
    }
    g.computeBoundingBox(); g.computeBoundingSphere();
    return g;
  };
  // Flat rounded rectangle (a card, a screen, a tile), in the XY plane facing +Z, with UVs 0..1 across it.
  K.roundedRect = (w, h, r = 0.05, seg = 8) => {
    const s = new THREE.Shape(), x = w / 2, y = h / 2; r = Math.min(r, x, y);
    s.moveTo(-x + r, -y); s.lineTo(x - r, -y); s.absarc(x - r, -y + r, r, -Math.PI / 2, 0); s.lineTo(x, y - r); s.absarc(x - r, y - r, r, 0, Math.PI / 2);
    s.lineTo(-x + r, y); s.absarc(-x + r, y - r, r, Math.PI / 2, Math.PI); s.lineTo(-x, -y + r); s.absarc(-x + r, -y + r, r, Math.PI, Math.PI * 1.5);
    const g = new THREE.ShapeGeometry(s, seg), p = g.attributes.position, uv = g.attributes.uv;
    for (let i = 0; i < p.count; i++) uv.setXY(i, p.getX(i) / w + 0.5, p.getY(i) / h + 0.5);
    return g;
  };
  // Tube along a list of [x,y,z] points (smooth Catmull-Rom). closed loops allowed.
  K.tube = (pts, radius = 0.05, o = {}) => {
    const curve = new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(p[0], p[1], p[2] || 0)), !!o.closed, 'centripetal');
    const g = new THREE.TubeGeometry(curve, o.segments || Math.max(8, pts.length * 3), radius, o.radial || 12, !!o.closed);
    g.userData.curve = curve;
    return g;
  };
  // Set instance i of an InstancedMesh: K.place(mesh, i, [x,y,z], [rx,ry,rz], scale | [sx,sy,sz]). Call
  // mesh.instanceMatrix.needsUpdate = true once after a batch.
  const _o = new THREE.Object3D();
  K.place = (mesh, i, p, r, s) => {
    _o.position.set(p[0], p[1], p[2]); if (r) _o.rotation.set(r[0], r[1], r[2]); else _o.rotation.set(0, 0, 0);
    if (s == null) _o.scale.set(1, 1, 1); else if (typeof s === 'number') _o.scale.set(s, s, s); else _o.scale.set(s[0], s[1], s[2]);
    _o.updateMatrix(); mesh.setMatrixAt(i, _o.matrix);
  };
  // Camera: position, look-at target, optional fov and roll. K.focus sets the lens: focus distance (or a point to
  // focus on) and aperture radius in world units (0 = everything sharp).
  const _v = new THREE.Vector3();
  K.look = (cam, pos, target, fov, roll) => {
    cam.position.set(pos[0], pos[1], pos[2]); cam.up.set(0, 1, 0); cam.lookAt(target[0], target[1], target[2]);
    if (roll) cam.rotateZ(roll);
    if (fov && fov !== cam.fov) { cam.fov = fov; cam.updateProjectionMatrix(); }
  };
  K.focus = (cam, at, aperture) => {
    cam.userData.focus = typeof at === 'number' ? at : _v.set(at[0], at[1], at[2]).distanceTo(cam.position);
    if (aperture != null) cam.userData.aperture = aperture;
  };

  // ---------------------------------------------------------------- lighting
  // Code-built lighting environment for reflections and soft fill (replaces an HDRI). K.env(S, { top, horizon,
  // bottom: sky gradient colours; panels: [{ pos:[x,y,z], size:[w,h], color, power }] bright rectangles that face the
  // origin (softboxes, windows, a sun); intensity; background: true to also show it behind the scene; blur }).
  // Metal and glass can only shine if the environment has something bright in it.
  K.env = (S, o = {}) => {
    const es = new THREE.Scene();
    const sky = new THREE.Mesh(new THREE.SphereGeometry(60, 48, 24), new THREE.ShaderMaterial({
      side: THREE.BackSide, depthWrite: false,
      uniforms: { top: { value: new THREE.Color(o.top || '#0b0d12') }, hor: { value: new THREE.Color(o.horizon || o.top || '#14171f') }, bot: { value: new THREE.Color(o.bottom || o.horizon || '#050506') }, gain: { value: o.skyPower == null ? 1 : o.skyPower } },
      vertexShader: 'varying vec3 vD; void main(){ vD = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); }',
      fragmentShader: 'varying vec3 vD; uniform vec3 top, hor, bot; uniform float gain; void main(){ float y = normalize(vD).y; vec3 c = y > 0.0 ? mix(hor, top, pow(y, 0.6)) : mix(hor, bot, pow(-y, 0.5)); gl_FragColor = vec4(c * gain, 1.0); }',
    }));
    es.add(sky);
    for (const p of o.panels || []) {
      const c = new THREE.Color(p.color || '#ffffff').multiplyScalar(p.power == null ? 5 : p.power);
      const m = new THREE.Mesh(p.round ? new THREE.CircleGeometry((p.size ? p.size[0] : 4) / 2, 40) : new THREE.PlaneGeometry(p.size ? p.size[0] : 4, p.size ? p.size[1] : 4), new THREE.MeshBasicMaterial({ color: c, side: THREE.DoubleSide }));
      m.position.set(p.pos[0], p.pos[1], p.pos[2]); m.lookAt(0, p.aimY || 0, 0); es.add(m);
    }
    const pm = new THREE.PMREMGenerator(S.renderer);
    const rt = pm.fromScene(es, o.blur == null ? 0.02 : o.blur, 0.1, 200);
    pm.dispose();
    S.scene.environment = rt.texture;
    S.scene.environmentIntensity = o.intensity == null ? 1 : o.intensity;
    if (o.background) { S.scene.background = rt.texture; S.scene.backgroundBlurriness = o.backgroundBlur == null ? 0.5 : o.backgroundBlur; S.scene.backgroundIntensity = o.backgroundIntensity == null ? 1 : o.backgroundIntensity; }
    return rt.texture;
  };
  // A shadow-casting spot light with a real size: `soft` is the radius of the light's surface in world units, which
  // gives true soft-edged shadows (bigger = softer). o: pos, target, color, power, angle, penumbra, soft, mapSize, near, far.
  K.spot = (S, o = {}) => {
    const l = new THREE.SpotLight(o.color || '#ffffff', o.power == null ? 80 : o.power, o.distance || 0, o.angle == null ? 0.5 : o.angle, o.penumbra == null ? 0.6 : o.penumbra, o.decay == null ? 2 : o.decay);
    l.position.set(...(o.pos || [3, 6, 4])); l.target.position.set(...(o.target || [0, 0, 0]));
    l.castShadow = o.shadow !== false; l.shadow.mapSize.setScalar(o.mapSize || 2048); l.shadow.bias = o.bias == null ? -0.0004 : o.bias; l.shadow.normalBias = o.normalBias == null ? 0.02 : o.normalBias;
    l.shadow.camera.near = o.near || 0.5; l.shadow.camera.far = o.far || 60;
    S.scene.add(l, l.target);
    if (o.soft) S.softLights.push({ light: l, radius: o.soft });
    return l;
  };
  // A sun: parallel light with shadows. `size` is the half-width of the area that gets shadows, `soft` the blur of
  // shadow edges in world units at the light (0.3-1.5 looks natural). o: pos, target, color, power, size, soft, mapSize.
  K.sun = (S, o = {}) => {
    const l = new THREE.DirectionalLight(o.color || '#ffffff', o.power == null ? 3 : o.power);
    l.position.set(...(o.pos || [6, 10, 5])); l.target.position.set(...(o.target || [0, 0, 0]));
    const s = o.size || 8, c = l.shadow.camera;
    l.castShadow = o.shadow !== false; c.left = -s; c.right = s; c.top = s; c.bottom = -s; c.near = 0.5; c.far = o.far || 80;
    l.shadow.mapSize.setScalar(o.mapSize || 2048); l.shadow.bias = o.bias == null ? -0.0004 : o.bias; l.shadow.normalBias = o.normalBias == null ? 0.02 : o.normalBias;
    S.scene.add(l, l.target);
    if (o.soft) S.softLights.push({ light: l, radius: o.soft });
    return l;
  };
  // Sky light with real occlusion: light arrives from the whole dome and is blocked by objects, so creases, contact
  // points and the ground under things darken softly (ambient occlusion, but physically made). o: color, power,
  // size (half-width covered), center, mapSize, spread (1 = full dome, lower = more from above).
  K.skyLight = (S, o = {}) => {
    const l = new THREE.DirectionalLight(o.color || '#ffffff', o.power == null ? 1.5 : o.power);
    const s = o.size || 8, c = l.shadow.camera;
    l.castShadow = true; c.left = -s; c.right = s; c.top = s; c.bottom = -s; c.near = 0.5; c.far = (o.dist || 30) * 2;
    l.shadow.mapSize.setScalar(o.mapSize || 1024); l.shadow.bias = o.bias == null ? -0.0006 : o.bias; l.shadow.normalBias = o.normalBias == null ? 0.03 : o.normalBias;
    l.target.position.set(...(o.center || [0, 0, 0]));
    S.scene.add(l, l.target);
    S.skyLights.push({ light: l, dist: o.dist || 30, spread: o.spread == null ? 1 : o.spread });
    return l;
  };
  // A real mirror floor at height y: reflects the scene, and still takes light and shadows like a normal material.
  // o: y, size, color, roughness (0 = perfect mirror, 0.3 = soft blurred reflection), strength (0..1), metalness,
  // fresnel (true = reflects more at grazing angles, like polished stone or wet ground), map/normalMap etc via `material`.
  K.mirrorFloor = (S, o = {}) => {
    const y = o.y || 0, W = S.W, H = S.H, scale = o.resolution || 1;
    const rt = new THREE.WebGLRenderTarget(Math.round(W * scale), Math.round(H * scale), { type: THREE.HalfFloatType, samples: S.msaa, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter });
    const mat = new THREE.MeshStandardMaterial(Object.assign({ color: o.color || '#111114', roughness: o.surfaceRoughness == null ? 0.35 : o.surfaceRoughness, metalness: o.metalness || 0 }, o.material || {}));
    const u = { tMirror: { value: rt.texture }, uMirrorMatrix: { value: new THREE.Matrix4() }, uMirrorStrength: { value: o.strength == null ? 0.6 : o.strength }, uMirrorFresnel: { value: o.fresnel === false ? 0 : 1 }, uMirrorFade: { value: o.fade || 0 }, uMirrorBlur: { value: (o.roughness || 0) * 7 } };
    mat.onBeforeCompile = (sh) => {
      Object.assign(sh.uniforms, u);
      sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nuniform mat4 uMirrorMatrix; varying vec4 vMirrorCoord; varying vec3 vMirrorWorld;')
        .replace('#include <begin_vertex>', '#include <begin_vertex>\nvec4 mw = modelMatrix * vec4(transformed, 1.0); vMirrorWorld = mw.xyz; vMirrorCoord = uMirrorMatrix * mw;');
      sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nuniform sampler2D tMirror; uniform float uMirrorStrength, uMirrorFresnel, uMirrorFade, uMirrorBlur; varying vec4 vMirrorCoord; varying vec3 vMirrorWorld;')
        .replace('#include <opaque_fragment>', `vec3 mRefl = min(texture2DProj(tMirror, vMirrorCoord, uMirrorBlur).rgb, vec3(12.0));
          float mF = pow(1.0 - saturate(dot(normalize(vViewPosition), normal)), 5.0);
          float mK = uMirrorStrength * mix(1.0, 0.06 + 0.94 * mF, uMirrorFresnel);
          if (uMirrorFade > 0.0) mK *= exp(-length(vMirrorWorld.xz) / uMirrorFade);
          outgoingLight += mRefl * mK;
          #include <opaque_fragment>`);
    };
    const mesh = new THREE.Mesh(new THREE.PlaneGeometry(o.size || 80, o.size || 80), mat);
    mesh.rotation.x = -Math.PI / 2; mesh.position.y = y; mesh.receiveShadow = true;
    S.scene.add(mesh);
    S.mirrors.push({ mesh, rt, u, y, rough: o.roughness || 0, cam: new THREE.PerspectiveCamera() });
    return mesh;
  };

  // ---------------------------------------------------------------- the stage
  const QUAD_VS = 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }';
  const TONE = `
    vec3 tmFilmic(vec3 c){ // ACES fitted (Stephen Hill)
      mat3 a = mat3(0.59719,0.07600,0.02840, 0.35458,0.90834,0.13383, 0.04823,0.01566,0.83777);
      mat3 b = mat3(1.60475,-0.10208,-0.00327, -0.53108,1.10813,-0.07276, -0.07367,-0.00605,1.07602);
      c = a * (c / 0.6); vec3 x = c * (c + 0.0245786) - 0.000090537; vec3 y = c * (0.983729 * c + 0.4329510) + 0.238081;
      return clamp(b * (x / y), 0.0, 1.0);
    }
    vec3 tmNeutral(vec3 c){ // Khronos PBR neutral: keeps colours true, only compresses highlights
      float x = min(c.r, min(c.g, c.b)); float off = x < 0.08 ? x - 6.25 * x * x : 0.04; c -= off;
      float peak = max(c.r, max(c.g, c.b)); if (peak < 0.76) return c;
      float d = 1.0 - 0.76; float np = 1.0 - d * d / (peak + d - 0.76); c *= np / peak;
      float g = 1.0 - 1.0 / (0.15 * (peak - np) + 1.0); return mix(c, vec3(np), g);
    }
    vec3 tmAgx(vec3 c){ // AgX (minimal, Benjamin Wrensch): soft, filmic, desaturates bright colours gracefully
      mat3 m = mat3(0.842479062253094,0.0423282422610123,0.0423756549057051, 0.0784335999999992,0.878468636469772,0.0784336, 0.0792237451477643,0.0791661274605434,0.879142973793104);
      mat3 mi = mat3(1.19687900512017,-0.0528968517574562,-0.0529716355144438, -0.0980208811401368,1.15190312990417,-0.0980434501171241, -0.0990297440797205,-0.0989611768448433,1.15107367264116);
      c = m * c; c = clamp((log2(max(c, 1e-10)) + 12.47393) / 16.5, 0.0, 1.0);
      vec3 x2 = c * c, x4 = x2 * x2;
      c = 15.5 * x4 * x2 - 40.14 * x4 * c + 31.96 * x4 - 6.868 * x2 * c + 0.4298 * x2 + 0.1191 * c - 0.00232;
      c = mi * c; return pow(max(c, 0.0), vec3(2.2));
    }`;

  function pass(frag, uniforms) {
    return new THREE.ShaderMaterial({ vertexShader: QUAD_VS, fragmentShader: 'precision highp float; varying vec2 vUv;\n' + frag, uniforms, depthTest: false, depthWrite: false });
  }

  // createStage(canvas, style, { samples }) -> S. S.seek(t) renders one finished frame.
  K.createStage = (canvas, style, opts = {}) => {
    const R = Object.assign({ samples: 32, preview: 3, shutter: 0.5, fps: 30, exposure: 1, tone: 'filmic', bloom: 0.25, bloomThreshold: 1.0, bloomRadius: 1, vignette: 0.25, grain: 0.03, ca: 0, saturation: 1, contrast: 1, lift: 0, fov: 35, near: 0.1, far: 200, background: '#000000', shadows: true }, style.render || {});
    const W = opts.width || 1920, H = opts.height || 1080;
    const N = Math.max(1, opts.samples || R.samples);
    const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, alpha: false, preserveDrawingBuffer: true, powerPreference: 'high-performance' });
    renderer.setPixelRatio(1); renderer.setSize(W, H, false);
    renderer.toneMapping = THREE.NoToneMapping;
    renderer.shadowMap.enabled = !!R.shadows; renderer.shadowMap.type = R.shadowType === 'vsm' ? THREE.VSMShadowMap : THREE.PCFShadowMap;
    const scene = new THREE.Scene(); scene.background = new THREE.Color(R.background);
    const camera = new THREE.PerspectiveCamera(R.fov, W / H, R.near, R.far);
    camera.position.set(0, 1.5, 8); camera.userData.aperture = 0; camera.userData.focus = 8;
    const msaa = N >= 8 ? 0 : 4;
    const S = { THREE, K, renderer, scene, camera, W, H, style, R, samples: N, msaa, softLights: [], skyLights: [], mirrors: [], duration: style.duration || 6 };

    const HF = { type: THREE.HalfFloatType, depthBuffer: false };
    const sceneRT = new THREE.WebGLRenderTarget(W, H, { type: THREE.HalfFloatType, samples: msaa });
    const accRT = new THREE.WebGLRenderTarget(W, H, HF);
    const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2));
    const qScene = new THREE.Scene(); qScene.add(quad);
    const qCam = new THREE.Camera();
    const draw = (mat, target) => { quad.material = mat; renderer.setRenderTarget(target); renderer.render(qScene, qCam); };

    const mAcc = pass('uniform sampler2D tex; uniform float w; void main(){ gl_FragColor = vec4(min(texture2D(tex, vUv).rgb, vec3(64.0)) * w, w); }', { tex: { value: sceneRT.texture }, w: { value: 1 } });
    mAcc.blending = THREE.CustomBlending; mAcc.blendEquation = THREE.AddEquation; mAcc.blendSrc = THREE.OneFactor; mAcc.blendDst = THREE.OneFactor; mAcc.transparent = true;

    // bloom: threshold, then a chain of down-samples and smooth up-samples (wide, soft, no blockiness)
    const LV = 7, bl = [];
    for (let i = 0, w = W >> 1, h = H >> 1; i < LV && w > 4 && h > 4; i++, w >>= 1, h >>= 1) bl.push({ d: new THREE.WebGLRenderTarget(w, h, HF), u: new THREE.WebGLRenderTarget(w, h, HF), w, h });
    const mPre = pass('uniform sampler2D tex; uniform float thr; void main(){ vec3 c = min(texture2D(tex, vUv).rgb, vec3(60.0)); float l = max(c.r, max(c.g, c.b)); float k = clamp((l - thr) / max(thr * 0.5, 1e-3), 0.0, 1.0); gl_FragColor = vec4(c * k * k * (3.0 - 2.0 * k), 1.0); }', { tex: { value: accRT.texture }, thr: { value: R.bloomThreshold } });
    const mDown = pass(`uniform sampler2D tex; uniform vec2 px;
      void main(){ vec3 a = texture2D(tex, vUv + px * vec2(-2, 2)).rgb, b = texture2D(tex, vUv + px * vec2(0, 2)).rgb, c = texture2D(tex, vUv + px * vec2(2, 2)).rgb,
        d = texture2D(tex, vUv + px * vec2(-2, 0)).rgb, e = texture2D(tex, vUv).rgb, f = texture2D(tex, vUv + px * vec2(2, 0)).rgb,
        g = texture2D(tex, vUv + px * vec2(-2, -2)).rgb, h = texture2D(tex, vUv + px * vec2(0, -2)).rgb, i = texture2D(tex, vUv + px * vec2(2, -2)).rgb,
        j = texture2D(tex, vUv + px * vec2(-1, 1)).rgb, k = texture2D(tex, vUv + px * vec2(1, 1)).rgb, l = texture2D(tex, vUv + px * vec2(-1, -1)).rgb, m = texture2D(tex, vUv + px * vec2(1, -1)).rgb;
        gl_FragColor = vec4(e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125, 1.0); }`, { tex: { value: null }, px: { value: new THREE.Vector2() } });
    const mUp = pass(`uniform sampler2D tex, add; uniform vec2 px; uniform float r;
      void main(){ vec2 o = px * r; vec3 s = texture2D(tex, vUv).rgb * 4.0 + (texture2D(tex, vUv + vec2(o.x, 0)).rgb + texture2D(tex, vUv - vec2(o.x, 0)).rgb + texture2D(tex, vUv + vec2(0, o.y)).rgb + texture2D(tex, vUv - vec2(0, o.y)).rgb) * 2.0
        + texture2D(tex, vUv + o).rgb + texture2D(tex, vUv - o).rgb + texture2D(tex, vUv + vec2(o.x, -o.y)).rgb + texture2D(tex, vUv + vec2(-o.x, o.y)).rgb;
        gl_FragColor = vec4(s / 16.0 + texture2D(add, vUv).rgb, 1.0); }`, { tex: { value: null }, add: { value: null }, px: { value: new THREE.Vector2() }, r: { value: R.bloomRadius } });

    const ovCanvas = document.createElement('canvas'); ovCanvas.width = W; ovCanvas.height = H;
    const ovCtx = ovCanvas.getContext('2d');
    const ovTex = new THREE.CanvasTexture(ovCanvas); ovTex.colorSpace = THREE.NoColorSpace; ovTex.premultiplyAlpha = true; ovTex.generateMipmaps = false; ovTex.minFilter = THREE.LinearFilter;
    const mOut = pass(TONE + `
      uniform sampler2D tex, bloom; uniform float exposure, bloomK, vig, ca, sat, con, lift, levels; uniform int tone; uniform vec2 res;
      void main(){
        vec2 d = vUv - 0.5; float r2 = dot(d, d);
        vec3 c;
        if (ca > 0.0) { c.r = texture2D(tex, 0.5 + d * (1.0 + ca * r2)).r; c.g = texture2D(tex, vUv).g; c.b = texture2D(tex, 0.5 + d * (1.0 - ca * r2)).b; }
        else c = texture2D(tex, vUv).rgb;
        c += texture2D(bloom, vUv).rgb * bloomK / levels;
        c = max(c * exposure, 0.0);
        c = tone == 0 ? tmFilmic(c) : tone == 1 ? tmNeutral(c) : tone == 2 ? tmAgx(c) : clamp(c, 0.0, 1.0);
        float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
        c = mix(vec3(l), c, sat); c = (c - 0.5) * con + 0.5; c = c + lift * (1.0 - c);
        c *= 1.0 - vig * smoothstep(0.22, 0.8, length(d * vec2(1.0, 0.82)));
        c = clamp(c, 0.0, 1.0);
        c = mix(c * 12.92, 1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, c));
        gl_FragColor = vec4(c, 1.0);
      }`, { tex: { value: accRT.texture }, bloom: { value: null }, exposure: { value: R.exposure }, bloomK: { value: R.bloom }, vig: { value: R.vignette }, ca: { value: R.ca }, sat: { value: R.saturation }, con: { value: R.contrast }, lift: { value: R.lift }, levels: { value: 1 }, tone: { value: { filmic: 0, neutral: 1, agx: 2, linear: 3 }[R.tone] ?? 0 }, res: { value: new THREE.Vector2(W, H) } });

    // after grading the picture is 8-bit display colour: optional style filters run here (painterly, dither, halftone...),
    // then grain and the 2D overlay go on top
    const LD = { depthBuffer: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter };
    const ldA = new THREE.WebGLRenderTarget(W, H, LD), ldB = new THREE.WebGLRenderTarget(W, H, LD);
    const mFin = pass(`uniform sampler2D tex, ov; uniform float grain, seed, useOv;
      float h21(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
      void main(){ vec3 c = texture2D(tex, vUv).rgb; float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
        float g = (h21(gl_FragCoord.xy + seed) + h21(gl_FragCoord.xy * 1.37 + seed * 1.7) - 1.0);
        c += g * grain * (0.55 + 0.45 * (1.0 - l));
        if (useOv > 0.5) { vec4 o = texture2D(ov, vUv); c = o.rgb + c * (1.0 - o.a); }
        gl_FragColor = vec4(c, 1.0); }`, { tex: { value: ldA.texture }, ov: { value: ovTex }, grain: { value: R.grain }, seed: { value: 0 }, useOv: { value: 0 } });
    const filters = [];
    // S.addFilter(fragmentShaderBody, uniforms): a full-screen pass over the graded picture. The shader gets
    // `uniform sampler2D tex; uniform vec2 res; uniform float time; varying vec2 vUv;` and must set gl_FragColor.
    S.addFilter = (frag, uniforms = {}) => { const m = pass('uniform sampler2D tex; uniform vec2 res; uniform float time;\n' + frag, Object.assign({ tex: { value: null }, res: { value: new THREE.Vector2(W, H) }, time: { value: 0 } }, uniforms)); filters.push(m); return m; };

    let api = null;
    const cp = new THREE.Vector3(), right = new THREE.Vector3(), up = new THREE.Vector3(), tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), nrm = new THREE.Vector3();
    const rot = new THREE.Matrix4(), plane = new THREE.Plane(), clip = new THREE.Vector4(), q = new THREE.Vector4(), saved = [];

    function renderMirrors(i) {
      for (const m of S.mirrors) {
        const cam = m.cam;
        // roughness: tilt the mirror plane a little differently on each sub-render, which blurs the reflection
        const a = m.rough * 0.12, th = 2 * Math.PI * halton(i + 1, 7), rr = Math.sqrt(halton(i + 1, 11)) * a;
        nrm.set(Math.cos(th) * rr, 1, Math.sin(th) * rr).normalize();
        const origin = tmp2.set(0, m.y, 0);
        camera.getWorldPosition(cp);
        const view = tmp.copy(origin).sub(cp);
        if (view.dot(nrm) > 0) continue;
        view.reflect(nrm).negate().add(origin);
        rot.extractRotation(camera.matrixWorld);
        const look = new THREE.Vector3(0, 0, -1).applyMatrix4(rot).add(cp);
        const target = origin.clone().sub(look).reflect(nrm).negate().add(origin);
        cam.position.copy(view); cam.up.set(0, 1, 0).applyMatrix4(rot).reflect(nrm); cam.lookAt(target);
        cam.near = camera.near; cam.far = camera.far; cam.updateMatrixWorld(); cam.projectionMatrix.copy(camera.projectionMatrix);
        m.u.uMirrorMatrix.value.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1).multiply(cam.projectionMatrix).multiply(cam.matrixWorldInverse);
        // clip everything below the mirror (oblique near plane)
        plane.setFromNormalAndCoplanarPoint(nrm, origin).applyMatrix4(cam.matrixWorldInverse);
        clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant);
        const pm = cam.projectionMatrix.elements;
        q.x = (Math.sign(clip.x) + pm[8]) / pm[0]; q.y = (Math.sign(clip.y) + pm[9]) / pm[5]; q.z = -1; q.w = (1 + pm[10]) / pm[14];
        clip.multiplyScalar(2 / clip.dot(q));
        pm[2] = clip.x; pm[6] = clip.y; pm[10] = clip.z + 1 - 0.003; pm[14] = clip.w;
        m.mesh.visible = false;
        renderer.setRenderTarget(m.rt); renderer.render(scene, cam);
        m.mesh.visible = true;
      }
    }

    function subRender(t, i, n) {
      api.update(t);
      saved.length = 0;
      // lights with a size: sample a different point on the light each sub-render
      S.softLights.forEach((s, k) => {
        const l = s.light; saved.push([l, l.position.clone()]);
        if (n === 1) return;
        const u = (halton(i + 1, 3) + k * 0.37) % 1, v = (halton(i + 1, 5) + k * 0.61) % 1, r = Math.sqrt(u) * s.radius, a = 2 * Math.PI * v;
        tmp.copy(l.position).sub(l.target ? l.target.position : tmp2.set(0, 0, 0)).normalize();
        right.set(0, 1, 0).cross(tmp); if (right.lengthSq() < 1e-6) right.set(1, 0, 0); right.normalize(); up.crossVectors(tmp, right);
        l.position.addScaledVector(right, Math.cos(a) * r).addScaledVector(up, Math.sin(a) * r);
      });
      S.skyLights.forEach((s, k) => {
        const u = (halton(i + 1, 2) + k * 0.31) % 1, v = (halton(i + 1, 3) + k * 0.53) % 1;
        const sinT = Math.sqrt(u) * s.spread, cosT = Math.sqrt(Math.max(0, 1 - sinT * sinT)), a = 2 * Math.PI * v;
        const c = s.light.target.position;
        if (n === 1) s.light.position.set(c.x + 0.15 * s.dist, c.y + s.dist, c.z + 0.1 * s.dist);
        else s.light.position.set(c.x + Math.cos(a) * sinT * s.dist, c.y + cosT * s.dist, c.z + Math.sin(a) * sinT * s.dist);
      });
      // lens: move the camera across the aperture and shear the view so the focus plane stays put (true depth of field)
      camera.updateMatrixWorld(); camera.updateProjectionMatrix();
      const camPos = camera.position.clone(), e = camera.projectionMatrix.elements;
      if (n > 1) {
        const ap = camera.userData.aperture || 0, fd = Math.max(0.05, camera.userData.focus || 8);
        if (ap > 0) {
          const r = Math.sqrt(halton(i + 1, 2)) * ap, a = 2 * Math.PI * halton(i + 1, 3), dx = Math.cos(a) * r, dy = Math.sin(a) * r;
          right.setFromMatrixColumn(camera.matrixWorld, 0); up.setFromMatrixColumn(camera.matrixWorld, 1);
          camera.position.addScaledVector(right, dx).addScaledVector(up, dy); camera.updateMatrixWorld();
          e[8] -= e[0] * dx / fd; e[9] -= e[5] * dy / fd;
        }
        e[8] += (halton(i + 1, 5) - 0.5) * 2 / W; e[9] += (halton(i + 1, 7) - 0.5) * 2 / H;
        camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
      }
      if (S.mirrors.length) renderMirrors(i);
      renderer.setRenderTarget(sceneRT); renderer.render(scene, camera);
      camera.position.copy(camPos); camera.updateMatrixWorld(); camera.updateProjectionMatrix();
      for (const [l, p] of saved) l.position.copy(p);
    }

    S.seek = (t, sampleOverride) => {
      const n = sampleOverride || S.samples;
      renderer.setRenderTarget(accRT); renderer.setClearColor(0x000000, 0); renderer.clear();
      mAcc.uniforms.w.value = 1 / n;
      for (let i = 0; i < n; i++) {
        const ts = n > 1 ? t + ((i + 0.5) / n - 0.5) * R.shutter / R.fps : t;
        subRender(K.clamp(ts, 0, S.duration), i, n);
        renderer.autoClear = false; draw(mAcc, accRT); renderer.autoClear = true;
      }
      api.update(t); // leave the scene at the exact frame time (for the overlay and anything that reads it)
      let bloomTex = null;
      if (R.bloom > 0) {
        mPre.uniforms.thr.value = R.bloomThreshold; draw(mPre, bl[0].d);
        for (let i = 1; i < bl.length; i++) { mDown.uniforms.tex.value = bl[i - 1].d.texture; mDown.uniforms.px.value.set(1 / bl[i - 1].w, 1 / bl[i - 1].h); draw(mDown, bl[i].d); }
        let prev = bl[bl.length - 1].d;
        for (let i = bl.length - 2; i >= 0; i--) { mUp.uniforms.tex.value = prev.texture; mUp.uniforms.add.value = bl[i].d.texture; mUp.uniforms.px.value.set(1 / prev.width, 1 / prev.height); draw(mUp, bl[i].u); prev = bl[i].u; }
        bloomTex = prev.texture;
      }
      const o = mOut.uniforms;
      o.bloom.value = bloomTex; o.bloomK.value = bloomTex ? R.bloom : 0; o.levels.value = bl.length; o.exposure.value = R.exposure; o.vig.value = R.vignette; o.ca.value = R.ca; o.sat.value = R.saturation; o.con.value = R.contrast; o.lift.value = R.lift;
      draw(mOut, ldA);
      let src = ldA, dst = ldB;
      for (const f of filters) { f.uniforms.tex.value = src.texture; f.uniforms.time.value = t; draw(f, dst); [src, dst] = [dst, src]; }
      const fu = mFin.uniforms;
      fu.tex.value = src.texture; fu.grain.value = R.grain; fu.seed.value = Math.round(t * R.fps) * 17.0 % 1000;
      if (api.overlay) { ovCtx.clearRect(0, 0, W, H); ovCtx.save(); api.overlay(ovCtx, t, W, H); ovCtx.restore(); ovTex.needsUpdate = true; fu.useOv.value = 1; } else fu.useOv.value = 0;
      draw(mFin, null);
    };
    S.setApi = (a) => { api = typeof a === 'function' ? { update: a } : a; };
    return S;
  };

  // Load fonts, build the style and return its stage. `K.run(canvas, style, { samples })`.
  K.run = async (canvas, style, opts) => {
    if (style.fonts && document.fonts) await Promise.all(style.fonts.map((f) => document.fonts.load(f).catch(() => null)));
    const S = K.createStage(canvas, style, opts);
    S.setApi(await style.build(S));
    return S;
  };

  root.K = K;
})(typeof window !== 'undefined' ? window : globalThis);
```

SOUND KIT (lib/sound.js)
```js
// sound.js: a small synthesized sound kit for the style explainers. Plain Web Audio, no audio files.
// (play(..., { minor: true }), tone/noise { minor: true }, or scheduled inside k.withMinor(() => ...)) at about 60%
// volume instead of full, and sits all effects a little lower, so the narration stays on top while the piece still
// sounds alive. In the full mix, minor sounds play at full volume. Scores can read k.vo to branch further.
// A style adds   explainerSound(k) { k.bed('room', 0, D); k.play('pop', 1.25); ... }   and the same
// call schedules into a live AudioContext (the player) or an OfflineAudioContext (the video render).
// Times are seconds on the explainer's own clock. Randomness is seeded, so every render is identical.
(function () {
  'use strict';
  const SOUND = (window.SOUND = {});
  const TINY = 1e-4;

  // seeded random in [0,1), keyed by any string
  function rand(key) {
    let h = 2166136261;
    for (let i = 0; i < key.length; i++) { h ^= key.charCodeAt(i); h = Math.imul(h, 16777619); }
    let a = h >>> 0 || 1;
    return () => { 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; };
  }

  // note names to Hz: 'A4' = 440, 'C#5', 'Eb3'
  const STEP = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };
  function hz(n) {
    if (typeof n === 'number') return n;
    const m = /^([A-G])([#b]?)(-?\d)$/.exec(n);
    const semis = STEP[m[1]] + (m[2] === '#' ? 1 : m[2] === 'b' ? -1 : 0) + (Number(m[3]) - 4) * 12 - 9;
    return 440 * Math.pow(2, semis / 12);
  }
  SOUND.hz = hz;

  SOUND.kit = function (ctx, opts) {
    const o = opts || {};
    const VO = !!o.voiceover;
    const MINOR = 0.6; // voiceover-mode volume for minor sounds
    let inMinor = false;
    const gainOf = (p, d) => (p.gain == null ? d : p.gain) * (VO && (p.minor || inMinor) ? MINOR : 1);
    const T0 = (o.start || 0) - 0; // explainer time that maps to ctx time `base`
    const base = ctx.currentTime + (o.delay || 0);
    // Start times snap to the sample grid (+ a quarter sample): in Chrome a source started a hair off the grid can
    // spike to about twice its set level.
    const SR = ctx.sampleRate;
    const at = (t) => (Math.round((base + (t - T0)) * SR) + 0.25) / SR;

    // ---- effect and ambience buses feed the master output
    const master = ctx.createGain(); master.gain.value = o.master == null ? 0.9 : o.master;
    const comp = ctx.createDynamicsCompressor();
    comp.threshold.value = -16; comp.knee.value = 8; comp.ratio.value = 3; comp.attack.value = 0.004; comp.release.value = 0.18;
    comp.connect(master); master.connect(o.dest || ctx.destination);
    const bus = {};
    for (const [name, g] of Object.entries({ sfx: VO ? 0.7 : 0.85, amb: 0.5 })) { bus[name] = ctx.createGain(); bus[name].gain.value = g; bus[name].connect(comp); }

    // generated room reverb: decaying stereo noise, darker toward the tail
    const verb = ctx.createConvolver();
    {
      const secs = 1.6, n = Math.floor(secs * ctx.sampleRate), ir = ctx.createBuffer(2, n, ctx.sampleRate);
      for (let c = 0; c < 2; c++) {
        const r = rand('verb' + c), d = ir.getChannelData(c); let lp = 0;
        for (let i = 0; i < n; i++) { const u = i / n; lp += (0.6 - 0.45 * u) * ((r() * 2 - 1) - lp); d[i] = lp * Math.pow(1 - u, 3); }
      }
      verb.buffer = ir;
    }
    const verbIn = ctx.createGain(); verbIn.gain.value = 0.9; verbIn.connect(verb); verb.connect(comp);

    // seeded noise buffers: white, pink-ish and brown
    const noiseBuf = {};
    {
      const n = Math.floor(2.5 * ctx.sampleRate);
      for (const kind of ['white', 'pink', 'brown']) {
        const b = ctx.createBuffer(1, n, ctx.sampleRate), d = b.getChannelData(0), r = rand('noise-' + kind);
        let p0 = 0, p1 = 0, p2 = 0, br = 0;
        for (let i = 0; i < n; i++) {
          const w = r() * 2 - 1;
          if (kind === 'white') d[i] = w;
          else if (kind === 'pink') { p0 = 0.997 * p0 + 0.029 * w; p1 = 0.985 * p1 + 0.032 * w; p2 = 0.95 * p2 + 0.048 * w; d[i] = (p0 + p1 + p2 + w * 0.05) * 2.2; }
          else { br = (br + 0.02 * w) / 1.02; d[i] = br * 3.2; }
        }
        noiseBuf[kind] = b;
      }
    }

    // ---- automation helpers
    // a value or [[dt, value], ...] from the voice start; ramps are exponential (frequencies)
    function sweep(param, v, t) {
      if (!Array.isArray(v)) { param.setValueAtTime(v, t); return; }
      param.setValueAtTime(v[0][1], t + v[0][0]);
      for (let i = 1; i < v.length; i++) param.exponentialRampToValueAtTime(Math.max(v[i][1], 1), t + v[i][0]);
    }
    // amplitude: linear attack to `gain`, optional hold, exponential release to silence by `dur`
    function shape(param, t, gain, dur, a, hold) {
      a = Math.min(a == null ? 0.004 : a, dur * 0.9);
      hold = Math.min(hold || 0, dur - a);
      param.setValueAtTime(0, t);
      param.linearRampToValueAtTime(gain, t + a);
      if (hold > 0) param.setValueAtTime(gain, t + a + hold);
      param.exponentialRampToValueAtTime(TINY, t + dur);
      param.setValueAtTime(0, t + dur + 0.001);
    }
    function out(node, p) {
      const pan = ctx.createStereoPanner(); pan.pan.value = Math.max(-1, Math.min(1, p.pan || 0));
      node.connect(pan); pan.connect(bus[p.bus || 'sfx']);
      if (p.verb) { const s = ctx.createGain(); s.gain.value = p.verb; pan.connect(s); s.connect(verbIn); }
    }
    function filterNode(p, t) {
      if (!p.filter) return null;
      const f = ctx.createBiquadFilter(); f.type = p.filter; f.Q.value = p.q == null ? 1 : p.q;
      sweep(f.frequency, p.f == null ? 1000 : p.f, t);
      return f;
    }

    // Live playback from the middle of a piece: a long sound (a bed, a pad) that began before that point has a start
    // time in the past, which Web Audio refuses. Pick it up now, at its held level, for the time it has left.
    function late(t, dur, p) {
      if (t >= ctx.currentTime) return null;   // never true in an offline render, so rendered sound is unchanged
      const now = ctx.currentTime + 0.01;
      const cut = now - t, left = dur - cut;
      if (left < 0.08) return { skip: true };
      const a = Math.min(0.05, left / 2);
      return { t: now, dur: left, p: Object.assign({}, p, { a, hold: Math.max(0, Math.min(left - a - 0.02, (p.a == null ? 0.004 : p.a) + (p.hold || 0) - cut)) }) };
    }

    // ---- primitives
    // tone(t, { f, type, dur, gain, a, hold, pan, verb, bus, filter, f2 (filter freq), q, detune })
    function tone(time, p) {
      let t = at(time), dur = p.dur || 0.2;
      if (t + dur < ctx.currentTime || (time < T0 - 0.001 && dur < 1.5)) return;
      const lt = late(t, dur, p); if (lt) { if (lt.skip) return; t = lt.t; dur = lt.dur; p = lt.p; }
      const osc = ctx.createOscillator(); osc.type = p.type || 'sine';
      sweep(osc.frequency, Array.isArray(p.f) ? p.f.map(([d, v]) => [d, hz(v)]) : hz(p.f || 440), t);
      if (p.detune) osc.detune.value = p.detune;
      const g = ctx.createGain(); shape(g.gain, t, gainOf(p, 0.3), dur, p.a, p.hold);
      let node = osc;
      if (p.filter) { const f = ctx.createBiquadFilter(); f.type = p.filter; f.Q.value = p.q == null ? 0.8 : p.q; sweep(f.frequency, p.f2 || 2000, t); osc.connect(f); node = f; }
      node.connect(g); out(g, p);
      osc.start(t); osc.stop(t + dur + 0.02);
    }
    // noise(t, { dur, color, filter, f, q, gain, a, hold, pan, verb, bus, rate })
    function noise(time, p) {
      let t = at(time), dur = p.dur || 0.2;
      if (t + dur < ctx.currentTime || (time < T0 - 0.001 && dur < 1.5)) return;
      const lt = late(t, dur, p); if (lt) { if (lt.skip) return; t = lt.t; dur = lt.dur; p = lt.p; }
      const src = ctx.createBufferSource(); src.buffer = noiseBuf[p.color || 'white']; src.loop = true;
      if (p.rate) src.playbackRate.value = p.rate;
      const g = ctx.createGain(); shape(g.gain, t, gainOf(p, 0.3), dur, p.a, p.hold);
      const f = filterNode(p, t);
      if (f) { src.connect(f); f.connect(g); } else src.connect(g);
      out(g, p);
      const off = rand('off' + time + (p.f || ''))() * 2;
      src.start(t, off); src.stop(t + dur + 0.02);
    }

    // ---- named sounds. play(name, t, opts): opts.gain scales the whole sound, opts.pan places it.
    const S = {
      // UI / motion graphics
      pop: (t, o) => { tone(t, { f: [[0, o.f || 620], [0.07, (o.f || 620) * 0.45]], dur: 0.1, gain: 0.32 * o.g, pan: o.pan }); noise(t, { dur: 0.012, filter: 'highpass', f: 3000, gain: 0.12 * o.g, pan: o.pan }); },
      tick: (t, o) => noise(t, { dur: 0.018, filter: 'bandpass', f: o.f || 4200, q: 2.5, gain: 0.3 * o.g, pan: o.pan }),
      click: (t, o) => { tone(t, { f: o.f || 1900, type: 'square', dur: 0.02, gain: 0.08 * o.g, filter: 'lowpass', f2: 3000, pan: o.pan }); noise(t, { dur: 0.01, filter: 'highpass', f: 2500, gain: 0.15 * o.g, pan: o.pan }); },
      tock: (t, o) => { tone(t, { f: o.f || 820, dur: 0.07, gain: 0.25 * o.g, pan: o.pan }); noise(t, { dur: 0.05, filter: 'bandpass', f: o.f || 820, q: 9, gain: 0.35 * o.g, pan: o.pan }); },
      blip: (t, o) => tone(t, { f: o.f || 'E6', type: o.type || 'square', dur: o.dur || 0.07, gain: 0.07 * o.g, a: 0.002, hold: (o.dur || 0.07) * 0.6, pan: o.pan }),
      whoosh: (t, o) => { const d = o.dur || 0.45; noise(t, { dur: d, color: 'pink', filter: 'bandpass', f: [[0, 350], [d * 0.55, o.top || 2600], [d, 700]], q: 0.9, gain: 0.32 * o.g, a: d * 0.5, pan: o.pan, verb: 0.15 }); },
      swish: (t, o) => { const d = o.dur || 0.18; noise(t, { dur: d, filter: 'highpass', f: [[0, 1800], [d, 5200]], q: 0.7, gain: 0.22 * o.g, a: d * 0.35, pan: o.pan }); },
      riser: (t, o) => { const d = o.dur || 0.8; noise(t, { dur: d, color: 'pink', filter: 'bandpass', f: [[0, 300], [d, 4000]], q: 1.2, gain: 0.25 * o.g, a: d * 0.95, pan: o.pan, verb: 0.2 }); tone(t, { f: [[0, 180], [d, 720]], type: 'triangle', dur: d, gain: 0.06 * o.g, a: d * 0.9 }); },
      thud: (t, o) => { tone(t, { f: [[0, o.f || 130], [0.16, 42]], dur: 0.26, gain: 0.55 * o.g, pan: o.pan }); noise(t, { dur: 0.09, color: 'brown', filter: 'lowpass', f: 500, gain: 0.35 * o.g, pan: o.pan }); },
      impact: (t, o) => { S.thud(t, o); noise(t, { dur: 0.7, color: 'pink', filter: 'lowpass', f: [[0, 2400], [0.6, 300]], gain: 0.3 * o.g, verb: 0.35, pan: o.pan }); },
      stamp: (t, o) => { S.thud(t, { ...o, f: 160 }); noise(t, { dur: 0.05, filter: 'bandpass', f: 1300, q: 1.2, gain: 0.4 * o.g, pan: o.pan }); noise(t + 0.004, { dur: 0.012, filter: 'highpass', f: 3500, gain: 0.25 * o.g, pan: o.pan }); },
      ding: (t, o) => { const f = hz(o.f || 'E6'); tone(t, { f, dur: 1.3, gain: 0.2 * o.g, verb: 0.3, pan: o.pan }); tone(t, { f: f * 2.76, dur: 0.5, gain: 0.05 * o.g, verb: 0.3, pan: o.pan }); },
      success: (t, o) => { S.ding(t, { ...o, f: o.f || 'C6' }); S.ding(t + 0.09, { ...o, f: hz(o.f || 'C6') * 1.5, g: o.g * 0.9 }); },
      error: (t, o) => { tone(t, { f: o.f || 'A3', type: 'square', dur: 0.13, gain: 0.09 * o.g, hold: 0.08, filter: 'lowpass', f2: 1400, pan: o.pan }); tone(t + 0.15, { f: hz(o.f || 'A3') * 0.8, type: 'square', dur: 0.22, gain: 0.09 * o.g, hold: 0.14, filter: 'lowpass', f2: 1200, pan: o.pan }); },
      buzz: (t, o) => { const d = o.dur || 0.3; tone(t, { f: o.f || 110, type: 'sawtooth', dur: d, gain: 0.12 * o.g, hold: d * 0.7, filter: 'lowpass', f2: 900, pan: o.pan }); tone(t, { f: (o.f || 110) * 1.01, type: 'sawtooth', dur: d, gain: 0.1 * o.g, hold: d * 0.7, filter: 'lowpass', f2: 900, pan: o.pan }); },
      sparkle: (t, o) => { const r = rand('sparkle' + t), notes = ['C6', 'D6', 'E6', 'G6', 'A6', 'C7']; for (let i = 0; i < (o.n || 6); i++) { const ti = t + i * 0.04 + r() * 0.01, f = hz(notes[Math.floor(r() * notes.length)]), pan = r() * 1.2 - 0.6; tone(ti, { f, dur: 0.6, gain: 0.04 * o.g, a: 0.002, verb: 0.35, pan }); tone(ti, { f: f * 2.76, dur: 0.2, gain: 0.012 * o.g, a: 0.002, pan }); } },
      glitch: (t, o) => { const r = rand('glitch' + t); for (let i = 0; i < 7; i++) tone(t + i * 0.022, { f: 200 + r() * 1800, type: 'square', dur: 0.02, gain: 0.07 * o.g, a: 0.001, hold: 0.015, pan: r() * 1.4 - 0.7 }); noise(t, { dur: 0.16, filter: 'bandpass', f: 2500, q: 0.6, gain: 0.12 * o.g }); },
      shutter: (t, o) => { S.click(t, o); noise(t + 0.06, { dur: 0.04, filter: 'bandpass', f: 2200, q: 1, gain: 0.2 * o.g, pan: o.pan }); },
      count: (t, o) => S.tick(t, { ...o, f: o.f || 5200, g: o.g * 0.7 }),

      // hand-made media
      // stroke: a pen/marker/chalk/pencil stroke over `dur` seconds. material sets the surface sound.
      stroke: (t, o) => {
        const d = o.dur || 0.4, m = o.material || 'marker', r = rand('stroke' + m + t);
        const M = {
          marker: { f: 2900, q: 2.2, g: 0.16, grain: 0.05 },
          chalk: { f: 1700, q: 0.6, g: 0.22, grain: 0.028 },
          pencil: { f: 4600, q: 0.8, g: 0.16, grain: 0.04, filter: 'highpass' },
          pen: { f: 4200, q: 1.6, g: 0.08, grain: 0.06 },
          brush: { f: 900, q: 0.5, g: 0.1, grain: 0.09, color: 'pink' },
          sharpie: { f: 2400, q: 1.4, g: 0.2, grain: 0.045 },
        }[m];
        for (let x = 0; x < d; x += M.grain * (0.7 + r() * 0.6)) {
          const gd = M.grain * (0.8 + r() * 0.9);
          noise(t + x, { dur: gd, color: M.color, filter: M.filter || 'bandpass', f: M.f * (0.8 + r() * 0.4), q: M.q, gain: M.g * o.g * (0.6 + r() * 0.5), a: gd * 0.3, pan: (o.pan || 0) + (r() - 0.5) * 0.2 });
        }
      },
      // paper: picking up / slapping down / turning a sheet
      paper: (t, o) => { const d = o.dur || 0.35, r = rand('paper' + t); for (let x = 0; x < d; x += 0.025 + r() * 0.03) noise(t + x, { dur: 0.05, filter: 'bandpass', f: 1200 + r() * 2600, q: 0.9, gain: 0.12 * o.g * (1 - x / d * 0.5), pan: o.pan }); },
      slap: (t, o) => { noise(t, { dur: 0.07, filter: 'highpass', f: 900, gain: 0.45 * o.g, a: 0.001, pan: o.pan }); tone(t, { f: [[0, 180], [0.06, 70]], dur: 0.1, gain: 0.25 * o.g, pan: o.pan }); },
      tape: (t, o) => { noise(t, { dur: o.dur || 0.5, filter: 'bandpass', f: [[0, 900], [o.dur || 0.5, 2200]], q: 1.8, gain: 0.18 * o.g, a: 0.02, pan: o.pan }); },
      press: (t, o) => { S.thud(t, { ...o, f: 95, g: o.g * 0.9 }); noise(t + 0.01, { dur: 0.25, color: 'brown', filter: 'lowpass', f: 700, gain: 0.25 * o.g, pan: o.pan }); },
      roller: (t, o) => { const d = o.dur || 0.6; noise(t, { dur: d, color: 'brown', filter: 'bandpass', f: 380, q: 1.5, gain: 0.3 * o.g, a: 0.05, hold: d * 0.6, pan: o.pan }); for (let x = 0; x < d; x += 0.07) S.tock(t + x, { f: 300, g: o.g * 0.15, pan: o.pan }); },
      erase: (t, o) => { const d = o.dur || 0.6, r = rand('erase' + t); for (let x = 0; x < d; x += 0.06 + r() * 0.04) noise(t + x, { dur: 0.08, color: 'pink', filter: 'bandpass', f: 700 + r() * 500, q: 0.8, gain: 0.22 * o.g, a: 0.03, pan: (r() - 0.5) * 0.5 }); },

      // machines and screens
      key: (t, o) => { const r = rand('key' + t); noise(t, { dur: 0.025, filter: 'bandpass', f: 2600 + r() * 1200, q: 2, gain: 0.25 * o.g, a: 0.001, pan: o.pan }); tone(t, { f: 160 + r() * 40, dur: 0.04, gain: 0.12 * o.g, pan: o.pan }); },
      typing: (t, o) => { const r = rand('typing' + t), n = o.n || 8, rate = o.rate || 0.09; for (let i = 0; i < n; i++) S.key(t + i * rate * (0.75 + r() * 0.5), { g: o.g * (0.7 + r() * 0.4), pan: o.pan }); },
      typebar: (t, o) => { S.key(t, o); noise(t + 0.008, { dur: 0.03, filter: 'bandpass', f: 1100, q: 4, gain: 0.35 * o.g, pan: o.pan }); },
      bell: (t, o) => S.ding(t, { ...o, f: o.f || 'A6' }),
      boot: (t, o) => { tone(t, { f: [[0, 80], [0.35, 1600]], type: 'sine', dur: 0.5, gain: 0.08 * o.g, a: 0.3 }); S.blip(t + 0.45, { ...o, f: 'C6', dur: 0.12 }); },
      crtOn: (t, o) => { noise(t, { dur: 0.25, filter: 'highpass', f: 2000, gain: 0.2 * o.g, a: 0.001 }); tone(t, { f: 15700, dur: 1.5, gain: 0.02 * o.g, a: 0.1, hold: 1 }); S.thud(t, { ...o, f: 90, g: o.g * 0.5 }); },
      neon: (t, o) => { const d = o.dur || 0.25, r = rand('neon' + t); for (let x = 0; x < d; x += 0.035 + r() * 0.04) tone(t + x, { f: 120, type: 'sawtooth', dur: 0.03, gain: 0.3 * o.g * (0.5 + r() * 0.5), filter: 'bandpass', f2: 1200, q: 1.2, pan: o.pan }); },
      // chip (8-bit console) sounds: raw square/triangle, no filtering
      coin: (t, o) => { tone(t, { f: 'B5', type: 'square', dur: 0.07, gain: 0.07 * o.g, a: 0.001, hold: 0.06 }); tone(t + 0.07, { f: 'E6', type: 'square', dur: 0.3, gain: 0.07 * o.g, a: 0.001, hold: 0.1 }); },
      jump: (t, o) => tone(t, { f: [[0, 260], [0.16, 820]], type: 'square', dur: 0.18, gain: 0.07 * o.g, a: 0.001, hold: 0.12 }),
      hurt: (t, o) => { tone(t, { f: [[0, 600], [0.25, 90]], type: 'square', dur: 0.28, gain: 0.08 * o.g, a: 0.001, hold: 0.2 }); noise(t, { dur: 0.2, filter: 'lowpass', f: 1800, gain: 0.15 * o.g, rate: 0.25 }); },
      powerup: (t, o) => ['C5', 'E5', 'G5', 'C6', 'E6', 'G6', 'C7'].forEach((n, i) => tone(t + i * 0.045, { f: n, type: 'square', dur: 0.06, gain: 0.06 * o.g, a: 0.001, hold: 0.05 })),
      select: (t, o) => { S.blip(t, { ...o, f: 'A5', dur: 0.04 }); S.blip(t + 0.05, { ...o, f: 'E6', dur: 0.05 }); },
      text: (t, o) => { const n = o.n || 10, rate = o.rate || 0.05; for (let i = 0; i < n; i++) tone(t + i * rate, { f: i % 2 ? 'C6' : 'G5', type: 'square', dur: 0.025, gain: 0.04 * o.g, a: 0.001, hold: 0.015 }); },
    };

    function play(name, t, opts) {
      const fn = S[name];
      if (!fn) throw new Error('unknown sound: ' + name);
      const o2 = Object.assign({}, opts); o2.g = o2.gain == null ? 1 : o2.gain;
      if (opts && opts.minor) withMinor(() => fn(t, o2)); else fn(t, o2);
    }

    // everything scheduled inside fn counts as minor (quieter in voiceover mode)
    function withMinor(fn) { const was = inMinor; inMinor = true; try { fn(); } finally { inMinor = was; } }

    // ---- beds: continuous sound under a stretch of time. bed(name, t0, t1, opts)
    function bed(name, t0, t1, p) {
      if (VO) return;
      p = p || {}; const g = p.gain == null ? 1 : p.gain, d = t1 - t0, fade = Math.min(0.4, d / 4);
      const long = (q) => Object.assign({ dur: d, a: fade, hold: d - fade * 2, bus: 'amb' }, q);
      if (name === 'room') noise(t0, long({ color: 'brown', filter: 'lowpass', f: 320, gain: 0.12 * g }));
      else if (name === 'hiss') noise(t0, long({ color: 'pink', filter: 'highpass', f: 5000, gain: 0.02 * g }));
      else if (name === 'hum') { tone(t0, long({ f: 60, gain: 0.05 * g })); tone(t0, long({ f: 120, gain: 0.025 * g })); tone(t0, long({ f: 180, type: 'triangle', gain: 0.012 * g })); }
      else if (name === 'rain') { noise(t0, long({ color: 'pink', filter: 'bandpass', f: 2500, q: 0.4, gain: 0.08 * g })); const r = rand('rain'); for (let x = 0; x < d; x += 0.04 + r() * 0.08) noise(t0 + x, { dur: 0.01, filter: 'highpass', f: 4000, gain: 0.04 * g * r(), bus: 'amb', pan: r() * 1.6 - 0.8 }); }
      else if (name === 'projector') { noise(t0, long({ color: 'pink', filter: 'highpass', f: 3000, gain: 0.03 * g })); for (let x = 0; x < d; x += 1 / 24) S.tock(t0 + x, { f: 700, g: 0.04 * g, pan: 0.3 }); }
      else if (name === 'vinyl') { noise(t0, long({ color: 'pink', filter: 'bandpass', f: 1500, q: 0.5, gain: 0.025 * g })); const r = rand('vinyl'); for (let x = 0; x < d; x += 0.08 + r() * 0.4) noise(t0 + x, { dur: 0.006, filter: 'highpass', f: 2500, gain: 0.08 * g * r(), bus: 'amb' }); }
      else throw new Error('unknown bed: ' + name);
    }

    return { play, bed, tone, noise, withMinor, hz, vo: VO, sounds: Object.keys(S) };
  };

  // Live playback for a player: SOUND.live(scoreFn, fromT, { voiceover, master }) starts the score from explainer time
  // fromT right now and returns stop(). Call stop() on pause or seek, and SOUND.live again on play.
  SOUND.live = function (fn, fromT, opts) {
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    fn(SOUND.kit(ctx, Object.assign({}, opts, { start: fromT || 0, delay: 0.03 })));
    return () => { try { ctx.close(); } catch (e) {} };
  };

  // Render a style's explainerSound into an OfflineAudioContext; returns interleaved float stereo.
  SOUND.renderOffline = async function (fn, duration, sampleRate, kitOpts) {
    const sr = sampleRate || 48000, len = Math.ceil(duration * sr);
    const ctx = new OfflineAudioContext(2, len, sr);
    fn(SOUND.kit(ctx, kitOpts || {}));
    const buf = await ctx.startRendering();
    const L = buf.getChannelData(0), R = buf.getChannelData(1), inter = new Float32Array(len * 2);
    let peak = 0;
    for (let i = 0; i < len; i++) { inter[2 * i] = L[i]; inter[2 * i + 1] = R[i]; peak = Math.max(peak, Math.abs(L[i]), Math.abs(R[i])); }
    return { inter, peak, frames: len, sr };
  };
})();
```

REFERENCE STYLE SOURCE (styles/low-poly.js; its sample topic was "The water cycle: evaporation from the sea, clouds forming, rain on the mountains, a river running back to the sea")
```js
{
  // ---------------------------------------------------------------- content (change this block for a new topic)
  // The four stages of the story. Each one gets a paper flag planted in the world when the camera reaches it.
  const STEPS = ['EVAPORATION', 'CONDENSATION', 'PRECIPITATION', 'COLLECTION'];
  // One schedule (seconds) for picture and sound.
  const T = {
    cloudA: 1.2,                  // the first cloud unfolds above the sea (flag 1 and the rising vapour are there on frame one)
    flag2: 2.05,
    cloudB: 2.6, cloudC: 3.1,     // the cloud bank grows inland, facet by facet
    rain: 4.1, flag3: 4.75,
    river: 4.9, riverDur: 1.9,    // water unfolds down the dry river bed, from the source to the mouth
    flag4: 6.6,
    meet: 6.85,                   // the river reaches the sea: a ring runs out over the water and the loop is closed
    end: 8.5,
  };
  // The trees the river brings: one every so often along its lower course (s = 0 source, 1 mouth), all on the far
  // bank so they never hide the water. Each springs up just after the water passes it.
  const BANK_TREES = Array.from({ length: 13 }, (_, i) => { const s = 0.3 + i * 0.05; return { s, t: T.river + s * T.riverDur + 0.16 }; });

  // ---------------------------------------------------------------- the palette
  // A short list of family tones. Nothing in the scene uses a colour that is not in here, which is what keeps a
  // low-poly world calm. Warm sand, coral and cream against teal water and sage greens; rock and cloud shadows lean violet.
  const PAL = {
    seaDeep: '#1f6a80', sea: '#2e8f9c', seaShallow: '#63bfb4', foam: '#e6f5ea', river: '#59b9cc',
    sand: '#ecd3a0', bed: '#c9b99a', grass: '#a5bf66', meadow: '#86ad5c', forest: '#5d9160', pine: '#3f7d62', leaf: '#74a857', ochre: '#e0a646',
    rock: '#a3929b', rockDark: '#857a8c', snow: '#fffbf4', trunk: '#7d5e4e',
    cloud: '#fff8ef', cloudSide: '#f4e7de', cloudBase: '#c8c4dc',
    paper: '#fff6e4', ink: '#22303c', accent: '#e9684a',
    skyTop: '#66a9cf', skyPale: '#f7ead9', haze: '#f8dcc0', sun: '#ffcf99',
  };
  // One tone for one facet: the family colour, nudged a little in hue, saturation and lightness by a hash of where the
  // facet sits. That small disagreement between neighbours is what makes a surface read as cut paper instead of plastic.
  const _hsl = {};
  function tone(hex, key, amount = 1) {
    const c = new THREE.Color(hex); c.getHSL(_hsl);
    return c.setHSL(_hsl.h + (K.hash(key, 1.3) - 0.5) * 0.03 * amount, K.clamp(_hsl.s * (1 + (K.hash(key, 7.7) - 0.5) * 0.22 * amount)), K.clamp(_hsl.l * (1 + (K.hash(key, 13.1) - 0.5) * 0.15 * amount)));
  }

  // ---------------------------------------------------------------- facet tools (work on any geometry)
  const _a = new THREE.Vector3(), _b = new THREE.Vector3(), _c = new THREE.Vector3(), _n = new THREE.Vector3(), _m = new THREE.Vector3();
  const vkey = (p, i) => Math.round(p.getX(i) * 500) + ',' + Math.round(p.getY(i) * 500) + ',' + Math.round(p.getZ(i) * 500);

  // jitter(): push every corner a little off its perfect place, so a primitive stops looking like a primitive.
  // Corners that share a position move together, so the shape stays closed.
  function jitter(geo, amount, seed = 1) {
    const p = geo.attributes.position;
    for (let i = 0; i < p.count; i++) {
      const k = Math.round(p.getX(i) * 500) * 0.731 + Math.round(p.getY(i) * 500) * 1.913 + Math.round(p.getZ(i) * 500) * 3.377 + seed * 17.17;
      p.setXYZ(i, p.getX(i) + (K.hash(k, 1) - 0.5) * 2 * amount, p.getY(i) + (K.hash(k, 2) - 0.5) * 2 * amount, p.getZ(i) + (K.hash(k, 3) - 0.5) * 2 * amount);
    }
    return geo;
  }
  // facet(): split any mesh into separate flat triangles and give each of them ONE colour.
  // paint(centroid, normal, index) returns a THREE.Color (use tone()). The result carries position, normal, color and
  // aCen (the triangle's centre, the same on its three corners, for per-facet effects in shaders).
  function facet(src, paint) {
    const g = src.index ? src.toNonIndexed() : src, p = g.attributes.position, pos = [], col = [], nor = [], cen = [];
    for (let i = 0; i < p.count; i += 3) {
      _a.fromBufferAttribute(p, i); _b.fromBufferAttribute(p, i + 1); _c.fromBufferAttribute(p, i + 2);
      _n.subVectors(_b, _a).cross(_m.subVectors(_c, _a));
      if (_n.length() < 1e-6) continue;                       // a triangle that collapsed to a line: drop it
      _n.normalize(); _m.copy(_a).add(_b).add(_c).divideScalar(3);
      const k = paint(_m, _n, i / 3);
      for (const v of [_a, _b, _c]) { pos.push(v.x, v.y, v.z); col.push(k.r, k.g, k.b); nor.push(_n.x, _n.y, _n.z); cen.push(_m.x, _m.y, _m.z); }
    }
    const out = new THREE.BufferGeometry();
    for (const [name, arr] of [['position', pos], ['color', col], ['normal', nor], ['aCen', cen]]) out.setAttribute(name, new THREE.Float32BufferAttribute(arr, 3));
    return out;
  }
  // merge(): several faceted geometries into one (core three.js has no merge helper)
  function merge(list) {
    const out = new THREE.BufferGeometry();
    for (const name of Object.keys(list[0].attributes)) {
      const size = list[0].attributes[name].itemSize, arr = new Float32Array(list.reduce((s, g) => s + g.attributes[name].array.length, 0));
      let o = 0; for (const g of list) { arr.set(g.attributes[name].array, o); o += g.attributes[name].array.length; }
      out.setAttribute(name, new THREE.BufferAttribute(arr, size));
    }
    return out;
  }
  // unfold(): give every triangle a birth time and a hinge, so the mesh can grow facet by facet. The order spreads
  // from the triangle nearest `from` across shared edges at `speed` units per second, and each triangle hinges on the
  // edge it shares with the neighbour that woke it. Parts that are not connected start when the front would reach them.
  // Give `duration` instead of `speed` to say how long the whole mesh takes. Use it with faceted({ unfold: true }).
  function unfold(geo, { from = [0, 0, 0], speed = 3, duration = 0, start = 0 } = {}) {
    const p = geo.attributes.position, cen = geo.attributes.aCen, n = p.count / 3, edges = new Map(), nb = Array.from({ length: n }, () => []);
    for (let f = 0; f < n; f++) for (let e = 0; e < 3; e++) {
      const k0 = vkey(p, f * 3 + e), k1 = vkey(p, f * 3 + (e + 1) % 3), k = k0 < k1 ? k0 + '|' + k1 : k1 + '|' + k0, o = edges.get(k);
      if (o) { nb[f].push([o.f, e, o.e]); nb[o.f].push([f, o.e, e]); } else edges.set(k, { f, e });
    }
    const born = new Float32Array(n).fill(Infinity), hinge = new Int8Array(n), seen = new Uint8Array(n);
    const dist = (f, x, y, z) => Math.hypot(cen.getX(f * 3) - x, cen.getY(f * 3) - y, cen.getZ(f * 3) - z);
    for (let k = 0; k < n; k++) {
      let f = -1, best = Infinity;
      for (let i = 0; i < n; i++) if (!seen[i] && born[i] < best) { best = born[i]; f = i; }
      if (f < 0) {                                            // a new island: start at its triangle nearest the origin of growth
        for (let i = 0; i < n; i++) if (!seen[i]) { const d = dist(i, from[0], from[1], from[2]); if (d < best) { best = d; f = i; } }
        born[f] = best / speed;
      }
      seen[f] = 1;
      for (const [g, , eg] of nb[f]) { const t = born[f] + dist(g, cen.getX(f * 3), cen.getY(f * 3), cen.getZ(f * 3)) / speed; if (!seen[g] && t < born[g]) { born[g] = t; hinge[g] = eg; } }
    }
    const last = Math.max(...born), pace = duration ? duration / last : 1;
    const A = new Float32Array(n * 9), B = new Float32Array(n * 9), bt = new Float32Array(n * 3);
    for (let f = 0; f < n; f++) {
      // hinge from corner e+1 to corner e: with this direction a positive angle folds the triangle INTO the shape
      _a.fromBufferAttribute(p, f * 3 + (hinge[f] + 1) % 3); _b.fromBufferAttribute(p, f * 3 + hinge[f]);
      for (let v = 0; v < 3; v++) { _a.toArray(A, f * 9 + v * 3); _b.toArray(B, f * 9 + v * 3); bt[f * 3 + v] = start + born[f] * pace + K.hash(f, 3.1) * 0.04; }
    }
    geo.setAttribute('aHingeA', new THREE.BufferAttribute(A, 3)); geo.setAttribute('aHingeB', new THREE.BufferAttribute(B, 3)); geo.setAttribute('aBorn', new THREE.BufferAttribute(bt, 1));
    return geo;
  }

  // faceted(): the one material of the style. Flat-shaded, coloured per facet, matte. Options switch on the motions:
  //   unfold: true   triangles swing open on their hinges at their birth time (geometry from unfold()), with a small overshoot
  //   wave: 0.06     the surface heaves like water (amplitude in world units), so its facets keep catching the light
  //   tint: '...'    GLSL run per corner after the facet colour is set (vColor), for travelling flashes and the like
  //   glow: 0.2      adds a share of the facet's own colour as light, for things that are bright in shadow (cloud, droplets)
  // All of them read one shared clock, so update(t) only has to set clock.value.
  const clock = { value: 0 };
  const WAVE = 'float seaWave(vec2 p, float t){ return sin(p.x * 1.25 + t * 1.35) * cos(p.y * 1.05 - t * 1.1) * 0.6 + sin(p.x * 2.7 - p.y * 2.2 + t * 2.3) * 0.4; }\n';
  function faceted(o = {}) {
    const m = new THREE.MeshStandardMaterial({ vertexColors: true, flatShading: true, roughness: o.roughness == null ? 0.9 : o.roughness, metalness: 0, side: o.unfold ? THREE.DoubleSide : THREE.FrontSide });
    const uniforms = Object.assign({ uTime: clock, uFold: { value: o.fold || 0.38 } }, o.uniforms || {});
    const patch = (sh, colour) => {
      Object.assign(sh.uniforms, uniforms);
      let head = 'uniform float uTime, uFold; attribute vec3 aCen;\n' + (o.head || ''), body = '';
      if (o.wave) { head += WAVE; body += `transformed.y += seaWave(transformed.xz, uTime) * ${o.wave.toFixed(4)};\n`; }
      if (o.unfold) {
        head += 'attribute vec3 aHingeA, aHingeB; attribute float aBorn;\n';
        body += `float fu = clamp((uTime - aBorn) / uFold, 0.0, 1.0);
          float fopen = 1.0 - pow(1.0 - fu, 3.0) + 0.3 * sin(fu * 3.14159) * fu * fu;      // 0 folded, 1 flat, a little past 1 on the way
          float fang = (1.0 - fopen) * 2.4;
          vec3 fax = normalize(aHingeB - aHingeA), frel = transformed - aHingeA;
          frel = frel * cos(fang) + cross(fax, frel) * sin(fang) + fax * dot(fax, frel) * (1.0 - cos(fang));
          transformed = mix(0.5 * (aHingeA + aHingeB), aHingeA + frel, smoothstep(0.0, 0.45, fu));   // it also grows out of its hinge\n`;
      }
      sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\n' + head).replace('#include <begin_vertex>', '#include <begin_vertex>\n' + body);
      if (colour && o.tint) sh.vertexShader = sh.vertexShader.replace('#include <color_vertex>', '#include <color_vertex>\n' + o.tint);
    };
    const id = JSON.stringify([o.wave, o.unfold, o.tint, o.head, o.glow]);
    m.onBeforeCompile = (sh) => {
      patch(sh, true);
      if (o.glow) sh.fragmentShader = sh.fragmentShader.replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>\ntotalEmissiveRadiance += diffuseColor.rgb * ${o.glow.toFixed(3)};`);   // lit from inside a little, like cloud or thin paper
    };
    m.customProgramCacheKey = () => 'facet' + id;
    if (o.unfold || o.wave) {                                   // shadows have to follow the moving triangles too
      m.depth = new THREE.MeshDepthMaterial({ side: m.side });
      m.depth.onBeforeCompile = (sh) => patch(sh, false); m.depth.customProgramCacheKey = () => 'facetDepth' + id;
    }
    return m;
  }
  const mesh = (geo, mat, o = {}) => { const m = new THREE.Mesh(geo, mat); m.castShadow = o.cast !== false; m.receiveShadow = true; if (mat.depth) m.customDepthMaterial = mat.depth; return m; };

  // ---------------------------------------------------------------- ground tools: scattered points and a triangulation
  // Low-poly ground looks best when its triangles are irregular and get larger with distance. scatter() drops one
  // point in every cell of a quadtree whose cells are as large as spacing(x, z) allows; triangulate() (Delaunay,
  // Bowyer-Watson) turns any set of [x, z] points into triangles.
  function scatter([x0, z0, x1, z1], spacing, seed, root = 11) {
    const r = K.rng(seed), out = [];
    const cell = (x, z, s) => { if (s > spacing(x + s / 2, z + s / 2)) { const h = s / 2; cell(x, z, h); cell(x + h, z, h); cell(x, z + h, h); cell(x + h, z + h, h); } else out.push([x + s * r.range(0.15, 0.85), z + s * r.range(0.15, 0.85)]); };
    for (let x = x0; x < x1; x += root) for (let z = z0; z < z1; z += root) cell(x, z, root);
    return out;
  }
  function triangulate(pts) {
    const n = pts.length, P = pts.concat([[-4e3, -4e3], [4e3, -4e3], [0, 4e3]]);
    const circ = (a, b, c) => {
      const [ax, ay] = P[a], [bx, by] = P[b], [cx, cy] = P[c], d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by));
      const x = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d, y = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d;
      return { a, b, c, x, y, r2: (ax - x) * (ax - x) + (ay - y) * (ay - y) };
    };
    let open = [circ(n, n + 1, n + 2)]; const done = [];
    for (const i of pts.map((_, k) => k).sort((u, v) => P[u][0] - P[v][0])) {     // sweep left to right
      const [px, py] = P[i], edge = new Map(), keep = [];
      for (const t of open) {
        const dx = px - t.x, dy = py - t.y;
        if (dx > 0 && dx * dx > t.r2) { done.push(t); continue; }                 // no later point can reach it
        if (dx * dx + dy * dy >= t.r2) { keep.push(t); continue; }
        for (const [u, v] of [[t.a, t.b], [t.b, t.c], [t.c, t.a]]) { const k = u < v ? u * 1e6 + v : v * 1e6 + u; if (edge.has(k)) edge.delete(k); else edge.set(k, [u, v]); }
      }
      open = keep; for (const [u, v] of edge.values()) open.push(circ(u, v, i));
    }
    return done.concat(open).filter((t) => t.a < n && t.b < n && t.c < n).map((t) => [t.a, t.b, t.c]);
  }
  // upward(): a list of triangles [[x, y, z] x 3] -> geometry with every triangle turned to face up, ready for facet()
  function upward(tris) {
    const pos = [];
    for (const [a, b, c] of tris) { const up = (b[2] - a[2]) * (c[0] - a[0]) - (b[0] - a[0]) * (c[2] - a[2]); pos.push(...a, ...(up < 0 ? c : b), ...(up < 0 ? b : c)); }
    const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
    return g;
  }
  // surface(): points [x, z] (or [x, z, y] to pin a height) + a height function -> a triangulated piece of ground
  const surface = (pts, height) => upward(triangulate(pts).map((tri) => tri.map((i) => [pts[i][0], pts[i][2] == null ? height(pts[i][0], pts[i][1]) : pts[i][2], pts[i][1]])));

  // ---------------------------------------------------------------- props: every shape is a jittered primitive, cut flat where it helps
  function rockGeo(seed) {
    const g = jitter(new THREE.IcosahedronGeometry(0.5, 1), 0.11, seed); g.scale(1.15, 0.72, 0.9);
    const p = g.attributes.position; for (let i = 0; i < p.count; i++) if (p.getY(i) < -0.12) p.setY(i, -0.12);
    return facet(g, (c, n) => tone(n.y > 0.55 ? PAL.rock : PAL.rockDark, c.x * 31 + c.y * 17 + c.z * 7 + seed));
  }
  function pineGeo(seed, slim = 1) {                            // three tilted cones on a stub, lighter toward the tip
    const r = K.rng(seed), parts = [];
    const trunk = new THREE.CylinderGeometry(0.04, 0.06, 0.26, 5); trunk.translate(0, 0.13, 0);
    parts.push(facet(trunk, (c) => tone(PAL.trunk, c.x * 9 + c.z * 5 + c.y)));
    [[0.33, 0.46, 0.2], [0.25, 0.42, 0.5], [0.165, 0.4, 0.78]].forEach(([rad, h, y], i) => {
      const g = jitter(new THREE.ConeGeometry(rad * slim, h, 6, 1), 0.022, seed + i);
      g.rotateZ(r.range(-0.07, 0.07)); g.rotateY(r.range(0, 6.28)); g.translate(r.range(-0.015, 0.015), y + h / 2, r.range(-0.015, 0.015));
      parts.push(facet(g, (c, n) => tone(PAL.pine, c.x * 13 + c.y * 7 + c.z * 3 + seed, 1).multiplyScalar(n.y < -0.5 ? 0.6 : 1 + i * 0.1)));
    });
    return merge(parts);
  }
  function treeGeo(seed, colour) {                              // a round crown: two jittered balls on a stick
    const parts = [], trunk = new THREE.CylinderGeometry(0.035, 0.055, 0.42, 5); trunk.translate(0, 0.21, 0);
    parts.push(facet(trunk, (c) => tone(PAL.trunk, c.x * 9 + c.z * 5 + c.y)));
    [[0, 0.68, 0, 0.36], [0.2, 0.52, 0.08, 0.22]].forEach(([x, y, z, rad], i) => {
      const g = jitter(new THREE.IcosahedronGeometry(rad, 1), rad * 0.16, seed + i * 3); g.scale(1, 0.92, 1); g.translate(x, y, z);
      parts.push(facet(g, (c, n) => tone(colour, c.x * 13 + c.y * 7 + c.z * 3 + seed, 1.2).multiplyScalar(0.92 + 0.14 * n.y)));
    });
    return merge(parts);
  }
  // A cloud: overlapping jittered balls, all cut flat at the same base height. puffs = [[x, y, z, radius], ...]
  function cloudGeo(puffs, seed) {
    return merge(puffs.map(([x, y, z, rad], i) => {
      const g = jitter(new THREE.IcosahedronGeometry(rad, 1), rad * 0.12, seed + i * 5); g.scale(1, 0.86, 0.92); g.translate(x, y, z);
      const p = g.attributes.position, base = -0.012 * i; for (let k = 0; k < p.count; k++) if (p.getY(k) < base) p.setY(k, base);   // a hair apart, so the flat bases never fight
      return facet(g, (c, n) => tone(n.y < -0.5 ? PAL.cloudBase : n.y > 0.3 ? PAL.cloud : PAL.cloudSide, c.x * 11 + c.y * 5 + c.z * 3 + seed + i, 0.55));
    }));
  }
  function dropGeo(w, h) { const g = new THREE.OctahedronGeometry(1, 0); g.scale(w, h, w); return facet(g, () => new THREE.Color(1, 1, 1)); }   // a cut-gem droplet
  function boatGeo() {                                          // a folded paper boat
    const P = { bow: [0.36, 0.13, 0], stern: [-0.36, 0.13, 0], l: [0, 0.11, 0.12], r: [0, 0.11, -0.12], keel: [0, -0.05, 0], mast: [0.02, 0.56, 0], s0: [-0.2, 0.14, 0], s1: [0.22, 0.14, 0] };
    const tris = [['bow', 'l', 'keel'], ['l', 'stern', 'keel'], ['stern', 'r', 'keel'], ['r', 'bow', 'keel'], ['bow', 'stern', 'l'], ['bow', 'r', 'stern'], ['s0', 's1', 'mast'], ['s1', 's0', 'mast']];
    const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.Float32BufferAttribute(tris.flatMap((t) => t.flatMap((k) => P[k])), 3));
    return facet(g, (c, n, i) => tone(i >= 6 ? PAL.accent : PAL.paper, i, 0.6));
  }

  // A paper flag on a pin: the label that sits in the world. The numeral is in the accent colour, the word in ink.
  // side = 1 hangs the flag to the right of the pin, -1 to the left. Returns { group, pole, board, width }.
  function flag(num, word, { height = 1.25, side = 1 } = {}) {
    const FONT = '700 150px "Oswald"', PXH = 250, BH = 0.64, u = BH / PXH, gap = 34, pad = 50, notch = 70;
    const meas = document.createElement('canvas').getContext('2d'); meas.font = FONT; meas.letterSpacing = '7px';
    const wn = meas.measureText(String(num)).width, ww = meas.measureText(word).width, W = Math.ceil(pad + wn + gap + ww + pad + notch);
    const x0 = side > 0 ? pad : notch + pad;                    // the swallow-tail is on the free end
    const tex = K.canvasTex(W, PXH, (ctx) => {
      ctx.fillStyle = PAL.paper; ctx.fillRect(0, 0, W, PXH);
      ctx.font = FONT; ctx.letterSpacing = '7px'; ctx.textBaseline = 'alphabetic';
      ctx.fillStyle = PAL.accent; ctx.fillText(String(num), x0, PXH / 2 + 60);
      ctx.fillStyle = PAL.ink; ctx.fillText(word, x0 + wn + gap, PXH / 2 + 60);
    });
    const w = W * u, s = new THREE.Shape();
    s.moveTo(0, 0); s.lineTo(w, 0); s.lineTo(w - notch * u, BH / 2); s.lineTo(w, BH); s.lineTo(0, BH); s.closePath();
    const sg = new THREE.ShapeGeometry(s), uv = sg.attributes.uv, sp = sg.attributes.position;
    for (let i = 0; i < sp.count; i++) { const fx = sp.getX(i) / w; uv.setXY(i, side > 0 ? fx : 1 - fx, sp.getY(i) / BH); if (side < 0) sp.setX(i, -sp.getX(i)); }
    if (side < 0) sg.index.array.reverse();
    const board = new THREE.Mesh(sg, new THREE.MeshStandardMaterial({ map: tex, emissiveMap: tex, emissive: '#ffffff', emissiveIntensity: 0.3, roughness: 0.95, side: THREE.DoubleSide }));
    board.position.set(0, height - BH - 0.05, 0.03); board.castShadow = true; board.receiveShadow = true;
    const pg = new THREE.CylinderGeometry(0.02, 0.02, height, 5); pg.translate(0, height / 2, 0);
    const pole = new THREE.Group(), pin = mesh(facet(pg, () => new THREE.Color(PAL.ink)), faceted({ roughness: 0.6 }));
    const head = mesh(facet(new THREE.IcosahedronGeometry(0.075, 0), (c, n, i) => tone(PAL.accent, i, 0.7)), faceted({ roughness: 0.5 })); head.position.y = height + 0.04;
    pole.add(pin, head, board);
    const group = new THREE.Group(); group.add(pole);
    // pop(t, t0): the pin shoots up out of the ground with a bounce, then the paper swings round it and settles
    const pop = (t, t0) => {
      const a = K.spring(t - t0, 2.6, 0.38), b = K.spring(t - t0 - 0.14, 2.1, 0.42);
      group.visible = t > t0; pole.scale.set(1, Math.max(0.001, a), 1);
      board.rotation.y = side * (1 - b) * -1.9; board.scale.set(Math.max(0.001, K.seg(t, t0 + 0.12, t0 + 0.34, K.ease.out)), 1, 1);
    };
    return { group, pop };
  }

  registerStyle({
    id: 'low-poly',
    name: 'Low-Poly',
    family: 'Filters over 3D',
    look: 'A miniature world of flat, faceted shapes, like folded paper or cut stone: every triangle is one tone, and neighbours differ slightly, inside a short palette of sand, coral and cream against teal water and sage greens.',
    motion: 'Things grow by unfolding facet by facet from one point, or pop out of the ground with a bounce; water heaves so its facets keep catching the light, clouds drift, small cut-gem droplets rise and fall.',
    light: 'One low, warm sun from the side with soft-edged shadows, a cool blue sky filling the shadow sides so every facet turns either warm or cool, and peach haze that swallows the distance.',
    materials: 'Matte paper-like facets with no texture at all; only the water is slightly glossy. Colour comes per triangle from the palette, never from gradients.',
    camera: 'One continuous crane move on a long lens with tilt-shift-shallow focus, so the landscape feels like a tabletop model: close on each stage in turn, then out to the whole scene.',
    post: 'True depth of field and motion blur, colours kept true (neutral tone curve), a gentle vignette and only enough grain to keep the sky from banding. No filter pass: the facets are real geometry.',
    explains: 'Processes that happen in a place: cycles, journeys, supply chains, how a system of parts feeds itself. Each stage is a spot in the landscape with a paper flag, and the camera travels the route between them.',
    topic: 'The water cycle: evaporation from the sea, clouds forming, rain on the mountains, a river running back to the sea',
    duration: T.end,
    fonts: ['700 150px "Oswald"'],
    render: { samples: 64, shutter: 0.4, tone: 'neutral', exposure: 1.0, bloom: 0.35, bloomThreshold: 1.25, vignette: 0.22, grain: 0.014, fov: 30, background: PAL.haze, far: 400 },

    build(S) {
      const { THREE, K, scene, camera } = S;
      const N = K.noise(7), smooth = K.smooth;

      // ------------------------------------------------------------ the place: a height function, designed by hand
      // Sea to the west and south, a plain, and peaks listed one by one: [x, z, height, radius].
      const PEAKS = [[3.6, -2.0, 3.9, 4.0], [6.6, -0.9, 2.7, 3.0], [0.6, -5.4, 3.0, 3.6], [9.5, -5.0, 4.4, 4.6], [-2.0, -10, 2.4, 4.5],
        [5, -15, 6.0, 8], [16, -9, 5.5, 7], [-6, -24, 6.5, 10], [22, -22, 8, 12], [14, 3, 2.6, 5], [24, 0, 5, 8]];
      const ISLES = [[-4.7, 1.9, 0.78, 1.5], [-13, -9, 2.6, 4.2], [-24, -22, 5.5, 9], [-17, -15.5, 1.5, 2.6], [-40, -34, 8, 14]];   // rise straight out of the sea
      const peak = (x, z, p, i) => {
        const dx = x - p[0], dz = z - p[1], a = Math.atan2(dz, dx);
        const r = p[3] * (1 + 0.17 * Math.sin(a * 3 + i * 1.9) + 0.09 * Math.sin(a * 5 + i * 3.1) + 0.05 * Math.sin(a * 9 + i));   // ridges and gullies
        return p[2] * Math.pow(Math.max(0, 1 - Math.hypot(dx, dz) / r), 1.35);
      };
      const smin = (a, b, k) => { const h = K.clamp(0.5 + 0.5 * (b - a) / k); return K.lerp(b, a, h) - k * h * (1 - h); };
      const coast = (x, z) => smin(x - (-2.9 + 0.22 * z + 0.35 * Math.sin(z * 0.8 + 0.6)), 5.9 + 0.4 * Math.sin(x * 0.6 + 1) - z, 2) + 0.3 * N.fbm(x * 0.35, z * 0.35, 0, 3);   // > 0 on land
      const natural = (x, z) => {
        const d = coast(x, z);
        let m = 0; PEAKS.forEach((p, i) => { m += Math.pow(peak(x, z, p, i), 4); }); m = Math.pow(m, 0.25);
        let h = d > 0 ? 0.08 + 0.5 * (1 - Math.exp(-d * 0.45)) + 0.015 * d + m * smooth(0.2, 2.6, d) + N.fbm(x * 0.6, z * 0.6, 1, 3) * (0.1 + 0.3 * smooth(0.3, 1.6, m)) * smooth(0, 1, d) : Math.max(-1.7, d * 0.55);
        ISLES.forEach((p, i) => { h = Math.max(h, peak(x, z, p, i + 20) - 0.3); });
        return h;
      };
      // The river: a hand-placed path from the mountain to the sea. Its bed only ever goes down, and the ground is
      // carved to it, so the water has a channel to lie in.
      const RIVER = [[2.9, -0.8], [2.15, 0.2], [1.2, 0.3], [0.45, 1.15], [-0.75, 1.0], [-1.5, 1.95], [-2.3, 2.3], [-2.75, 2.5]];
      const river = (() => {
        const curve = new THREE.CatmullRomCurve3(RIVER.map(([x, z]) => new THREE.Vector3(x, 0, z)), false, 'centripetal'), n = 140, pts = curve.getSpacedPoints(n);
        let y = pts.map((p) => natural(p.x, p.z));
        for (let i = 1; i <= n; i++) y[i] = Math.min(y[i], y[i - 1]);
        y = y.map((v, i) => K.lerp(v, 0.0, smooth(0.72, 0.97, i / n)));
        for (let k = 0; k < 6; k++) y = y.map((v, i) => (y[Math.max(0, i - 1)] + v + y[Math.min(n, i + 1)]) / 3);
        const rows = pts.map((p, i) => { const tg = curve.getTangentAt(i / n); return { x: p.x, z: p.z, y: y[i] + 0.03, s: i / n, w: 0.13 + 0.22 * (i / n), nx: -tg.z, nz: tg.x }; });   // y is the water level
        const near = (x, z) => { let best = rows[0], bd = Infinity; for (const r of rows) { const d = (r.x - x) * (r.x - x) + (r.z - z) * (r.z - z); if (d < bd) { bd = d; best = r; } } return { d: Math.sqrt(bd), row: best }; };
        return { rows, near, n };
      })();
      const height = (x, z) => {
        const h = natural(x, z), { d, row } = river.near(x, z);
        return d > row.w + 1.7 || h < 0 ? h : Math.max(Math.min(h, 0.02), K.lerp(row.y + 0.1, h, smooth(row.w + 0.24, row.w + 1.7, d)));
      };

      // ------------------------------------------------------------ light, sky and haze
      // A low warm sun from the west, a cool sky that fills the shadows, and haze the colour of the horizon.
      const SUN = new THREE.Vector3(-0.78, 0.4, 0.3).normalize();
      K.env(S, { top: '#7db7dd', horizon: '#ffe2c4', bottom: '#8fa98a', intensity: 0.55, panels: [{ pos: [SUN.x * 30, SUN.y * 30, SUN.z * 30], size: [10, 10], color: PAL.sun, power: 14, round: true }] });
      K.sun(S, { pos: [SUN.x * 45, SUN.y * 45, SUN.z * 45], target: [0, 0, 0], color: '#ffe0ba', power: 3.5, size: 15, soft: 2.2, mapSize: 4096, far: 110, normalBias: 0.03 });
      K.skyLight(S, { color: '#a9c9ff', power: 0.9, size: 13, center: [0, 1, 0], mapSize: 2048, spread: 0.9 });
      scene.fog = new THREE.Fog(PAL.haze, 12, 56);
      const sky = new THREE.Mesh(new THREE.SphereGeometry(300, 32, 16), new THREE.ShaderMaterial({
        side: THREE.BackSide, depthWrite: false, fog: false,
        uniforms: { top: { value: new THREE.Color(PAL.skyTop) }, pale: { value: new THREE.Color(PAL.skyPale) }, haze: { value: new THREE.Color(PAL.haze) }, sunC: { value: new THREE.Color(PAL.sun) }, sunDir: { value: SUN } },
        vertexShader: 'varying vec3 vD; void main(){ vD = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
        fragmentShader: `varying vec3 vD; uniform vec3 top, haze, pale, sunC, sunDir;
          void main(){ vec3 d = normalize(vD); float s = max(dot(d, sunDir), 0.0);
            float y = max(d.y, 0.0);
            vec3 c = mix(mix(haze, pale, smoothstep(0.0, 0.12, y)), top, smoothstep(0.06, 0.5, y));      // through pale cream, so peach and blue never mix to grey
            c += sunC * (pow(s, 5.0) * 0.35 + pow(s, 40.0) * 0.8 + smoothstep(0.9988, 0.9992, s) * 5.0);
            gl_FragColor = vec4(c, 1.0); }`,
      }));
      scene.add(sky);

      // ------------------------------------------------------------ land
      const hero = (x, z) => Math.max(Math.abs(x - 0.5) - 8.5, -7 - z, z - 8.5, 0);       // 0 inside the part of the world the story happens in
      const landPts = scatter([-55, -77, 55, 11], (x, z) => 0.69 * (1 + hero(x, z) * 0.2), 3).filter(([x, z]) => river.near(x, z).d > river.near(x, z).row.w + 0.5);
      PEAKS.concat(ISLES).forEach((p) => landPts.push([p[0], p[1]]));                  // every summit is a real corner
      river.rows.forEach((r, i) => {                                                    // the channel: bed, water's edge, top of the bank
        if (i % 3 || natural(r.x, r.z) < 0.03) return;
        const j = (K.hash(i, 1) - 0.5) * 0.06;
        for (const [k, dy] of [[0, -0.13], [-1, -0.08], [1, -0.08], [-1.9, 0.11], [1.9, 0.11]]) { const off = k * r.w + Math.sign(k) * (Math.abs(k) > 1 ? 0.24 - 0.9 * r.w : 0); landPts.push([r.x + r.nx * off + j, r.z + r.nz * off - j, r.y + dy]); }
      });
      const paintLand = (c, n) => {
        const key = c.x * 12.9898 + c.z * 78.233 + c.y * 37.7, j = K.hash(key, 5) - 0.5, { d, row } = river.near(c.x, c.z);
        let name;
        if (d < row.w + 0.1 && c.y < row.y + 0.02) name = 'bed';
        else if (c.y < 0.15 + j * 0.08) name = 'sand';
        else if (c.y > 2.75 + j * 0.5 && n.y > 0.5) name = 'snow';
        else if (n.y < 0.76 + j * 0.06 || c.y > 2.4) name = K.hash(key, 9) < 0.6 ? 'rock' : 'rockDark';
        else if (c.y > 1.2 + j * 0.5) name = 'forest';
        else name = N.fbm(c.x * 0.3, c.z * 0.3, 3, 2) > 0.02 ? 'meadow' : 'grass';
        return tone(PAL[name], key, name === 'snow' ? 0.35 : 1);
      };
      const land = mesh(facet(surface(landPts, height), paintLand), faceted());
      scene.add(land);

      // ------------------------------------------------------------ sea: the same kind of mesh, heaving, coloured by depth
      const seaPts = scatter([-121, -121, 99, 33], (x, z) => 0.69 * (1 + hero(x, z) * 0.25), 5);
      const paintSea = (c) => {
        const depth = -height(c.x, c.z), key = c.x * 3.1 + c.z * 7.7;
        return tone(depth < 0.055 ? PAL.foam : depth < 0.36 ? PAL.seaShallow : depth < 1.0 ? PAL.sea : PAL.seaDeep, key, 1.1);
      };
      const MOUTH = river.rows[Math.round(river.n * 0.93)];
      const sea = mesh(facet(surface(seaPts, () => 0), paintSea), faceted({ roughness: 0.3, wave: 0.075,
        // when the river arrives, a ring of lighter facets runs out from the mouth
        uniforms: { uRing: { value: new THREE.Vector3(MOUTH.x, MOUTH.z, T.meet) } }, head: 'uniform vec3 uRing;\n',
        tint: 'float rd = distance(aCen.xz, uRing.xy), rt = (uTime - uRing.z) * 2.6; vColor.rgb = mix(vColor.rgb, vec3(0.75, 0.95, 0.93), 0.75 * smoothstep(0.55, 0.0, abs(rd - rt)) * step(0.0, rt) * smoothstep(5.5, 1.0, rt));' }), { cast: false });
      scene.add(sea);

      // ------------------------------------------------------------ river water: a ribbon of facets that unfolds downstream and then keeps flashing
      const riverGeo = (() => {
        // four corners across the stream at every other row; the two inner ones are nudged so no two facets match
        const rows = river.rows.filter((_, i) => i % 2 === 0), tris = [];
        const at = (r, k, i) => { const inner = k === 1 || k === 2, j = inner ? (K.hash(i, k) - 0.5) * 0.09 : 0, off = [-1, -0.36, 0.36, 1][k] * (r.w + 0.2); return [r.x + r.nx * off + r.nz * j, r.y + (inner ? (K.hash(i, k + 5) - 0.5) * 0.02 : 0), r.z + r.nz * off - r.nx * j]; };
        for (let i = 0; i + 1 < rows.length; i++) for (let k = 0; k < 3; k++) {
          const a = at(rows[i], k, i), b = at(rows[i], k + 1, i), c = at(rows[i + 1], k, i + 1), d = at(rows[i + 1], k + 1, i + 1);
          if ((i + k) % 2) tris.push([a, b, c], [b, d, c]); else tris.push([a, b, d], [a, d, c]);
        }
        const g = facet(upward(tris), (c) => tone(PAL.river, c.x * 5.3 + c.z * 9.1, 1.3));
        return unfold(g, { from: [river.rows[0].x, river.rows[0].y, river.rows[0].z], duration: T.riverDur, start: T.river });
      })();
      const water = mesh(riverGeo, faceted({ roughness: 0.35, unfold: true, fold: 0.3,
        tint: 'float fl = fract((aCen.x * 0.9 - aCen.z * 0.5) * 0.9 + uTime * 1.3 + fract(aCen.x * 37.0 + aCen.z * 17.0) * 0.4); vColor.rgb = mix(vColor.rgb, vec3(0.86, 0.97, 0.96), 0.5 * smoothstep(0.7, 0.85, fl) * smoothstep(1.0, 0.85, fl));' }), { cast: false });
      scene.add(water);

      // where the four flags stand: [x, z] (flag 2 is in cloud A's own space), which way they face, and which side the paper hangs
      const FLAGS = [{ at: [-4.95, 1.95], yaw: 0.25, height: 1.3 }, { at: [-1.35, 0.1], yaw: 0, height: 1.35 }, { at: [5.95, 1.2], yaw: -0.05, height: 1.4, side: -1 }, { at: [0.9, 3.6], yaw: 0, height: 1.0 }];
      const clear = (x, z) => (x > 1.9 && x < 6.3 && z > 0.9 && z < 3.4) || (x > 0.5 && x < 4.3 && z > 3.2 && z < 6.5);   // nothing grows in front of a flag

      // ------------------------------------------------------------ trees and rocks: placed by rules, not sprinkled
      const slope = (x, z) => Math.hypot(height(x + 0.2, z) - height(x - 0.2, z), height(x, z + 0.2) - height(x, z - 0.2)) / 0.4;
      const plants = { pine: [], pine2: [], tree: [], ochre: [], rock: [], rock2: [] };
      {
        const r = K.rng(21), taken = [];
        const free = (x, z, gap) => taken.every((q) => Math.hypot(q[0] - x, q[1] - z) > gap);
        const put = (kind, x, z, s, t0 = -9) => { taken.push([x, z]); plants[kind].push({ x, z, y: height(x, z) - 0.03, s, rot: r.range(0, 6.28), t0, lean: r.range(-0.06, 0.06) }); };
        BANK_TREES.forEach((b, i) => {
          const row = river.rows[Math.round(b.s * river.n)], off = -Math.sign(row.nz) * (row.w + 0.6 + 0.45 * K.hash(i, 4));
          put(i % 4 === 1 ? 'ochre' : 'tree', row.x + row.nx * off, row.z + row.nz * off, r.range(0.7, 0.95), b.t);
        });
        for (let i = 0; i < 2600; i++) {
          const x = r.range(-4, 16), z = r.range(-9, 6.2), y = height(x, z), sl = slope(x, z), { d, row } = river.near(x, z);
          if (y < 0.2 || d < row.w + 0.6 || clear(x, z) || (d < row.w + 1.5 && ((x - row.x) * row.nx + (z - row.z) * row.nz) * row.nz > 0)) continue;   // and nothing tall in front of the river
          const grove = N.fbm(x * 0.45, z * 0.45, 9, 2);                                 // woods come in patches
          if (y > 0.75 && y < 2.3 && sl < 1.1 && grove > -0.06 && free(x, z, 0.36)) put(r.chance(0.5) ? 'pine' : 'pine2', x, z, r.range(0.62, 1.0) * (1.15 - y * 0.12));
          else if (y < 0.8 && sl < 0.5 && grove > 0.1 && free(x, z, 0.55)) put(r.chance(0.16) ? 'ochre' : r.chance(0.3) ? 'pine' : 'tree', x, z, r.range(0.6, 1.0));
        }
        for (let i = 0; i < 500; i++) {                                                  // rocks: along the shore, at the foot of the mountains, round the islet
          const x = r.range(-7, 9), z = r.range(-6, 6.5), y = height(x, z), { d, row } = river.near(x, z);
          if (d < row.w + 0.3 || !free(x, z, 0.5)) continue;
          if ((y > -0.12 && y < 0.1 && r.chance(0.35)) || (y > 1.6 && y < 2.6 && r.chance(0.12)) || (d < row.w + 0.6 && row.s > 0.3 && r.chance(0.5))) put(r.chance(0.5) ? 'rock' : 'rock2', x, z, r.range(0.22, 0.6));
        }
      }
      const kinds = { pine: pineGeo(1), pine2: pineGeo(2, 0.8), tree: treeGeo(3, PAL.leaf), ochre: treeGeo(4, PAL.ochre), rock: rockGeo(5), rock2: rockGeo(6) };
      const plantMat = faceted(), inst = {};
      for (const k of Object.keys(kinds)) {
        const m = inst[k] = new THREE.InstancedMesh(kinds[k], plantMat, Math.max(1, plants[k].length)); m.count = plants[k].length; m.castShadow = true; m.receiveShadow = true; m.frustumCulled = false; scene.add(m);
        plants[k].forEach((q, i) => m.setColorAt(i, new THREE.Color().setScalar(0.9 + 0.2 * K.hash(q.x, q.z))));
      }

      // ------------------------------------------------------------ clouds: A forms over the sea, B and C carry it inland, C darkens and rains
      const cloudMat = () => faceted({ unfold: true, fold: 0.42, glow: 0.22 });
      const mkCloud = (puffs, seed, pos, from, start, speed) => { const m = mesh(unfold(cloudGeo(puffs, seed), { from, start, speed }), cloudMat()); const g = new THREE.Group(); g.add(m); g.position.set(...pos); g.userData = { pos, mesh: m }; scene.add(g); return g; };
      const cloudA = mkCloud([[0, 0.3, 0, 1.0], [-1.05, 0.12, 0.1, 0.72], [1.0, 0.18, -0.05, 0.8], [1.8, 0.02, 0.12, 0.5], [0.25, 0.02, 0.55, 0.62], [-0.45, 0.72, -0.1, 0.55]], 1, [-3.5, 3.75, -0.7], [-0.6, 0, 0.3], T.cloudA, 2.3);
      const cloudB = mkCloud([[0, 0.2, 0, 0.6], [0.7, 0.08, 0.05, 0.45], [-0.6, 0.05, 0.1, 0.4]], 2, [0.1, 4.75, -1.6], [-1, 0, 0], T.cloudB, 2.6);
      const cloudC = mkCloud([[0, 0.35, 0, 1.05], [-1.1, 0.15, 0.15, 0.75], [1.05, 0.2, -0.1, 0.82], [0.3, 0.05, 0.6, 0.66], [-0.4, 0.05, -0.6, 0.6], [0.45, 0.85, -0.05, 0.6], [1.85, 0.03, 0.1, 0.48]], 3, [3.3, 4.3, -1.0], [-1.8, 0, 0], T.cloudC, 2.6);
      const STORM = new THREE.Color(0.52, 0.5, 0.62), WHITE = new THREE.Color(1, 1, 1);
      // far clouds that are simply there, for depth
      [[[-27, 5.4, -30], 2.2, 11], [[13, 8.6, -26], 2.0, 12], [[-34, 7.5, -48], 3.0, 13]].forEach(([pos, s, seed]) => {
        const m = mesh(cloudGeo([[0, 0.25, 0, 0.9], [-0.95, 0.1, 0.1, 0.65], [0.9, 0.12, 0, 0.7], [1.6, 0.02, 0.1, 0.42]], seed), faceted({ glow: 0.22 })); m.position.set(...pos); m.scale.setScalar(s); scene.add(m);
      });

      // ------------------------------------------------------------ droplets: vapour rising off the sea into cloud A, rain falling from cloud C
      const dropMat = new THREE.MeshStandardMaterial({ color: '#dff6ff', emissive: '#bfeaff', emissiveIntensity: 0.55, flatShading: true, roughness: 0.4 });
      const NV = 110, vapour = new THREE.InstancedMesh(dropGeo(0.045, 0.085), dropMat, NV); vapour.frustumCulled = false; vapour.castShadow = false; scene.add(vapour);
      const VAP = Array.from({ length: NV }, (_, i) => ({ x: -4.2 + (K.hash(i, 1) - 0.5) * 3.8, z: 0.6 + (K.hash(i, 2) - 0.5) * 3.0, ph: K.hash(i, 3), life: 2.3 + K.hash(i, 4) * 1.2, tx: -3.5 + (K.hash(i, 5) - 0.5) * 2.4, tz: -0.6 + (K.hash(i, 6) - 0.5) * 0.9, s: 0.7 + K.hash(i, 7) * 0.7 }));
      const NR = 150, rain = new THREE.InstancedMesh(dropGeo(0.022, 0.15), dropMat, NR); rain.frustumCulled = false; rain.castShadow = false; scene.add(rain);
      const RAIN = Array.from({ length: NR }, (_, i) => { const x = 3.3 + (K.hash(i, 11) - 0.5) * 3.6, z = -0.9 + (K.hash(i, 12) - 0.5) * 1.7; return { x, z, top: 4.35, fall: 4.35 - Math.max(0, height(x - 0.2, z)), ph: K.hash(i, 13), v: 6.5 + K.hash(i, 14) * 1.5 }; });

      // ------------------------------------------------------------ small things: a paper boat, and the four flags
      const boat = mesh(boatGeo(), faceted({ roughness: 0.8 })); boat.material.side = THREE.DoubleSide; scene.add(boat);
      const flags = STEPS.map((word, i) => flag(i + 1, word, FLAGS[i]));
      flags.forEach((f, i) => {
        const [x, z] = FLAGS[i].at;
        if (i === 1) { f.group.position.set(x, 0.6, z); cloudA.add(f.group); }           // stuck into the cloud (its foot is below the puff's top), so it drifts with it
        else { f.group.position.set(x, height(x, z) - 0.02, z); scene.add(f.group); }
        f.group.rotation.y = FLAGS[i].yaw;
      });
      const FLAG_T = [-9, T.flag2, T.flag3, T.flag4];

      // ------------------------------------------------------------ camera: one continuous crane move (position and aim both flow through their keys)
      const cam = {
        pos: K.path([[0, [-0.9, 1.2, 9.0]], [1.5, [-1.4, 2.3, 10.6]], [2.8, [-2.4, 4.3, 7.6]], [4.4, [2.8, 4.6, 9.6]], [5.3, [4.0, 3.8, 10.8]], [6.6, [1.6, 4.8, 13.4]], [7.5, [0.35, 5.25, 14.0]], [8.5, [0.2, 5.4, 14.3]]]),
        aim: K.path([[0, [-3.8, 1.45, 1.6]], [1.5, [-3.7, 2.7, 0.8]], [2.8, [-3.1, 4.7, -0.5]], [4.4, [3.1, 3.8, -0.4]], [5.3, [3.9, 2.8, 0.4]], [6.6, [0.7, 2.3, 0.8]], [7.5, [0.1, 2.65, 0]], [8.5, [0.1, 2.7, 0]]]),
        // the lens: sharp on whichever flag the story is at, then on the plane all four share
        focus: K.track([[0, [-3.8, 1.3, 1.9]], [1.3, [-3.8, 1.3, 1.9]], [2.5, [-3.2, 4.6, -0.6], 'inOut'], [3.5, [-3.2, 4.6, -0.6]], [4.6, [4.4, 2.6, 1.2], 'inOut'], [5.4, [4.4, 2.6, 1.2]], [7.3, [0.1, 2.2, 0.8], 'inOut']]),
        ap: K.track([[0, 0.06], [5.4, 0.06], [7.3, 0.05, 'inOut']]),
      };

      return {
        update(t) {
          clock.value = t;
          // clouds drift inland a little and bob; C turns to a storm cloud just before the rain
          [cloudA, cloudB, cloudC].forEach((c, i) => c.position.set(c.userData.pos[0] + 0.07 * t, c.userData.pos[1] + 0.05 * Math.sin(t * 0.9 + i * 2.1), c.userData.pos[2]));
          cloudC.userData.mesh.material.color.copy(WHITE).lerp(STORM, K.seg(t, T.rain - 0.7, T.rain + 0.5, K.ease.inOut));
          // vapour: each droplet leaves the sea, leans toward the cloud as it climbs, and is taken up
          VAP.forEach((q, i) => {
            const u = ((t / q.life + q.ph) % 1 + 1) % 1, e = u * u * (3 - 2 * u), top = cloudA.position.y + 0.25;
            const sc = q.s * Math.min(1, u * 16) * (1 - K.smooth(0.75, 1, u));
            K.place(vapour, i, [K.lerp(q.x, q.tx, e * e) + 0.08 * Math.sin(u * 9 + i), 0.03 + top * Math.pow(u, 1.35), K.lerp(q.z, q.tz, e * e) + 0.08 * Math.cos(u * 7 + i * 1.7)], [0, u * 5 + i, 0.25 * Math.sin(u * 11 + i)], sc);
          });
          vapour.instanceMatrix.needsUpdate = true;
          // rain: falls on a slant from the flat base of cloud C to the slope below it
          RAIN.forEach((q, i) => {
            const t1 = t - T.rain - q.ph * 0.5, period = q.fall / q.v + 0.08, k = t1 / period, u = k - Math.floor(k);
            const y = q.top - u * period * q.v, on = t1 > 0 && y > q.top - q.fall;
            K.place(rain, i, [q.x + cloudC.position.x - 3.3 - (q.top - y) * 0.09, y, q.z], [0, i, -0.09], on ? 1 : 0);
          });
          rain.instanceMatrix.needsUpdate = true;
          // trees: the ones along the river spring up as the water reaches them
          for (const k of Object.keys(inst)) {
            plants[k].forEach((q, i) => { const a = q.t0 < 0 ? 1 : K.spring(t - q.t0, 2.4, 0.36), w = q.t0 < 0 ? 1 : K.spring(t - q.t0, 1.9, 0.5); K.place(inst[k], i, [q.x, q.y, q.z], [q.lean, q.rot, q.lean * 0.7], [q.s * w, q.s * a, q.s * w]); });
            inst[k].instanceMatrix.needsUpdate = true;
          }
          flags.forEach((f, i) => f.pop(t, FLAG_T[i]));
          // the boat rides the same wave as the sea
          const bx = -6.9 + 0.1 * t, bz = -1.4, wv = (x, z) => 0.075 * (Math.sin(x * 1.25 + t * 1.35) * Math.cos(z * 1.05 - t * 1.1) * 0.6 + Math.sin(x * 2.7 - z * 2.2 + t * 2.3) * 0.4);
          boat.position.set(bx, wv(bx, bz) + 0.03, bz); boat.rotation.set(0.08 * Math.sin(t * 1.3), 0.5, (wv(bx + 0.3, bz) - wv(bx - 0.3, bz)) * 1.2);
          const p = cam.pos(t), a = cam.aim(t);
          K.look(camera, p, a); K.focus(camera, cam.focus(t), cam.ap(t));
          sky.position.copy(camera.position);
        },
      };
    },

    sound(k) {
      const K = globalThis.K, r = K.rng(4);
      // a soft major pad under everything, sea air, and rain once the cloud breaks
      k.bed('room', 0, T.end, { gain: 0.6 }); k.bed('hiss', 0, T.rain, { gain: 0.5 });
      k.bed('rain', T.rain - 0.1, T.end, { gain: 0.9 });
      k.withMinor(() => {
        // vapour leaving the water: small rising glassy notes
        for (let t = 0.15; t < T.cloudA + 0.6; t += 0.22 + r() * 0.12) k.tone(t, { f: [[0, 1300 + r() * 500], [0.25, 2100 + r() * 900]], dur: 0.3, gain: 0.035, a: 0.05, pan: -0.5 + r() * 0.4, verb: 0.4 });
        // clouds folding open: paper
        [[T.cloudA, 1.2, -0.3], [T.cloudB, 0.55, 0], [T.cloudC, 1.2, 0.3]].forEach(([t, dur, pan]) => { k.play('paper', t, { dur, gain: 0.8, pan }); k.play('paper', t + dur * 0.45, { dur: dur * 0.6, gain: 0.5, pan }); });
        // the river unfolding: a run of small water notes that speeds up and falls in pitch as it reaches the sea
        for (let u = 0; u < 1; u += 0.035 + r() * 0.02) k.tone(T.river + u * T.riverDur, { f: [[0, 2300 - 900 * u + r() * 400], [0.06, 1500 - 600 * u]], dur: 0.09, gain: 0.05, a: 0.004, pan: 0.4 - 0.7 * u, verb: 0.25 });
        // trees springing up along the banks
        BANK_TREES.forEach((b, i) => k.play('pop', b.t, { gain: 0.3, f: 520 + (i * 97) % 340, pan: 0.3 - 0.04 * i }));
      });
      // the flags: pin in, paper round
      [T.flag2, T.flag3, T.flag4].forEach((t, i) => { k.play('pop', t, { gain: 0.9, f: 560 + i * 60, pan: [-0.3, 0.35, 0][i] }); k.play('swish', t + 0.12, { gain: 0.5, dur: 0.2 }); k.play('tock', t + 0.3, { gain: 0.45, f: 700 }); });
      k.play('thud', T.rain - 0.25, { gain: 0.22, f: 70, pan: 0.3 });       // the cloud breaks, far-off thunder
      k.play('whoosh', T.river - 0.1, { gain: 0.35, dur: 0.8, top: 1800, pan: 0.3 });
      k.play('success', T.meet, { gain: 0.6, f: 'A5' }); k.play('sparkle', T.meet + 0.1, { gain: 0.6 });   // the loop closes
    },
  });
}
```