Skip to content

A free, open-source framework for cinematic, interactive 3D websites with AI-generated assets (Nano Banana 2 + Meshy 7.1 on fal). 20 example sites.

Dioramas: a framework for cinematic, interactive 3D websites, with 20 examples

blendi-remade868539fb5b64
diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..f7f2072
--- /dev/null
+++ b/.env.example
@@ -0,0 +1 @@
+FAL_KEY=
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8295864
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
+node_modules
+dist
+.env
+.env.local
+assets/raw
+assets/src
+assets/*.log
+shots
+.claude
diff --git a/ASSET-LICENSES.md b/ASSET-LICENSES.md
new file mode 100644
index 0000000..d15c12b
--- /dev/null
+++ b/ASSET-LICENSES.md
@@ -0,0 +1,7 @@
+# Asset licenses
+
+The 3D models in `public/models/` were generated with Meshy 7.1 (image-to-3D) and the images in `public/img/` and
+`docs/media/` with Nano Banana 2, both via fal, from the prompts in `assets/jobs/`. They are released under
+**Creative Commons Attribution 4.0 (CC BY 4.0)**. Credit: "Dioramas (github.com/blendi-remade/dioramas)".
+
+Fonts are loaded from Google Fonts and remain under the SIL Open Font License.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..3053e38
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Blendi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..3c0490d
--- /dev/null
+++ b/README.md
@@ -0,0 +1,98 @@
+# Dioramas
+
+**A free, open-source framework for cinematic, interactive 3D websites — with AI-generated hero assets.**
+
+Dioramas is a way of building landing pages where the 3D scene *is* the page: a hyper-detailed object, real lighting,
+a choreographed camera, and one interaction you can touch. It ships with **20 complete example sites** built with it.
+
+Everything is free. No paid tier, no account, no CLI to install.
+
+![The twenty examples](docs/media/all-1.jpg)
+![The twenty examples](docs/media/all-2.jpg)
+
+## The framework
+
+Dioramas is three layers that work together:
+
+### 1. Asset pipeline — prompt → image → 3D model
+Hero objects are generated, not modelled:
+
+1. **Nano Banana 2** (on [fal](https://fal.ai)) renders a clean product plate of the object on white.
+2. **Meshy 7.1 image-to-3D** (on fal) turns it into a 60k–250k-triangle PBR model at 4K geometry (optionally rigged + animated).
+3. **`scripts/optimize.mjs`** welds, compresses (meshopt) and converts textures to WebP — a 25 MB raw model becomes 3–8 MB.
+
+```bash
+cp .env.example .env # add your FAL_KEY
+node scripts/gen.mjs all assets/jobs/<your-job>.json # images + meshes (resumable)
+node scripts/optimize-all.mjs # → public/models/<example>/
+```
+Every prompt used for the 20 examples is in `assets/jobs/` and `assets/manifest.json`. A textured model costs about $1.20; the
+whole collection (65 models, 111 images) cost roughly $90.
+
+### 2. Engine — `src/core/`
+A small three.js layer that makes generated models look expensive:
+HDR post stack (N8AO ambient occlusion, mip-chain bloom, AgX tone mapping, grain, vignette), raymarched **volumetric
+spotlights**, **planar reflections** with roughness blur, GPU-baked procedural textures, Lenis + GSAP scroll choreography,
+custom cursor, preloader and cross-site navigation. See [`docs/ENGINE.md`](docs/ENGINE.md).
+
+### 3. Method — brief → build → review → revise
+Each example started as a one-page brief (`docs/briefs/`) and was built by an AI coding agent against the engine, then
+iterated with a headless-GPU screenshot battery (`scripts/review.mjs`) and a brutal art-direction review until every scroll
+stop was a composed frame. Hand a brief plus `docs/ENGINE.md` to your agent to build your own world, or re-theme an example.
+
+## The 20 examples
+
+| | Example | Signature interaction |
+|---|---|---|
+| 01 | Reliquary | Explore a dark museum by lantern; photograph relics to light them |
+| 02 | Abyssal | Scroll is an 11 km dive; steer the submersible's floodlights |
+| 03 | Hammer & Ember | Scroll heats a damascus blade; click to strike sparks |
+| 04 | Bell & Moss | Wipe condensation off a glass cloche |
+| 05 | Still Water | A koi pond with real ripple simulation; feed the fish |
+| 06 | Florae | 200k-particle flowers that morph and scatter in your breeze |
+| 07 | Velocity Lab | An X-ray / thermal / CAD lens that sees through a shoe |
+| 08 | Hangar Nine | Press and hold to power up a mech |
+| 09 | Maison Sucre | Real physics with photoreal pastries |
+| 10 | Monolith | Drag the sun across a cliff house |
+| 11 | Low Frequency | Play and scratch a record (synthesized audio) |
+| 12 | Gambit | The Immortal Game replayed on scroll, then free play |
+| 13 | Atlas of Drifting Isles | Fly between floating islands |
+| 14 | Lithos | Press and hold to crack a geode open |
+| 15 | Artemis | Scroll to walk a rigged astronaut on the Moon |
+| 16 | The Keeper | Aim a lighthouse beam through a storm |
+| 17 | Kōen | One bonsai through four seasons |
+| 18 | Nocturne | A perfume bottle with sloshing liquid |
+| 19 | Nightshift Motor Co. | Hold to rev a café racer in the rain |
+| 20 | Aurel Horologie | Take a watch movement apart |
+
+<p>
+<img src="docs/media/reliquary.jpg" width="49%"> <img src="docs/media/hangar.jpg" width="49%">
+<img src="docs/media/lithos.jpg" width="49%"> <img src="docs/media/sucre.jpg" width="49%">
+<img src="docs/media/keeper.jpg" width="49%"> <img src="docs/media/abyssal.jpg" width="49%">
+<img src="docs/media/florae.jpg" width="49%"> <img src="docs/media/velocity.jpg" width="49%">
+<img src="docs/media/koi.jpg" width="49%"> <img src="docs/media/nocturne.jpg" width="49%">
+<img src="docs/media/monolith.jpg" width="49%"> <img src="docs/media/racer.jpg" width="49%">
+</p>
+
+## Run it
+
+```bash
+git clone https://github.com/blendi-remade/dioramas && cd dioramas
+npm install
+npm run dev # http://127.0.0.1:5190 — the gallery; each example at /examples/<name>/
+```
+Models ship in the repo (plain git, ~330 MB, no LFS). A desktop GPU is recommended; everything is tuned for 60 fps.
+
+## Layout
+```
+examples/<name>/ the 20 example sites (index.html, main.js, style.css)
+src/core/ the engine
+src/index/ the gallery
+scripts/ asset pipeline + QA (gen, optimize, shot, review, thumbs)
+assets/jobs/ every prompt used to generate the assets
+public/models/ optimized GLBs docs/ engine guide, briefs, media
+```
+
+## License
+Code is MIT. Generated models and images are released under CC BY 4.0 — see [`ASSET-LICENSES.md`](ASSET-LICENSES.md).
+Third-party libraries keep their own licenses — see [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md).
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
new file mode 100644
index 0000000..a282555
--- /dev/null
+++ b/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,10 @@
+# Third-party notices
+
+- three.js — MIT
+- postprocessing (pmndrs) — Zlib
+- n8ao — CC0-1.0
+- GSAP (incl. ScrollTrigger, SplitText) — GSAP Standard "no charge" license (https://gsap.com/standard-license)
+- Lenis — MIT
+- @dimforge/rapier3d-compat — Apache-2.0
+- @fal-ai/client — MIT
+- @gltf-transform/* — MIT; meshoptimizer — MIT; sharp — Apache-2.0; playwright — Apache-2.0
diff --git a/assets/jobs/all.json b/assets/jobs/all.json
new file mode 100644
index 0000000..9532343
--- /dev/null
+++ b/assets/jobs/all.json
@@ -0,0 +1,522 @@
+{
+ "images": [
+ {
+ "id": "reliq-helmet",
+ "prompt": "An ancient Greek bronze Corinthian hoplite helmet, deep verdigris green-blue patina with exposed warm bronze on the high points, dented and scratched, engraved brow line, narrow eye slits and nose guard, resting on a small rough-cut dark basalt display block."
+ },
+ {
+ "id": "reliq-mask",
+ "prompt": "An ancient Maya jade mosaic funerary mask, hundreds of fitted green jade tesserae, inlaid white shell eyes with black obsidian pupils, subtle cracks, museum artifact, facing forward at a slight three-quarter angle, mounted on a small black metal museum stand."
+ },
+ {
+ "id": "reliq-bust",
+ "prompt": "A weathered white Carrara marble classical Greek bust of a young woman with braided hair tied up, nose slightly chipped, subtle grey veining and soft erosion, on a square marble socle, museum sculpture."
+ },
+ {
+ "id": "reliq-amphora",
+ "prompt": "An ancient Greek black-figure terracotta amphora with two handles, orange clay with black painted figures of running athletes and meander bands, small chips and wear, standing upright."
+ },
+ {
+ "id": "abyss-angler",
+ "prompt": "A deep-sea anglerfish, menacing wide jaw with long translucent needle teeth, bulbous glowing lure on a stalk above its head, dark brown-black rough warty skin, small eyes, fins spread, side three-quarter view, museum-quality natural history model."
+ },
+ {
+ "id": "abyss-nautilus",
+ "prompt": "A living chambered nautilus, cream shell with bold red-brown tiger stripes, pearly aperture, many small tentacles and a hood emerging from the shell opening, three-quarter view."
+ },
+ {
+ "id": "abyss-sub",
+ "prompt": "A compact deep-sea research submersible, rounded white and safety-orange hull, large clear acrylic viewing dome at the front, two articulated manipulator arms, cluster of LED floodlights, ballast tanks, thrusters, sampling basket, realistic industrial design."
+ },
+ {
+ "id": "abyss-vent",
+ "prompt": "A hydrothermal vent chimney diorama from the deep ocean floor: a tall craggy black-and-rust mineral chimney, dense clusters of giant red-plumed white tube worms at its base, pale crabs and mussels, on a round chunk of dark volcanic seabed."
+ },
+ {
+ "id": "ember-sword",
+ "prompt": "A hand-forged Viking longsword lying diagonally across the frame from bottom-left to top-right, entire sword visible with margin, damascus pattern-welded steel blade with a clearly visible flowing wood-grain pattern, bronze crossguard and lobed pommel with knotwork, dark leather-wrapped grip.",
+ "aspect_ratio": "1:1"
+ },
+ {
+ "id": "ember-anvil",
+ "prompt": "A heavy old blacksmith's anvil, dark forged steel with a polished worn face and horn, scale and scratches, bolted on top of a thick weathered oak tree-stump base with iron bands."
+ },
+ {
+ "id": "ember-hammer",
+ "prompt": "A blacksmith's cross-peen forging hammer with a dark forged steel head showing hammer marks, and a worn ash-wood handle, lying diagonally."
+ },
+ {
+ "id": "terra-moss",
+ "prompt": "A miniature forest terrarium landscape without any glass: rolling hills of lush green cushion moss, lichen-covered grey stones, tiny ferns, a small gnarled bonsai-like tree, a white pebble path winding through, tiny red mushrooms, all built on a round turned walnut wood base disc."
+ },
+ {
+ "id": "terra-desert",
+ "prompt": "A miniature desert terrarium landscape without any glass: pale golden sand dunes, sculptural sandstone rocks, small green and blue-grey succulents and echeverias, a tiny flowering cactus with pink blooms, all built on a round turned walnut wood base disc."
+ },
+ {
+ "id": "terra-tropic",
+ "prompt": "A miniature tropical rainforest terrarium landscape without any glass: dark volcanic rocks, a tiny cascading waterfall, lush miniature ferns, fittonia with pink veins, a small white orchid, mossy roots, all built on a round turned walnut wood base disc."
+ },
+ {
+ "id": "koi-kohaku",
+ "prompt": "A single koi carp fish seen from above at a slight three-quarter angle, kohaku pattern: glossy pearl-white body with large vivid red-orange patches, long flowing translucent fins and tail spread out, gentle S-curve swimming pose, realistic scales."
+ },
+ {
+ "id": "koi-showa",
+ "prompt": "A single koi carp fish seen from above at a slight three-quarter angle, showa sanshoku pattern: black body with red-orange and white patches, long flowing translucent fins and tail spread out, gentle S-curve swimming pose, realistic scales."
+ },
+ {
+ "id": "koi-lotus",
+ "prompt": "A single open pink lotus flower with layered soft pink petals, golden seed pod center and yellow stamens, sitting on one round flat green lotus leaf."
+ },
+ {
+ "id": "koi-lantern",
+ "prompt": "A traditional Japanese granite stone lantern (kasuga toro), weathered grey stone with moss on the roof and base, hexagonal fire box with carved openings, tall pillar, on a rough rock."
+ },
+ {
+ "id": "flora-rose",
+ "prompt": "A single perfect deep crimson red rose bloom with many velvety layered petals and a short stem with two green leaves, botanical specimen."
+ },
+ {
+ "id": "flora-protea",
+ "prompt": "A single king protea flower head, large crown of pink-tipped pointed bracts around a silvery-cream fuzzy center, short stem with leathery green leaves, botanical specimen."
+ },
+ {
+ "id": "flora-morpho",
+ "prompt": "A blue morpho butterfly with wings spread open, iridescent electric-blue upper wings with black edges and white spots, body and antennae, seen from above at a slight angle, natural history specimen."
+ },
+ {
+ "id": "flora-orchid",
+ "prompt": "A single white phalaenopsis orchid spray: arching stem with five open white flowers with magenta-veined lips and two buds, botanical specimen without pot."
+ },
+ {
+ "id": "velo-white",
+ "prompt": "A futuristic performance running sneaker resting flat on the ground, clean side three-quarter view with the entire shoe visible from toe to heel with wide margins, white engineered knit upper with subtle translucent ripstop overlays, sculpted chunky pale-grey foam midsole with a visible black carbon plate slit, volt-orange heel pull tab and orange laces, premium product design."
+ },
+ {
+ "id": "hangar-mech",
+ "prompt": "A large bipedal combat mech robot standing, full body head to feet, military gunmetal grey armor plates with orange hazard stripes and stencilled numbers, weathered and chipped paint, armored cockpit head with glowing visor slit, heavy digitigrade legs with hydraulic pistons, shoulder-mounted cannon, realistic hard-surface design."
+ },
+ {
+ "id": "hangar-drone",
+ "prompt": "A heavy industrial quadcopter drone, carbon fiber and matte grey body, four large rotors with guards, orange safety markings, sensor gimbal camera underneath, realistic hard-surface design."
+ },
+ {
+ "id": "sucre-cake",
+ "prompt": "An elegant three-tier pastel pink and cream wedding cake with piped buttercream ruffles, fresh raspberries and pale roses, gold leaf flakes, on a white porcelain cake stand."
+ },
+ {
+ "id": "sucre-macaron",
+ "prompt": "A single French macaron, pastel pink shells with smooth domed tops and ruffled feet, raspberry buttercream filling, slightly tilted."
+ },
+ {
+ "id": "sucre-macaron2",
+ "prompt": "A single French macaron, pastel pistachio green shells with smooth domed tops and ruffled feet, cream filling, slightly tilted."
+ },
+ {
+ "id": "sucre-croissant",
+ "prompt": "A single golden buttery French croissant with flaky glossy laminated layers."
+ },
+ {
+ "id": "sucre-strawberry",
+ "prompt": "A single ripe glossy red strawberry with green leafy calyx."
+ },
+ {
+ "id": "sucre-tart",
+ "prompt": "A small round French strawberry tart: golden fluted pastry shell, vanilla custard, glazed halved strawberries arranged in a spiral, a mint leaf."
+ },
+ {
+ "id": "mono-house",
+ "prompt": "An architectural diorama: a minimalist modern concrete villa with long cantilevered floors and floor-to-ceiling glass cantilevered dramatically over a rugged granite sea cliff, a few windswept pine trees, infinity pool, all on a chunk of rocky terrain with rough cut edges, highly detailed architectural model."
+ },
+ {
+ "id": "lf-turntable",
+ "prompt": "A premium high-end record turntable, thick walnut wood plinth, heavy brushed aluminum platter with a black vinyl record, polished tonearm with counterweight, two rotary knobs, no dust cover."
+ },
+ {
+ "id": "lf-speaker",
+ "prompt": "A premium bookshelf studio speaker, walnut wood cabinet, exposed woven paper woofer cone and a silk dome tweeter, brass bolts, front-facing three-quarter view."
+ },
+ {
+ "id": "gambit-king",
+ "prompt": "A tall ornate Staunton king chess piece carved from polished white Carrara marble with delicate grey veining, cross on top, standing upright."
+ },
+ {
+ "id": "gambit-queen",
+ "prompt": "A tall ornate Staunton queen chess piece carved from polished white Carrara marble with delicate grey veining, coronet crown on top, standing upright."
+ },
+ {
+ "id": "gambit-bishop",
+ "prompt": "A Staunton bishop chess piece carved from polished white Carrara marble with delicate grey veining, mitre with diagonal cut and small ball finial, standing upright."
+ },
+ {
+ "id": "gambit-knight",
+ "prompt": "A Staunton knight chess piece carved from polished white Carrara marble with delicate grey veining, finely sculpted horse head with flowing mane, standing upright, three-quarter side view."
+ },
+ {
+ "id": "gambit-rook",
+ "prompt": "A Staunton rook chess piece carved from polished white Carrara marble with delicate grey veining, castle turret top with crenellations, standing upright."
+ },
+ {
+ "id": "gambit-pawn",
+ "prompt": "A Staunton pawn chess piece carved from polished white Carrara marble with delicate grey veining, sphere head on a collar and stepped base, standing upright."
+ },
+ {
+ "id": "atlas-lighthouse",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: a grassy cliff-top with a small white lighthouse with red top and a cozy stone cottage, winding path, wildflowers, the island's underside a jagged rock cone with hanging roots, floating in the air."
+ },
+ {
+ "id": "atlas-falls",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: lush forest with round trees, a waterfall pouring off the edge from a small lake, mossy boulders, the island's underside a jagged rock cone with hanging vines, floating in the air."
+ },
+ {
+ "id": "atlas-pagoda",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: a red Japanese pagoda with pink cherry blossom trees, stone steps and a torii gate, the island's underside a jagged rock cone with hanging roots, floating in the air."
+ },
+ {
+ "id": "atlas-windmill",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: rolling golden wheat fields, a wooden windmill, a red barn, hay bales and a tiny winding river, the island's underside a jagged rock cone with hanging roots, floating in the air."
+ },
+ {
+ "id": "lithos-geode",
+ "prompt": "One half of a large split amethyst geode, cut face up and tilted toward the viewer: a rough grey-brown rocky outer crust, a white agate banding rim, and a deep cavity densely lined with sparkling purple amethyst crystal points."
+ },
+ {
+ "id": "lithos-quartz",
+ "prompt": "A cluster of clear quartz crystal points growing from a small matrix rock, tall hexagonal terminated crystals, water-clear with slight internal veils and rainbow inclusions."
+ },
+ {
+ "id": "lithos-pyrite",
+ "prompt": "A cluster of natural pyrite cubes, sharp interlocking metallic brass-gold cubic crystals with striated faces, on a small dark rock matrix."
+ },
+ {
+ "id": "lithos-ammonite",
+ "prompt": "A polished ammonite fossil, spiral shell cut and polished showing iridescent mother-of-pearl surface and intricate suture patterns, on a small rough stone base."
+ },
+ {
+ "id": "artemis-astro",
+ "prompt": "A full-body astronaut in a modern white and light grey lunar exploration spacesuit with a reflective gold visor, backpack life-support system, orange accents, gloves and boots, standing in a relaxed A-pose with arms slightly away from the body, facing the viewer, full figure head to toe visible.",
+ "aspect_ratio": "3:4"
+ },
+ {
+ "id": "artemis-lander",
+ "prompt": "A modern lunar lander spacecraft on four spindly landing legs with round footpads, gold foil insulated descent stage, white and grey ascent cabin with windows, antennas, thrusters, solar panel, realistic aerospace design."
+ },
+ {
+ "id": "keeper-lighthouse",
+ "prompt": "A diorama of a tall weathered stone lighthouse painted with red and white bands, black iron lantern gallery at the top, attached small white keeper's cottage with slate roof and chimney, standing on a tall jagged dark wet basalt sea-rock outcrop with steep sides, the rock cut flat at the bottom, no water, no waves, no sea."
+ },
+ {
+ "id": "keeper-boat",
+ "prompt": "A small weathered wooden fishing trawler boat, dark green hull with a white wheelhouse, rust streaks, nets, buoys and a small mast with lights."
+ },
+ {
+ "id": "koen-maple",
+ "prompt": "A Japanese maple bonsai tree in full summer foliage, thick flared tapering trunk with nebari surface roots, elegant branch structure with dense green palmate leaf pads, in a shallow oval dark-glazed ceramic pot covered with moss."
+ },
+ {
+ "id": "noct-iris",
+ "prompt": "A single purple bearded iris flower with ruffled violet falls and standards, golden beard, short green stem and a blade leaf, botanical specimen."
+ },
+ {
+ "id": "noct-bergamot",
+ "prompt": "Two bergamot oranges with one cut in half showing the juicy pale yellow segments, glossy textured green-yellow peel, a sprig with two dark leaves."
+ },
+ {
+ "id": "noct-vanilla",
+ "prompt": "A small bundle of glossy dark brown cured vanilla bean pods tied with twine, next to a cured vanilla orchid flower."
+ },
+ {
+ "id": "noct-oud",
+ "prompt": "A piece of rare resinous agarwood (oud) wood, dark streaks of resin through pale gnarled wood, sculptural twisted chunk."
+ },
+ {
+ "id": "noct-cap",
+ "prompt": "An ornate heavy perfume bottle stopper cap, faceted black obsidian crystal top in a sculpted polished gold art-deco collar with fluted ridges, standing upright."
+ },
+ {
+ "id": "racer-bike",
+ "prompt": "A custom cafe racer motorcycle, three-quarter side view, glossy black fuel tank with brass pinstripe, tan leather hump seat, round chrome headlight, clip-on handlebars, exposed polished twin-cylinder engine, spoked wheels with black tires, brass and chrome details."
+ },
+ {
+ "id": "racer-helmet",
+ "prompt": "A vintage open-face motorcycle helmet, glossy cream paint with a thin red racing stripe, brown leather trim and chin strap, with a bubble visor raised."
+ },
+ {
+ "id": "horo-watch",
+ "prompt": "A luxury skeleton mechanical wristwatch, round polished rose-gold case, openworked dial exposing gears, bridges and a balance wheel, blued steel hands, sapphire crystal, dark brown alligator leather strap, three-quarter view."
+ },
+ {
+ "id": "velo-black",
+ "raw": true,
+ "edit_from": [
+ "velo-white"
+ ],
+ "prompt": "Recolor this exact sneaker, keeping the identical shape, angle, framing and pure white background: make the knit upper deep matte black, the foam midsole charcoal graphite, the carbon plate slit glossy black, and change the heel tab and laces to electric volt yellow-green. Photorealistic product render."
+ }
+ ],
+ "meshes": [
+ {
+ "id": "reliq-helmet",
+ "polycount": 150000
+ },
+ {
+ "id": "reliq-mask",
+ "polycount": 150000
+ },
+ {
+ "id": "reliq-bust",
+ "polycount": 150000
+ },
+ {
+ "id": "reliq-amphora",
+ "polycount": 80000
+ },
+ {
+ "id": "abyss-angler",
+ "polycount": 150000
+ },
+ {
+ "id": "abyss-nautilus",
+ "polycount": 100000
+ },
+ {
+ "id": "abyss-sub",
+ "polycount": 150000
+ },
+ {
+ "id": "abyss-vent",
+ "polycount": 150000
+ },
+ {
+ "id": "ember-sword",
+ "polycount": 80000
+ },
+ {
+ "id": "ember-anvil",
+ "polycount": 100000
+ },
+ {
+ "id": "ember-hammer",
+ "polycount": 40000
+ },
+ {
+ "id": "terra-moss",
+ "polycount": 200000
+ },
+ {
+ "id": "terra-desert",
+ "polycount": 200000
+ },
+ {
+ "id": "terra-tropic",
+ "polycount": 200000
+ },
+ {
+ "id": "koi-kohaku",
+ "polycount": 60000
+ },
+ {
+ "id": "koi-showa",
+ "polycount": 60000
+ },
+ {
+ "id": "koi-lotus",
+ "polycount": 60000
+ },
+ {
+ "id": "koi-lantern",
+ "polycount": 80000
+ },
+ {
+ "id": "flora-rose",
+ "polycount": 100000
+ },
+ {
+ "id": "flora-protea",
+ "polycount": 100000
+ },
+ {
+ "id": "flora-morpho",
+ "polycount": 60000
+ },
+ {
+ "id": "flora-orchid",
+ "polycount": 100000
+ },
+ {
+ "id": "velo-white",
+ "polycount": 150000
+ },
+ {
+ "id": "hangar-mech",
+ "polycount": 200000
+ },
+ {
+ "id": "hangar-drone",
+ "polycount": 100000
+ },
+ {
+ "id": "sucre-cake",
+ "polycount": 150000
+ },
+ {
+ "id": "sucre-macaron",
+ "polycount": 20000
+ },
+ {
+ "id": "sucre-macaron2",
+ "polycount": 20000
+ },
+ {
+ "id": "sucre-croissant",
+ "polycount": 30000
+ },
+ {
+ "id": "sucre-strawberry",
+ "polycount": 20000
+ },
+ {
+ "id": "sucre-tart",
+ "polycount": 40000
+ },
+ {
+ "id": "mono-house",
+ "polycount": 250000
+ },
+ {
+ "id": "lf-turntable",
+ "polycount": 150000
+ },
+ {
+ "id": "lf-speaker",
+ "polycount": 80000
+ },
+ {
+ "id": "gambit-king",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "gambit-queen",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "gambit-bishop",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "gambit-knight",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "gambit-rook",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "gambit-pawn",
+ "polycount": 60000,
+ "symmetry": "on"
+ },
+ {
+ "id": "atlas-lighthouse",
+ "polycount": 150000
+ },
+ {
+ "id": "atlas-falls",
+ "polycount": 150000
+ },
+ {
+ "id": "atlas-pagoda",
+ "polycount": 150000
+ },
+ {
+ "id": "atlas-windmill",
+ "polycount": 150000
+ },
+ {
+ "id": "lithos-geode",
+ "polycount": 200000
+ },
+ {
+ "id": "lithos-quartz",
+ "polycount": 100000
+ },
+ {
+ "id": "lithos-pyrite",
+ "polycount": 100000
+ },
+ {
+ "id": "lithos-ammonite",
+ "polycount": 80000
+ },
+ {
+ "id": "artemis-astro",
+ "polycount": 60000,
+ "opts": {
+ "pose_mode": "a-pose",
+ "enable_rigging": true,
+ "rigging_height_meters": 1.85,
+ "enable_animation": true,
+ "animation_action_id": 0
+ },
+ "symmetry": "on"
+ },
+ {
+ "id": "artemis-lander",
+ "polycount": 150000
+ },
+ {
+ "id": "keeper-lighthouse",
+ "polycount": 200000
+ },
+ {
+ "id": "keeper-boat",
+ "polycount": 100000
+ },
+ {
+ "id": "koen-maple",
+ "polycount": 200000
+ },
+ {
+ "id": "noct-iris",
+ "polycount": 80000
+ },
+ {
+ "id": "noct-bergamot",
+ "polycount": 80000
+ },
+ {
+ "id": "noct-vanilla",
+ "polycount": 80000
+ },
+ {
+ "id": "noct-oud",
+ "polycount": 80000
+ },
+ {
+ "id": "noct-cap",
+ "polycount": 80000
+ },
+ {
+ "id": "racer-bike",
+ "polycount": 250000
+ },
+ {
+ "id": "racer-helmet",
+ "polycount": 80000
+ },
+ {
+ "id": "horo-watch",
+ "polycount": 150000
+ },
+ {
+ "id": "velo-black",
+ "polycount": 150000
+ }
+ ]
+}
\ No newline at end of file
diff --git a/assets/jobs/artemis-extra.json b/assets/jobs/artemis-extra.json
new file mode 100644
index 0000000..7cbdc6d
--- /dev/null
+++ b/assets/jobs/artemis-extra.json
@@ -0,0 +1,10 @@
+{ "images": [
+ { "id": "artemis-earth", "raw": true, "aspect_ratio": "16:9", "resolution": "4K",
+ "prompt": "Seamless equirectangular projection texture map of the whole planet Earth, unwrapped globe, 2:1 cylindrical projection edge to edge, realistic NASA Blue Marble satellite imagery: deep navy oceans, green and ochre continents, Sahara, Amazon, white polar ice caps at top and bottom edges, dense realistic swirling white cloud cover with cyclones and weather fronts over the oceans, natural colours, no text, no labels, no grid lines, no borders, no stars, no black background, the texture fills the entire frame." },
+ { "id": "artemis-habitat", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Interior of a compact lunar surface habitat module photographed on medium format film: four sleeping berths with pale grey fabric curtains, white composite wall panels with handrails and stowage lockers, one small warm reading lamp, a round thick porthole window showing a pitch black sky and a small blue half-lit Earth just above a grey lunar horizon, stark white sunlight raking across the floor from the window, calm, minimal, NASA archival documentary style, subtle film grain, muted colours, no people, no text, no logos." },
+ { "id": "artemis-training", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Black and white archival documentary photograph: a trainee in a white pressurised spacesuit walking on a grey simulated lunar dust field inside a dark cavernous training hangar, a single harsh spotlight from the side casting a very long black shadow, a reduced-gravity harness cable rising from the suit shoulders into darkness, footprints in the dust, high contrast, 1960s NASA film grain, cinematic, no text, no logos." },
+ { "id": "artemis-centrifuge", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Black and white archival documentary photograph of a human centrifuge training facility: a long steel arm with an enclosed white gondola capsule at its end sweeping around a circular concrete hall, slight motion blur on the capsule, dramatic single overhead light, deep shadows, 1960s NASA film grain, high contrast, no people visible, no text, no logos." }
+] }
diff --git a/assets/jobs/ember-extra.json b/assets/jobs/ember-extra.json
new file mode 100644
index 0000000..cb5dd75
--- /dev/null
+++ b/assets/jobs/ember-extra.json
@@ -0,0 +1,25 @@
+{
+ "images": [
+ {
+ "id": "ember-brick",
+ "raw": true,
+ "prompt": "Seamless tileable texture, orthographic flat front view of an old blacksmith workshop wall: hand-made clay bricks in running bond, heavily blackened by a century of forge soot and smoke, crumbling lime mortar joints, subtle warm brown-red brick showing through the soot in places, chipped edges, flat even diffuse lighting with no shadows or highlights, no perspective, fills the entire frame edge to edge, photographic PBR albedo texture, no text.",
+ "aspect_ratio": "1:1",
+ "resolution": "2K"
+ },
+ {
+ "id": "ember-floor",
+ "raw": true,
+ "prompt": "Seamless tileable texture, top-down orthographic view of a blacksmith forge floor: packed dark earth and worn flagstones covered in black soot, coal dust and tiny flakes of iron forge scale, a few scattered small cinders, very dark charcoal and umber tones, flat even diffuse lighting with no shadows, fills the entire frame edge to edge, photographic PBR albedo texture, no objects, no text.",
+ "aspect_ratio": "1:1",
+ "resolution": "2K"
+ },
+ {
+ "id": "ember-damascus",
+ "raw": true,
+ "prompt": "Extreme macro photograph of a polished and acid-etched random-pattern damascus steel sword blade surface, flat-on orthographic view filling the entire frame edge to edge, flowing wood-grain and topographic contour layers of bright silver nickel steel and dark grey carbon steel, hundreds of fine sinuous stretched layers running horizontally along the length, even soft lighting, no reflections of objects, no edges of the blade visible, no text.",
+ "aspect_ratio": "21:9",
+ "resolution": "2K"
+ }
+ ]
+}
diff --git a/assets/jobs/hangar-extra.json b/assets/jobs/hangar-extra.json
new file mode 100644
index 0000000..c870872
--- /dev/null
+++ b/assets/jobs/hangar-extra.json
@@ -0,0 +1,6 @@
+{ "images": [
+ { "id": "hangar-dawn", "raw": true, "aspect_ratio": "16:9", "resolution": "2K",
+ "prompt": "Clean full-frame landscape photograph of a vast empty military airfield apron at dawn, camera at standing eye level in the open, horizon exactly across the middle of the frame. Lower half: wet dark concrete apron slabs with faint yellow taxi lines and mirror-like reflections of the sky, two long rows of warm amber runway edge lights converging to a vanishing point at the centre of the horizon, thin low ground fog. Horizon: a distant dark jagged mountain ridge silhouette. Upper half: sky graded from deep steel blue at the top to burning amber and pale gold low at the centre where the sun is about to rise, a few thin clouds lit orange from below. Nothing else: no building, no door frame, no walls, no poles, no vignette border, no people, no vehicles, no aircraft, no text, no watermark. Anamorphic, moody, high dynamic range, 35mm film grain." },
+ { "id": "hangar-pilot", "raw": true, "aspect_ratio": "3:4", "resolution": "2K",
+ "prompt": "Cinematic portrait photograph of a female test pilot in her late thirties with short dark hair, wearing a gunmetal grey flight suit with amber hazard-stripe details and a mission patch, holding a matte grey pilot helmet under her arm, standing in a dark industrial hangar. Hard amber rim light from behind-left, cool steel-blue fill from the front, haze in the air, shallow depth of field, a blurred giant mechanical robot leg in the background out of focus. Serious calm expression looking just off camera. 85mm lens, film grain, desaturated teal and amber grade. No text, no logos with letters, no watermark." }
+] }
diff --git a/assets/jobs/keeper-extra.json b/assets/jobs/keeper-extra.json
new file mode 100644
index 0000000..d578744
--- /dev/null
+++ b/assets/jobs/keeper-extra.json
@@ -0,0 +1,10 @@
+{ "images": [
+ { "id": "keeper-room-lamp", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of the lamp room at the very top of a Victorian lighthouse, converted into a single hotel bedroom. A huge antique brass-and-glass Fresnel lens stands beside a low double bed made with crisp white linen and a heavy undyed wool blanket. Curved floor-to-ceiling glass walls with dark cast-iron glazing bars on every side, beyond them a dark stormy North Atlantic at blue hour with whitecaps and low racing cloud. Rain beads on the outside of the glass. The lens throws warm sodium-yellow prisms of light across the white sheets and the curved iron. Moody, quiet, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." },
+ { "id": "keeper-room-quarters", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of a lighthouse keeper's quarters in a whitewashed granite cottage, converted into a hotel room. Thick walls with a deep-set small sash window showing a grey heaving sea. A black cast-iron stove glows with a peat fire, a narrow scrubbed oak table holds a brass oil lamp and an open handwritten logbook, a worn leather armchair with a folded tartan wool blanket, painted tongue-and-groove panelling in pale grey-blue, a single low bed with white linen tucked in tight. Warm lamplight against cold blue window light, deep shadows. Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." },
+ { "id": "keeper-room-fog", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of an old fog signal house on a sea rock converted into a hotel room. Rough dark granite walls, the enormous flared mouth of a brass foghorn trumpet mounted through the wall, polished and green with age. A freestanding copper bathtub full of steaming water stands under a small arched window looking straight down at white surf smashing on black rocks. Slate floor, a thick sheepskin rug, a wrought-iron candle stand. Cold grey daylight from the window, warm candle glow, steam in the air. Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." },
+ { "id": "keeper-room-watch", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of the circular watch room of a lighthouse, just below the lantern, converted into a hotel room at dawn. A curved window seat with linen cushions runs along a band of small round-topped windows, a brass telescope on a wooden tripod points out to a calm pale sea, old nautical charts are pinned to the curved whitewashed wall, a narrow iron spiral stair rises through the ceiling, a daybed with a grey wool throw. Soft pink and apricot dawn light pours in low through the windows. Serene, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." }
+] }
diff --git a/assets/jobs/koen-extra.json b/assets/jobs/koen-extra.json
new file mode 100644
index 0000000..2f8a751
--- /dev/null
+++ b/assets/jobs/koen-extra.json
@@ -0,0 +1,14 @@
+{ "images": [
+ { "id": "koen-enso", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "A single zen ensō circle painted in one confident stroke of black sumi ink with a large soft calligraphy brush on plain white paper. The stroke starts thick and wet at the lower left, sweeps clockwise, thins out and breaks into dry-brush streaks (kasure) near the end, leaving a small open gap at the top. Pure flat white background, nothing else on the paper, no seal, no stamp, no signature, no text, no characters, no shadows, no frame. Scanned artwork, high contrast, crisp fibre texture in the dry brush." },
+ { "id": "koen-washi", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Flat overhead macro scan of handmade Japanese kozo washi paper, warm off-white cream colour, long translucent mulberry fibres visible, very subtle cloudy thickness variation, a few tiny darker fibre flecks, perfectly even diffuse lighting, no shadows, no folds, no edges, no objects, fills the entire frame, seamless texture, extremely subtle and low contrast." },
+ { "id": "koen-pine", "raw": true, "aspect_ratio": "3:4", "resolution": "2K",
+ "prompt": "Traditional Japanese sumi-e ink painting of a Japanese black pine bonsai in formal upright style in a shallow rectangular pot. Loose confident brushwork, the needle pads rendered as grey ink wash clouds, the trunk in dark dry-brush strokes with flaky bark, a pale ink wash suggests the pot. Black and grey ink only on plain warm white paper, large empty margins, subject centred in the lower two thirds. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border." },
+ { "id": "koen-juniper", "raw": true, "aspect_ratio": "3:4", "resolution": "2K",
+ "prompt": "Traditional Japanese sumi-e ink painting of an ancient shimpaku juniper bonsai with twisting white deadwood (shari and jin) spiralling up the trunk, a few dense foliage pads, in a small round pot. Loose expressive brushwork, the deadwood left as bare paper outlined by thin ink lines, foliage as soft grey ink washes. Black and grey ink only on plain warm white paper, large empty margins, subject centred. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border." },
+ { "id": "koen-azalea", "raw": true, "aspect_ratio": "3:4", "resolution": "2K",
+ "prompt": "Traditional Japanese sumi-e ink painting of a satsuki azalea bonsai in full bloom in a shallow oval pot, the gnarled trunk and branches in dark ink, the flower clusters painted as soft dabs of muted vermilion red watercolour, small leaves in grey ink wash. Black ink with a single restrained vermilion accent on plain warm white paper, large empty margins, subject centred. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border." },
+ { "id": "koen-quince", "raw": true, "aspect_ratio": "3:4", "resolution": "2K",
+ "prompt": "Traditional Japanese sumi-e ink painting of a tiny shohin chojubai flowering quince bonsai in a small glazed square pot, a knotted miniature trunk with a few thorny twigs and a handful of small blossoms painted in pale coral pink watercolour, tiny leaves in grey ink wash. Mostly black and grey ink on plain warm white paper, very large empty margins, small subject centred low. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border." }
+] }
diff --git a/assets/jobs/koen-retry.json b/assets/jobs/koen-retry.json
new file mode 100644
index 0000000..c1bd918
--- /dev/null
+++ b/assets/jobs/koen-retry.json
@@ -0,0 +1,9 @@
+{
+ "images": [
+ { "id": "koen-maple2", "prompt": "A Japanese maple bonsai tree, thick gnarled tapering trunk with visible surface roots, elegant sculpted branch structure with rounded compact cloud-like pads of small bright green maple leaves, clear gaps between the foliage pads showing branches, in a shallow oval dark brown glazed ceramic pot topped with green moss." }
+ ],
+ "meshes": [
+ { "id": "koen-maple", "image": "koen-maple", "polycount": 120000, "geometry": "standard" },
+ { "id": "koen-maple2", "polycount": 150000, "geometry": "standard" }
+ ]
+}
diff --git a/assets/jobs/koi-extra.json b/assets/jobs/koi-extra.json
new file mode 100644
index 0000000..15acf32
--- /dev/null
+++ b/assets/jobs/koi-extra.json
@@ -0,0 +1,14 @@
+{ "images": [
+ { "id": "koi-floor", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Top-down flat-lay photograph of a dry riverbed texture, camera pointing straight down: densely packed smooth rounded river stones of mixed sizes from small 2 cm pebbles to 20 cm cobbles, colours dark slate grey, charcoal, muted olive, rust ochre and a few pale granite ones, with coarse pale sand and fine gravel filling the gaps, a few dark sunken leaves, slightly damp matte look. Soft even overcast lighting with no directional shadows, uniform density and scale across the entire frame edge to edge, seamless tileable material texture, no horizon, no perspective, no water, no text, no watermark." },
+ { "id": "koi-canopy", "raw": true, "aspect_ratio": "16:9", "resolution": "2K",
+ "prompt": "Photograph looking straight up from beneath an old Japanese maple tree (Acer palmatum) toward a bright white overcast sky. Hundreds of delicate seven-pointed star-shaped leaves in dark silhouette, some layers glowing translucent green where light passes through, thin dark twisting branches reaching in from the left and top edges. The canopy is dense on the left half and top of the frame and opens to bright empty white sky toward the lower right. High contrast, crisp leaf edges, no sun, no lens flare, no text, no watermark." },
+ { "id": "koi-moss", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Top-down flat-lay photograph of a Japanese temple moss garden floor, camera pointing straight down: dense velvety cushion moss (sugigoke and hair-cap moss) in emerald, olive and a little golden green, soft undulating mounds, a few small dark wet stones half buried, scattered brown pine needles and two or three fallen red maple leaves. Soft even overcast light, no directional shadows, uniform density across the whole frame edge to edge, seamless tileable material texture, no horizon, no perspective, no text, no watermark." },
+ { "id": "koi-room-moss", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of a quiet ground-floor room in a traditional Kyoto ryokan. Pale green tatami mats, a low dark wooden table with a single ceramic tea cup, a folded futon with undyed linen, sliding shoji screens pulled fully open onto a narrow engawa veranda of weathered cedar boards, beyond it a lush moss garden with a mossy stone lantern and the dark green edge of a koi pond. Soft diffused morning light, faint mist, deep shadows inside the room. Serene, minimal, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." },
+ { "id": "koi-room-maple", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of a traditional Kyoto ryokan room in late autumn. Tatami floor, a low lacquered table, a round hinoki cedar soaking tub by an open window, sliding shoji screens framing an old Japanese maple tree blazing vermilion and crimson that overhangs a dark koi pond, fallen red leaves floating on the water. Warm late-afternoon light through the leaves casts dappled red light across the tatami. Serene, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." },
+ { "id": "koi-room-moon", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Editorial interior photograph of the upper room of a traditional Kyoto ryokan at night. A tatami room lit only by a glowing paper andon floor lamp, shoji opened onto a small wooden moon-viewing platform built out over a koi pond. A full moon hangs in a deep blue night sky above dark pine and maple silhouettes and its reflection sits perfectly in the still black water below. Two zabuton cushions and a tray with a sake flask on the platform. Deep blue and warm amber palette, quiet, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark." }
+] }
diff --git a/assets/jobs/lithos-extra.json b/assets/jobs/lithos-extra.json
new file mode 100644
index 0000000..dd72339
--- /dev/null
+++ b/assets/jobs/lithos-extra.json
@@ -0,0 +1,10 @@
+{ "images": [
+ { "id": "lithos-ring", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Luxury fine-jewellery campaign photograph: a heavy polished platinum signet ring set with a deep saturated violet amethyst cabochon, the ring resting at a slight angle on crushed jet-black silk velvet, single small hard spotlight from the upper left, tiny sparkling internal facets in the amethyst, crisp specular highlights on the platinum, deep velvety black shadows filling most of the frame, shallow depth of field, 100mm macro lens, medium format, museum-quiet mood, violet and platinum palette, no text, no logo, no hands." },
+ { "id": "lithos-pendant", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Luxury fine-jewellery campaign photograph: a raw natural water-clear quartz crystal point pendant, about 3 cm, capped in brushed platinum on a very fine platinum chain, the chain draped in a loose curve across crushed jet-black silk velvet, the crystal backlit by a narrow rim light so its edges glow and a faint rainbow fracture is visible inside, deep black background, shallow depth of field, 100mm macro lens, medium format, no text, no logo, no hands." },
+ { "id": "lithos-studs", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Luxury fine-jewellery campaign photograph: a pair of tiny natural pyrite cube stud earrings, each a perfect 5 mm brassy mirror-bright cube with fine growth striations, set in minimal platinum claw settings, lying on crushed jet-black silk velvet, one hard small spotlight creating mirror-sharp highlights on the cube faces, deep black shadows, shallow depth of field, 100mm macro lens, medium format, museum-quiet mood, no text, no logo, no hands." },
+ { "id": "lithos-miner", "raw": true, "aspect_ratio": "16:9", "resolution": "2K",
+ "prompt": "Documentary photograph, respectful and quiet: two weathered hands of a miner holding a freshly opened amethyst geode half, deep violet crystals glittering inside, in a dim basalt mine tunnel in northern Uruguay lit only by a warm headlamp from above, dust in the air, rough dark rock walls, the person's face is out of frame, shallow depth of field, 35mm film grain, natural muted colours with violet accent, no text, no logo." }
+] }
diff --git a/assets/jobs/lowfreq-extra.json b/assets/jobs/lowfreq-extra.json
new file mode 100644
index 0000000..6d6ec2c
--- /dev/null
+++ b/assets/jobs/lowfreq-extra.json
@@ -0,0 +1,14 @@
+{ "images": [
+ { "id": "lowfreq-cover-aubergine", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square vintage jazz record album cover artwork, no text, no letters, no typography. Grainy 35mm film photograph: close-up of a pianist's hands resting on the keys of a worn Fender Rhodes electric piano, lit by a single warm amber lamp from above, everything else falling into deep aubergine-purple shadow, shallow depth of field, heavy film grain, faded 1970s Japanese jazz label aesthetic, moody, intimate, photographic print texture." },
+ { "id": "lowfreq-cover-tidal", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square minimalist record album cover artwork, no text, no letters, no typography. A single large pale lavender circle hovering just above a flat dark indigo sea horizon, a thin amber line where sky meets water, vast empty space, risograph print with visible grain and slight ink misregistration, 1960s Japanese modernist graphic design, calm, flat colour fields on uncoated paper." },
+ { "id": "lowfreq-cover-counter", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography. High-contrast black and white photograph of an empty narrow Tokyo listening bar at closing time: a long polished wooden counter with a row of round bar stools, a single pendant lamp making a pool of light, walls of vinyl records fading into darkness, heavy grain, deep blacks, 1960s Blue Note style photography, cropped tight, cinematic." },
+ { "id": "lowfreq-cover-rain", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography, no signs with readable writing. Night photograph of a narrow Tokyo back alley in heavy rain, wet asphalt reflecting smeared purple and amber neon glow, a lone figure with a transparent umbrella walking away, soft motion blur, bokeh, cinematic colour grade, film grain, melancholy lo-fi mood." },
+ { "id": "lowfreq-cover-valves", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography. Macro photograph of four glowing vacuum tubes on a black amplifier chassis in total darkness, orange-amber filaments burning inside smoky glass, reflections on chrome, creamy bokeh, violet rim light from behind, dark and warm, analog hi-fi still life, film grain." },
+ { "id": "lowfreq-cover-geometry", "raw": true, "aspect_ratio": "1:1", "resolution": "1K",
+ "prompt": "Square abstract record album cover artwork, no text, no letters, no typography. Swiss and Japanese modernist composition: overlapping amber semicircles, a lavender quarter-disc and thin black parallel stripes arranged like sound waves on warm off-white paper, screen-printed texture with slight ink spread and paper fibres, bold, balanced, 1960s jazz label design." }
+] }
diff --git a/assets/jobs/monolith-extra.json b/assets/jobs/monolith-extra.json
new file mode 100644
index 0000000..ba8ae0d
--- /dev/null
+++ b/assets/jobs/monolith-extra.json
@@ -0,0 +1,12 @@
+{ "images": [
+ { "id": "monolith-stal", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Architectural photograph, Julius Shulman / Iwan Baan style. A small minimalist cabin made of black weathered steel and board-formed concrete, a single long rectangular volume with one huge frameless window, perched on a bare granite outcrop above a dark Arctic sea in Lofoten, Norway. Blue polar twilight, low pink sun on the horizon, thin snow on the rocks, one warm light inside. Shot on medium-format camera, 45mm lens, perfectly vertical lines, deep natural colour, fine detail, no people, no text, no watermark." },
+ { "id": "monolith-mertola", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Architectural photograph of a low courtyard house of pale sand-coloured concrete in the Alentejo, Portugal. Hard midday sun, razor-sharp black shadows from a deep concrete pergola falling across a white wall and a gravel courtyard with a single old olive tree. Deep blue cloudless sky. Minimal, monolithic, almost abstract composition, Swiss architectural photography, medium format, perfectly vertical lines, no people, no text, no watermark." },
+ { "id": "monolith-ulvik", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Architectural photograph of a long, slender board-formed concrete house cantilevered dramatically out of a steep mossy cliff above a Norwegian fjord, Hardanger. Golden hour, the low sun raking across the concrete so every formwork line and tie-hole casts a tiny shadow, long shadows of pine trees across the facade, full-height glazing reflecting the warm sky, mist on the fjord far below. Medium format, 35mm lens, perfectly vertical lines, rich but natural colour, no people, no text, no watermark." },
+ { "id": "monolith-lajes", "raw": true, "aspect_ratio": "4:5", "resolution": "2K",
+ "prompt": "Architectural photograph at blue hour of a house built from black basalt and grey concrete on the edge of a volcanic sea cliff in the Azores. Deep blue dusk sky, the Atlantic below, warm golden light glowing from a long horizontal strip window and a small lit infinity pool glowing turquoise on the terrace. Moody, quiet, cinematic, medium format, long exposure smooth sea, perfectly vertical lines, no people, no text, no watermark." },
+ { "id": "monolith-studio", "raw": true, "aspect_ratio": "3:2", "resolution": "2K",
+ "prompt": "Photograph of a quiet architecture studio in an old Lisbon warehouse: long pale oak tables covered with white and grey concrete architectural massing models of cliff houses, tracing paper drawings, a brass desk lamp. A single hard shaft of late afternoon sunlight from a tall window cuts diagonally across the room, casting long crisp shadows of the models across the table. Muted warm off-white palette, dust in the light, calm, editorial interior photography, 35mm, no people, no text, no watermark." }
+] }
diff --git a/assets/jobs/pilot.json b/assets/jobs/pilot.json
new file mode 100644
index 0000000..32f1b1e
--- /dev/null
+++ b/assets/jobs/pilot.json
@@ -0,0 +1,10 @@
+{
+ "images": [
+ { "id": "pilot-astrolabe", "prompt": "An intricate antique brass astrolabe on a small carved walnut stand, engraved rete with star pointers, nested rings, fine filigree, patinated brass with worn highlights." },
+ { "id": "pilot-guardian", "prompt": "An ancient weathered stone guardian statue of a seated lion-dog (komainu), carved granite with moss patches and lichen, cracked chipped edges, sitting on a square carved plinth." }
+ ],
+ "meshes": [
+ { "id": "pilot-astrolabe" },
+ { "id": "pilot-guardian" }
+ ]
+}
diff --git a/assets/jobs/plates.json b/assets/jobs/plates.json
new file mode 100644
index 0000000..ec9c0c4
--- /dev/null
+++ b/assets/jobs/plates.json
@@ -0,0 +1,4 @@
+{ "images": [
+ { "id": "plate-reliq-court", "raw": true, "aspect_ratio": "9:16", "resolution": "2K",
+ "prompt": "A moonlit cloister courtyard garden at night seen straight on, photographed at eye level: tall dark Italian cypress trees silhouetted against a deep blue night sky with scattered stars, a full moon high in the sky with a soft halo, a weathered stone fountain in the middle distance catching moonlight, pale gravel path leading away, low boxwood hedges, cool silver-blue moonlight, cinematic, photorealistic, calm, no people, no text." }
+] }
diff --git a/assets/jobs/racer-extra.json b/assets/jobs/racer-extra.json
new file mode 100644
index 0000000..59f2ae4
--- /dev/null
+++ b/assets/jobs/racer-extra.json
@@ -0,0 +1,12 @@
+{ "images": [
+ { "id": "racer-brick", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Seamless tileable texture. Straight-on orthographic photograph of an old industrial brick wall, soot-darkened charcoal and deep oxblood bricks in running bond, recessed dark mortar joints, wet from rain with subtle vertical water streaks and faint white efflorescence, evenly and flatly lit, no perspective, no shadows, no objects, no text, the bricks fill the entire frame edge to edge." },
+ { "id": "racer-shutter", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Straight-on orthographic photograph of a closed steel roll-up garage shutter, horizontal corrugated slats filling the entire frame edge to edge, dark gunmetal grey paint worn to bare steel along the ridges, rust streaks and rain runs, grime near the bottom, even flat lighting, no frame, no surrounding wall, no text, no graffiti, no logos." },
+ { "id": "racer-asphalt", "raw": true, "aspect_ratio": "1:1", "resolution": "2K",
+ "prompt": "Seamless tileable texture. Top-down orthographic photograph of dark city asphalt road surface, fine black aggregate with occasional grey stones, a couple of thin sealed tar crack lines, faint oil stains, evenly lit, no puddles, no road markings, no shadows, fills the entire frame." },
+ { "id": "racer-workshop", "raw": true, "aspect_ratio": "21:9", "resolution": "2K",
+ "prompt": "Cinematic low photograph taken at floor level inside a small custom motorcycle workshop at night, warm amber tungsten work lights, polished concrete floor with oil stains and reflections, a red rolling tool chest, spoked motorcycle wheels leaning against a workbench, a bike frame on a stand, shallow depth of field, dim moody atmosphere, film grain, no people, no text." },
+ { "id": "racer-city", "raw": true, "aspect_ratio": "21:9", "resolution": "2K",
+ "prompt": "Very dark rainy city street at night seen far in the distance, everything heavily out of focus, soft round bokeh of sodium street lamps, red tail lights and a few magenta and teal shop signs, wet road reflections, thin fog, cinematic anamorphic look, restrained palette, mostly black, no people, no readable text." }
+] }
diff --git a/assets/manifest.json b/assets/manifest.json
new file mode 100644
index 0000000..ca3638e
--- /dev/null
+++ b/assets/manifest.json
@@ -0,0 +1,2042 @@
+{
+ "images": {
+ "pilot-astrolabe": {
+ "url": "https://v3b.fal.media/files/b/0aac5b2c/8IDIhjGIt9vPZjQLcaSep_ncXhpnwN.png",
+ "prompt": "An intricate antique brass astrolabe on a small carved walnut stand, engraved rete with star pointers, nested rings, fine filigree, patinated brass with worn highlights.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:15:39.308Z"
+ },
+ "pilot-guardian": {
+ "url": "https://v3b.fal.media/files/b/0aac5b2c/fujbp1ruXevlrZkK1S7CH_5lu3fYdM.png",
+ "prompt": "An ancient weathered stone guardian statue of a seated lion-dog (komainu), carved granite with moss patches and lichen, cracked chipped edges, sitting on a square carved plinth.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:15:40.085Z"
+ },
+ "reliq-helmet": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/sJHNwY5SJTN_iB_4wCVsd_E6wUYZMo.png",
+ "prompt": "An ancient Greek bronze Corinthian hoplite helmet, deep verdigris green-blue patina with exposed warm bronze on the high points, dented and scratched, engraved brow line, narrow eye slits and nose guard, resting on a small rough-cut dark basalt display block.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:04.550Z"
+ },
+ "abyss-nautilus": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/p7pYbaBPK7NuWtDvgFNr__KWOJjXEW.png",
+ "prompt": "A living chambered nautilus, cream shell with bold red-brown tiger stripes, pearly aperture, many small tentacles and a hood emerging from the shell opening, three-quarter view.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:06.220Z"
+ },
+ "reliq-mask": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/-3GIYdVk22Nz5ajCQPgTC_Ed1Ds9Gb.png",
+ "prompt": "An ancient Maya jade mosaic funerary mask, hundreds of fitted green jade tesserae, inlaid white shell eyes with black obsidian pupils, subtle cracks, museum artifact, facing forward at a slight three-quarter angle, mounted on a small black metal museum stand.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:08.456Z"
+ },
+ "reliq-bust": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/x1yFtWmVNkqOpyLzNwNJv_agLblIXw.png",
+ "prompt": "A weathered white Carrara marble classical Greek bust of a young woman with braided hair tied up, nose slightly chipped, subtle grey veining and soft erosion, on a square marble socle, museum sculpture.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:09.483Z"
+ },
+ "abyss-angler": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/mqKXGEfd7pwargiH6TNIo_7ETOblAv.png",
+ "prompt": "A deep-sea anglerfish, menacing wide jaw with long translucent needle teeth, bulbous glowing lure on a stalk above its head, dark brown-black rough warty skin, small eyes, fins spread, side three-quarter view, museum-quality natural history model.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:10.518Z"
+ },
+ "abyss-vent": {
+ "url": "https://v3b.fal.media/files/b/0aac5b66/dOx3hZfIBwPplwPQf_oO-_A7yAgCBi.png",
+ "prompt": "A hydrothermal vent chimney diorama from the deep ocean floor: a tall craggy black-and-rust mineral chimney, dense clusters of giant red-plumed white tube worms at its base, pale crabs and mussels, on a round chunk of dark volcanic seabed.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:22.621Z"
+ },
+ "abyss-sub": {
+ "url": "https://v3b.fal.media/files/b/0aac5b66/oFyY6ngTR1VgnHUoVePCy_8v7LJXzx.png",
+ "prompt": "A compact deep-sea research submersible, rounded white and safety-orange hull, large clear acrylic viewing dome at the front, two articulated manipulator arms, cluster of LED floodlights, ballast tanks, thrusters, sampling basket, realistic industrial design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:22.939Z"
+ },
+ "reliq-amphora": {
+ "url": "https://v3b.fal.media/files/b/0aac5b64/DrT4kJuEVGyCQmI4AWFAw_ojUj9BiU.png",
+ "prompt": "An ancient Greek black-figure terracotta amphora with two handles, orange clay with black painted figures of running athletes and meander bands, small chips and wear, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:23.072Z"
+ },
+ "ember-hammer": {
+ "url": "https://v3b.fal.media/files/b/0aac5b67/pV4vG45lL9DMjedtfN-eV_oNYpjzla.png",
+ "prompt": "A blacksmith's cross-peen forging hammer with a dark forged steel head showing hammer marks, and a worn ash-wood handle, lying diagonally.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:28.385Z"
+ },
+ "ember-anvil": {
+ "url": "https://v3b.fal.media/files/b/0aac5b67/j73SyGu2BNr4j3XWgucZz_ImSc2ZVR.png",
+ "prompt": "A heavy old blacksmith's anvil, dark forged steel with a polished worn face and horn, scale and scratches, bolted on top of a thick weathered oak tree-stump base with iron bands.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:30.169Z"
+ },
+ "ember-sword": {
+ "url": "https://v3b.fal.media/files/b/0aac5b7f/j6Lwz9abPTaYgra7YTqep_HuorDmFp.png",
+ "prompt": "A hand-forged Viking longsword lying diagonally across the frame from bottom-left to top-right, entire sword visible with margin, damascus pattern-welded steel blade with a clearly visible flowing wood-grain pattern, bronze crossguard and lobed pommel with knotwork, dark leather-wrapped grip.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:29:33.186Z"
+ },
+ "terra-tropic": {
+ "url": "https://v3b.fal.media/files/b/0aac5b68/tcAHdxux8ZTw4OOtUesz-_uBEMAds6.png",
+ "prompt": "A miniature tropical rainforest terrarium landscape without any glass: dark volcanic rocks, a tiny cascading waterfall, lush miniature ferns, fittonia with pink veins, a small white orchid, mossy roots, all built on a round turned walnut wood base disc.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:41.780Z"
+ },
+ "terra-desert": {
+ "url": "https://v3b.fal.media/files/b/0aac5b68/hUqq2XOCl0LDklCgAzLUE_T0FLf5lL.png",
+ "prompt": "A miniature desert terrarium landscape without any glass: pale golden sand dunes, sculptural sandstone rocks, small green and blue-grey succulents and echeverias, a tiny flowering cactus with pink blooms, all built on a round turned walnut wood base disc.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:46.150Z"
+ },
+ "koi-kohaku": {
+ "url": "https://v3b.fal.media/files/b/0aac5b68/DCQl2Om_-yKmf3O4SY7iP_8bt31tU7.png",
+ "prompt": "A single koi carp fish seen from above at a slight three-quarter angle, kohaku pattern: glossy pearl-white body with large vivid red-orange patches, long flowing translucent fins and tail spread out, gentle S-curve swimming pose, realistic scales.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:46.781Z"
+ },
+ "terra-moss": {
+ "url": "https://v3b.fal.media/files/b/0aac5b68/NJSvXhVg-vGxf7G4a70lW_rGuPuvKZ.png",
+ "prompt": "A miniature forest terrarium landscape without any glass: rolling hills of lush green cushion moss, lichen-covered grey stones, tiny ferns, a small gnarled bonsai-like tree, a white pebble path winding through, tiny red mushrooms, all built on a round turned walnut wood base disc.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:49.137Z"
+ },
+ "koi-lotus": {
+ "url": "https://v3b.fal.media/files/b/0aac5b69/S6ZTtSQRVTHtmXmdy1EbR_WcYPyGYm.png",
+ "prompt": "A single open pink lotus flower with layered soft pink petals, golden seed pod center and yellow stamens, sitting on one round flat green lotus leaf.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:49.491Z"
+ },
+ "koi-showa": {
+ "url": "https://v3b.fal.media/files/b/0aac5b69/X_e4mpGk1QijK7Dbokmtj_EsB2NIen.png",
+ "prompt": "A single koi carp fish seen from above at a slight three-quarter angle, showa sanshoku pattern: black body with red-orange and white patches, long flowing translucent fins and tail spread out, gentle S-curve swimming pose, realistic scales.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:53.159Z"
+ },
+ "koi-lantern": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6a/hTpOkVDbYMd8ifpvklVul_4ulCpYnD.png",
+ "prompt": "A traditional Japanese granite stone lantern (kasuga toro), weathered grey stone with moss on the roof and base, hexagonal fire box with carved openings, tall pillar, on a rough rock.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:25:59.995Z"
+ },
+ "flora-rose": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6a/KKBNJaRRRs6sNrBbCTvLk_27kuVv8A.png",
+ "prompt": "A single perfect deep crimson red rose bloom with many velvety layered petals and a short stem with two green leaves, botanical specimen.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:02.128Z"
+ },
+ "flora-protea": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6a/eSMln200Uw97azg-DA0hL_qcJYVLbm.png",
+ "prompt": "A single king protea flower head, large crown of pink-tipped pointed bracts around a silvery-cream fuzzy center, short stem with leathery green leaves, botanical specimen.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:04.308Z"
+ },
+ "flora-orchid": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6b/aRN1Es2Vl1yhPlQOgljuD_xc2DmbpW.png",
+ "prompt": "A single white phalaenopsis orchid spray: arching stem with five open white flowers with magenta-veined lips and two buds, botanical specimen without pot.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:04.992Z"
+ },
+ "flora-morpho": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6b/PONFL4W8yAS0eXXjWmcCP_vAUJuKta.png",
+ "prompt": "A blue morpho butterfly with wings spread open, iridescent electric-blue upper wings with black edges and white spots, body and antennae, seen from above at a slight angle, natural history specimen.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:11.193Z"
+ },
+ "velo-white": {
+ "url": "https://v3b.fal.media/files/b/0aac5b7f/8S0FAwBH1iA1vPem0Gc_y_vQfod9aL.png",
+ "prompt": "A futuristic performance running sneaker resting flat on the ground, clean side three-quarter view with the entire shoe visible from toe to heel with wide margins, white engineered knit upper with subtle translucent ripstop overlays, sculpted chunky pale-grey foam midsole with a visible black carbon plate slit, volt-orange heel pull tab and orange laces, premium product design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:29:33.423Z"
+ },
+ "hangar-drone": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6c/AlPhN02Q2PI6jOjpE75-7_2JhlQcOH.png",
+ "prompt": "A heavy industrial quadcopter drone, carbon fiber and matte grey body, four large rotors with guards, orange safety markings, sensor gimbal camera underneath, realistic hard-surface design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:17.791Z"
+ },
+ "hangar-mech": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6c/X3fzf43XJ6lR3urfllTLe_cxhNPksx.png",
+ "prompt": "A large bipedal combat mech robot standing, full body head to feet, military gunmetal grey armor plates with orange hazard stripes and stencilled numbers, weathered and chipped paint, armored cockpit head with glowing visor slit, heavy digitigrade legs with hydraulic pistons, shoulder-mounted cannon, realistic hard-surface design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:17.902Z"
+ },
+ "sucre-macaron": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6c/WaciDTwOW8j9lroQDay-W_UhIgQNN8.png",
+ "prompt": "A single French macaron, pastel pink shells with smooth domed tops and ruffled feet, raspberry buttercream filling, slightly tilted.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:20.892Z"
+ },
+ "sucre-cake": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6c/bdomvv1HKuE5lMlezSlWP_QUx7phmk.png",
+ "prompt": "An elegant three-tier pastel pink and cream wedding cake with piped buttercream ruffles, fresh raspberries and pale roses, gold leaf flakes, on a white porcelain cake stand.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:21.815Z"
+ },
+ "sucre-croissant": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6d/i8Dq8ljtQwH_0WbcFeRUx_OUxmdBmd.png",
+ "prompt": "A single golden buttery French croissant with flaky glossy laminated layers.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:29.041Z"
+ },
+ "sucre-macaron2": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6d/E1W1eKXjoocd1qTB2-bWG_Dhs09tUK.png",
+ "prompt": "A single French macaron, pastel pistachio green shells with smooth domed tops and ruffled feet, cream filling, slightly tilted.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:33.809Z"
+ },
+ "sucre-tart": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6d/HlpM1uQ5Rg1WFtubYpv_1_AU0tioGW.png",
+ "prompt": "A small round French strawberry tart: golden fluted pastry shell, vanilla custard, glazed halved strawberries arranged in a spiral, a mint leaf.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:37.575Z"
+ },
+ "mono-house": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6e/lhkuv4SUfgcu7TAuoD8mq_QSsRThSy.png",
+ "prompt": "An architectural diorama: a minimalist modern concrete villa with long cantilevered floors and floor-to-ceiling glass cantilevered dramatically over a rugged granite sea cliff, a few windswept pine trees, infinity pool, all on a chunk of rocky terrain with rough cut edges, highly detailed architectural model.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:38.292Z"
+ },
+ "lf-turntable": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6e/lBeNGl4IcV9q6Z8VhuDyk_mjAwQBO0.png",
+ "prompt": "A premium high-end record turntable, thick walnut wood plinth, heavy brushed aluminum platter with a black vinyl record, polished tonearm with counterweight, two rotary knobs, no dust cover.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:44.016Z"
+ },
+ "gambit-king": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6f/VBpH_ZfVXYGgihpg_JDzz_uPNTpT3d.png",
+ "prompt": "A tall ornate Staunton king chess piece carved from polished white Carrara marble with delicate grey veining, cross on top, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:50.388Z"
+ },
+ "lf-speaker": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6f/JrAGayVte_onoCHZiBy0h_AiDxrzgW.png",
+ "prompt": "A premium bookshelf studio speaker, walnut wood cabinet, exposed woven paper woofer cone and a silk dome tweeter, brass bolts, front-facing three-quarter view.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:51.201Z"
+ },
+ "sucre-strawberry": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6d/GvWF0FpGdTuLtWgSUeqA4_MHOOaDOO.png",
+ "prompt": "A single ripe glossy red strawberry with green leafy calyx.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:52.546Z"
+ },
+ "gambit-bishop": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6f/SkV-kGh0epoqf24PYqk9H_tWAhetaR.png",
+ "prompt": "A Staunton bishop chess piece carved from polished white Carrara marble with delicate grey veining, mitre with diagonal cut and small ball finial, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:56.657Z"
+ },
+ "gambit-queen": {
+ "url": "https://v3b.fal.media/files/b/0aac5b6f/z1WT9J-RpBIYU1eCdnxlm_GEiiDjtf.png",
+ "prompt": "A tall ornate Staunton queen chess piece carved from polished white Carrara marble with delicate grey veining, coronet crown on top, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:26:58.530Z"
+ },
+ "gambit-knight": {
+ "url": "https://v3b.fal.media/files/b/0aac5b70/8U3H8UimPuzF7yzLq2bRj_9bhMU3AC.png",
+ "prompt": "A Staunton knight chess piece carved from polished white Carrara marble with delicate grey veining, finely sculpted horse head with flowing mane, standing upright, three-quarter side view.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:02.908Z"
+ },
+ "gambit-rook": {
+ "url": "https://v3b.fal.media/files/b/0aac5b71/KqhNM8txSZyxSBhOiQcQQ_3hSe8wmk.png",
+ "prompt": "A Staunton rook chess piece carved from polished white Carrara marble with delicate grey veining, castle turret top with crenellations, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:06.315Z"
+ },
+ "gambit-pawn": {
+ "url": "https://v3b.fal.media/files/b/0aac5b71/oiej4x2cmXRblDdU39Wd3_UcKfM6y7.png",
+ "prompt": "A Staunton pawn chess piece carved from polished white Carrara marble with delicate grey veining, sphere head on a collar and stepped base, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:09.357Z"
+ },
+ "atlas-falls": {
+ "url": "https://v3b.fal.media/files/b/0aac5b71/Nyjc7yVPl_wv3xucFdvSK_sbsmmbvc.png",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: lush forest with round trees, a waterfall pouring off the edge from a small lake, mossy boulders, the island's underside a jagged rock cone with hanging vines, floating in the air.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:13.149Z"
+ },
+ "atlas-lighthouse": {
+ "url": "https://v3b.fal.media/files/b/0aac5b71/tDIxteDr_dOK5ydS5iCHq_oaLF1LOV.png",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: a grassy cliff-top with a small white lighthouse with red top and a cozy stone cottage, winding path, wildflowers, the island's underside a jagged rock cone with hanging roots, floating in the air.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:20.163Z"
+ },
+ "atlas-windmill": {
+ "url": "https://v3b.fal.media/files/b/0aac5b72/t8apRFrA23bFA_KO6zKh6_G9Wz1kXc.png",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: rolling golden wheat fields, a wooden windmill, a red barn, hay bales and a tiny winding river, the island's underside a jagged rock cone with hanging roots, floating in the air.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:22.133Z"
+ },
+ "atlas-pagoda": {
+ "url": "https://v3b.fal.media/files/b/0aac5b71/epBFDyoJm15rosV5_ocGo_Kw7xFJcD.png",
+ "prompt": "A stylized floating sky island, hand-painted stylized game art style: a red Japanese pagoda with pink cherry blossom trees, stone steps and a torii gate, the island's underside a jagged rock cone with hanging roots, floating in the air.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:23.315Z"
+ },
+ "lithos-geode": {
+ "url": "https://v3b.fal.media/files/b/0aac5b72/nltDk7gY6mbtU0i8EO4o6_i4M6KR7V.png",
+ "prompt": "One half of a large split amethyst geode, cut face up and tilted toward the viewer: a rough grey-brown rocky outer crust, a white agate banding rim, and a deep cavity densely lined with sparkling purple amethyst crystal points.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:24.625Z"
+ },
+ "lithos-quartz": {
+ "url": "https://v3b.fal.media/files/b/0aac5b73/_vto5DWnu7tp_mtz7yWsi_WAwMgVVM.png",
+ "prompt": "A cluster of clear quartz crystal points growing from a small matrix rock, tall hexagonal terminated crystals, water-clear with slight internal veils and rainbow inclusions.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:29.801Z"
+ },
+ "lithos-pyrite": {
+ "url": "https://v3b.fal.media/files/b/0aac5b73/Y7CTs0WC6bCNLJBsmvnG4_lFYYqLCb.png",
+ "prompt": "A cluster of natural pyrite cubes, sharp interlocking metallic brass-gold cubic crystals with striated faces, on a small dark rock matrix.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:32.504Z"
+ },
+ "lithos-ammonite": {
+ "url": "https://v3b.fal.media/files/b/0aac5b74/tTbB4Pu67vb_3uDJZQt8I_fy4kJrir.png",
+ "prompt": "A polished ammonite fossil, spiral shell cut and polished showing iridescent mother-of-pearl surface and intricate suture patterns, on a small rough stone base.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:38.990Z"
+ },
+ "keeper-lighthouse": {
+ "url": "https://v3b.fal.media/files/b/0aac5b7f/a8-pAcfkKRGbRRa6YJZoA_K0t3ANUD.png",
+ "prompt": "A diorama of a tall weathered stone lighthouse painted with red and white bands, black iron lantern gallery at the top, attached small white keeper's cottage with slate roof and chimney, standing on a tall jagged dark wet basalt sea-rock outcrop with steep sides, the rock cut flat at the bottom, no water, no waves, no sea.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:29:33.179Z"
+ },
+ "keeper-boat": {
+ "url": "https://v3b.fal.media/files/b/0aac5b75/dFYJ5u5KggSnM99OWBrkE_qMEFdNUZ.png",
+ "prompt": "A small weathered wooden fishing trawler boat, dark green hull with a white wheelhouse, rust streaks, nets, buoys and a small mast with lights.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:45.307Z"
+ },
+ "artemis-astro": {
+ "url": "https://v3b.fal.media/files/b/0aac5b74/kyyiEKqDWO91R-pE8UKBv_maJfkxAY.png",
+ "prompt": "A full-body astronaut in a modern white and light grey lunar exploration spacesuit with a reflective gold visor, backpack life-support system, orange accents, gloves and boots, standing in a relaxed A-pose with arms slightly away from the body, facing the viewer, full figure head to toe visible.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:47.221Z"
+ },
+ "artemis-lander": {
+ "url": "https://v3b.fal.media/files/b/0aac5b74/CExYOxp_oTaosGCthXglh_s4FwxSfc.png",
+ "prompt": "A modern lunar lander spacecraft on four spindly landing legs with round footpads, gold foil insulated descent stage, white and grey ascent cabin with windows, antennas, thrusters, solar panel, realistic aerospace design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:49.288Z"
+ },
+ "koen-maple": {
+ "url": "https://v3b.fal.media/files/b/0aac5b75/52TJfefWqGJl14s2Z9-7l_X131q33k.png",
+ "prompt": "A Japanese maple bonsai tree in full summer foliage, thick flared tapering trunk with nebari surface roots, elegant branch structure with dense green palmate leaf pads, in a shallow oval dark-glazed ceramic pot covered with moss.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:27:50.683Z"
+ },
+ "noct-bergamot": {
+ "url": "https://v3b.fal.media/files/b/0aac5b76/Z4iL9WwosyWlag6vJv0cq_VWapd2N0.png",
+ "prompt": "Two bergamot oranges with one cut in half showing the juicy pale yellow segments, glossy textured green-yellow peel, a sprig with two dark leaves.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:00.331Z"
+ },
+ "noct-oud": {
+ "url": "https://v3b.fal.media/files/b/0aac5b76/An0TELL41aJVxcbvrAzR4_qNlpEAIQ.png",
+ "prompt": "A piece of rare resinous agarwood (oud) wood, dark streaks of resin through pale gnarled wood, sculptural twisted chunk.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:05.945Z"
+ },
+ "noct-cap": {
+ "url": "https://v3b.fal.media/files/b/0aac5b77/t9vxutlhTVZURbtdSt8MS_RAzYeP6c.png",
+ "prompt": "An ornate heavy perfume bottle stopper cap, faceted black obsidian crystal top in a sculpted polished gold art-deco collar with fluted ridges, standing upright.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:08.542Z"
+ },
+ "noct-iris": {
+ "url": "https://v3b.fal.media/files/b/0aac5b76/c8VRYVaGNGuhwTjloFr_l_wK1WTybU.png",
+ "prompt": "A single purple bearded iris flower with ruffled violet falls and standards, golden beard, short green stem and a blade leaf, botanical specimen.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:12.522Z"
+ },
+ "noct-vanilla": {
+ "url": "https://v3b.fal.media/files/b/0aac5b76/0t2EnbZxxANCldwUYGJVl_XWi9bmft.png",
+ "prompt": "A small bundle of glossy dark brown cured vanilla bean pods tied with twine, next to a cured vanilla orchid flower.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:14.742Z"
+ },
+ "racer-helmet": {
+ "url": "https://v3b.fal.media/files/b/0aac5b78/gDf-CWYG6Df6vOHfPYRwJ_51lCYVhZ.png",
+ "prompt": "A vintage open-face motorcycle helmet, glossy cream paint with a thin red racing stripe, brown leather trim and chin strap, with a bubble visor raised.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:19.768Z"
+ },
+ "horo-watch": {
+ "url": "https://v3b.fal.media/files/b/0aac5b78/RwF0kiq7SCAVelzsuCyPo_c7lqzriC.png",
+ "prompt": "A luxury skeleton mechanical wristwatch, round polished rose-gold case, openworked dial exposing gears, bridges and a balance wheel, blued steel hands, sapphire crystal, dark brown alligator leather strap, three-quarter view.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:23.659Z"
+ },
+ "racer-bike": {
+ "url": "https://v3b.fal.media/files/b/0aac5b77/XVvpt4-Lhv2soLnApizig_XwzDgwG0.png",
+ "prompt": "A custom cafe racer motorcycle, three-quarter side view, glossy black fuel tank with brass pinstripe, tan leather hump seat, round chrome headlight, clip-on handlebars, exposed polished twin-cylinder engine, spoked wheels with black tires, brass and chrome details.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:28:25.239Z"
+ },
+ "velo-black": {
+ "url": "https://v3b.fal.media/files/b/0aac5b83/eXVKlk511QxIpNoTjnDJO_alammmAK.png",
+ "prompt": "Recolor this exact sneaker, keeping the identical shape, angle, framing and pure white background: make the knit upper deep matte black, the foam midsole charcoal graphite, the carbon plate slit glossy black, and change the heel tab and laces to electric volt yellow-green. Photorealistic product render.",
+ "endpoint": "fal-ai/nano-banana-2/edit",
+ "at": "2026-09-29T10:30:17.318Z"
+ },
+ "plate-reliq-court": {
+ "url": "https://v3b.fal.media/files/b/0aac5bd2/RI1zLSDHAymJOvTZtgOzP_dnbYNxE5.png",
+ "prompt": "A moonlit cloister courtyard garden at night seen straight on, photographed at eye level: tall dark Italian cypress trees silhouetted against a deep blue night sky with scattered stars, a full moon high in the sky with a soft halo, a weathered stone fountain in the middle distance catching moonlight, pale gravel path leading away, low boxwood hedges, cool silver-blue moonlight, cinematic, photorealistic, calm, no people, no text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:43:28.118Z"
+ },
+ "hangar-pilot": {
+ "url": "https://v3b.fal.media/files/b/0aac5c2d/wo9HwQsvCl3OSNtTwMl6Q_Iw9JvyqH.png",
+ "prompt": "Cinematic portrait photograph of a female test pilot in her late thirties with short dark hair, wearing a gunmetal grey flight suit with amber hazard-stripe details and a mission patch, holding a matte grey pilot helmet under her arm, standing in a dark industrial hangar. Hard amber rim light from behind-left, cool steel-blue fill from the front, haze in the air, shallow depth of field, a blurred giant mechanical robot leg in the background out of focus. Serious calm expression looking just off camera. 85mm lens, film grain, desaturated teal and amber grade. No text, no logos with letters, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:58:33.399Z"
+ },
+ "hangar-dawn": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4c/l_1_JqHvTt4xuCRUQxzNr_ZF8Z4MI1.png",
+ "prompt": "Clean full-frame landscape photograph of a vast empty military airfield apron at dawn, camera at standing eye level in the open, horizon exactly across the middle of the frame. Lower half: wet dark concrete apron slabs with faint yellow taxi lines and mirror-like reflections of the sky, two long rows of warm amber runway edge lights converging to a vanishing point at the centre of the horizon, thin low ground fog. Horizon: a distant dark jagged mountain ridge silhouette. Upper half: sky graded from deep steel blue at the top to burning amber and pale gold low at the centre where the sun is about to rise, a few thin clouds lit orange from below. Nothing else: no building, no door frame, no walls, no poles, no vignette border, no people, no vehicles, no aircraft, no text, no watermark. Anamorphic, moody, high dynamic range, 35mm film grain.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:43.932Z"
+ },
+ "keeper-room-quarters": {
+ "url": "https://v3b.fal.media/files/b/0aac5c31/VPisDRIdTnqc_3v7KYFwk_rESnv33I.png",
+ "prompt": "Editorial interior photograph of a lighthouse keeper's quarters in a whitewashed granite cottage, converted into a hotel room. Thick walls with a deep-set small sash window showing a grey heaving sea. A black cast-iron stove glows with a peat fire, a narrow scrubbed oak table holds a brass oil lamp and an open handwritten logbook, a worn leather armchair with a folded tartan wool blanket, painted tongue-and-groove panelling in pale grey-blue, a single low bed with white linen tucked in tight. Warm lamplight against cold blue window light, deep shadows. Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:59:13.809Z"
+ },
+ "keeper-room-lamp": {
+ "url": "https://v3b.fal.media/files/b/0aac5c31/cPkxpwrDpG-tf3pFVkadv_eBwI1dpF.png",
+ "prompt": "Editorial interior photograph of the lamp room at the very top of a Victorian lighthouse, converted into a single hotel bedroom. A huge antique brass-and-glass Fresnel lens stands beside a low double bed made with crisp white linen and a heavy undyed wool blanket. Curved floor-to-ceiling glass walls with dark cast-iron glazing bars on every side, beyond them a dark stormy North Atlantic at blue hour with whitecaps and low racing cloud. Rain beads on the outside of the glass. The lens throws warm sodium-yellow prisms of light across the white sheets and the curved iron. Moody, quiet, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:59:17.255Z"
+ },
+ "keeper-room-watch": {
+ "url": "https://v3b.fal.media/files/b/0aac5c31/0jgLDfVGqIe5jfCaVPRO__2mkRXiQd.png",
+ "prompt": "Editorial interior photograph of the circular watch room of a lighthouse, just below the lantern, converted into a hotel room at dawn. A curved window seat with linen cushions runs along a band of small round-topped windows, a brass telescope on a wooden tripod points out to a calm pale sea, old nautical charts are pinned to the curved whitewashed wall, a narrow iron spiral stair rises through the ceiling, a daybed with a grey wool throw. Soft pink and apricot dawn light pours in low through the windows. Serene, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:59:18.343Z"
+ },
+ "keeper-room-fog": {
+ "url": "https://v3b.fal.media/files/b/0aac5c31/VCcYoUI1QdVv3j9_WHNqg_bHnBQLhR.png",
+ "prompt": "Editorial interior photograph of an old fog signal house on a sea rock converted into a hotel room. Rough dark granite walls, the enormous flared mouth of a brass foghorn trumpet mounted through the wall, polished and green with age. A freestanding copper bathtub full of steaming water stands under a small arched window looking straight down at white surf smashing on black rocks. Slate floor, a thick sheepskin rug, a wrought-iron candle stand. Cold grey daylight from the window, warm candle glow, steam in the air. Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T10:59:23.870Z"
+ },
+ "artemis-habitat": {
+ "url": "https://v3b.fal.media/files/b/0aac5c38/gmYVGLjqws1yNWOBrljR0_drrZz1Z4.png",
+ "prompt": "Interior of a compact lunar surface habitat module photographed on medium format film: four sleeping berths with pale grey fabric curtains, white composite wall panels with handrails and stowage lockers, one small warm reading lamp, a round thick porthole window showing a pitch black sky and a small blue half-lit Earth just above a grey lunar horizon, stark white sunlight raking across the floor from the window, calm, minimal, NASA archival documentary style, subtle film grain, muted colours, no people, no text, no logos.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:20.190Z"
+ },
+ "artemis-training": {
+ "url": "https://v3b.fal.media/files/b/0aac5c38/gfRW3yjYYphZKni70-Stw_Ue7WVe6t.png",
+ "prompt": "Black and white archival documentary photograph: a trainee in a white pressurised spacesuit walking on a grey simulated lunar dust field inside a dark cavernous training hangar, a single harsh spotlight from the side casting a very long black shadow, a reduced-gravity harness cable rising from the suit shoulders into darkness, footprints in the dust, high contrast, 1960s NASA film grain, cinematic, no text, no logos.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:20.728Z"
+ },
+ "artemis-centrifuge": {
+ "url": "https://v3b.fal.media/files/b/0aac5c38/LoiNgZEr99E8Az1XHUciR_Wwb8TCnQ.png",
+ "prompt": "Black and white archival documentary photograph of a human centrifuge training facility: a long steel arm with an enclosed white gondola capsule at its end sweeping around a circular concrete hall, slight motion blur on the capsule, dramatic single overhead light, deep shadows, 1960s NASA film grain, high contrast, no people visible, no text, no logos.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:21.375Z"
+ },
+ "ember-floor": {
+ "url": "https://v3b.fal.media/files/b/0aac5c39/oS3WaaLPjThjf5pXTU6ij_6iTrEmxu.png",
+ "prompt": "Seamless tileable texture, top-down orthographic view of a blacksmith forge floor: packed dark earth and worn flagstones covered in black soot, coal dust and tiny flakes of iron forge scale, a few scattered small cinders, very dark charcoal and umber tones, flat even diffuse lighting with no shadows, fills the entire frame edge to edge, photographic PBR albedo texture, no objects, no text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:34.150Z"
+ },
+ "ember-brick": {
+ "url": "https://v3b.fal.media/files/b/0aac5c39/iXDk5PbHxyZmJu_vKYDLg_T7UJMohR.png",
+ "prompt": "Seamless tileable texture, orthographic flat front view of an old blacksmith workshop wall: hand-made clay bricks in running bond, heavily blackened by a century of forge soot and smoke, crumbling lime mortar joints, subtle warm brown-red brick showing through the soot in places, chipped edges, flat even diffuse lighting with no shadows or highlights, no perspective, fills the entire frame edge to edge, photographic PBR albedo texture, no text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:34.592Z"
+ },
+ "artemis-earth": {
+ "url": "https://v3b.fal.media/files/b/0aac5c38/DA4Wx_Oe6IH-r4SULm8IO_6PXvCSW7.png",
+ "prompt": "Seamless equirectangular projection texture map of the whole planet Earth, unwrapped globe, 2:1 cylindrical projection edge to edge, realistic NASA Blue Marble satellite imagery: deep navy oceans, green and ochre continents, Sahara, Amazon, white polar ice caps at top and bottom edges, dense realistic swirling white cloud cover with cyclones and weather fronts over the oceans, natural colours, no text, no labels, no grid lines, no borders, no stars, no black background, the texture fills the entire frame.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:35.677Z"
+ },
+ "ember-damascus": {
+ "url": "https://v3b.fal.media/files/b/0aac5c39/j330IHIsaD96EvAWv8VFi_x6rpiOgN.png",
+ "prompt": "Extreme macro photograph of a polished and acid-etched random-pattern damascus steel sword blade surface, flat-on orthographic view filling the entire frame edge to edge, flowing wood-grain and topographic contour layers of bright silver nickel steel and dark grey carbon steel, hundreds of fine sinuous stretched layers running horizontally along the length, even soft lighting, no reflections of objects, no edges of the blade visible, no text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:00:42.720Z"
+ },
+ "koi-room-maple": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/v692a6cnDioJflfQrnmtA_XjazgLv2.png",
+ "prompt": "Editorial interior photograph of a traditional Kyoto ryokan room in late autumn. Tatami floor, a low lacquered table, a round hinoki cedar soaking tub by an open window, sliding shoji screens framing an old Japanese maple tree blazing vermilion and crimson that overhangs a dark koi pond, fallen red leaves floating on the water. Warm late-afternoon light through the leaves casts dappled red light across the tatami. Serene, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:06.298Z"
+ },
+ "koi-room-moon": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/VWEuhwpArt-qhwFuWQKUT_QbAadp1U.png",
+ "prompt": "Editorial interior photograph of the upper room of a traditional Kyoto ryokan at night. A tatami room lit only by a glowing paper andon floor lamp, shoji opened onto a small wooden moon-viewing platform built out over a koi pond. A full moon hangs in a deep blue night sky above dark pine and maple silhouettes and its reflection sits perfectly in the still black water below. Two zabuton cushions and a tray with a sake flask on the platform. Deep blue and warm amber palette, quiet, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:07.836Z"
+ },
+ "koi-floor": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/fFey-sfNgoft_kUoYDNvk_gjD0vJEt.png",
+ "prompt": "Top-down flat-lay photograph of a dry riverbed texture, camera pointing straight down: densely packed smooth rounded river stones of mixed sizes from small 2 cm pebbles to 20 cm cobbles, colours dark slate grey, charcoal, muted olive, rust ochre and a few pale granite ones, with coarse pale sand and fine gravel filling the gaps, a few dark sunken leaves, slightly damp matte look. Soft even overcast lighting with no directional shadows, uniform density and scale across the entire frame edge to edge, seamless tileable material texture, no horizon, no perspective, no water, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:08.417Z"
+ },
+ "koi-moss": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/bnfAKcBlbPCgpRR-JuNih_LCIO6Z4d.png",
+ "prompt": "Top-down flat-lay photograph of a Japanese temple moss garden floor, camera pointing straight down: dense velvety cushion moss (sugigoke and hair-cap moss) in emerald, olive and a little golden green, soft undulating mounds, a few small dark wet stones half buried, scattered brown pine needles and two or three fallen red maple leaves. Soft even overcast light, no directional shadows, uniform density across the whole frame edge to edge, seamless tileable material texture, no horizon, no perspective, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:08.787Z"
+ },
+ "koi-canopy": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/L3y4TS_g6rBxqCroB3cA4_L2bithuQ.png",
+ "prompt": "Photograph looking straight up from beneath an old Japanese maple tree (Acer palmatum) toward a bright white overcast sky. Hundreds of delicate seven-pointed star-shaped leaves in dark silhouette, some layers glowing translucent green where light passes through, thin dark twisting branches reaching in from the left and top edges. The canopy is dense on the left half and top of the frame and opens to bright empty white sky toward the lower right. High contrast, crisp leaf edges, no sun, no lens flare, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:09.095Z"
+ },
+ "koi-room-moss": {
+ "url": "https://v3b.fal.media/files/b/0aac5c3d/OC5T8ZoWwrMUCMX-vJlwA_52tMGuiS.png",
+ "prompt": "Editorial interior photograph of a quiet ground-floor room in a traditional Kyoto ryokan. Pale green tatami mats, a low dark wooden table with a single ceramic tea cup, a folded futon with undyed linen, sliding shoji screens pulled fully open onto a narrow engawa veranda of weathered cedar boards, beyond it a lush moss garden with a mossy stone lantern and the dark green edge of a koi pond. Soft diffused morning light, faint mist, deep shadows inside the room. Serene, minimal, luxurious, Kinfolk / Cereal magazine style, 35mm film photograph, natural grain, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:01:09.377Z"
+ },
+ "monolith-mertola": {
+ "url": "https://v3b.fal.media/files/b/0aac5c44/uOssw0MGe2jvP4yE3BklE_hRkn2Z47.png",
+ "prompt": "Architectural photograph of a low courtyard house of pale sand-coloured concrete in the Alentejo, Portugal. Hard midday sun, razor-sharp black shadows from a deep concrete pergola falling across a white wall and a gravel courtyard with a single old olive tree. Deep blue cloudless sky. Minimal, monolithic, almost abstract composition, Swiss architectural photography, medium format, perfectly vertical lines, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:20.631Z"
+ },
+ "monolith-lajes": {
+ "url": "https://v3b.fal.media/files/b/0aac5c44/sB6hpxTkGwmox3WqPSEQT_HWGmhht1.png",
+ "prompt": "Architectural photograph at blue hour of a house built from black basalt and grey concrete on the edge of a volcanic sea cliff in the Azores. Deep blue dusk sky, the Atlantic below, warm golden light glowing from a long horizontal strip window and a small lit infinity pool glowing turquoise on the terrace. Moody, quiet, cinematic, medium format, long exposure smooth sea, perfectly vertical lines, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:21.083Z"
+ },
+ "monolith-stal": {
+ "url": "https://v3b.fal.media/files/b/0aac5c44/-MdMPs8A0lFAjmP1NCbt8_R8dAlDci.png",
+ "prompt": "Architectural photograph, Julius Shulman / Iwan Baan style. A small minimalist cabin made of black weathered steel and board-formed concrete, a single long rectangular volume with one huge frameless window, perched on a bare granite outcrop above a dark Arctic sea in Lofoten, Norway. Blue polar twilight, low pink sun on the horizon, thin snow on the rocks, one warm light inside. Shot on medium-format camera, 45mm lens, perfectly vertical lines, deep natural colour, fine detail, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:21.227Z"
+ },
+ "monolith-ulvik": {
+ "url": "https://v3b.fal.media/files/b/0aac5c44/QmRmmWgFm2DMiiqa8NRwb_UzONhsfB.png",
+ "prompt": "Architectural photograph of a long, slender board-formed concrete house cantilevered dramatically out of a steep mossy cliff above a Norwegian fjord, Hardanger. Golden hour, the low sun raking across the concrete so every formwork line and tie-hole casts a tiny shadow, long shadows of pine trees across the facade, full-height glazing reflecting the warm sky, mist on the fjord far below. Medium format, 35mm lens, perfectly vertical lines, rich but natural colour, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:21.956Z"
+ },
+ "monolith-studio": {
+ "url": "https://v3b.fal.media/files/b/0aac5c44/M1AL9Y0WxRqfonxrA-N1t_a4rWdHyd.png",
+ "prompt": "Photograph of a quiet architecture studio in an old Lisbon warehouse: long pale oak tables covered with white and grey concrete architectural massing models of cliff houses, tracing paper drawings, a brass desk lamp. A single hard shaft of late afternoon sunlight from a tall window cuts diagonally across the room, casting long crisp shadows of the models across the table. Muted warm off-white palette, dust in the light, calm, editorial interior photography, 35mm, no people, no text, no watermark.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:22.892Z"
+ },
+ "lithos-studs": {
+ "url": "https://v3b.fal.media/files/b/0aac5c46/eT6UvQeaY55U8nj_dR3q6_5YQ8SVet.png",
+ "prompt": "Luxury fine-jewellery campaign photograph: a pair of tiny natural pyrite cube stud earrings, each a perfect 5 mm brassy mirror-bright cube with fine growth striations, set in minimal platinum claw settings, lying on crushed jet-black silk velvet, one hard small spotlight creating mirror-sharp highlights on the cube faces, deep black shadows, shallow depth of field, 100mm macro lens, medium format, museum-quiet mood, no text, no logo, no hands.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:42.475Z"
+ },
+ "lithos-pendant": {
+ "url": "https://v3b.fal.media/files/b/0aac5c46/95pcS375M5Euz3WbHpSnE_3LOSR0y8.png",
+ "prompt": "Luxury fine-jewellery campaign photograph: a raw natural water-clear quartz crystal point pendant, about 3 cm, capped in brushed platinum on a very fine platinum chain, the chain draped in a loose curve across crushed jet-black silk velvet, the crystal backlit by a narrow rim light so its edges glow and a faint rainbow fracture is visible inside, deep black background, shallow depth of field, 100mm macro lens, medium format, no text, no logo, no hands.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:44.534Z"
+ },
+ "lithos-ring": {
+ "url": "https://v3b.fal.media/files/b/0aac5c46/E_i7BdV99PkApNzoEA_q4_sdrLcz1j.png",
+ "prompt": "Luxury fine-jewellery campaign photograph: a heavy polished platinum signet ring set with a deep saturated violet amethyst cabochon, the ring resting at a slight angle on crushed jet-black silk velvet, single small hard spotlight from the upper left, tiny sparkling internal facets in the amethyst, crisp specular highlights on the platinum, deep velvety black shadows filling most of the frame, shallow depth of field, 100mm macro lens, medium format, museum-quiet mood, violet and platinum palette, no text, no logo, no hands.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:44.836Z"
+ },
+ "lithos-miner": {
+ "url": "https://v3b.fal.media/files/b/0aac5c46/zt7VLqGulx62O5Ldg2vjK_udFXaV0R.png",
+ "prompt": "Documentary photograph, respectful and quiet: two weathered hands of a miner holding a freshly opened amethyst geode half, deep violet crystals glittering inside, in a dim basalt mine tunnel in northern Uruguay lit only by a warm headlamp from above, dust in the air, rough dark rock walls, the person's face is out of frame, shallow depth of field, 35mm film grain, natural muted colours with violet accent, no text, no logo.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:45.108Z"
+ },
+ "koen-juniper": {
+ "url": "https://v3b.fal.media/files/b/0aac5c47/hjodaC6MIS50KYhLZfJYM_cSgsJlw3.png",
+ "prompt": "Traditional Japanese sumi-e ink painting of an ancient shimpaku juniper bonsai with twisting white deadwood (shari and jin) spiralling up the trunk, a few dense foliage pads, in a small round pot. Loose expressive brushwork, the deadwood left as bare paper outlined by thin ink lines, foliage as soft grey ink washes. Black and grey ink only on plain warm white paper, large empty margins, subject centred. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:56.770Z"
+ },
+ "koen-azalea": {
+ "url": "https://v3b.fal.media/files/b/0aac5c47/tIB-TCDoCCSS9SjmAVTOR_25eOBmrj.png",
+ "prompt": "Traditional Japanese sumi-e ink painting of a satsuki azalea bonsai in full bloom in a shallow oval pot, the gnarled trunk and branches in dark ink, the flower clusters painted as soft dabs of muted vermilion red watercolour, small leaves in grey ink wash. Black ink with a single restrained vermilion accent on plain warm white paper, large empty margins, subject centred. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:56.902Z"
+ },
+ "koen-pine": {
+ "url": "https://v3b.fal.media/files/b/0aac5c47/SIZZXieckw-xeBcwl8Fen_WM4hC9f9.png",
+ "prompt": "Traditional Japanese sumi-e ink painting of a Japanese black pine bonsai in formal upright style in a shallow rectangular pot. Loose confident brushwork, the needle pads rendered as grey ink wash clouds, the trunk in dark dry-brush strokes with flaky bark, a pale ink wash suggests the pot. Black and grey ink only on plain warm white paper, large empty margins, subject centred in the lower two thirds. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:57.213Z"
+ },
+ "koen-washi": {
+ "url": "https://v3b.fal.media/files/b/0aac5c47/wDn3iO5PG3fpsRWIvSjOo_ySsV0zRZ.png",
+ "prompt": "Flat overhead macro scan of handmade Japanese kozo washi paper, warm off-white cream colour, long translucent mulberry fibres visible, very subtle cloudy thickness variation, a few tiny darker fibre flecks, perfectly even diffuse lighting, no shadows, no folds, no edges, no objects, fills the entire frame, seamless texture, extremely subtle and low contrast.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:58.257Z"
+ },
+ "koen-quince": {
+ "url": "https://v3b.fal.media/files/b/0aac5c47/MSR8A7zGBq906BinTrA6F_kZNF3khY.png",
+ "prompt": "Traditional Japanese sumi-e ink painting of a tiny shohin chojubai flowering quince bonsai in a small glazed square pot, a knotted miniature trunk with a few thorny twigs and a handful of small blossoms painted in pale coral pink watercolour, tiny leaves in grey ink wash. Mostly black and grey ink on plain warm white paper, very large empty margins, small subject centred low. No seal, no stamp, no calligraphy, no text, no signature, no frame, no border.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:02:58.494Z"
+ },
+ "koen-enso": {
+ "url": "https://v3b.fal.media/files/b/0aac5c48/fmzdZutZfixC-XQuZjcfj_tiQkYL0H.png",
+ "prompt": "A single zen ensō circle painted in one confident stroke of black sumi ink with a large soft calligraphy brush on plain white paper. The stroke starts thick and wet at the lower left, sweeps clockwise, thins out and breaks into dry-brush streaks (kasure) near the end, leaving a small open gap at the top. Pure flat white background, nothing else on the paper, no seal, no stamp, no signature, no text, no characters, no shadows, no frame. Scanned artwork, high contrast, crisp fibre texture in the dry brush.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:00.950Z"
+ },
+ "lowfreq-cover-valves": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/sTUdb4m8xbDkjn1qemrmD_RnFIejtX.png",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography. Macro photograph of four glowing vacuum tubes on a black amplifier chassis in total darkness, orange-amber filaments burning inside smoky glass, reflections on chrome, creamy bokeh, violet rim light from behind, dark and warm, analog hi-fi still life, film grain.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:19.856Z"
+ },
+ "lowfreq-cover-counter": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/2klj60HicBfqk1e9DsqOf_88GetNaA.png",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography. High-contrast black and white photograph of an empty narrow Tokyo listening bar at closing time: a long polished wooden counter with a row of round bar stools, a single pendant lamp making a pool of light, walls of vinyl records fading into darkness, heavy grain, deep blacks, 1960s Blue Note style photography, cropped tight, cinematic.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:20.617Z"
+ },
+ "lowfreq-cover-rain": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/SohaXFOi3KKGPjrvUfXBk_Q2H2TjR9.png",
+ "prompt": "Square record album cover artwork, no text, no letters, no typography, no signs with readable writing. Night photograph of a narrow Tokyo back alley in heavy rain, wet asphalt reflecting smeared purple and amber neon glow, a lone figure with a transparent umbrella walking away, soft motion blur, bokeh, cinematic colour grade, film grain, melancholy lo-fi mood.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:21.517Z"
+ },
+ "lowfreq-cover-tidal": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/DBqPTkH2F5SIuiq8O3a5j_2BJtCUFw.png",
+ "prompt": "Square minimalist record album cover artwork, no text, no letters, no typography. A single large pale lavender circle hovering just above a flat dark indigo sea horizon, a thin amber line where sky meets water, vast empty space, risograph print with visible grain and slight ink misregistration, 1960s Japanese modernist graphic design, calm, flat colour fields on uncoated paper.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:22.108Z"
+ },
+ "lowfreq-cover-geometry": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/bjGIamMbXg6ejdG3Kfb60_fzXhlV8D.png",
+ "prompt": "Square abstract record album cover artwork, no text, no letters, no typography. Swiss and Japanese modernist composition: overlapping amber semicircles, a lavender quarter-disc and thin black parallel stripes arranged like sound waves on warm off-white paper, screen-printed texture with slight ink spread and paper fibres, bold, balanced, 1960s jazz label design.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:27.055Z"
+ },
+ "lowfreq-cover-aubergine": {
+ "url": "https://v3b.fal.media/files/b/0aac5c4a/W-R4VZ55JeUS4D4fVke0e_QtkwfU9e.png",
+ "prompt": "Square vintage jazz record album cover artwork, no text, no letters, no typography. Grainy 35mm film photograph: close-up of a pianist's hands resting on the keys of a worn Fender Rhodes electric piano, lit by a single warm amber lamp from above, everything else falling into deep aubergine-purple shadow, shallow depth of field, heavy film grain, faded 1970s Japanese jazz label aesthetic, moody, intimate, photographic print texture.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:03:38.121Z"
+ },
+ "racer-brick": {
+ "url": "https://v3b.fal.media/files/b/0aac5c50/yCwH9mYJxi3WVlPJ1Aa5K_5nps12Sh.png",
+ "prompt": "Seamless tileable texture. Straight-on orthographic photograph of an old industrial brick wall, soot-darkened charcoal and deep oxblood bricks in running bond, recessed dark mortar joints, wet from rain with subtle vertical water streaks and faint white efflorescence, evenly and flatly lit, no perspective, no shadows, no objects, no text, the bricks fill the entire frame edge to edge.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:04:25.785Z"
+ },
+ "racer-workshop": {
+ "url": "https://v3b.fal.media/files/b/0aac5c50/I135fFlZiukoZ0N5NnWRs_wEPyQaxC.png",
+ "prompt": "Cinematic low photograph taken at floor level inside a small custom motorcycle workshop at night, warm amber tungsten work lights, polished concrete floor with oil stains and reflections, a red rolling tool chest, spoked motorcycle wheels leaning against a workbench, a bike frame on a stand, shallow depth of field, dim moody atmosphere, film grain, no people, no text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:04:26.455Z"
+ },
+ "racer-asphalt": {
+ "url": "https://v3b.fal.media/files/b/0aac5c50/fe4goO3SnXoCOONtOM5Jp_XQEiGYum.png",
+ "prompt": "Seamless tileable texture. Top-down orthographic photograph of dark city asphalt road surface, fine black aggregate with occasional grey stones, a couple of thin sealed tar crack lines, faint oil stains, evenly lit, no puddles, no road markings, no shadows, fills the entire frame.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:04:26.771Z"
+ },
+ "racer-city": {
+ "url": "https://v3b.fal.media/files/b/0aac5c50/R5rbyx85Ql5Zu8-vHT7WA_Q9lEONPW.png",
+ "prompt": "Very dark rainy city street at night seen far in the distance, everything heavily out of focus, soft round bokeh of sodium street lamps, red tail lights and a few magenta and teal shop signs, wet road reflections, thin fog, cinematic anamorphic look, restrained palette, mostly black, no people, no readable text.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:04:29.364Z"
+ },
+ "racer-shutter": {
+ "url": "https://v3b.fal.media/files/b/0aac5c50/7rBLn5MbRJWeOdYREU8F7_n3BhhtZY.png",
+ "prompt": "Straight-on orthographic photograph of a closed steel roll-up garage shutter, horizontal corrugated slats filling the entire frame edge to edge, dark gunmetal grey paint worn to bare steel along the ridges, rust streaks and rain runs, grime near the bottom, even flat lighting, no frame, no surrounding wall, no text, no graffiti, no logos.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:04:30.201Z"
+ },
+ "koen-maple2": {
+ "url": "https://v3b.fal.media/files/b/0aac5cf1/lA-IIlTrmrC7U1uTeCvz9_NDA7NfQB.png",
+ "prompt": "A Japanese maple bonsai tree, thick gnarled tapering trunk with visible surface roots, elegant sculpted branch structure with rounded compact cloud-like pads of small bright green maple leaves, clear gaps between the foliage pads showing branches, in a shallow oval dark brown glazed ceramic pot topped with green moss.",
+ "endpoint": "fal-ai/nano-banana-2",
+ "at": "2026-09-29T11:31:11.699Z"
+ }
+ },
+ "meshes": {
+ "pilot-guardian": {
+ "request_id": "01a0eca9-e0e9-7ab3-b4d2-0d1c395b1f4a",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b2c/fujbp1ruXevlrZkK1S7CH_5lu3fYdM.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:15:50.315Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b57/NRndPQV14hLf3cZ6dsT0W_model.glb",
+ "size": 20890688,
+ "done": "2026-09-29T10:24:01.115Z"
+ },
+ "pilot-astrolabe": {
+ "request_id": "01a0eca9-e0ef-7cd1-b383-cbb8341ab69c",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b2c/8IDIhjGIt9vPZjQLcaSep_ncXhpnwN.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:15:50.318Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b4c/NzWMKEme93cVl3HR2t_t4_model.glb",
+ "size": 22983228,
+ "done": "2026-09-29T10:21:18.292Z"
+ },
+ "abyss-angler": {
+ "request_id": "01a0ecb7-7d74-7f60-80c4-538e6e98c542",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/mqKXGEfd7pwargiH6TNIo_7ETOblAv.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.342Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5ba1/fCf4w3zVcdJX7GRAKSPve_model.glb",
+ "size": 19122888,
+ "done": "2026-09-29T10:35:19.330Z"
+ },
+ "reliq-amphora": {
+ "request_id": "01a0ecb7-7d74-78a2-a742-6668560270d0",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/DrT4kJuEVGyCQmI4AWFAw_ojUj9BiU.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.345Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5baf/pkXb01NHRjeKgwzWdR6C0_model.glb",
+ "size": 16326204,
+ "done": "2026-09-29T10:37:41.696Z"
+ },
+ "reliq-mask": {
+ "request_id": "01a0ecb7-7d74-7013-9512-0d30636eab36",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/-3GIYdVk22Nz5ajCQPgTC_Ed1Ds9Gb.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.346Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5ba6/crzCSpjAxJtmCw5Uf-lUw_model.glb",
+ "size": 20220032,
+ "done": "2026-09-29T10:36:11.629Z"
+ },
+ "terra-tropic": {
+ "request_id": "01a0ecb7-7d7c-7cd3-8847-c7968a3b0000",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b68/tcAHdxux8ZTw4OOtUesz-_uBEMAds6.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.348Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc6/nk6WimHaLO_H9LVH3_hl-_model.glb",
+ "size": 26863692,
+ "done": "2026-09-29T10:41:25.666Z"
+ },
+ "flora-protea": {
+ "request_id": "01a0ecb7-7d7c-7cd3-8847-c780594ca3eb",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6a/eSMln200Uw97azg-DA0hL_qcJYVLbm.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.350Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc5/Pbaz83gvJ_3MRmv5rECG7_model.glb",
+ "size": 19483484,
+ "done": "2026-09-29T10:41:16.055Z"
+ },
+ "ember-anvil": {
+ "request_id": "01a0ecb7-7d7d-72b2-8bd2-e99f2afde8f3",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b67/j73SyGu2BNr4j3XWgucZz_ImSc2ZVR.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.351Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5baa/t1aLUxwdG2IvNfTmHi6xA_model.glb",
+ "size": 17506912,
+ "done": "2026-09-29T10:36:50.530Z"
+ },
+ "terra-desert": {
+ "request_id": "01a0ecb7-7d7d-7182-b7bb-21b995441e23",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b68/hUqq2XOCl0LDklCgAzLUE_T0FLf5lL.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.352Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb4/raPWOgb1f884JIL7eGlc2_model.glb",
+ "size": 25927340,
+ "done": "2026-09-29T10:38:42.676Z"
+ },
+ "ember-hammer": {
+ "request_id": "01a0ecb7-7d7d-7bb2-8417-cdd636eea18b",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 40000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b67/pV4vG45lL9DMjedtfN-eV_oNYpjzla.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.354Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b9a/sIg6RpRT6xdr5KgYUilhR_model.glb",
+ "size": 13464312,
+ "done": "2026-09-29T10:34:29.080Z"
+ },
+ "abyss-sub": {
+ "request_id": "01a0ecb7-7d7d-7573-b3b3-dec40ea7518f",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b66/oFyY6ngTR1VgnHUoVePCy_8v7LJXzx.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.356Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb0/X1m_HTwa5OMSS9bdVr213_model.glb",
+ "size": 22606932,
+ "done": "2026-09-29T10:37:52.016Z"
+ },
+ "abyss-nautilus": {
+ "request_id": "01a0ecb7-7d7d-72b2-8bd2-e98b0e00089d",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/p7pYbaBPK7NuWtDvgFNr__KWOJjXEW.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.357Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5ba8/69rvOfhNTQUGMOFxiBPlL_model.glb",
+ "size": 16958328,
+ "done": "2026-09-29T10:36:19.906Z"
+ },
+ "terra-moss": {
+ "request_id": "01a0ecb7-7d7e-79e3-a44d-e3333df38efa",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b68/NJSvXhVg-vGxf7G4a70lW_rGuPuvKZ.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.361Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc6/HG889FPLy_eCO8kebHR88_model.glb",
+ "size": 29519712,
+ "done": "2026-09-29T10:42:27.080Z"
+ },
+ "koi-showa": {
+ "request_id": "01a0ecb7-7d7d-7fa1-950a-71fa212246eb",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b69/X_e4mpGk1QijK7Dbokmtj_EsB2NIen.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.362Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b9e/9oJWTPuKwQp8DEvMocTuq_model.glb",
+ "size": 14196188,
+ "done": "2026-09-29T10:35:29.420Z"
+ },
+ "koi-lantern": {
+ "request_id": "01a0ecb7-7d7d-73a2-94bd-97a7db31b370",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6a/hTpOkVDbYMd8ifpvklVul_4ulCpYnD.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.364Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b9d/j80HuQEhKsCqfiPpihdEH_model.glb",
+ "size": 16299340,
+ "done": "2026-09-29T10:34:28.065Z"
+ },
+ "flora-rose": {
+ "request_id": "01a0ecb7-7d7d-7412-9e4d-de0b1cdf8da8",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6a/KKBNJaRRRs6sNrBbCTvLk_27kuVv8A.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.365Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb5/kTxDrJ7kqSid0ZuB8i0sT_model.glb",
+ "size": 14073208,
+ "done": "2026-09-29T10:38:52.689Z"
+ },
+ "koi-kohaku": {
+ "request_id": "01a0ecb7-7d7d-7182-b7bb-21a14fa98fc2",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b68/DCQl2Om_-yKmf3O4SY7iP_8bt31tU7.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.366Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b9e/zk_HwJY_lM3jJiO8av2IH_model.glb",
+ "size": 13503480,
+ "done": "2026-09-29T10:35:29.042Z"
+ },
+ "koi-lotus": {
+ "request_id": "01a0ecb7-7d7e-79e3-a44d-e34da97b1008",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b69/S6ZTtSQRVTHtmXmdy1EbR_WcYPyGYm.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.368Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb4/wFVP604-X4kL1iZqX2vLy_model.glb",
+ "size": 12594052,
+ "done": "2026-09-29T10:39:03.246Z"
+ },
+ "reliq-bust": {
+ "request_id": "01a0ecb7-7d7d-7412-9e4d-de1bc3f3a390",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/x1yFtWmVNkqOpyLzNwNJv_agLblIXw.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.369Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5ba5/KvQdZlJVMwd1CHVwx0I6I_model.glb",
+ "size": 18951540,
+ "done": "2026-09-29T10:36:11.865Z"
+ },
+ "abyss-vent": {
+ "request_id": "01a0ecb7-7d7d-7573-b3b3-ded4c6e82d71",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b66/dOx3hZfIBwPplwPQf_oO-_A7yAgCBi.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.370Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc6/SEcoBv7HNA-ywMrzBLVMA_model.glb",
+ "size": 24252464,
+ "done": "2026-09-29T10:42:17.281Z"
+ },
+ "reliq-helmet": {
+ "request_id": "01a0ecb7-7d7f-7c93-9da8-3d11db496a6d",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b64/sJHNwY5SJTN_iB_4wCVsd_E6wUYZMo.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.372Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb2/I2RGBaZljc2DE2XiQMcDW_model.glb",
+ "size": 19288756,
+ "done": "2026-09-29T10:38:44.662Z"
+ },
+ "ember-sword": {
+ "request_id": "01a0ecb7-7d7e-77d1-8a55-8279cbc55928",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b7f/j6Lwz9abPTaYgra7YTqep_HuorDmFp.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:30:42.373Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5b98/EqlDTTMBjzaaXqMXwFse-_model.glb",
+ "size": 12377896,
+ "done": "2026-09-29T10:34:07.972Z"
+ },
+ "flora-morpho": {
+ "request_id": "01a0ecba-a0f5-7342-bee3-d27dfbf29a2e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6b/PONFL4W8yAS0eXXjWmcCP_vAUJuKta.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:34:08.034Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb0/D3RBZBIL4IuOkOGdd9GcM_model.glb",
+ "size": 15572840,
+ "done": "2026-09-29T10:38:02.053Z"
+ },
+ "flora-orchid": {
+ "request_id": "01a0ecba-ef72-7080-9893-2f3b4d6d3a0e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6b/aRN1Es2Vl1yhPlQOgljuD_xc2DmbpW.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:34:28.126Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb2/I7Pkrfx9mE1IQhMCDch35_model.glb",
+ "size": 15586756,
+ "done": "2026-09-29T10:38:02.668Z"
+ },
+ "velo-white": {
+ "request_id": "01a0ecba-f36b-7462-9f8d-bbcfb21115e7",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b7f/8S0FAwBH1iA1vPem0Gc_y_vQfod9aL.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:34:29.183Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bb9/VP3DdY0027qX--eJtvzfZ_model.glb",
+ "size": 17885164,
+ "done": "2026-09-29T10:39:33.661Z"
+ },
+ "hangar-mech": {
+ "request_id": "01a0ecbb-b7b1-7d93-a985-9a5bce6e7c01",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6c/X3fzf43XJ6lR3urfllTLe_cxhNPksx.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:35:19.388Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd0/z0rHgJWFiR3TAjaVpSLVl_model.glb",
+ "size": 25978508,
+ "done": "2026-09-29T10:43:29.797Z"
+ },
+ "hangar-drone": {
+ "request_id": "01a0ecbb-dda6-71c3-beca-8ca308dad871",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6c/AlPhN02Q2PI6jOjpE75-7_2JhlQcOH.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:35:29.103Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc5/-axL-Kz2chcfJoDgYWlu__model.glb",
+ "size": 18704440,
+ "done": "2026-09-29T10:41:15.484Z"
+ },
+ "sucre-cake": {
+ "request_id": "01a0ecbb-df1e-7e53-8df1-cbb1ce960011",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6c/bdomvv1HKuE5lMlezSlWP_QUx7phmk.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:35:29.482Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd1/V6umqJqj3Sgleunzwkexi_model.glb",
+ "size": 22548032,
+ "done": "2026-09-29T10:44:50.127Z"
+ },
+ "sucre-macaron": {
+ "request_id": "01a0ecbc-8401-7991-ba7f-84731ac1b1c4",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 20000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6c/WaciDTwOW8j9lroQDay-W_UhIgQNN8.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:36:11.692Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bce/aPShkSqGdSnvBq3B6MiCP_model.glb",
+ "size": 12209944,
+ "done": "2026-09-29T10:42:47.199Z"
+ },
+ "sucre-macaron2": {
+ "request_id": "01a0ecbc-84e5-7e91-99a9-d30f574b10a1",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 20000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6d/E1W1eKXjoocd1qTB2-bWG_Dhs09tUK.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:36:11.917Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bce/mb6gA8aTTCsd9-mebHklv_model.glb",
+ "size": 12558768,
+ "done": "2026-09-29T10:43:27.792Z"
+ },
+ "sucre-croissant": {
+ "request_id": "01a0ecbc-a45c-7253-a91f-78b9235aec80",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 30000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6d/i8Dq8ljtQwH_0WbcFeRUx_OUxmdBmd.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:36:19.974Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bc3/HAvTOcsWzt5HW1Qm9jYzP_model.glb",
+ "size": 12421032,
+ "done": "2026-09-29T10:40:54.780Z"
+ },
+ "sucre-strawberry": {
+ "request_id": "01a0ecbd-1bff-7c40-b1bf-2f15bd6cf9c2",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 20000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6d/GvWF0FpGdTuLtWgSUeqA4_MHOOaDOO.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:36:50.601Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd0/2FnoG5GqGA00RE7RevVGm_model.glb",
+ "size": 13853684,
+ "done": "2026-09-29T10:43:17.456Z"
+ },
+ "sucre-tart": {
+ "request_id": "01a0ecbd-e3d4-7970-b596-a7ac7957c48f",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 40000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6d/HlpM1uQ5Rg1WFtubYpv_1_AU0tioGW.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:37:41.757Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd7/QUJqjv6HcNdS6fhwQPPKN_model.glb",
+ "size": 14276712,
+ "done": "2026-09-29T10:44:08.506Z"
+ },
+ "mono-house": {
+ "request_id": "01a0ecbe-0c21-7700-a280-0787fc5d7c19",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 250000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6e/lhkuv4SUfgcu7TAuoD8mq_QSsRThSy.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:37:52.074Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf1/0onNQsksEo5qMQSnXiMLW_model.glb",
+ "size": 30863264,
+ "done": "2026-09-29T10:48:53.896Z"
+ },
+ "lf-turntable": {
+ "request_id": "01a0ecbe-3358-7570-ab8e-405fcbda285e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6e/lBeNGl4IcV9q6Z8VhuDyk_mjAwQBO0.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:38:02.113Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd1/-C6SXcW6ojxdSnS_vZ6gx_model.glb",
+ "size": 18069536,
+ "done": "2026-09-29T10:44:50.346Z"
+ },
+ "lf-speaker": {
+ "request_id": "01a0ecbe-35bf-7171-be7a-893380260e3b",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6f/JrAGayVte_onoCHZiBy0h_AiDxrzgW.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:38:02.727Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd7/jSkrYPZALtMJYwSQIw4tS_model.glb",
+ "size": 15530776,
+ "done": "2026-09-29T10:44:29.383Z"
+ },
+ "gambit-king": {
+ "request_id": "01a0ecbe-d209-75e1-94bc-d44ee1cf276c",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6f/VBpH_ZfVXYGgihpg_JDzz_uPNTpT3d.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:38:42.737Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bcf/WXCTbvwxpjexgzpANeCRi_model.glb",
+ "size": 13819144,
+ "done": "2026-09-29T10:43:07.238Z"
+ },
+ "gambit-queen": {
+ "request_id": "01a0ecbe-d9c5-73a2-91c9-b12644ae22d8",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6f/z1WT9J-RpBIYU1eCdnxlm_GEiiDjtf.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:38:44.718Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bcd/fCONyPDG3K44Pawss939M_model.glb",
+ "size": 11952784,
+ "done": "2026-09-29T10:42:37.794Z"
+ },
+ "gambit-bishop": {
+ "request_id": "01a0ecbe-f924-7f51-9105-793e9d402a47",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b6f/SkV-kGh0epoqf24PYqk9H_tWAhetaR.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:38:52.748Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bcb/gNkNStRZYBtxt1hIzH4vf_model.glb",
+ "size": 9776040,
+ "done": "2026-09-29T10:42:16.772Z"
+ },
+ "gambit-knight": {
+ "request_id": "01a0ecbf-2260-7102-aa0a-171fcb573911",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b70/8U3H8UimPuzF7yzLq2bRj_9bhMU3AC.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:39:03.305Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd1/5Ba6A02sLAtUFMg2GeIG6_model.glb",
+ "size": 12321948,
+ "done": "2026-09-29T10:43:29.122Z"
+ },
+ "gambit-rook": {
+ "request_id": "01a0ecbf-9937-7f73-8c4a-79218039fd93",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b71/KqhNM8txSZyxSBhOiQcQQ_3hSe8wmk.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:39:33.725Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bd9/tME4s-1rNeAdKbFOp_cPx_model.glb",
+ "size": 9319992,
+ "done": "2026-09-29T10:47:11.584Z"
+ },
+ "gambit-pawn": {
+ "request_id": "01a0ecc0-d611-7e82-abbe-51b49d3ca123",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b71/oiej4x2cmXRblDdU39Wd3_UcKfM6y7.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:40:54.837Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bde/QYRmQ2iQUblffmOqzHH6A_model.glb",
+ "size": 9774304,
+ "done": "2026-09-29T10:47:31.940Z"
+ },
+ "atlas-lighthouse": {
+ "request_id": "01a0ecc1-2703-7ca2-8aef-0fbd58adced1",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b71/tDIxteDr_dOK5ydS5iCHq_oaLF1LOV.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:41:15.606Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf5/1mpf04NCl80uC8CU1jXAD_model.glb",
+ "size": 27212736,
+ "done": "2026-09-29T10:49:46.140Z"
+ },
+ "atlas-falls": {
+ "request_id": "01a0ecc1-292d-7ff2-8ec7-2c93733ed03e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b71/Nyjc7yVPl_wv3xucFdvSK_sbsmmbvc.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:41:16.114Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c02/5pyBkRUKEJG1EI5k33xRr_model.glb",
+ "size": 27012816,
+ "done": "2026-09-29T10:51:47.304Z"
+ },
+ "atlas-pagoda": {
+ "request_id": "01a0ecc1-4eb9-7533-9423-1447f1c8c209",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b71/epBFDyoJm15rosV5_ocGo_Kw7xFJcD.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:41:25.727Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bee/hQ46sQ-CvORB-ux-lpRL4_model.glb",
+ "size": 26463936,
+ "done": "2026-09-29T10:48:13.179Z"
+ },
+ "atlas-windmill": {
+ "request_id": "01a0ecc2-165b-71f0-96b4-f406c8fd27af",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b72/t8apRFrA23bFA_KO6zKh6_G9Wz1kXc.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:42:16.854Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf7/RshiPXDalcHtRTbWTkbHe_model.glb",
+ "size": 23381784,
+ "done": "2026-09-29T10:49:55.029Z"
+ },
+ "lithos-geode": {
+ "request_id": "01a0ecc2-1859-7953-9508-9368a709d5f7",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b72/nltDk7gY6mbtU0i8EO4o6_i4M6KR7V.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:42:17.341Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bfb/_2MKFAltA0LyPnn8AaU2V_model.glb",
+ "size": 24323376,
+ "done": "2026-09-29T10:50:56.530Z"
+ },
+ "lithos-quartz": {
+ "request_id": "01a0ecc2-3ea2-76d1-a03c-220263484a3b",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b73/_vto5DWnu7tp_mtz7yWsi_WAwMgVVM.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:42:27.142Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bfa/y-CHZ5U8-3uqedoXaoR5p_model.glb",
+ "size": 17874368,
+ "done": "2026-09-29T10:50:35.496Z"
+ },
+ "lithos-pyrite": {
+ "request_id": "01a0ecc2-687c-7562-9215-a698f4c00d4a",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b73/Y7CTs0WC6bCNLJBsmvnG4_lFYYqLCb.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:42:37.856Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bee/iCI0Y4i_whuJtArDh4-1U_model.glb",
+ "size": 18167052,
+ "done": "2026-09-29T10:48:23.074Z"
+ },
+ "lithos-ammonite": {
+ "request_id": "01a0ecc2-8d38-74c2-9ec9-895f60e3edbe",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b74/tTbB4Pu67vb_3uDJZQt8I_fy4kJrir.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:42:47.259Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bef/Tcy-CpJetIXxAW6M2b3Wy_model.glb",
+ "size": 18985700,
+ "done": "2026-09-29T10:48:33.289Z"
+ },
+ "artemis-astro": {
+ "request_id": "01a0ecc2-db7d-7992-a122-fdb07472e0ec",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 60000,
+ "symmetry_mode": "on",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "pose_mode": "a-pose",
+ "enable_rigging": true,
+ "rigging_height_meters": 1.85,
+ "enable_animation": true,
+ "animation_action_id": 0,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b74/kyyiEKqDWO91R-pE8UKBv_maJfkxAY.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:43:07.298Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bec/0rx_h_w_FLiXJiAIwTPHI_model.glb",
+ "size": 15452632,
+ "done": "2026-09-29T10:49:14.844Z"
+ },
+ "artemis-lander": {
+ "request_id": "01a0ecc3-0368-72e3-8a42-bfaaaba27aec",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b74/CExYOxp_oTaosGCthXglh_s4FwxSfc.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:43:17.514Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bfb/yWByfq2421943soOrDNxd_model.glb",
+ "size": 21888956,
+ "done": "2026-09-29T10:50:15.175Z"
+ },
+ "keeper-lighthouse": {
+ "request_id": "01a0ecc3-2bd1-7cc1-915a-72652682a87c",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 200000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b7f/a8-pAcfkKRGbRRa6YJZoA_K0t3ANUD.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:43:27.863Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf6/gSPl7iiZTAIFHd8-yyL3S_model.glb",
+ "size": 26097588,
+ "done": "2026-09-29T10:49:45.106Z"
+ },
+ "keeper-boat": {
+ "request_id": "01a0ecc3-30fe-7ac0-868a-cd36ed6e9e0f",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 100000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b75/dFYJ5u5KggSnM99OWBrkE_qMEFdNUZ.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:43:29.185Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf1/hyD-h7iWec3bPEZJzrCaY_model.glb",
+ "size": 18968404,
+ "done": "2026-09-29T10:49:03.910Z"
+ },
+ "koen-maple": {
+ "request_id": "01a0ecee-e018-7a20-80e2-f4a022b6fdaf",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 120000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "standard",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b75/52TJfefWqGJl14s2Z9-7l_X131q33k.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T11:31:12.017Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5d15/njMpZna4_O0t23p9O7G1-_model.glb",
+ "size": 12000604,
+ "done": "2026-09-29T11:37:10.053Z"
+ },
+ "noct-iris": {
+ "request_id": "01a0ecc3-cae0-7422-82d7-3228a743c81e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b76/c8VRYVaGNGuhwTjloFr_l_wK1WTybU.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:44:08.577Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf5/s4iFIScrpaj_2OoJFJfXP_model.glb",
+ "size": 18034604,
+ "done": "2026-09-29T10:49:14.019Z"
+ },
+ "noct-bergamot": {
+ "request_id": "01a0ecc4-1c5d-7362-89d1-5676d6d59960",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b76/Z4iL9WwosyWlag6vJv0cq_VWapd2N0.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:44:29.441Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bf8/4RxygW_ezj6OOsZU2O_jO_model.glb",
+ "size": 13806280,
+ "done": "2026-09-29T10:50:04.978Z"
+ },
+ "noct-vanilla": {
+ "request_id": "01a0ecc4-6d68-7702-8582-5a7cd936ac9e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b76/0t2EnbZxxANCldwUYGJVl_XWi9bmft.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:44:50.187Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5bfc/oHbhD2UQOs6EAYuXsXTEg_model.glb",
+ "size": 17543832,
+ "done": "2026-09-29T10:51:06.149Z"
+ },
+ "noct-oud": {
+ "request_id": "01a0ecc4-6e41-7c42-a773-dc0ceb9ee49e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b76/An0TELL41aJVxcbvrAzR4_qNlpEAIQ.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:44:50.404Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c09/z-UNfu8SQQfOrhrw13Bt4_model.glb",
+ "size": 19094156,
+ "done": "2026-09-29T10:54:40.127Z"
+ },
+ "noct-cap": {
+ "request_id": "01a0ecc6-95fa-7eb1-9188-692f4dbd6641",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b77/t9vxutlhTVZURbtdSt8MS_RAzYeP6c.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:47:11.641Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c09/oTzQ4EcfgsybRr0Akb-lY_model.glb",
+ "size": 13610308,
+ "done": "2026-09-29T10:54:19.597Z"
+ },
+ "racer-bike": {
+ "request_id": "01a0ecc6-e580-7b73-bc4b-1d8659a013b5",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 250000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b77/XVvpt4-Lhv2soLnApizig_XwzDgwG0.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:47:31.998Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c12/DXa_0NOc-EFwQCrwCuCsN_model.glb",
+ "size": 28966752,
+ "done": "2026-09-29T10:55:21.111Z"
+ },
+ "racer-helmet": {
+ "request_id": "01a0ecc7-8697-7f00-aa99-b3997423dc4e",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 80000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b78/gDf-CWYG6Df6vOHfPYRwJ_51lCYVhZ.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:48:13.237Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c1f/ziTOMRTSZ5Ue7Cna_rv27_model.glb",
+ "size": 15045696,
+ "done": "2026-09-29T10:56:12.404Z"
+ },
+ "horo-watch": {
+ "request_id": "01a0ecc7-ad3f-7763-a260-19e45cc9ba96",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b78/RwF0kiq7SCAVelzsuCyPo_c7lqzriC.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:48:23.132Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c1d/Nqh88DZ9wj-S9WV8MyDm0_model.glb",
+ "size": 21877520,
+ "done": "2026-09-29T10:56:01.523Z"
+ },
+ "velo-black": {
+ "request_id": "01a0ecc7-d529-70e3-ad2f-47609827a2a8",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "4k",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5b83/eXVKlk511QxIpNoTjnDJO_alammmAK.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T10:48:33.352Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5c0f/KXoJIIgr6tcUuRcbOLLQC_model.glb",
+ "size": 17920444,
+ "done": "2026-09-29T10:53:39.134Z"
+ },
+ "koen-maple2": {
+ "request_id": "01a0ecee-e019-7bb0-98e9-3ee71a6e2483",
+ "endpoint": "meshy/v7.1/image-to-3d",
+ "input": {
+ "topology": "triangle",
+ "target_polycount": 150000,
+ "symmetry_mode": "auto",
+ "should_remesh": true,
+ "should_texture": true,
+ "enable_pbr": true,
+ "enable_safety_checker": false,
+ "geometry_resolution": "standard",
+ "model_type": "standard",
+ "image_url": "https://v3b.fal.media/files/b/0aac5cf1/lA-IIlTrmrC7U1uTeCvz9_NDA7NfQB.png"
+ },
+ "status": "done",
+ "at": "2026-09-29T11:31:12.020Z",
+ "glb": "https://v3b.fal.media/files/b/0aac5d28/TbHTEewJitNmZWYeJimGO_model.glb",
+ "size": 27221104,
+ "done": "2026-09-29T11:40:24.066Z"
+ }
+ }
+}
\ No newline at end of file
diff --git a/docs/ENGINE.md b/docs/ENGINE.md
new file mode 100644
index 0000000..0d2ab9c
--- /dev/null
+++ b/docs/ENGINE.md
@@ -0,0 +1,107 @@
+# Twenty Worlds — engine & quality guide
+
+Twenty interactive 3D landing pages, each a complete, fictional brand website whose 3D scene carries the whole page
+(not a hero-only canvas). Built on three.js r186 + pmndrs postprocessing + N8AO + GSAP/Lenis, with hyper-detailed
+Meshy 7.1 GLB assets. The benchmark we must beat by a wide margin is ThreeUI (threeui.com): procedural, stylised
+3D heroes next to conventional UI sections. Our pages must feel like Awwwards Site-of-the-Day work: cinematic lighting,
+real materials, choreographed camera, a signature interaction nobody has seen on a landing page, and flawless UI.
+
+The reference implementation is `pages/reliquary/` — read it first. It shows the page structure, the boot sequence
+(loader → compile → start → intro), scroll choreography, HTML cards projected from 3D, post-render capture, etc.
+
+## Layout
+- `pages/<slug>/index.html | main.js | style.css` — each world is self-contained. Put page-only images in
+ `public/img/<slug>/`, extra models in `public/models/<slug>/`.
+- `src/core/*` — shared engine. **Do not edit files in src/core** (other pages are being built in parallel).
+ If you need different behaviour, copy the function into your page folder and change it there.
+- Dev server is already running: `http://127.0.0.1:5190/pages/<slug>/` (Vite, HMR). Do not start another.
+ If it is down, tell the lead in your report instead of starting one.
+- Model viewer: `http://127.0.0.1:5190/pages/_viewer/?m=models/<slug>/<file>.glb&rot=-30&d=4&h=1.4`
+
+## Core API (src/core)
+- `engine.js`
+ - `new Engine({ canvas, fov, near, far, dpr, background, shadows, post })` → `{ renderer, scene, camera, time }`.
+ `post` = `{ ao: {aoRadius, intensity, distanceFalloff} | false, bloom: {intensity, luminanceThreshold, luminanceSmoothing, radius} | false,
+ pre: (camera, scene) => [effects before tone mapping], extra: (camera, scene) => [effects after tone mapping],
+ tone: 'agx'|'aces'|'neutral'|'reinhard'|'linear', vignette: {offset, darkness} | false, noise: 0.06 | false, ca: 0.001, smaa }`.
+ Tone mapping happens in post; renderer.toneMapping stays NoToneMapping. HalfFloat HDR buffers.
+ - `engine.onTick((dt, t) => …)`, `engine.onAfterRender(fn)`, `engine.onResize((w, h, dpr) => …)`, `engine.start()`,
+ `engine.paused = true` skips rendering (use when HTML panels fully cover the canvas).
+ - `engine.post.{bloom, ao, vignette, noise, tone, ca}` for live tweaks.
+ - `studioEnvironment(renderer, { top, bottom, panels:[{pos,size,intensity,color}] })` → PMREM env texture (softboxes).
+ - `normalize(obj, size, { ground=true, axis='max'|'y'|'x' })` fits a model into `size` and rests it on y=0.
+ - `prepModel(obj, renderer, { cast, receive, env, rough, metal, onMat(mat, mesh) })`.
+ - `damp(a,b,lambda,dt)`, `clamp`, `lerp`, `smooth(a,b,v)` (smoothstep), `range(v,a,b)`.
+- `assets.js`: `const assets = new Assets()`; `await assets.gltf('models/<slug>/x.glb')`, `assets.texture('img/..')`,
+ `assets.progress` (0..1). `sampleSurface(mesh, count)` → `{position, normal, color, uv}` Float32Arrays in world space
+ (colours read from the base-colour texture) — for particle systems. `firstMesh(root)`.
+- `input.js`: `new Pointer()` → `x,y` NDC raw, `sx,sy` damped, `px,py` pixels, `vx,vy` velocity, `down`, `.on('down'|'up'|'move', fn)`;
+ call `pointer.update(dt)` each tick.
+- `scroll.js`: `smoothScroll()` (Lenis, sets `window.__lenis`), `gsap`, `ScrollTrigger`, `SplitText`,
+ `elementProgress(el)` (0..1 through an element's scroll span), `pageProgress()`, `reveal(selector, {type:'lines'|'words'|'chars'})`.
+- `ui.js`: `preloader({ assets, el, onValue, minTime, exit })` → `.finish()`; `cursor({ color, blend, size })` →
+ `.set(state, label)` states: '', 'link', 'drag', 'label', 'hidden'; `magnetic('[data-magnetic]')`;
+ **`worldNav(slug, { theme: 'dark'|'light', corner: 'bl'|'br'|'tl'|'tr' })` is mandatory on every page.**
+- `reflector.js`: `new PlanarReflection(renderer, { resolution })`, `.hidden.push(floorMesh)`, `.patch(material, { strength, distort, lodScale, lodBias, f0 })`,
+ `.setSize(w,h,dpr)` in onResize, `.update(scene, camera)` each tick. Roughness map drives blur.
+- `volumetric.js`: `new VolumetricSpotEffect(camera, { density, noise, noiseScale, maxDist, wind, floorY })` — put it in
+ `post.pre`; `.add(spotLight, { scale, range, softness })` (max 4). Raymarched beams that stop at scene depth.
+- `textures.js`: `fbmTexture`, `fbmNormal`, `bakeTexture(renderer, size, glslBody)` — tileable GPU-baked noise textures.
+ In `bakeTexture` bodies you can use `vUv`, `pnoise(p, period)`, `fbm(p, period, octaves, gain)`, `ridge(p, period, octaves)`.
+- `worlds.js`: the list of 20 worlds (slug, name, line, hue).
+
+## Assets
+- Meshy 7.1 GLBs are already optimised in `public/models/<slug>/` (meshopt + WebP, 2048² base/normal/metalRough PBR,
+ 60k–250k triangles). Models face **+Z**, are single meshes, arbitrary scale — always `normalize()`.
+- The clean reference image each model was built from: `assets/src/<prefix>-<name>.png` (look at it!).
+- Viewer renders of every model: `shots/models/<slug>-<name>.png`.
+- You may generate extra 2D images with Nano Banana 2 (backgrounds, plates, product photos, textures):
+ write a job file `assets/jobs/<slug>-extra.json` like `{ "images": [{ "id": "<slug>-foo", "raw": true, "prompt": "…", "aspect_ratio": "16:9", "resolution": "2K" }] }`
+ and run `node scripts/gen.mjs images assets/jobs/<slug>-extra.json`; output lands in `assets/src/<id>.png`. Convert to WebP into
+ `public/img/<slug>/` with sharp. Budget: at most 6 images per page. `raw: true` skips the white-background product suffix.
+- Do **not** start new Meshy generations without asking the lead; if a model is unusable, say so in your report.
+- Heavy models: prefer ≤1.6M triangles on screen, ≤45 MB total download per page.
+
+## QA tooling (use it constantly — you cannot see the page otherwise)
+- `node scripts/shot.mjs "<url>" shots/<slug>/<name> --wait 6000 --mouse 0.6,0.45 --scrolls 0,0.2,0.5,0.8,1 [--click 0.5,0.5 --clickwait 1500] [--mobile] [--settle 1800]`
+ → one PNG per scroll stop (headless Chrome on the RTX 4090, real WebGL), prints `{gl, docH, fps, loadMs}` and console errors.
+ `--actions "js"` evaluates JS after load (e.g. to trigger a state). The page receives real mouse moves/clicks.
+- `node scripts/contact.mjs shots/sheets/<name> 2 720 a.png b.png …` → contact sheet JPG (cheaper to review than many PNGs).
+- Harmless console noise: `THREE.Clock deprecated`, D3D shader warnings `X3595`/`X4122`, a favicon 404.
+- `window.__fps` is set by the engine; aim for 60 at 1440×900 on the 4090 (it will be ~2–3× slower on laptops, so budget).
+
+## Quality bar — be brutal
+Review every screenshot as a picky art director would. Iterate until every answer is yes:
+1. Would this stop someone scrolling on Awwwards? Is the hero frame a poster you'd print?
+2. Lighting: motivated key light, rim/fill, real shadows and AO contact; nothing looks flat, grey or "default three.js".
+3. Materials: Meshy PBR maps used; env map present; no blown-out whites, no crushed blacks without intent, no plastic look.
+4. Composition: the 3D subject and the typography are designed together; nothing overlaps awkwardly; clear hierarchy; generous spacing.
+5. The signature interaction works, is discoverable within 3 seconds (hint UI), and looks spectacular in a still frame.
+6. Scroll choreography: every section has a distinct camera/scene state; transitions are eased, never jumpy.
+7. Complete landing page: nav, hero, ≥4 content sections with real (fictional but specific, well-written) copy, CTA, footer. No lorem ipsum.
+8. Typography: a deliberate Google Fonts pairing unique to this world; sizes fluid (clamp); legible over 3D.
+9. Loader that fits the world; intro animation after load; `renderer.compile()` before start to avoid hitches.
+10. Mobile (`--mobile`): layout holds at 390×844, interaction has a touch equivalent, no horizontal scroll.
+11. No console errors. 60 fps on the 4090.
+Distinctiveness: every world must look and feel unlike the others (palette, type, layout, motion language).
+
+## Gotchas
+- `PCFSoftShadowMap` was removed in r186 (engine uses PCFShadowMap). Set `light.shadow.radius`/bias as needed.
+- Give spot/dir lights a `.target` added to the scene.
+- When the camera is inside a volumetric beam the whole view hazes — keep density low (0.02–0.05) and let noise shape it.
+- Canvas is `position: fixed`; HTML sections scroll over it. Put `pointer-events: none` on overlay text wrappers that sit
+ over interactive 3D, re-enable on buttons/links.
+- AudioContext needs a user gesture; audio must be optional and never auto-start loudly; give a mute toggle if used.
+- Keep the page's JS in one `main.js` (split into more files in the page folder if it gets long).
+
+## Lessons from the build (added after all twenty worlds shipped)
+- **Chromatic aberration** samples its input buffer directly, so it now runs in its own EffectPass after tone mapping
+ (fixed in `engine.js`); before that it re-sampled un-tone-mapped HDR for the red/blue channels.
+- **Env strength:** in r186 `material.envMapIntensity` only applies when the material has its own `envMap`; with
+ `scene.environment` use `scene.environmentIntensity` (so `prepModel({ env })` is effectively a no-op).
+- **Transmission glass** refracts the clear colour; with the post stack's clear alpha of 0 that is a white void —
+ give scenes with glass a `scene.background` (or a backdrop mesh).
+- **Dev server** runs with `hmr: false`: with many pages edited in parallel every save used to full-reload every tab.
+- **Planar reflections** skip their first two frames so the shadow maps exist before the mirrored render.
+- Meshy rigged characters: the idle preset can be broken (hip scale); the rigged GLB carries only base colour — reuse the
+ static model's normal/roughness maps (same UV layout).
diff --git a/docs/briefs/abyssal.md b/docs/briefs/abyssal.md
new file mode 100644
index 0000000..85a675e
--- /dev/null
+++ b/docs/briefs/abyssal.md
@@ -0,0 +1,33 @@
+# 02 · Abyssal — "Descend eleven thousand metres"
+Brand: **Abyssal** — a private deep-ocean expedition house that takes 3 guests per dive to the Challenger Deep in the submersible *Pelagia*.
+
+## Signature interaction
+Scroll IS the descent. A fixed depth gauge counts 0 → 10,935 m (numbers roll like an instrument). The ocean changes
+physically with depth: surface = bright turquoise with animated caustics dancing on everything and god-ray shafts from
+the surface; 200 m twilight blue; 1,000 m black. Red/orange wavelengths fade first (tint materials/fog by depth).
+From ~800 m the submersible's floodlights (VolumetricSpotEffect, 2–3 beams) are the only light and **the cursor steers
+the floodlights** — you search the dark. Moving the cursor fast leaves a trail of bioluminescent plankton (additive
+particles spawned along the pointer ray that flash cyan and fade).
+
+## Scene & choreography
+- The submersible (`models/abyssal/sub.glb`) descends with the camera, framed off-centre, slowly rotating, lights on.
+- Zones (each a section with copy): Sunlight 0–200 m (nautilus `nautilus.glb` drifting), Twilight 200–1,000 m (procedural
+ jellyfish: translucent bell shader + trailing tentacle lines, pulsing), Midnight 1,000–4,000 m (anglerfish `angler.glb`
+ looms out of the dark — its lure is an emissive bulb + small point light; it turns toward the beam), Abyss
+ 4,000–6,000 m (hydrothermal vent `vent.glb` on the seabed with shimmering heat haze, rising mineral particles and a
+ warm glow), Hadal 6,000–10,935 m (trench floor: silt, a lone marker beacon at the bottom).
+- Marine snow: thousands of drifting particles that rush upward relative to the descending camera (speed = scroll speed).
+- Fog colour/density driven by depth; seabed appears near the end.
+
+## Page sections
+Nav (Abyssal logo, Dives, Pelagia, Science, Book) · Hero ("The last unexplored place on Earth is 11 km down") · the 5
+zones (each: depth range, temperature, pressure in atm, what you'll see) · "Pelagia" vessel specs with 3–4 hotspots
+projected from the 3D sub (titanium sphere, 16 h life support, …) · Expedition pricing / dates · Crew & safety · Footer ("Surface").
+
+## Art direction
+Deep navy → absolute black; accents bioluminescent cyan `#3fd6c9` and the sub's safety orange. Fonts: "Space Grotesk"
+display + "IBM Plex Mono" readouts. Instrument-panel UI: thin rules, tabular numbers.
+
+## Must be true in screenshots
+Surface frame glows with caustics and light shafts; midnight frame is black except beams, the anglerfish and its lure;
+the vent frame has warm glow and haze. Readable depth gauge in every frame.
diff --git a/docs/briefs/artemis.md b/docs/briefs/artemis.md
new file mode 100644
index 0000000..74df0d2
--- /dev/null
+++ b/docs/briefs/artemis.md
@@ -0,0 +1,27 @@
+# 15 · Artemis — "Scroll to walk on the Moon"
+Brand: **Artemis** — lunar tourism: a seven-day stay at a south-pole outpost.
+
+## Signature interaction
+**Scroll to walk.** The astronaut was generated rigged by Meshy. Check `assets/manifest.json` (meshes["artemis-astro"]) and the
+raw GLBs: `assets/raw/artemis-astro.glb` may be the static mesh; the rigged + animated files are separate URLs in the fal
+result (`rigged_character_glb`, `animation_glb`, `basic_animations` with walking/running). If they are not downloaded yet,
+fetch them with a small node script using `scripts/fal.mjs`'s `fal.queue.result('meshy/v7.1/image-to-3d', { requestId })`
+(request id is in the manifest) and save to `assets/raw/`. Optimise without simplify (`node scripts/optimize.mjs in out`)
+and verify animations survive (`npx gltf-transform inspect`).
+Tie the walk cycle to scroll velocity (AnimationMixer timeScale ∝ scroll speed; crossfade to idle when still); the astronaut
+advances across the regolith with a low-gravity bounce. **Footprints** are stamped where each foot lands (decals or a
+render-target normal painter on the terrain). Dust kicks up in slow ballistic arcs (1/6 g, no drag, no billowing). Harsh single
+sun, pitch-black sky with Earth over the horizon (procedural Earth shader with clouds + atmosphere rim, or an NB2 plate), very
+long black shadows, only faint earthshine fill. Terrain: large displaced plane with craters and instanced rocks.
+The lander (`lander.glb`) appears as the destination.
+
+## Page sections
+Nav · Hero ("One small step, repeated 40,000 times.") · The walk (pinned long scroll) · The outpost · The seven days
+(itinerary timeline) · Training & medical · Price ("$4.2M, all-inclusive") · Footer.
+
+## Art direction
+Stark greyscale, pure black, white, one accent: suit orange. Fonts: "Space Grotesk" + "Barlow Condensed" mission readouts.
+NASA-archival meets Apple.
+
+## Must be true
+Walking frame: astronaut mid-stride, footprints trailing, long shadow, Earth in the black sky.
diff --git a/docs/briefs/atlas.md b/docs/briefs/atlas.md
new file mode 100644
index 0000000..8c8a52f
--- /dev/null
+++ b/docs/briefs/atlas.md
@@ -0,0 +1,22 @@
+# 13 · Atlas of Drifting Isles — "Travel between floating islands"
+Brand: **Atlas of Drifting Isles** — a whimsical sky-travel agency (airship tours) for a fantasy archipelago.
+
+## Signature interaction
+Four floating islands (`models/atlas/{lighthouse,falls,pagoda,windmill}.glb`, stylised hand-painted) drift in an endless sky
+of soft layered clouds. **Click an island (or a map dot) and the camera flies there** along a curved path through the clouds
+(banking, FOV breathing), then orbits it gently while its destination panel slides in. Scroll also advances the tour island to
+island. Islands bob; waterfalls pour off edges (particle streams + mist); birds flock between islands (boids, instanced);
+a procedural airship crosses the sky. Hover an island → soft rim glow and a label pin.
+Clouds: many soft sprite billboards with depth-fade (soft particles) or a raymarched layer — must look soft and volumetric,
+never like flat cards. Sky gradient with a warm sun and atmospheric haze.
+
+## Page sections
+Nav · Hero ("The map is not the territory. The territory floats.") · 4 destination sections (name, "3 h from Port Aubade",
+highlights, price) · The airship fleet · Booking CTA · Footer.
+
+## Art direction
+Soft sky blue `#7cc4ff`, peach, cream; storybook but premium. Fonts: "Young Serif" + "Nunito Sans". Lighting that respects the
+painted textures (lower env, soft key, gentle rim).
+
+## Must be true
+Hero: all four islands in a luminous cloudscape with depth; a fly-to frame mid-bank through clouds.
diff --git a/docs/briefs/ember.md b/docs/briefs/ember.md
new file mode 100644
index 0000000..c2041b7
--- /dev/null
+++ b/docs/briefs/ember.md
@@ -0,0 +1,29 @@
+# 03 · Hammer & Ember — "Heat the blade. Strike the steel."
+Brand: **Hammer & Ember** — a two-person bladesmith atelier forging pattern-welded (damascus) swords to commission.
+
+## Signature interaction
+The Viking sword (`models/ember/sword.glb`) lies across the anvil (`anvil.glb`) in a dark smithy lit by a coal forge.
+- **Scroll heats the steel**: patch the sword's material (onBeforeCompile) to add blackbody emission — heat spreads from
+ the tip region toward the guard with noise-broken edges: dull red → cherry → orange → yellow-white (proper blackbody
+ ramp, HDR emission so bloom catches it), plus heat shimmer (screen-space distortion above the hot zone) and glowing scale flakes.
+- **Click to strike**: the hammer (`hammer.glb`) swings down on the hot spot (anticipation → impact), a burst of GPU spark
+ particles (hundreds, stretched along velocity, gravity + floor bounce, cooling colour), camera shake, a flash of light
+ on the walls, a synthesized metallic clang (WebAudio, optional, mute toggle). Counter "folds: 3/512".
+- **Hold to pump the bellows**: the forge coals brighten, embers roar upward, heat spreads faster.
+- End of scroll: the quench — steam billows (soft particle sprites), heat dies out and the cooled blade shows its damascus pattern.
+
+## Scene
+Stone/brick forge with glowing coals (emissive animated noise, flickering orange point lights, one shadow-casting),
+tools on the wall catching rim light, embers always drifting upward. Soot-dark floor.
+
+## Page sections
+Nav · Hero ("Every blade is folded 512 times. None are made twice.") · The process (Fold / Forge / Quench / Polish, each a
+camera state around the anvil) · The steel (layer count, carbon %, hardness HRC 58–60, big numbers) · Commissions
+(blade types & price from €4,800) · Testimonials · Footer.
+
+## Art direction
+Black and soot, molten orange `#ff6a1f`, bone white. Fonts: a condensed display ("Oswald"/"Bebas Neue") + "Crimson Pro".
+Grain and heat glow. Must feel heavy, hot and loud even when silent.
+
+## Must be true
+A mid-scroll frame where the blade glows orange-white on the anvil with sparks in the air is poster-worthy.
diff --git a/docs/briefs/florae.md b/docs/briefs/florae.md
new file mode 100644
index 0000000..02dc368
--- /dev/null
+++ b/docs/briefs/florae.md
@@ -0,0 +1,24 @@
+# 06 · Florae — "Two hundred thousand petals, one gesture"
+Brand: **Florae** — a botanical archive and flower atelier that sends one extraordinary specimen per month.
+
+## Signature interaction
+A GPGPU particle sculpture (≥150k particles; `sampleSurface()` on each Meshy model for positions + texture colours).
+Scroll morphs between specimens: rose (`models/florae/rose.glb`) → king protea (`protea.glb`) → phalaenopsis orchid
+(`orchid.glb`) → blue morpho butterfly (`morpho.glb`, whose wings then flap: rotate particles by wing side). Transitions
+are not linear lerps: particles lift into a curl-noise wind, swirl, and settle into the new form (stagger by per-particle
+seed). **The cursor is a breeze**: particles near the pointer ray are pushed away and spring back (GPGPU velocity texture or
+analytic displacement). Click = a gust that scatters the flower, which then re-blooms.
+Soft round particles, size by depth + faux depth-of-field (bigger, fainter out of focus). Colours from the textures,
+slightly lifted, on a pale background — pointillist and luminous, not neon.
+
+## Page sections
+Nav · Hero (the rose, "Florae — a flower a month, from the edge of the map.") · 4 specimen sections, each with a specimen
+label (Latin name, origin, bloom season, notes) pinned while the morph completes · "The archive" (next months) ·
+Subscription (€48/month, 3 tiers) · Footer.
+
+## Art direction
+Warm cream `#f4efe6`, deep crimson `#d6456b`, ink. Fonts: "Cormorant"/"EB Garamond" italics + "Inter Tight".
+Editorial botanical-plate feel, generous whitespace.
+
+## Must be true
+Hero: a rose made of glowing points that is clearly a rose, with depth; a mid-morph frame is a swirl of petals.
diff --git a/docs/briefs/gambit.md b/docs/briefs/gambit.md
new file mode 100644
index 0000000..fe956cb
--- /dev/null
+++ b/docs/briefs/gambit.md
@@ -0,0 +1,24 @@
+# 12 · Gambit — "The Immortal Game, replayed in marble"
+Brand: **Gambit** — makers of hand-carved marble chess sets and a members' chess salon.
+
+## Signature interaction
+Scroll replays **the Immortal Game** (Anderssen vs Kieseritzky, London 1851, 23 moves; hardcode the moves as from/to squares)
+on a glossy marble board with planar reflections. Each scroll step plays one move: pieces slide with easing, knights arc
+through the air, captured pieces topple, slide off and settle beside the board. The camera choreographs cinematically (low
+angles near the action, overhead at key moments, the final mating net framed). A side column shows the notation with the
+current move highlighted and one-line annotations ("Anderssen gives up both rooks"). After the replay, **free play**: drag
+any piece (raycast pick, lift with shadow, snap to squares) — no chess engine needed.
+Pieces: `models/gambit/{king,queen,bishop,knight,rook,pawn}.glb` are white Carrara marble. Make the black set from the same
+models with a material transform (onBeforeCompile: remap base colour to nero marquina black with light/gold veins).
+Knights must face the opponent.
+
+## Page sections
+Nav · Hero ("Some games are never finished.") · The replay (pinned, long) · The set (Carrara & Nero Marquina, walnut board,
+€3,900) · The salon (members' evenings) · Footer.
+
+## Art direction
+Black, bone, brass `#b89b6a`. Fonts: "Bodoni Moda"/"Playfair Display" + "Inter". Low-key studio lighting, a strong key from
+above-side, rim lights for silhouettes. Luxurious and cerebral.
+
+## Must be true
+A frame mid-game with a knight in mid-leap over the reflective board, dramatic light, looks like a luxury ad.
diff --git a/docs/briefs/hangar.md b/docs/briefs/hangar.md
new file mode 100644
index 0000000..d6b4e91
--- /dev/null
+++ b/docs/briefs/hangar.md
@@ -0,0 +1,27 @@
+# 08 · Hangar Nine — "Power up a forty-ton machine"
+Brand: **Hangar Nine** — a (fictional) mech manufacturer's recruitment site for its test-pilot program.
+
+## Signature interaction
+**Press and hold to power up.** The hangar starts almost black (the mech `models/hangar/mech.glb` barely visible, rim-lit by
+emergency red strobes). Holding mouse/space fills a radial "INITIATE" gauge; on completion: overhead floodlights clank on bay
+by bay (VolumetricSpotEffect beams, dust in the beams), the cockpit visor glows, steam bursts from vents, a HUD overlay boots
+(scan line sweep, reticles, readouts), and a **scan plane** travels up the mech revealing a glowing hologram/wire overlay on the
+mesh (shader using world height; barycentric-free wire via fwidth of a triplanar grid is fine). After power-up the scroll orbits
+the camera around the mech with hotspots (Reactor, Actuators, Armour, Weapons) projected from 3D. The drone (`drone.glb`)
+circles with its own sweeping spotlight.
+
+## Scene
+Industrial hangar: procedural gantries, catwalks, hazard-striped floor markings, reflective wet concrete (PlanarReflection),
+fog, welding sparks from a gantry arm.
+
+## Page sections
+Nav · Hero ("HN-9 'Warden'. Forty tons. One pilot.") · Power-up · Specifications (hotspots) · Stats (height 11.4 m, reactor
+42 MW, top speed 68 km/h) · Test-pilot program application CTA · Footer.
+
+## Art direction
+Gunmetal, fog grey, hazard amber `#ffb000`, sparing HUD cyan. Fonts: "Chakra Petch"/"Rajdhani" + "Share Tech Mono".
+Cinematic — Titanfall / Pacific Rim title sequences.
+
+## Must be true
+Powered frame: towering mech under crossing volumetric floodlights, reflections on the floor, HUD overlay. Pre-power frame:
+moody black with red strobes and the hold hint.
diff --git a/docs/briefs/horologie.md b/docs/briefs/horologie.md
new file mode 100644
index 0000000..07af198
--- /dev/null
+++ b/docs/briefs/horologie.md
@@ -0,0 +1,24 @@
+# 20 · Aurel Horologie — "Take a movement apart"
+Brand: **Aurel Horologie** — an independent Genevan watchmaker; the calibre AH-01 skeleton tourbillon.
+
+## Signature interaction
+Hero: the Meshy watch (`models/horologie/watch.glb`) floating; the cursor tilts it; studio light glints on rose gold.
+Then **scroll takes the movement apart**: the watch turns and the camera moves into an exploded view of a **fully procedural
+movement** stacked along the axis: mainplate, barrel with mainspring, going train (centre, third, fourth, escape wheels with real
+tooth profiles via extruded Shapes), pallet fork, balance wheel with hairspring (oscillating at 4 Hz, 8 beats/s), bridges with
+Côtes de Genève stripes (procedural), ruby jewels (transmission). Every gear rotates at the correct ratio and meshes with its
+neighbour. Layers separate with labels (leader lines to 3D anchors: "Barrel · 72 h reserve", "Escapement · 28,800 vph").
+**Click and hold the crown to wind**: the mainspring tightens, a power-reserve indicator fills, the train speeds up briefly.
+Scroll back reassembles.
+
+## Page sections
+Nav · Hero ("Two hundred and eleven parts. One heartbeat.") · The exploded movement (pinned, long) · Finishing (anglage,
+perlage, Geneva stripes — close-ups) · The collection (3 references, CHF 48,000+) · Atelier (6 watchmakers, 38 watches a year) · Footer.
+
+## Art direction
+Ivory `#f3efe7`, navy, rose gold `#c89b6d`. Fonts: "Cormorant Garamond" + "Montserrat" small caps. Light mode, precise, editorial.
+Studio env with long softboxes so metals look expensive.
+
+## Must be true
+Exploded frame: a floating stack of gleaming gears and bridges with labels, crisp like a technical render.
+If the Meshy watch looks poor up close, keep it small/far or replace the hero with the procedural assembled movement.
diff --git a/docs/briefs/keeper.md b/docs/briefs/keeper.md
new file mode 100644
index 0000000..e7b6f15
--- /dev/null
+++ b/docs/briefs/keeper.md
@@ -0,0 +1,20 @@
+# 16 · The Keeper — "Hold the light against the storm"
+Brand: **The Keeper** — a four-room lighthouse hotel on a rock in the North Atlantic.
+
+## Signature interaction
+Night, storm. The lighthouse (`models/keeper/lighthouse.glb`) stands on its rock in a violent sea: Gerstner-wave ocean
+(several waves, foam on crests and around the rock, green subsurface in wave backs, reflections), wind-driven rain streaks,
+lightning that flashes the scene for a few frames, low racing clouds. The lamp's beam rotates (VolumetricSpotEffect, twin
+beams, very visible in rain). **The cursor takes the beam**: moving the pointer grabs the rotating beam and aims it; a fishing
+boat (`boat.glb`) is lost in the swell — hold the beam on it for 2 s and it's "guided home" and sails toward the harbour
+(reward + counter "Boats guided home: 1"). Scroll moves the night toward dawn: rain stops, waves calm, clouds break, pink dawn.
+
+## Page sections
+Nav · Hero ("Four rooms. One light. No one else for nine miles.") · The storm (interaction) · The rooms (Lamp Room, Keeper's
+Quarters, Fog Signal, Watch) · The crossing (boat transfer, weather permitting) · Dawn (rates from £420) · Footer.
+
+## Art direction
+Storm blue-black, sodium-yellow beam `#ffd27a`, foam white; dawn pinks at the end. Fonts: "Libre Caslon Display" + "Karla".
+
+## Must be true
+Storm frame: beam cutting through rain over heaving waves with foam around the rock; dawn frame: calm sea, pink light.
diff --git a/docs/briefs/koen.md b/docs/briefs/koen.md
new file mode 100644
index 0000000..4a80ed5
--- /dev/null
+++ b/docs/briefs/koen.md
@@ -0,0 +1,22 @@
+# 17 · Kōen — "One tree, four seasons"
+Brand: **Kōen** — a bonsai nursery in Saitama with trees older than the country's railways.
+
+## Signature interaction
+A Japanese maple bonsai (`models/koen/maple.glb`). **Scroll (and a draggable season dial) turns the year**: spring (fresh lime
+leaves + a few falling blossoms), summer (deep green, haze), autumn (foliage turns crimson/orange — a shader hue remap that
+affects only foliage-coloured texels; leaves fall as instanced particles with tumbling motion and pile on the moss), winter
+(leaves dissolve via a noise threshold leaving the branch structure — check what's under the foliage in the mesh; if there is
+little, fake it with sparse foliage + procedural twig lines; snow accumulates on top-facing surfaces via a normal·up shader;
+snowfall particles). Background colour, light temperature, shadow softness and ambient particles change per season. Hovering
+the tree: a soft breeze (vertex sway on foliage by height).
+
+## Page sections
+Nav · Hero ("This tree has seen 180 autumns.") · Four seasons (pinned, with vertical labels 春 夏 秋 冬) · The nursery (trees for
+adoption with age & price, ¥380,000+) · The craft (pruning, wiring, repotting) · Visit · Footer.
+
+## Art direction
+Washi paper `#f1ece2`, sumi ink, seasonal accents (autumn `#d2553b`). Fonts: "Noto Serif JP" + "Cormorant Garamond". Ink-brush
+SVG dividers. Extremely restrained, meditative.
+
+## Must be true
+Autumn frame: crimson canopy with leaves falling onto moss, soft side light; winter frame: bare branches with snow.
diff --git a/docs/briefs/koi.md b/docs/briefs/koi.md
new file mode 100644
index 0000000..4a817e9
--- /dev/null
+++ b/docs/briefs/koi.md
@@ -0,0 +1,25 @@
+# 05 · Still Water — "Touch the pond"
+Brand: **Still Water** — a seven-room ryokan in Kyoto built around a 200-year-old koi pond.
+
+## Signature interaction
+Top-down (slightly tilted) koi pond filling the viewport with a **real-time GPGPU ripple simulation** (height-field wave
+equation in ping-pong float render targets, ~512²). The cursor drags through the water leaving wakes; clicking drops a food
+pellet (splash + ring ripple) and the koi turn and swim to it (steering: wander, separation, seek).
+- Koi: `models/koi/kohaku.glb` and `showa.glb`, 6–10 instances with vertex-shader body undulation (sine wave along the body's
+ long axis, amplitude growing toward the tail; tail flicks harder when swimming fast). Render them below the surface so they
+ are refracted and darkened by depth.
+- Water: refraction of the pond floor (dark river stones + sand, procedural) using the ripple normals, fresnel sky reflection
+ with overhanging maple silhouettes (you may generate a plate), sun glints, caustics on the floor.
+- Floating: lotus `lotus.glb` bobbing with the ripples; maple leaves that fall, land, spin and float.
+- Stone lantern `lantern.glb` on a rock at the pond edge; moss.
+
+## Page sections
+Nav · Hero ("Seven rooms. One pond. No clocks.") · The rooms (3 cards: Moss, Maple, Moon, from ¥68,000) · Kaiseki & tea ·
+The seasons at Still Water · Booking CTA · Footer. As you scroll the camera drifts across the pond.
+
+## Art direction
+Ink-green water, vermilion `#e0503a` accents, washi paper `#f3efe6` panels. Fonts: "Shippori Mincho" + "Zen Kaku Gothic New";
+small vertical Japanese text accents. Quiet, meditative motion.
+
+## Must be true
+The hero shot looks like a photograph of a real pond with koi under rippling water.
diff --git a/docs/briefs/lithos.md b/docs/briefs/lithos.md
new file mode 100644
index 0000000..7b29705
--- /dev/null
+++ b/docs/briefs/lithos.md
@@ -0,0 +1,23 @@
+# 14 · Lithos — "Crack the stone open"
+Brand: **Lithos** — a gallery of museum-grade mineral specimens and a fine-jewellery line cut from them.
+
+## Signature interaction
+**Crack the geode.** A closed rough geode sits on black velvet: build it from two copies of `models/lithos/geode.glb` (a cut
+half, cavity facing up) — the top one mirrored/flipped so the cut faces meet. Press-and-hold: hairline cracks glow violet along
+the seam (shader + falling dust particles), the stone trembles, then splits: the top half lifts and turns away revealing the
+amethyst cavity sparkling (glint shader: high-frequency noise × specular × view dependence → twinkling facets; bloom).
+Then scroll through the collection: clear quartz cluster (`quartz.glb`; blend its material toward MeshPhysicalMaterial
+transmission + dispersion + iridescence so it reads as real crystal), pyrite (`pyrite.glb`, mirror metal with sharp studio
+reflections), ammonite (`ammonite.glb`, thin-film iridescence). **The cursor is a light**: moving it orbits a small point light
+around the specimen producing moving glints and shadows.
+
+## Page sections
+Nav · Hero ("Four billion years of patience.") · Crack · The collection (4 specimens: locality, age, weight, price) ·
+Jewellery (2–3 NB2 product photos) · Provenance & ethics · Footer.
+
+## Art direction
+Velvet black, amethyst violet `#9d6bff`, platinum. Fonts: "Cinzel"/"Italiana" + "Jost". Museum vitrine lighting: small hard key
++ softbox, deep shadow.
+
+## Must be true
+The opened-geode frame with glittering amethyst is jaw-dropping; the quartz frame looks like real glassy crystal, not plastic.
diff --git a/docs/briefs/lowfreq.md b/docs/briefs/lowfreq.md
new file mode 100644
index 0000000..bb17b44
--- /dev/null
+++ b/docs/briefs/lowfreq.md
@@ -0,0 +1,26 @@
+# 11 · Low Frequency — "Put your hand on the record"
+Brand: **Low Frequency** — a Tokyo-style listening bar and record label.
+
+## Signature interaction
+A turntable (`models/lowfreq/turntable.glb`) you can play. Overlay a procedural vinyl record (fine grooves: anisotropic-looking
+rotating radial highlight, printed label) and animate it. **Press play → the record spins up and music plays**: synthesize an
+original lo-fi house/jazz loop in WebAudio (kick, snare, hats, bass, Rhodes-like chords) rendered into an AudioBuffer via
+OfflineAudioContext, played by an AudioBufferSourceNode. **Drag the record to scratch**: playbackRate follows drag angular
+velocity (backward via a reversed-buffer swap), releasing lets it spin back up. Audio-reactive visuals from an AnalyserNode:
+the speaker (`speaker.glb`) woofer pulses, room light breathes, dust in the light beam dances, a circular spectrum ring around
+the platter. The muted/no-audio state must still look alive (idle spin + fake spectrum).
+
+## Scene
+A dim listening bar: wall of records (procedural sleeves with generated cover art — you may generate a few NB2 covers),
+warm tube-amp glow, a single warm spotlight over the deck, haze. Purple/amber night palette.
+
+## Page sections
+Nav · Hero ("Put your hand on the record.") · This week's pressing (tracklist with play buttons that cue the deck) ·
+The bar (hours, 12 seats, "no phones on the counter") · Label catalogue (sleeves that tilt on hover) · Record club
+membership · Footer.
+
+## Art direction
+Near-black aubergine, amber, lavender `#a78bfa`. Fonts: "Syne"/"Unbounded" + "Space Mono". Grainy, analog.
+
+## Must be true
+Hero: moody close-up of the spinning record under a warm spotlight with the spectrum ring; UI clearly invites "drag to scratch".
diff --git a/docs/briefs/monolith.md b/docs/briefs/monolith.md
new file mode 100644
index 0000000..3b1f581
--- /dev/null
+++ b/docs/briefs/monolith.md
@@ -0,0 +1,23 @@
+# 10 · Monolith — "Drag the sun across a house"
+Brand: **Monolith** — a small architecture practice (Lisbon/Oslo) known for houses on extreme sites.
+
+## Signature interaction
+**The sun is a handle.** The cliff villa diorama (`models/monolith/house.glb`) sits on a plinth in a gallery void (or a
+real sky — decide what looks better). Drag the sun along a visible arc (or scroll) through a day: dawn (low, pink) → noon
+(hard, white, short shadows) → golden hour (long, amber) → blue hour → night (moonlight, stars, windows glow warm, pool
+glows turquoise). Directional light direction/colour/intensity, sky, fog, env intensity and exposure interpolate.
+High-quality shadows (tight shadow camera, 4096 map, tuned bias) sweeping across the concrete are the star. A time readout
+(06:12, 12:00, 19:41…) and sun azimuth/altitude. Night: emissive window planes placed on the model's glass (inspect the
+model, place thin boxes) and a warm point light inside.
+
+## Page sections
+Nav · Hero ("Houses that answer to the sun.") · Selected works (list with hover-reveal images — generate 3–4 NB2 architectural
+photos) · The house on the cliff (case study: plan view, section, detail camera states) · Principles (3–4 numbered) ·
+Studio / Awards · Contact · Footer.
+
+## Art direction
+Swiss-minimal: warm off-white `#ecebe6`, concrete grey, black type, one accent (sun amber). Fonts: "Inter Tight" +
+"IBM Plex Serif" italic. Whitespace, strict 12-col grid, big numerals.
+
+## Must be true
+Golden-hour frame: long raking shadows across the house and cliff; night frame: glowing windows and stars.
diff --git a/docs/briefs/nocturne.md b/docs/briefs/nocturne.md
new file mode 100644
index 0000000..0a64253
--- /dev/null
+++ b/docs/briefs/nocturne.md
@@ -0,0 +1,22 @@
+# 18 · Nocturne — "A fragrance you can pour"
+Brand: **Nocturne** — an extrait de parfum ("No. 9, Iris & Oud") from a small Grasse house.
+
+## Signature interaction
+A heavy faceted glass flacon (procedural: bevelled box or faceted lathe; MeshPhysicalMaterial transmission, thickness, ior 1.5,
+dispersion, attenuation colour) with the cap `models/nocturne/cap.glb`, **full of amber liquid that behaves like liquid**: drag
+to tilt/rotate the bottle; the liquid surface stays level in world space and sloshes with a damped spring wobble driven by
+angular velocity (classic liquid shader: discard above a world-space plane with wobble; back faces drawn as the liquid top;
+fresnel rim/meniscus). Caustic light pools on the black marble floor. **Scroll: the notes arrive** — iris (`iris.glb`),
+bergamot (`bergamot.glb`), vanilla (`vanilla.glb`), oud (`oud.glb`) each float in beside the bottle in its own section, then
+dissolve into glowing golden particles (`sampleSurface`) that stream into the bottle, raising the liquid level.
+
+## Page sections
+Nav · Hero ("Nocturne No. 9 — iris, bergamot, vanilla, oud.") · Top / Heart / Base notes · The house (Grasse, since 1911) ·
+Discovery set & 50 ml (€290) · Footer.
+
+## Art direction
+Black, champagne gold `#d8b56a`, deep amber. Fonts: "Bodoni Moda"/"Italiana" + "Hanken Grotesk". Studio product lighting:
+strip softboxes giving long vertical highlights on the glass (studioEnvironment with tall panels).
+
+## Must be true
+Hero: the glass bottle with believable refraction, gold highlights and liquid; a frame where golden particles stream into it.
diff --git a/docs/briefs/racer.md b/docs/briefs/racer.md
new file mode 100644
index 0000000..943eda3
--- /dev/null
+++ b/docs/briefs/racer.md
@@ -0,0 +1,20 @@
+# 19 · Nightshift Motor Co. — "Rev a café racer in the rain"
+Brand: **Nightshift Motor Co.** — a custom motorcycle workshop building 12 café racers a year.
+
+## Signature interaction
+Midnight, rain, the bike (`models/racer/bike.glb`) under a flickering neon sign on wet asphalt (PlanarReflection with rain-ripple
+normal distortion; puddles). **Hold to rev**: hold mouse/space → RPM climbs on a big tachometer, WebAudio engine (twin-cylinder:
+pulse/saw oscillators at firing frequency + noise + distortion + low-pass tied to RPM; optional, mute toggle), the bike vibrates,
+exhaust heat haze (screen-space refraction), the headlight snaps on with a volumetric beam through the rain, neon buzzes brighter,
+rain streaks bend. Release → decel pops. Scroll: the camera circles the bike (slow turntable), then macro details (tank pinstripe,
+engine fins, leather seat) with depth of field. The helmet (`helmet.glb`) rests on a crate or the seat.
+
+## Page sections
+Nav · Hero ("Twelve bikes a year. This is number seven.") · Rev (interaction) · The build (tank, engine, seat, wheels with spec
+numbers) · Waitlist (2027 build slots, €5,000 deposit) · The garage (story) · Footer.
+
+## Art direction
+Wet black, neon red-magenta `#ff3b5c`, brass. Fonts: "Anton" + "Inter" + a neon-script accent. Blade Runner restraint, not cheesy.
+
+## Must be true
+Hero: the bike glistening with neon reflections on wet asphalt, rain streaks, headlight beam — like a car-ad still.
diff --git a/docs/briefs/sucre.md b/docs/briefs/sucre.md
new file mode 100644
index 0000000..948f95e
--- /dev/null
+++ b/docs/briefs/sucre.md
@@ -0,0 +1,24 @@
+# 09 · Maison Sucre — "A patisserie with gravity"
+Brand: **Maison Sucre** — a Parisian patisserie famous for its macarons.
+
+## Signature interaction
+Real physics (Rapier: `import RAPIER from '@dimforge/rapier3d-compat'; await RAPIER.init()`). Pastries rain onto a pale pink
+marble counter and pile up with believable bounces: pink & pistachio macarons (`models/sucre/macaron.glb`, `macaron2.glb`),
+strawberries (`strawberry.glb`), croissants (`croissant.glb`), tarts (`tart.glb`). InstancedMesh per type, simplified
+colliders (cylinder for macarons, ball for strawberries, capsule/convex hull for croissants). **The cursor is a kinematic body
+that nudges them** (an invisible sphere following the pointer on the counter plane); click-drag picks one up (spring) and you
+can toss it. "Build a box": drop 6 macarons into a gift box (procedural box with slots) — filled slots snap and the box closes
+with a ribbon when full (counter + CTA "Order this box — €24"). The hero centrepiece: the tiered cake (`cake.glb`) slowly
+turning on its stand, lit like a magazine cover.
+
+## Page sections
+Nav · Hero ("Sugar, almonds, and a little gravity.") · La Carte (menu; hovering an item makes it hop on the counter) ·
+Build a box (interactive) · L'Atelier (story, since 1962, rue du Bac) · Visit (hours, address) · Footer.
+
+## Art direction
+Pastel pink `#f6d9df`, pistachio, cream, gold foil. Fonts: "Playfair Display" italic + "DM Sans". Soft daylight, soft shadows,
+subtle depth of field. Joyful, tactile, pristine.
+
+## Must be true
+A frame with a delightful pile of photoreal macarons and strawberries on marble, mid-bounce, that makes you hungry.
+Keep 60 fps: ≤120 bodies; simplify meshes if needed (`node scripts/optimize.mjs assets/raw/sucre-x.glb public/models/sucre/x-lo.glb --ratio 0.3 --tex 1024`).
diff --git a/docs/briefs/terrarium.md b/docs/briefs/terrarium.md
new file mode 100644
index 0000000..fe414a1
--- /dev/null
+++ b/docs/briefs/terrarium.md
@@ -0,0 +1,24 @@
+# 04 · Bell & Moss — "Wipe the glass. Meet the world inside."
+Brand: **Bell & Moss** — a London studio building sealed glass-cloche terrariums that live for decades without watering.
+
+## Signature interaction
+A hand-blown glass cloche (procedural LatheGeometry bell with a knob; MeshPhysicalMaterial transmission, thickness, ior 1.5,
+slight dispersion) covers a living miniature world. **The inside of the glass is fogged with condensation and the cursor
+wipes it clear**: raycast the cloche, paint the hit UVs into a canvas/render-target mask; the mask drives glass roughness
+and a milky condensation tint (fogged = frosted, wiped = crystal clear) plus a droplet normal map; the fog slowly re-forms
+over ~8 s; droplets bead at wiped edges and run down. It must be obvious and satisfying.
+- **Three climates**: moss forest (`models/terrarium/moss.glb`), desert (`desert.glb`), tropical (`tropic.glb`). Switching lifts
+ the cloche (animated), the walnut base turns, the world swaps, the cloche descends and fogs over again.
+- Tiny floating spores/fireflies inside; soft window light from the left with a real shadow, gentle AO.
+
+## Page sections
+Nav · Hero ("A whole climate under glass. Water it once, in 2031.") · Climates (3 tabs driving the 3D) · "Inside the glass":
+exploded layer diagram — on scroll the world lifts and procedural layers separate below it (drainage stones, charcoal, mesh,
+soil, moss) with labels · Care ("Light: bright, indirect. Water: never.") · Shop (3 terrariums £240–£680) · Footer.
+
+## Art direction
+Warm linen `#efe9dd`, sage and moss greens, walnut. Fonts: "Fraunces" (soft serif display) + "Manrope".
+Soft, calm, tactile — the opposite of the dark pages.
+
+## Must be true
+A frame showing a fogged cloche with one clear wiped streak revealing the moss world is the hero shot.
diff --git a/docs/briefs/velocity.md b/docs/briefs/velocity.md
new file mode 100644
index 0000000..63e58fd
--- /dev/null
+++ b/docs/briefs/velocity.md
@@ -0,0 +1,22 @@
+# 07 · Velocity Lab — "See through the shoe"
+Brand: **Velocity Lab** — launch page for the VX-1 Carbon, a carbon-plated racing trainer.
+
+## Signature interaction
+**The X-ray lens.** A circular lens follows the cursor. Outside the lens the shoe (`models/velocity/white.glb`) renders as a
+premium product shot; inside it renders in an alternate mode. Render the scene twice (normal + alternate materials) into
+render targets and composite with a circular mask with a refractive rim (slight distortion, chromatic fringe, thin bright ring).
+Modes (click or keys 1–3, label on the lens): X-RAY (fresnel-glow translucent shell + procedural internals: the carbon plate
+as a curved glowing sheet, foam cells as a noise lattice), THERMAL (heat-map palette from a pressure field on the sole),
+CAD (clean edges + measurements). Scroll rotates and repositions the shoe through tech callouts (leader lines from 3D anchor
+points to labels). Colourway switch white ↔ black (`black.glb`) via a noise dissolve with a hot glowing edge.
+
+## Page sections
+Nav · Hero ("VX-1 Carbon. 186 grams of unfair advantage.") · Lens exploration · Tech (Plate / Foam / Upper, each a camera move
++ stats: 38 mm stack, 8 mm drop, 186 g) · Colourways · Drop countdown with live timer + CTA · Footer.
+
+## Art direction
+Clinical lab white `#f2f3f5`, graphite, volt/orange accents; precise grid, measurement ticks, monospace captions.
+Fonts: "Archivo" (expanded display) + "JetBrains Mono". Studio floor with soft planar reflection.
+
+## Must be true
+Hero shows the lens mid-shoe revealing the glowing carbon plate inside a product-shot shoe. Nike/On-level launch work.
diff --git a/docs/media/abyssal.jpg b/docs/media/abyssal.jpg
new file mode 100644
index 0000000..80b7831
Binary files /dev/null and b/docs/media/abyssal.jpg differ
diff --git a/docs/media/all-1.jpg b/docs/media/all-1.jpg
new file mode 100644
index 0000000..e0c9c5e
Binary files /dev/null and b/docs/media/all-1.jpg differ
diff --git a/docs/media/all-2.jpg b/docs/media/all-2.jpg
new file mode 100644
index 0000000..57612da
Binary files /dev/null and b/docs/media/all-2.jpg differ
diff --git a/docs/media/florae.jpg b/docs/media/florae.jpg
new file mode 100644
index 0000000..9e7bd5a
Binary files /dev/null and b/docs/media/florae.jpg differ
diff --git a/docs/media/hangar.jpg b/docs/media/hangar.jpg
new file mode 100644
index 0000000..7213afc
Binary files /dev/null and b/docs/media/hangar.jpg differ
diff --git a/docs/media/keeper.jpg b/docs/media/keeper.jpg
new file mode 100644
index 0000000..7bbc0c8
Binary files /dev/null and b/docs/media/keeper.jpg differ
diff --git a/docs/media/koi.jpg b/docs/media/koi.jpg
new file mode 100644
index 0000000..551cd46
Binary files /dev/null and b/docs/media/koi.jpg differ
diff --git a/docs/media/lithos.jpg b/docs/media/lithos.jpg
new file mode 100644
index 0000000..af847d8
Binary files /dev/null and b/docs/media/lithos.jpg differ
diff --git a/docs/media/monolith.jpg b/docs/media/monolith.jpg
new file mode 100644
index 0000000..74b345e
Binary files /dev/null and b/docs/media/monolith.jpg differ
diff --git a/docs/media/nocturne.jpg b/docs/media/nocturne.jpg
new file mode 100644
index 0000000..22eb59c
Binary files /dev/null and b/docs/media/nocturne.jpg differ
diff --git a/docs/media/racer.jpg b/docs/media/racer.jpg
new file mode 100644
index 0000000..bae293c
Binary files /dev/null and b/docs/media/racer.jpg differ
diff --git a/docs/media/reliquary.jpg b/docs/media/reliquary.jpg
new file mode 100644
index 0000000..563aa7a
Binary files /dev/null and b/docs/media/reliquary.jpg differ
diff --git a/docs/media/sucre.jpg b/docs/media/sucre.jpg
new file mode 100644
index 0000000..57e973a
Binary files /dev/null and b/docs/media/sucre.jpg differ
diff --git a/docs/media/velocity.jpg b/docs/media/velocity.jpg
new file mode 100644
index 0000000..b25bc31
Binary files /dev/null and b/docs/media/velocity.jpg differ
diff --git a/examples/_viewer/index.html b/examples/_viewer/index.html
new file mode 100644
index 0000000..f878138
--- /dev/null
+++ b/examples/_viewer/index.html
@@ -0,0 +1,5 @@
+<!doctype html>
+<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
+<title>Model Viewer</title>
+<style>html,body{margin:0;height:100%;background:#0b0b0d;color:#ccc;font:12px ui-monospace,monospace}canvas{display:block;width:100vw;height:100vh}#i{position:fixed;left:12px;top:10px}</style>
+</head><body><canvas id="c"></canvas><div id="i"></div><script type="module" src="./main.js"></script></body></html>
diff --git a/examples/_viewer/main.js b/examples/_viewer/main.js
new file mode 100644
index 0000000..de29e74
--- /dev/null
+++ b/examples/_viewer/main.js
@@ -0,0 +1,25 @@
+import { Engine, THREE, studioEnvironment, normalize, prepModel } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+const q = new URLSearchParams(location.search);
+const eng = new Engine({ canvas: document.getElementById('c'), background: 0x0b0b0d, post: { bloom: { intensity: 0.3 }, noise: 0.02 } });
+const { scene, camera, renderer } = eng;
+scene.environment = studioEnvironment(renderer);
+scene.environmentIntensity = +(q.get('env') ?? 1);
+const key = new THREE.DirectionalLight(0xffffff, +(q.get('key') ?? 2.5));
+key.position.set(3, 5, 4); key.castShadow = true; key.shadow.mapSize.set(2048, 2048);
+key.shadow.camera.left = key.shadow.camera.bottom = -2; key.shadow.camera.right = key.shadow.camera.top = 2; key.shadow.bias = -0.0005;
+scene.add(key);
+const floor = new THREE.Mesh(new THREE.CircleGeometry(4, 64), new THREE.MeshStandardMaterial({ color: 0x151517, roughness: 0.9 }));
+floor.rotation.x = -Math.PI / 2; floor.receiveShadow = true; scene.add(floor);
+const assets = new Assets();
+const g = await assets.gltf(q.get('m'));
+const m = g.scene; normalize(m, 2); prepModel(m, renderer); scene.add(m);
+const rot = +(q.get('rot') ?? 0) * Math.PI / 180;
+m.rotation.y = rot;
+const dist = +(q.get('d') ?? 4.2);
+camera.position.set(0, +(q.get('h') ?? 1.4), dist); camera.lookAt(0, 0.9, 0);
+let tris = 0; m.traverse(o => { if (o.isMesh) tris += o.geometry.index.count / 3; });
+document.getElementById('i').textContent = `${q.get('m')} — ${Math.round(tris)} tris`;
+if (q.get('spin')) eng.onTick(dt => { m.rotation.y += dt * 0.4; });
+if (q.get('wire')) m.traverse(o => { if (o.isMesh) o.material = new THREE.MeshStandardMaterial({ color: 0x999999, roughness: 0.6, flatShading: false }); });
+eng.start();
diff --git a/examples/abyssal/beams.js b/examples/abyssal/beams.js
new file mode 100644
index 0000000..f3a5b44
--- /dev/null
+++ b/examples/abyssal/beams.js
@@ -0,0 +1,129 @@
+// Abyssal's floodlight beams: a fork of src/core/volumetric.js tuned for submersible LED arrays.
+// Same raymarch (stops at scene depth), but with a hot axial core, a crisp cone edge, a bright throat near
+// the lamp that falls off with distance, and more steps so the edge doesn't dissolve into jitter.
+import * as THREE from 'three';
+import { Effect, EffectAttribute, BlendFunction } from 'postprocessing';
+
+const frag = /* glsl */`
+uniform mat4 uProjInv;
+uniform mat4 uCamWorld;
+uniform vec3 uCamPos;
+uniform int uCount;
+uniform vec3 uLPos[4];
+uniform vec3 uLDir[4];
+uniform vec3 uLCol[4];
+uniform vec2 uLCone[4];
+uniform float uLRange[4];
+uniform float uDensity;
+uniform float uTime;
+uniform float uNoise;
+uniform float uNoiseScale;
+uniform float uMaxDist;
+uniform vec3 uWind;
+uniform float uFloorY;
+
+float vhash(vec3 p){ p = fract(p * 0.3183099 + .1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
+float vnoise(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(vhash(i), vhash(i + vec3(1,0,0)), f.x), mix(vhash(i + vec3(0,1,0)), vhash(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(vhash(i + vec3(0,0,1)), vhash(i + vec3(1,0,1)), f.x), mix(vhash(i + vec3(0,1,1)), vhash(i + vec3(1,1,1)), f.x), f.y), f.z);
+}
+
+void mainImage(const in vec4 inputColor, const in vec2 uv, const in float depth, out vec4 outputColor) {
+ vec4 clip = vec4(uv * 2. - 1., depth * 2. - 1., 1.);
+ vec4 vp = uProjInv * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vec4(vp.xyz, 1.)).xyz;
+ vec3 ro = uCamPos;
+ vec3 rd = wp - ro;
+ float len = min(length(rd), uMaxDist);
+ rd = normalize(rd);
+ const int STEPS = 48;
+ float stepL = len / float(STEPS);
+ float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
+ vec3 acc = vec3(0.);
+ for (int i = 0; i < STEPS; i++) {
+ float t = (float(i) + jitter) * stepL;
+ vec3 p = ro + rd * t;
+ vec3 q = p * uNoiseScale + uWind * uTime;
+ float n = vnoise(q) * 0.65 + vnoise(q * 2.7 + 7.1) * 0.35;
+ float dens = uDensity * mix(1.0, n * n * 2.4, uNoise) * smoothstep(uFloorY - 0.2, uFloorY + 0.6, p.y);
+ for (int l = 0; l < 4; l++) {
+ if (l >= uCount) break;
+ vec3 d = p - uLPos[l];
+ float dist = max(length(d), 1e-3);
+ float c = dot(d / dist, uLDir[l]);
+ float edge = smoothstep(uLCone[l].x, uLCone[l].y, c);
+ // 0 at the rim, 1 on the axis: a hot core that makes the cone read even at low density.
+ float axial = clamp((c - uLCone[l].x) / max(1.0 - uLCone[l].x, 1e-4), 0.0, 1.0);
+ float core = 0.28 + 0.72 * pow(axial, 3.0) + 2.2 * pow(axial, 14.0);
+ // Bright throat at the lamp, then inverse-square-ish falloff into the dark.
+ float att = (1.0 / (1.0 + dist * dist * uLRange[l])) * (0.55 + 2.4 * exp(-dist * 0.45));
+ acc += uLCol[l] * edge * core * att * dens * stepL;
+ }
+ }
+ outputColor = vec4(inputColor.rgb + acc, inputColor.a);
+}`;
+
+export class FloodBeamEffect extends Effect {
+ constructor(camera, { density = 0.08, noise = 0.8, noiseScale = 1.4, maxDist = 30, wind = new THREE.Vector3(0.02, 0.05, 0.01), floorY = -100 } = {}) {
+ const vec3s = () => [0, 1, 2, 3].map(() => new THREE.Vector3());
+ super('FloodBeamEffect', frag, {
+ attributes: EffectAttribute.DEPTH,
+ blendFunction: BlendFunction.NORMAL,
+ uniforms: new Map([
+ ['uProjInv', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamWorld', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamPos', new THREE.Uniform(new THREE.Vector3())],
+ ['uCount', new THREE.Uniform(0)],
+ ['uLPos', new THREE.Uniform(vec3s())],
+ ['uLDir', new THREE.Uniform(vec3s())],
+ ['uLCol', new THREE.Uniform(vec3s())],
+ ['uLCone', new THREE.Uniform([0, 1, 2, 3].map(() => new THREE.Vector2(0.9, 0.95)))],
+ ['uLRange', new THREE.Uniform([0.05, 0.05, 0.05, 0.05])],
+ ['uDensity', new THREE.Uniform(density)],
+ ['uTime', new THREE.Uniform(0)],
+ ['uNoise', new THREE.Uniform(noise)],
+ ['uNoiseScale', new THREE.Uniform(noiseScale)],
+ ['uMaxDist', new THREE.Uniform(maxDist)],
+ ['uWind', new THREE.Uniform(wind)],
+ ['uFloorY', new THREE.Uniform(floorY)],
+ ]),
+ });
+ this.camera = camera;
+ this.lights = [];
+ this._d = new THREE.Vector3();
+ this._p = new THREE.Vector3();
+ }
+
+ /** Track a THREE.SpotLight. `scale` multiplies its colour*intensity into the fog; `range` is quadratic falloff. */
+ add(light, { scale = 0.02, range = 0.04, softness = 0.12 } = {}) {
+ this.lights.push({ light, scale, range, softness });
+ return this;
+ }
+
+ update(renderer, inputBuffer, dt) {
+ const u = this.uniforms;
+ const cam = this.camera;
+ u.get('uProjInv').value.copy(cam.projectionMatrixInverse);
+ u.get('uCamWorld').value.copy(cam.matrixWorld);
+ u.get('uCamPos').value.setFromMatrixPosition(cam.matrixWorld);
+ u.get('uTime').value += dt;
+ const n = Math.min(4, this.lights.length);
+ u.get('uCount').value = n;
+ for (let i = 0; i < n; i++) {
+ const { light, scale, range, softness } = this.lights[i];
+ light.updateMatrixWorld();
+ light.target.updateMatrixWorld();
+ this._p.setFromMatrixPosition(light.matrixWorld);
+ this._d.setFromMatrixPosition(light.target.matrixWorld).sub(this._p).normalize();
+ u.get('uLPos').value[i].copy(this._p);
+ u.get('uLDir').value[i].copy(this._d);
+ const on = light.visible ? light.intensity * scale : 0;
+ u.get('uLCol').value[i].set(light.color.r * on, light.color.g * on, light.color.b * on);
+ const outer = Math.cos(light.angle);
+ const inner = Math.cos(light.angle * (1 - Math.max(light.penumbra, softness)));
+ u.get('uLCone').value[i].set(outer, inner);
+ u.get('uLRange').value[i] = range;
+ }
+ }
+}
diff --git a/examples/abyssal/hud.js b/examples/abyssal/hud.js
new file mode 100644
index 0000000..c714b6d
--- /dev/null
+++ b/examples/abyssal/hud.js
@@ -0,0 +1,86 @@
+// The instrument panel: an odometer-style depth readout that rolls like a mechanical counter,
+// environmental readouts, the rail marker and the dive log.
+const PLACES = 5; // 10,935 needs five digits
+
+export function odometer(el) {
+ el.innerHTML = '';
+ const cols = [];
+ for (let k = PLACES - 1; k >= 0; k--) {
+ const c = document.createElement('span');
+ c.className = 'col';
+ const strip = document.createElement('span');
+ strip.innerHTML = '01234567890'.split('').map(d => `<i>${d}</i>`).join('');
+ c.appendChild(strip);
+ el.appendChild(c);
+ cols.push({ el: c, strip, k, last: -1, lead: null });
+ if (k === 3) { const s = document.createElement('span'); s.className = 'sep'; s.textContent = ','; el.appendChild(s); cols.sep = s; }
+ }
+ const unit = document.createElement('span');
+ unit.className = 'unit'; unit.textContent = 'm';
+ el.appendChild(unit);
+ return {
+ set(v) {
+ v = Math.max(0, v);
+ for (const c of cols) {
+ const p = 10 ** c.k;
+ let pos;
+ // Detent: each wheel rests on its digit and snaps over in the last third of a count, like a mechanical counter.
+ const snap = f => { const x = Math.min(1, Math.max(0, (f - 0.66) / 0.34)); return x * x * (3 - 2 * x); };
+ if (c.k === 0) pos = Math.floor(v) % 10 + snap(v % 1);
+ else {
+ const digit = Math.floor(v / p) % 10;
+ const lower = v % p;
+ // Carry: the digit rolls only while the digits below it pass from 9 to 0.
+ pos = digit + snap(Math.max(0, lower - (p - 1)));
+ }
+ const q = Math.round(pos * 1000) / 1000;
+ if (q !== c.last) { c.strip.style.transform = `translateY(${(-q).toFixed(3)}em)`; c.last = q; }
+ const lead = v < p && c.k > 0;
+ if (lead !== c.lead) { c.el.classList.toggle('lead', lead); c.lead = lead; }
+ }
+ cols.sep.classList.toggle('lead', v < 1000);
+ },
+ };
+}
+
+// Depth profile of the Mariana Trench water column (approximate, for the readouts).
+const TEMP = [[0, 27.2], [60, 26.4], [120, 23.5], [200, 19], [350, 11], [600, 6.5], [1000, 4.1], [2000, 2.2], [4000, 1.5], [6000, 1.55], [8000, 1.9], [10935, 2.4]];
+export function tempAt(d) {
+ for (let i = 1; i < TEMP.length; i++) {
+ if (d <= TEMP[i][0]) { const [a, ta] = TEMP[i - 1], [b, tb] = TEMP[i]; return ta + (tb - ta) * (d - a) / (b - a); }
+ }
+ return 2.4;
+}
+export const pressureAt = d => 1 + d / 10.08;
+export const lightAt = d => 100 * Math.exp(-0.023 * d);
+export function fmtLight(l) {
+ if (l >= 10) return l.toFixed(0);
+ if (l >= 0.1) return l.toFixed(1);
+ if (l < 1e-12) return '0.0';
+ const e = Math.floor(Math.log10(l));
+ return `${(l / 10 ** e).toFixed(1)}e${e}`;
+}
+export function fmtTime(s) {
+ const h = Math.floor(s / 3600), m = Math.floor(s / 60) % 60, sec = Math.floor(s) % 60;
+ return `T+ ${h}:${String(m).padStart(2, '0')}:${String(sec).padStart(2, '0')}`;
+}
+export function zoneAt(d) {
+ if (d < 200) return 'Epipelagic';
+ if (d < 1000) return 'Mesopelagic';
+ if (d < 4000) return 'Bathypelagic';
+ if (d < 6000) return 'Abyssopelagic';
+ if (d < 10900) return 'Hadopelagic';
+ return 'Challenger Deep';
+}
+
+export const LOG = [
+ [0, '06:40', 'Released from the A-frame. Vents open.'],
+ [45, '06:41', 'Support ship’s hull out of sight'],
+ [200, '06:43', 'Red wavelengths gone. Hull reads grey.'],
+ [750, '06:52', 'Floodlights on'],
+ [1000, '06:57', 'Sunlight: none detected'],
+ [2300, '07:18', 'Sonar contact, bearing 040'],
+ [4900, '08:02', 'Plume detected. Vent fluid 380 °C'],
+ [6000, '08:20', 'Entering the trench'],
+ [10900, '09:42', 'Touchdown. Challenger Deep.'],
+];
diff --git a/examples/abyssal/index.html b/examples/abyssal/index.html
new file mode 100644
index 0000000..0cc37e0
--- /dev/null
+++ b/examples/abyssal/index.html
@@ -0,0 +1,249 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Abyssal — Descend eleven thousand metres</title>
+ <meta name="description" content="A private deep-ocean expedition house. Three guests per dive to the bottom of the Challenger Deep in the titanium submersible Pelagia.">
+ <meta name="theme-color" content="#02070c">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=Space+Grotesk:wght@300;400;500;600&display=swap" rel="stylesheet">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 28 28%22%3E%3Crect width=%2228%22 height=%2228%22 rx=%226%22 fill=%22%2302070c%22/%3E%3Ccircle cx=%2214%22 cy=%2210%22 r=%225.5%22 fill=%22none%22 stroke=%22%233fd6c9%22 stroke-width=%221.6%22/%3E%3Cpath d=%22M14 15.5V22%22 stroke=%22%233fd6c9%22 stroke-width=%221.6%22/%3E%3Ccircle cx=%2214%22 cy=%2223.2%22 r=%221.6%22 fill=%22%233fd6c9%22/%3E%3C/svg%3E">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="scope" aria-hidden="true">
+ <i class="scope-sweep"></i><i class="scope-ring r1"></i><i class="scope-ring r2"></i><i class="scope-ring r3"></i>
+ <b class="scope-blip"></b>
+ <span class="scope-pct"><em>000</em>%</span>
+ </div>
+ <p class="loader-title mono">Pelagia · pre-dive checks</p>
+ <ol class="checks mono">
+ <li data-at="0.18"><span>Ballast trim</span><b>—</b></li>
+ <li data-at="0.42"><span>Life support · 16 h</span><b>—</b></li>
+ <li data-at="0.66"><span>Floodlight array</span><b>—</b></li>
+ <li data-at="0.9"><span>Surface acoustic link</span><b>—</b></li>
+ </ol>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Abyssal home">
+ <svg viewBox="0 0 28 28" aria-hidden="true"><circle cx="14" cy="9" r="6.2" fill="none" stroke="currentColor" stroke-width="1.3"/><path d="M14 15.2V24" stroke="currentColor" stroke-width="1.3"/><circle cx="14" cy="25.2" r="1.5" fill="currentColor"/><path d="M8.6 9h10.8" stroke="currentColor" stroke-width="1" opacity=".5"/></svg>
+ <span>Abyssal</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#dates">Dives</a>
+ <a href="#pelagia">Pelagia</a>
+ <a href="#twilight">Science</a>
+ <a href="#book">Book</a>
+ </nav>
+ <div class="nav-end">
+ <button class="sound mono" type="button" aria-pressed="false" data-cursor="link"><i></i><span>Sound off</span></button>
+ <a class="btn btn-solid" href="#book" data-magnetic>Reserve a seat</a>
+ </div>
+ </header>
+
+ <!-- The instrument: travels down the rail as you descend -->
+ <aside class="gauge" aria-label="Depth gauge">
+ <div class="rail">
+ <ol class="rail-zones mono" aria-hidden="true">
+ <li style="--p:0"><span>Epipelagic</span><b>0</b></li>
+ <li style="--p:.2"><span>Mesopelagic</span><b>200</b></li>
+ <li style="--p:.4"><span>Bathypelagic</span><b>1,000</b></li>
+ <li style="--p:.6"><span>Abyssopelagic</span><b>4,000</b></li>
+ <li style="--p:.8"><span>Hadopelagic</span><b>6,000</b></li>
+ <li style="--p:1"><span>Challenger Deep</span><b>10,935</b></li>
+ </ol>
+ <div class="rail-fill"></div>
+ <div class="mark"><div class="mark-body">
+ <p class="mark-label mono"><span class="mark-zone">Epipelagic</span><span class="mark-time">T+ 0:00:00</span></p>
+ <div class="odo" aria-hidden="true"></div>
+ <p class="sr-only depth-sr" aria-live="off">0 metres</p>
+ <dl class="reads mono">
+ <div><dt>Temp</dt><dd><b class="r-temp">27.0</b> °C</dd></div>
+ <div><dt>Press</dt><dd><b class="r-press">1</b> atm</dd></div>
+ <div><dt>Light</dt><dd><b class="r-light">100</b> %</dd></div>
+ </dl>
+ </div></div>
+ </div>
+ </aside>
+
+ <ol class="divelog mono" aria-label="Dive log"></ol>
+ <div class="hint mono" aria-hidden="true"><span class="hint-a"><i class="chev"></i>Scroll to descend</span><span class="hint-b"><span class="hint-mouse"><kbd>Move</kbd> steer floodlights <kbd>Fast</kbd> stir plankton <kbd>Click</kbd> sonar ping</span><span class="hint-touch"><kbd>Drag</kbd> steer &amp; stir <kbd>Tap</kbd> sonar ping</span></span></div>
+ <div class="toast mono" role="status"></div>
+ <div class="tags" aria-hidden="true"></div>
+ <div class="hotspots" aria-hidden="true"></div>
+
+ <main>
+ <section class="stage hero" id="top" data-station="0">
+ <div class="hero-copy">
+ <p class="eyebrow mono">Challenger Deep · 11°22′N 142°35′E · three guests per dive</p>
+ <h1><span class="l"><span>The last unexplored</span></span> <span class="l"><span>place on Earth is</span></span> <span class="l"><span><em>11 km down.</em></span></span></h1>
+ <p class="sub">Abyssal takes three guests at a time to the deepest point of the ocean, in a titanium submersible built for nothing else. The round trip is nine hours. Four of them are spent on the floor.</p>
+ <div class="cta">
+ <a class="btn btn-solid" href="#book" data-magnetic>Reserve a seat</a>
+ <a class="btn btn-ghost" href="#sunlight" data-magnetic>Begin the descent <span aria-hidden="true">↓</span></a>
+ </div>
+ </div>
+ </section>
+
+ <section class="stage zone left" id="sunlight" data-station="1">
+ <article class="zone-card">
+ <header><span class="mono">Zone 01 / 05</span><span class="mono">0 — 200 m</span></header>
+ <h2>Sunlight <em>Epipelagic</em></h2>
+ <p class="lede">The first two hundred metres hold most of the ocean's life and all of its sunlight. Pelagia leaves the A-frame at 06:40 and falls through it in three minutes. Look up while you can: the surface is a moving ceiling of light, and you will not see anything like it for the next nine hours.</p>
+ <dl class="stats mono">
+ <div><dt>Temperature</dt><dd>27 → 19 °C</dd></div>
+ <div><dt>Pressure</dt><dd>1 → 21 atm</dd></div>
+ <div><dt>Light</dt><dd>100 → 1 %</dd></div>
+ <div><dt>Elapsed</dt><dd>0:00 → 0:03</dd></div>
+ </dl>
+ <p class="see"><span class="mono">You'll see</span>Chambered nautilus rising from their daytime depth, bait balls of bigeye scad, and caustics sliding over the hull.</p>
+ </article>
+ </section>
+
+ <section class="stage zone left" id="twilight" data-station="2">
+ <article class="zone-card">
+ <header><span class="mono">Zone 02 / 05</span><span class="mono">200 — 1,000 m</span></header>
+ <h2>Twilight <em>Mesopelagic</em></h2>
+ <p class="lede">Red is the first colour the water takes from you. By 300 m Pelagia's orange hull reads as wet slate; by 600 m everything is one shade of blue. This is where animals start making their own light. At 750 m the floodlights come on, and colour comes back with them.</p>
+ <dl class="stats mono">
+ <div><dt>Temperature</dt><dd>19 → 4 °C</dd></div>
+ <div><dt>Pressure</dt><dd>21 → 100 atm</dd></div>
+ <div><dt>Light</dt><dd>1 → 0 %, blue only</dd></div>
+ <div><dt>Elapsed</dt><dd>0:03 → 0:17</dd></div>
+ </dl>
+ <p class="see"><span class="mono">You'll see</span>Atolla and crown jellies pulsing blue alarms, lanternfish on their nightly climb, the last grey trace of the sun.</p>
+ </article>
+ </section>
+
+ <section class="stage zone left" id="midnight" data-station="3">
+ <article class="zone-card">
+ <header><span class="mono">Zone 03 / 05</span><span class="mono">1,000 — 4,000 m</span></header>
+ <h2>Midnight <em>Bathypelagic</em></h2>
+ <p class="lede">No sunlight has ever reached this water. The only light down here is made by the living, and most of it is bait. An anglerfish can wait months for a meal; she lets the lure do the hunting. Keep the floodlights moving. She is closer than she looks.</p>
+ <dl class="stats mono">
+ <div><dt>Temperature</dt><dd>4 → 1.5 °C</dd></div>
+ <div><dt>Pressure</dt><dd>100 → 398 atm</dd></div>
+ <div><dt>Light</dt><dd>None, ever</dd></div>
+ <div><dt>Elapsed</dt><dd>0:17 → 1:07</dd></div>
+ </dl>
+ <p class="see"><span class="mono">You'll see</span>Humpback anglerfish, vampire squid, and marine snow — the slow fall of everything that died above you.</p>
+ </article>
+ </section>
+
+ <section class="stage zone left" id="abyss" data-station="4">
+ <article class="zone-card">
+ <header><span class="mono">Zone 04 / 05</span><span class="mono">4,000 — 6,000 m</span></header>
+ <h2>Abyss <em>Abyssopelagic</em></h2>
+ <p class="lede">The abyssal plain looks empty until it doesn't. On the trench lip at 4,970 m a black smoker vents water at 380 °C, kept liquid by the pressure. Around it grow tube worms with no mouth and no gut, fed by bacteria that eat sulphur. Life, it turns out, never needed the sun.</p>
+ <dl class="stats mono">
+ <div><dt>Temperature</dt><dd>1.5 °C · vent 380 °C</dd></div>
+ <div><dt>Pressure</dt><dd>398 → 596 atm</dd></div>
+ <div><dt>Light</dt><dd>Vent glow only</dd></div>
+ <div><dt>Elapsed</dt><dd>1:07 → 1:40</dd></div>
+ </dl>
+ <p class="see"><span class="mono">You'll see</span>Giant tube worms, vent crabs, mussel beds, and water shimmering as it leaves the chimney.</p>
+ </article>
+ </section>
+
+ <section class="stage zone left" id="hadal" data-station="5">
+ <article class="zone-card">
+ <header><span class="mono">Zone 05 / 05</span><span class="mono">6,000 — 10,935 m</span></header>
+ <h2>Hadal <em>Hadopelagic</em></h2>
+ <p class="lede">Named for Hades. Until 2019, more people had walked on the Moon than had stood here. The pressure is over seven tonnes on every square inch of the sphere, and the silt is so fine it hangs in the lights like smoke. We touch down beside Beacon 07, still pinging on the spot where we first landed.</p>
+ <dl class="stats mono">
+ <div><dt>Temperature</dt><dd>1.5 → 2.4 °C</dd></div>
+ <div><dt>Pressure</dt><dd>596 → 1,086 atm</dd></div>
+ <div><dt>Bottom time</dt><dd>4 h</dd></div>
+ <div><dt>Elapsed</dt><dd>1:40 → 3:02</dd></div>
+ </dl>
+ <p class="see"><span class="mono">You'll see</span>Amphipods the length of your hand, sea cucumbers walking on the silt, and the deepest footprint on the planet: yours.</p>
+ </article>
+ </section>
+
+ <section class="stage pelagia" id="pelagia" data-station="6">
+ <div class="pelagia-copy">
+ <p class="eyebrow mono">The vessel</p>
+ <h2>Pelagia</h2>
+ <p class="lede">Four people, one titanium sphere, and a hull built around the idea that nothing should need to go right for you to come home.</p>
+ <dl class="specs mono">
+ <div><dt>Crew</dt><dd>1 pilot + 3 guests</dd></div>
+ <div><dt>Rated depth</dt><dd>11,000 m, full ocean</dd></div>
+ <div><dt>Descent</dt><dd>1.0 m/s · 3 h 02 min</dd></div>
+ <div><dt>Length / mass</dt><dd>4.6 m · 11.8 t</dd></div>
+ <div><dt>Dives completed</dt><dd>61</dd></div>
+ </dl>
+ <div class="hs-detail" aria-live="polite"><p class="mono"><span class="hs-d-num">01</span> · <span class="hs-d-sub"></span></p><h3 class="hs-d-title"></h3><p class="hs-d-text"></p></div>
+ </div>
+ </section>
+
+ <section class="stage book" id="book" data-station="7">
+ <div class="glass">
+ <p class="eyebrow mono">Expedition 2027</p>
+ <h2>One dive. Three seats. <em>Eleven kilometres.</em></h2>
+ <div class="price-row">
+ <div class="price">
+ <p class="mono">Per seat, all-inclusive from Guam</p>
+ <b>US$ 750,000</b>
+ </div>
+ <ul class="incl">
+ <li><span>Nine days aboard the support ship <i>Halcyon</i>, from Apra Harbor</span></li>
+ <li>Two training dives to 1,000 m before the full descent</li>
+ <li>Four hours on the floor of the Challenger Deep</li>
+ <li>Every external camera, in 8K, delivered on the voyage home</li>
+ <li>A vial of hadal silt, engraved with your coordinates</li>
+ </ul>
+ </div>
+ <table class="dates mono" id="dates">
+ <thead><tr><th>Window</th><th>Dates</th><th>Swell forecast</th><th>Seats</th></tr></thead>
+ <tbody>
+ <tr><td>CD-27·01</td><td>08 — 19 Feb 2027</td><td>0.8 m</td><td><span class="seats"><i class="on"></i><i></i><i></i></span> 1 left</td></tr>
+ <tr><td>CD-27·02</td><td>05 — 16 Apr 2027</td><td>1.1 m</td><td><span class="seats"><i class="on"></i><i class="on"></i><i class="on"></i></span> 3 left</td></tr>
+ <tr class="full"><td>CD-27·03</td><td>06 — 17 Dec 2027</td><td>1.4 m</td><td><span class="seats"><i></i><i></i><i></i></span> Waitlist</td></tr>
+ </tbody>
+ </table>
+ <div class="book-cta"><a class="btn btn-solid" href="#surface" data-magnetic>Request a seat</a><p class="mono">A refundable deposit of 10% holds your seat. Medical and a pool session in Guam are the only requirements.</p></div>
+ </div>
+ </section>
+
+ <section class="stage crew" id="crew" data-station="8">
+ <div class="glass">
+ <p class="eyebrow mono">Crew &amp; safety</p>
+ <h2>Every system has two backups. <em>The third is gravity.</em></h2>
+ <div class="crew-grid">
+ <article><span class="mono">Chief pilot</span><h3>Ines Marlow</h3><p>212 dives, 31 to full ocean depth. Twelve years in submarine rescue before this. Speaks very little on the way down, and all of it is useful.</p></article>
+ <article><span class="mono">Sphere &amp; systems</span><h3>Kenji Aoba</h3><p>Designed Pelagia's life-support loop and still inspects every O-ring on the sphere hatch himself, twice, with the ship's clocks stopped.</p></article>
+ <article><span class="mono">Hadal biologist</span><h3>Dr. Adaeze Okafor</h3><p>Has described four species of amphipod and will name, on the intercom, everything that moves in the lights. Bring questions.</p></article>
+ </div>
+ <ul class="safety mono">
+ <li><b>3</b><span>independent ways up: drop weights, jettisonable batteries, and a corrodible link that frees the ballast on its own after 24 h</span></li>
+ <li><b>96 h</b><span>of emergency life support behind the 16 h mission loop</span></li>
+ <li><b>2 min</b><span>between acoustic check-ins with the surface, the whole way down</span></li>
+ <li><b>61 / 0</b><span>dives completed / incidents</span></li>
+ </ul>
+ </div>
+ </section>
+
+ <footer class="stage foot" id="surface" data-station="9">
+ <div class="foot-inner">
+ <p class="eyebrow mono">10,935 m · 1,086 atm · you are here</p>
+ <h2 class="foot-title">Surface.</h2>
+ <button class="btn btn-solid ascend" type="button" data-magnetic>Begin the ascent <span aria-hidden="true">↑</span></button>
+ <div class="foot-cols mono">
+ <p>Abyssal Expeditions<br>Apra Harbor, Guam<br>[email protected]</p>
+ <p>Dive season: Dec — May<br>Next window: 08 Feb 2027</p>
+ <nav aria-label="Footer"><a href="#dates">Dives</a><a href="#pelagia">Pelagia</a><a href="#twilight">Science</a><a href="#book">Book</a></nav>
+ </div>
+ <p class="fine mono">A fictional expedition house · Part of Twenty Worlds</p>
+ </div>
+ </footer>
+ </main>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/abyssal/life.js b/examples/abyssal/life.js
new file mode 100644
index 0000000..12a2b6d
--- /dev/null
+++ b/examples/abyssal/life.js
@@ -0,0 +1,483 @@
+// Everything procedural that lives in the water column.
+import * as THREE from 'three';
+import { patchWater } from './ocean.js';
+
+const rnd = (a = 0, b = 1) => a + Math.random() * (b - a);
+
+// Floodlight cone test shared by particle shaders.
+const FLOOD_GLSL = /* glsl */`
+uniform vec3 uLPos[3]; uniform vec3 uLDir[3]; uniform float uLCos; uniform float uLPow;
+float floodAt(vec3 p) {
+ float l = 0.0;
+ for (int i = 0; i < 3; i++) {
+ vec3 d = p - uLPos[i]; float dd = length(d);
+ float c = smoothstep(uLCos, uLCos + 0.05, dot(d / max(dd, 1e-3), uLDir[i]));
+ l += c * smoothstep(0.4, 2.2, dd) / (1.0 + dd * dd * 0.018);
+ }
+ return l * uLPow;
+}`;
+export const floodUniforms = {
+ uLPos: { value: [new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()] },
+ uLDir: { value: [new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, 0, -1), new THREE.Vector3(0, 0, -1)] },
+ uLCos: { value: 0.95 },
+ uLPow: { value: 0 },
+};
+
+/** Marine snow: a box of flakes wrapped around the camera (or fixed, for silt). Lit by sun ambient + floodlights. */
+export function marineSnow({ count = 7000, box = 28, fixed = null, size = 1, color = new THREE.Color(0.8, 0.95, 1) } = {}) {
+ const pos = new Float32Array(count * 3), seed = new Float32Array(count);
+ for (let i = 0; i < count; i++) { pos[i * 3] = Math.random(); pos[i * 3 + 1] = Math.random(); pos[i * 3 + 2] = Math.random(); seed[i] = Math.random(); }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: {
+ ...floodUniforms,
+ uCam: { value: new THREE.Vector3() }, uBox: { value: fixed ? new THREE.Vector3(...fixed.size) : new THREE.Vector3(box, box, box) },
+ uCenter: { value: fixed ? new THREE.Vector3(...fixed.center) : new THREE.Vector3() }, uWrap: { value: fixed ? 0 : 1 },
+ uT: { value: 0 }, uStretch: { value: 0 }, uAmb: { value: 1 }, uAmbCol: { value: color.clone() }, uFogD: { value: 0.05 },
+ uDpr: { value: 1 }, uSize: { value: size }, uWarm: { value: 0 }, uFloodMul: { value: 1 },
+ },
+ vertexShader: /* glsl */`
+ attribute float seed;
+ uniform vec3 uCam, uBox, uCenter; uniform float uWrap, uT, uStretch, uAmb, uFogD, uDpr, uSize, uFloodMul;
+ ${FLOOD_GLSL}
+ varying float vA; varying float vS; varying float vF;
+ void main(){
+ vec3 p = position * uBox;
+ float t = uT;
+ p += vec3(sin(t * 0.13 + seed * 30.0) * 0.5, -t * (0.04 + seed * 0.05), cos(t * 0.11 + seed * 17.0) * 0.5);
+ if (uWrap > 0.5) p = mod(p - uCam + uBox * 0.5, uBox) - uBox * 0.5 + uCam;
+ else p = mod(p, uBox) - uBox * 0.5 + uCenter;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ float dist = max(-mv.z, 0.1);
+ float fl = floodAt(p);
+ vF = fl / (fl + uAmb + 1e-4);
+ vA = min(uAmb * 0.55 + fl * uFloodMul, 1.6) * (0.3 + 0.7 * fract(seed * 91.7)) * exp(-dist * uFogD) * smoothstep(0.4, 1.4, dist);
+ vS = uStretch;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = min((0.9 + seed * seed * 2.8) * uSize * uDpr * (7.0 / dist) * (1.0 + uStretch), 40.0);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uAmbCol; uniform float uWarm;
+ varying float vA; varying float vS; varying float vF;
+ void main(){
+ vec2 c = gl_PointCoord - 0.5;
+ c.x *= 1.0 + vS;
+ float a = smoothstep(0.5, 0.05, length(c));
+ vec3 col = mix(uAmbCol, mix(vec3(0.92, 0.97, 1.0), vec3(1.0, 0.8, 0.55), uWarm), vF);
+ gl_FragColor = vec4(col * a * vA, 1.0);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 5;
+ return { points: pts, mat };
+}
+
+/** Bioluminescent plankton trail + air bubbles, spawned along the pointer ray. Ring buffer on the GPU. */
+export function spawner(count = 4000) {
+ const pos = new Float32Array(count * 3), birth = new Float32Array(count).fill(-100), seed = new Float32Array(count), kind = new Float32Array(count);
+ for (let i = 0; i < count; i++) seed[i] = Math.random();
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('birth', new THREE.BufferAttribute(birth, 1));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ geo.setAttribute('kind', new THREE.BufferAttribute(kind, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uT: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: /* glsl */`
+ attribute float birth, seed, kind; uniform float uT, uDpr;
+ varying float vA; varying float vK; varying float vAge;
+ void main(){
+ float age = uT - birth;
+ float life = kind > 0.5 ? 3.2 : 2.6;
+ vec3 p = position;
+ if (kind > 0.5) {
+ p.y += age * (0.7 + seed * 0.8) + age * age * 0.12;
+ p.x += sin(age * 9.0 + seed * 40.0) * 0.04 * age;
+ p.z += cos(age * 8.0 + seed * 20.0) * 0.04 * age;
+ } else {
+ p += vec3(sin(seed * 60.0 + age * 0.9), 0.4 + sin(seed * 13.0 + age), cos(seed * 31.0 + age * 0.8)) * 0.06 * age;
+ }
+ float alive = step(0.0, age) * step(age, life);
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ float dist = max(-mv.z, 0.1);
+ if (kind > 0.5) vA = alive * smoothstep(0.0, 0.15, age) * smoothstep(life, life * 0.5, age) * 0.6;
+ else vA = alive * (smoothstep(0.0, 0.04, age) * exp(-age * 2.0) * 3.4 + exp(-age * 0.8) * 0.5 * smoothstep(life, life * 0.6, age)) * (0.75 + 0.25 * sin(age * 31.0 + seed * 90.0));
+ vK = kind; vAge = age;
+ gl_Position = projectionMatrix * mv;
+ float s = kind > 0.5 ? (1.5 + seed * 5.0) : (2.2 + seed * 3.2) * (1.0 + 1.5 * exp(-age * 5.0));
+ gl_PointSize = alive * min(s * uDpr * (6.0 / dist), 48.0);
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA; varying float vK; varying float vAge;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ vec3 col; float a;
+ if (vK > 0.5) {
+ a = smoothstep(0.5, 0.42, d) * (0.25 + smoothstep(0.3, 0.46, d) * 0.9) + smoothstep(0.2, 0.0, length(gl_PointCoord - vec2(0.36, 0.34))) * 0.8;
+ col = vec3(0.75, 0.95, 1.0);
+ } else {
+ a = smoothstep(0.5, 0.0, d); a *= a;
+ col = mix(vec3(0.8, 1.0, 1.0), mix(vec3(0.25, 0.84, 0.79), vec3(0.08, 0.35, 0.9), smoothstep(0.4, 2.2, vAge)), smoothstep(0.0, 0.25, vAge));
+ }
+ gl_FragColor = vec4(col * a * vA, 1.0);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 6;
+ let head = 0, dirty = false;
+ return {
+ points: pts, mat,
+ emit(x, y, z, t, k = 0) {
+ const i = head; head = (head + 1) % count;
+ pos[i * 3] = x; pos[i * 3 + 1] = y; pos[i * 3 + 2] = z; birth[i] = t; kind[i] = k; dirty = true;
+ },
+ flush() {
+ if (!dirty) return;
+ geo.attributes.position.needsUpdate = true; geo.attributes.birth.needsUpdate = true; geo.attributes.kind.needsUpdate = true;
+ dirty = false;
+ },
+ };
+}
+
+// ─── Jellyfish ───────────────────────────────────────────────────────────
+const bellGeo = (() => {
+ const pts = [];
+ for (let i = 0; i <= 28; i++) {
+ const a = i / 28, phi = a * 1.78;
+ const r = Math.sin(phi) * (1 + 0.06 * Math.sin(a * Math.PI)), y = Math.cos(phi) * 0.72 + (a > 0.85 ? -(a - 0.85) * 0.25 : 0);
+ pts.push(new THREE.Vector2(Math.max(r, 0.001), y));
+ }
+ return new THREE.LatheGeometry(pts, 64);
+})();
+const jellyBellMat = () => new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ uniforms: { uT: { value: 0 }, uPhase: { value: 0 }, uRate: { value: 1 }, uColA: { value: new THREE.Color() }, uColB: { value: new THREE.Color() }, uGlow: { value: 1 }, uFogD: { value: 0.05 } },
+ vertexShader: /* glsl */`
+ uniform float uT, uPhase, uRate;
+ varying vec3 vN; varying vec3 vV; varying vec2 vUv; varying float vPulse; varying float vDist;
+ float pulseAt(float t) { float s = fract(t); return smoothstep(0.0, 0.18, s) * (1.0 - smoothstep(0.18, 0.75, s)); }
+ void main(){
+ vec3 p = position;
+ float pu = pulseAt(uT * uRate + uPhase);
+ float along = uv.y;
+ float k = pu * 0.24 * smoothstep(0.15, 1.0, along);
+ p.xz *= 1.0 - k;
+ p.y += pu * 0.1 * along - k * 0.12;
+ float ang = atan(p.z, p.x);
+ p.xz *= 1.0 + 0.035 * sin(ang * 8.0 + uT * 1.3) * along;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vN = normalize(normalMatrix * normal); vV = -mv.xyz; vUv = uv; vPulse = pu; vDist = -mv.z;
+ gl_Position = projectionMatrix * mv;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uColA, uColB; uniform float uGlow, uFogD;
+ varying vec3 vN; varying vec3 vV; varying vec2 vUv; varying float vPulse; varying float vDist;
+ void main(){
+ float fres = pow(1.0 - abs(dot(normalize(vN), normalize(vV))), 2.2);
+ float ang = vUv.x * 6.28318;
+ float canal = smoothstep(0.9, 1.0, cos(ang * 8.0)) * smoothstep(0.08, 0.5, vUv.y) * 0.8;
+ float gon = smoothstep(0.55, 1.0, cos(ang * 4.0)) * smoothstep(0.1, 0.26, vUv.y) * smoothstep(0.5, 0.3, vUv.y);
+ float rim = smoothstep(0.82, 1.0, vUv.y);
+ float dots = smoothstep(0.8, 1.0, cos(ang * 32.0)) * smoothstep(0.9, 0.97, vUv.y) * smoothstep(1.0, 0.97, vUv.y);
+ vec3 col = uColA * (fres * 0.9 + rim * 0.9 + canal * 0.5 + 0.05) + uColB * (gon * 1.3 + dots * 5.0 * (0.4 + vPulse * 2.0));
+ col *= uGlow * (0.8 + vPulse * 0.8);
+ col *= exp(-vDist * uFogD);
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+});
+const tentacleMat = () => new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uT: { value: 0 }, uPhase: { value: 0 }, uRate: { value: 1 }, uColA: { value: new THREE.Color() }, uGlow: { value: 1 }, uLen: { value: 2.5 }, uFogD: { value: 0.05 } },
+ vertexShader: /* glsl */`
+ attribute float aT, aAng, aR;
+ uniform float uT, uPhase, uRate, uLen;
+ varying float vT; varying float vDist;
+ float pulseAt(float t) { float s = fract(t); return smoothstep(0.0, 0.18, s) * (1.0 - smoothstep(0.18, 0.75, s)); }
+ void main(){
+ float pu = pulseAt(uT * uRate + uPhase - aT * 0.35);
+ float r = aR * (1.0 - pu * 0.2);
+ vec3 p = vec3(cos(aAng) * r, -0.08 - aT * uLen * aR, sin(aAng) * r);
+ float sway = aT * aT;
+ p.x += sin(uT * 0.9 + aT * 5.0 + aAng * 3.0) * 0.18 * sway * uLen * 0.4;
+ p.z += cos(uT * 0.7 + aT * 4.0 + aAng * 2.0) * 0.18 * sway * uLen * 0.4;
+ p.xz *= 1.0 - aT * 0.5;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vT = aT; vDist = -mv.z;
+ gl_Position = projectionMatrix * mv;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uColA; uniform float uGlow, uFogD; varying float vT; varying float vDist;
+ void main(){ gl_FragColor = vec4(uColA * (1.0 - vT) * 0.7 * uGlow * exp(-vDist * uFogD), 1.0); }`,
+});
+function tentacleGeo(count, segs, spread = 0.92) {
+ const n = count * segs * 2;
+ const aT = new Float32Array(n), aAng = new Float32Array(n), aR = new Float32Array(n), pos = new Float32Array(n * 3);
+ let k = 0;
+ for (let c = 0; c < count; c++) {
+ const ang = (c / count) * Math.PI * 2 + rnd(-0.1, 0.1);
+ const r = c % 5 === 0 ? 0.25 : spread * rnd(0.9, 1.0); // a few oral arms from the centre
+ const len = c % 5 === 0 ? 0.55 : rnd(0.7, 1.15);
+ for (let s = 0; s < segs; s++) {
+ for (const e of [s, s + 1]) { aT[k] = (e / segs) * len; aAng[k] = ang; aR[k] = r; k++; }
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('aT', new THREE.BufferAttribute(aT, 1));
+ g.setAttribute('aAng', new THREE.BufferAttribute(aAng, 1));
+ g.setAttribute('aR', new THREE.BufferAttribute(aR, 1));
+ g.boundingSphere = new THREE.Sphere(new THREE.Vector3(), 10);
+ return g;
+}
+export function jellyfish({ scale = 1, colA = 0x7fe8ff, colB = 0xff4fa8, rate = 0.55, len = 3 } = {}) {
+ const g = new THREE.Group();
+ const bm = jellyBellMat();
+ bm.uniforms.uColA.value.set(colA); bm.uniforms.uColB.value.set(colB); bm.uniforms.uRate.value = rate; bm.uniforms.uPhase.value = Math.random();
+ const bell = new THREE.Mesh(bellGeo, bm);
+ const tm = tentacleMat();
+ tm.uniforms.uColA.value.set(colA); tm.uniforms.uRate.value = rate; tm.uniforms.uPhase.value = bm.uniforms.uPhase.value; tm.uniforms.uLen.value = len;
+ const tent = new THREE.LineSegments(tentacleGeo(30, 36), tm);
+ bell.renderOrder = 7; tent.renderOrder = 7;
+ g.add(tent, bell);
+ g.scale.setScalar(scale);
+ g.userData = { mats: [bm, tm], vel: rnd(0.04, 0.1), spin: rnd(-0.1, 0.1) };
+ return g;
+}
+
+// ─── A school of silver scad ────────────────────────────────────────────
+export function fishSchool(count = 280) {
+ const base = new THREE.SphereGeometry(1, 14, 8);
+ const p = base.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ let x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ const taper = x < 0 ? 1 + x * 0.72 : 1 - x * x * 0.25;
+ y *= 0.3 * taper; z *= 0.11 * taper;
+ p.setXYZ(i, x, y, z);
+ }
+ base.computeVertexNormals();
+ // Forked tail.
+ const tail = new THREE.BufferGeometry();
+ tail.setAttribute('position', new THREE.Float32BufferAttribute([-0.9, 0, 0, -1.35, 0.32, 0, -1.2, 0, 0, -0.9, 0, 0, -1.2, 0, 0, -1.35, -0.32, 0], 3));
+ tail.setAttribute('normal', new THREE.Float32BufferAttribute([0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1], 3));
+ tail.setAttribute('uv', new THREE.Float32BufferAttribute(new Array(12).fill(0.5), 2));
+ const geo = mergeSimple([base.toNonIndexed(), tail]);
+ const mat = new THREE.MeshStandardMaterial({ color: 0xd9e4e8, metalness: 0.92, roughness: 0.26, side: THREE.DoubleSide, envMapIntensity: 1.6 });
+ mat.name = 'fish';
+ patchWater(mat, {
+ extra(sh) {
+ sh.uniforms.uFishT = { value: 0 };
+ mat.userData.shader = sh;
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform float uFishT;\nvarying float vFy;')
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ float ph = float(gl_InstanceID) * 1.618;
+ float tailw = smoothstep(0.4, -1.3, position.x);
+ transformed.z += sin(uFishT * 11.0 + ph - position.x * 3.2) * 0.2 * tailw;
+ vFy = position.y;`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying float vFy;')
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ diffuseColor.rgb *= mix(vec3(0.16, 0.26, 0.3), vec3(1.0), smoothstep(0.12, -0.04, vFy));`);
+ },
+ });
+ const mesh = new THREE.InstancedMesh(geo, mat, count);
+ mesh.castShadow = true;
+ mesh.frustumCulled = false;
+ const fish = Array.from({ length: count }, () => ({ th: rnd(0, Math.PI * 2), dr: rnd(-1, 1) ** 3 * 1.6, dy: rnd(-1, 1) * 1.1, sp: rnd(0.85, 1.15), s: rnd(0.13, 0.19), wob: rnd(0, 10) }));
+ const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), v = new THREE.Vector3(), sc = new THREE.Vector3();
+ return {
+ mesh, mat,
+ update(t, center, R = 3.2) {
+ if (mat.userData.shader) mat.userData.shader.uniforms.uFishT.value = t;
+ for (let i = 0; i < count; i++) {
+ const f = fish[i];
+ const th = f.th + t * 0.3 * f.sp;
+ const r = R + f.dr + Math.sin(t * 0.4 + f.wob) * 0.3;
+ v.set(center.x + Math.cos(th) * r, center.y + f.dy + Math.sin(th * 2 + f.wob) * 0.35, center.z + Math.sin(th) * r * 0.75);
+ // heading: tangent of the ellipse (counter-clockwise when seen from above)
+ const tx = -Math.sin(th) * r, tz = Math.cos(th) * r * 0.75;
+ e.set(0, Math.atan2(-tz, tx), Math.cos(th * 2 + f.wob) * 0.25);
+ q.setFromEuler(e);
+ sc.setScalar(f.s);
+ m4.compose(v, q, sc);
+ mesh.setMatrixAt(i, m4);
+ }
+ mesh.instanceMatrix.needsUpdate = true;
+ },
+ };
+}
+function mergeSimple(geos) {
+ const attrs = ['position', 'normal', 'uv'];
+ const out = new THREE.BufferGeometry();
+ for (const a of attrs) {
+ const arrs = geos.map(g => g.attributes[a].array);
+ const len = arrs.reduce((s, x) => s + x.length, 0);
+ const buf = new Float32Array(len);
+ let o = 0; for (const x of arrs) { buf.set(x, o); o += x.length; }
+ out.setAttribute(a, new THREE.BufferAttribute(buf, geos[0].attributes[a].itemSize));
+ }
+ return out;
+}
+
+// ─── Hydrothermal vent: plume smoke, mineral sparks ─────────────────────
+export function ventPlume({ top, count = 900 }) {
+ const seed = new Float32Array(count * 3);
+ for (let i = 0; i < count * 3; i++) seed[i] = Math.random();
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3));
+ geo.setAttribute('sd', new THREE.BufferAttribute(seed, 3));
+ const common = {
+ uT: { value: 0 }, uTop: { value: top.clone() }, uDpr: { value: 1 }, uAmt: { value: 1 },
+ };
+ const smoke = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.NormalBlending,
+ uniforms: { ...common },
+ vertexShader: /* glsl */`
+ attribute vec3 sd; uniform float uT, uDpr; uniform vec3 uTop;
+ varying float vA; varying float vH;
+ void main(){
+ float ph = fract(uT * (0.05 + sd.x * 0.03) + sd.y);
+ float h = ph * 7.0;
+ float spread = 0.12 + h * 0.2;
+ float ang = sd.z * 6.2831 + uT * 0.2 + h * 0.6;
+ vec3 p = uTop + vec3(cos(ang) * spread * sd.x + sin(uT * 0.3 + h) * 0.25 * ph, h, sin(ang) * spread * sd.x);
+ p.x += h * h * 0.02;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vA = smoothstep(0.0, 0.06, ph) * (1.0 - ph);
+ vH = ph;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = min((50.0 + h * 50.0) * uDpr / -mv.z, 180.0);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform float uAmt; varying float vA; varying float vH;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ float a = smoothstep(0.5, 0.0, d);
+ vec3 col = mix(vec3(0.5, 0.2, 0.06), vec3(0.03, 0.028, 0.03), smoothstep(0.0, 0.35, vH));
+ gl_FragColor = vec4(col, a * vA * 0.32 * uAmt);
+ }`,
+ });
+ const sparks = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { ...common },
+ vertexShader: /* glsl */`
+ attribute vec3 sd; uniform float uT, uDpr; uniform vec3 uTop;
+ varying float vA; varying float vH;
+ void main(){
+ float ph = fract(uT * (0.08 + sd.x * 0.1) + sd.y);
+ float h = ph * (3.0 + sd.z * 4.0);
+ float ang = sd.z * 40.0 + uT * (0.5 + sd.x);
+ float r = (0.08 + h * 0.3) * sd.x;
+ vec3 p = uTop + vec3(cos(ang) * r, h - 0.3, sin(ang) * r);
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vA = smoothstep(0.0, 0.05, ph) * pow(1.0 - ph, 2.0) * (0.4 + 0.6 * sd.x);
+ vH = ph;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = min((1.5 + sd.z * 2.5) * uDpr * 6.0 / -mv.z, 20.0);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform float uAmt; varying float vA; varying float vH;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ float a = smoothstep(0.5, 0.0, d);
+ vec3 col = mix(vec3(1.0, 0.72, 0.35), vec3(1.0, 0.3, 0.06), vH) * 2.4;
+ gl_FragColor = vec4(col * a * vA * uAmt, 1.0);
+ }`,
+ });
+ const a = new THREE.Points(geo, smoke), b = new THREE.Points(geo, sparks);
+ a.frustumCulled = b.frustumCulled = false;
+ a.renderOrder = 8; b.renderOrder = 9;
+ return { smoke: a, sparks: b, mats: [smoke, sparks] };
+}
+
+// ─── Terrain: the abyssal shelf at the trench lip, the cliff, the hadal floor ─
+function hash(x, y) { const s = Math.sin(x * 127.1 + y * 311.7) * 43758.5453; return s - Math.floor(s); }
+function vnoise(x, y) {
+ const xi = Math.floor(x), yi = Math.floor(y), xf = x - xi, yf = y - yi;
+ const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf);
+ const a = hash(xi, yi), b = hash(xi + 1, yi), c = hash(xi, yi + 1), d = hash(xi + 1, yi + 1);
+ return a + (b - a) * u + (c - a) * v + (a - b - c + d) * u * v;
+}
+function fbm(x, y, oct = 5) { let s = 0, a = 0.5, f = 1; for (let i = 0; i < oct; i++) { s += a * vnoise(x * f, y * f); f *= 2.03; a *= 0.5; } return s; }
+
+export function terrain({ shelfY, floorY, edgeZ, w = 110, d = 110, seg = 260 }) {
+ const geo = new THREE.PlaneGeometry(w, d, seg, seg);
+ geo.rotateX(-Math.PI / 2);
+ const p = geo.attributes.position;
+ const col = new Float32Array(p.count * 3);
+ const heightAt = (x, z) => {
+ const edge = edgeZ + (fbm(x * 0.08, 3.1) - 0.5) * 7 + Math.sin(x * 0.11) * 2;
+ const t = smoothstepJS(edge - 5.5, edge + 4.5, z);
+ const shelf = shelfY + (fbm(x * 0.12, z * 0.12) - 0.5) * 1.6 + (fbm(x * 0.5, z * 0.5, 3) - 0.5) * 0.35;
+ const floor = floorY + (fbm(x * 0.05 + 7, z * 0.05) - 0.5) * 1.4 + Math.sin(x * 0.9 + z * 0.3) * 0.05;
+ // Cliff face: rough, ledged.
+ const ledges = (fbm(x * 0.35, z * 0.35 + 4) - 0.5) * 2.2 * Math.sin(t * Math.PI);
+ return shelf + (floor - shelf) * t + ledges;
+ };
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), z = p.getZ(i);
+ p.setY(i, heightAt(x, z));
+ }
+ geo.computeVertexNormals();
+ const n = geo.attributes.normal;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), z = p.getZ(i), y = p.getY(i);
+ const slope = 1 - n.getY(i);
+ const silt = smoothstepJS(0.35, 0.08, slope);
+ const blot = fbm(x * 0.3, z * 0.3, 4);
+ const deep = smoothstepJS(shelfY - 3, floorY + 2, y);
+ // Hadal silt is pale diatom ooze; the shelf is darker basalt with sediment dusting.
+ const sr = 0.30 + blot * 0.1, sg = 0.29 + blot * 0.09, sb = 0.26 + blot * 0.07;
+ const rr = 0.07 + blot * 0.05, rg = 0.066 + blot * 0.045, rb = 0.063 + blot * 0.04;
+ const k = silt * (0.55 + deep * 0.45);
+ col[i * 3] = rr + (sr - rr) * k; col[i * 3 + 1] = rg + (sg - rg) * k; col[i * 3 + 2] = rb + (sb - rb) * k;
+ }
+ geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ return { geo, heightAt };
+}
+export const smoothstepJS = (a, b, v) => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); };
+
+// ─── Beacon 07 on the trench floor ──────────────────────────────────────
+export function beacon() {
+ const g = new THREE.Group();
+ const metal = new THREE.MeshStandardMaterial({ color: 0x5b6266, metalness: 0.85, roughness: 0.42 });
+ const dark = new THREE.MeshStandardMaterial({ color: 0x15191b, metalness: 0.6, roughness: 0.5 });
+ const orange = new THREE.MeshStandardMaterial({ color: 0xff5a14, metalness: 0.0, roughness: 0.55 });
+ const glass = new THREE.MeshStandardMaterial({ color: 0x0b2224, emissive: new THREE.Color(0x3fd6c9), emissiveIntensity: 0, roughness: 0.15, metalness: 0 });
+ for (let i = 0; i < 3; i++) {
+ const a = (i / 3) * Math.PI * 2;
+ const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.024, 0.95, 8), metal);
+ leg.position.set(Math.cos(a) * 0.32, 0.42, Math.sin(a) * 0.32);
+ leg.lookAt(0, 0.95, 0); leg.rotateX(Math.PI / 2);
+ leg.castShadow = true;
+ g.add(leg);
+ const foot = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.08, 0.03, 12), dark);
+ foot.position.set(Math.cos(a) * 0.62, 0.015, Math.sin(a) * 0.62);
+ g.add(foot);
+ }
+ const body = new THREE.Mesh(new THREE.CylinderGeometry(0.1, 0.1, 0.62, 20), dark);
+ body.position.y = 0.95; body.castShadow = true; g.add(body);
+ const bands = new THREE.Mesh(new THREE.CylinderGeometry(0.104, 0.104, 0.05, 20), metal);
+ bands.position.y = 0.72; g.add(bands);
+ const b2 = bands.clone(); b2.position.y = 1.18; g.add(b2);
+ const lamp = new THREE.Mesh(new THREE.CylinderGeometry(0.075, 0.075, 0.14, 20), glass);
+ lamp.position.y = 1.33; g.add(lamp);
+ const cap = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.09, 0.03, 20), metal);
+ cap.position.y = 1.415; g.add(cap);
+ const mast = new THREE.Mesh(new THREE.CylinderGeometry(0.006, 0.006, 0.5, 6), metal);
+ mast.position.y = 1.66; g.add(mast);
+ const float = new THREE.Mesh(new THREE.SphereGeometry(0.2, 28, 18), orange);
+ float.position.set(0, 2.1, 0); float.castShadow = true; g.add(float);
+ const tether = new THREE.Mesh(new THREE.CylinderGeometry(0.004, 0.004, 0.3, 4), dark);
+ tether.position.y = 1.9; g.add(tether);
+ const light = new THREE.PointLight(0x5fe6da, 0, 7, 1.6);
+ light.position.y = 1.33;
+ for (const m of [metal, dark, orange]) patchWater(m, { caustics: false });
+ return { group: g, glass, light, float };
+}
diff --git a/examples/abyssal/main.js b/examples/abyssal/main.js
new file mode 100644
index 0000000..8126390
--- /dev/null
+++ b/examples/abyssal/main.js
@@ -0,0 +1,1073 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { FloodBeamEffect } from './beams.js';
+import { fbmNormal, fbmTexture } from '../../src/core/textures.js';
+import { AbyssEffect, waterSurface, waterDome, patchWater, waterUniforms } from './ocean.js';
+import { marineSnow, spawner, jellyfish, fishSchool, ventPlume, terrain, beacon, floodUniforms } from './life.js';
+import { odometer, tempAt, pressureAt, lightAt, fmtLight, fmtTime, zoneAt, LOG } from './hud.js';
+
+const DBG = new URLSearchParams(location.search);
+const V3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const rnd = (a = 0, b = 1) => a + Math.random() * (b - a);
+const MOBILE = matchMedia('(max-width: 900px)').matches;
+
+// ─── The water column ─────────────────────────────────────────────────────────
+// World y is linear in "station" s (one station per section); the gauge maps s to real depth.
+const STEP = 14, Y0 = -4;
+const descY = s => Y0 - STEP * clamp(s, 0, 5);
+const SHELF_Y = -62.6, FLOOR_Y = -76.6, EDGE_Z = -1.4;
+const DKEYS = [[0, 0], [0.5, 30], [1, 110], [1.5, 200], [2, 600], [2.5, 1000], [3, 2400], [3.5, 4000], [4, 4970], [4.5, 6000], [5, 10935]];
+function depthAt(s) {
+ if (s <= 0) return 0;
+ for (let i = 1; i < DKEYS.length; i++) if (s <= DKEYS[i][0]) {
+ const [a, da] = DKEYS[i - 1], [b, db] = DKEYS[i];
+ return da + (db - da) * (s - a) / (b - a);
+ }
+ return 10935;
+}
+const WATER = [[0, 0x2aa5b4], [50, 0x178aa3], [140, 0x0e6190], [240, 0x0a3f73], [450, 0x06214b], [700, 0x030d24], [1000, 0x01040b], [1800, 0x000103], [11000, 0x000000]]
+ .map(([d, c]) => [d, new THREE.Color(c)]);
+const waterCol = new THREE.Color();
+function waterAt(d, out) {
+ for (let i = 1; i < WATER.length; i++) if (d <= WATER[i][0]) {
+ const [a, ca] = WATER[i - 1], [b, cb] = WATER[i];
+ return out.copy(ca).lerp(cb, (d - a) / (b - a));
+ }
+ return out.set(0, 0, 0);
+}
+
+// Camera + submersible choreography. x/z are world, y is relative to descY(s).
+const D = Math.PI / 180;
+const STATIONS = [
+ { sub: [1.35, 0, 0], yaw: -2.5, cam: [-1.4, -1.7, 8.2], look: [0.05, 0.9, 0] }, // 0 hero
+ { sub: [2.4, 0.9, -3.2], yaw: -2.95, cam: [-1.0, 0.2, 8.6], look: [1.3, -0.1, 0.6] }, // 1 sunlight · nautilus
+ { sub: [1.6, 0, -0.5], yaw: -2.85, cam: [-1.6, 0.8, 9.2], look: [-0.4, 0, 0] }, // 2 twilight · jellies
+ { sub: [0.9, -1.4, 2.0], yaw: 0.62, cam: [3.0, 1.2, 12.4], look: [0.6, -0.1, -0.6] }, // 3 midnight · angler
+ { sub: [-1.5, -0.3, -0.6], yaw: 2.75, cam: [-7.6, 0.3, 8.8], look: [-3.3, -0.9, -2.8] }, // 4 abyss · vent
+ { sub: [1.4, -1.28, 5.0], yaw: 0.25, cam: [-2.6, -0.9, 13.2], look: [1.2, -1.9, 3.0] }, // 5 hadal · landing
+ { sub: [1.4, -1.28, 5.0], yaw: 0.25, orbit: true, look: [1.4, -1.3, 5.0] }, // 6 pelagia
+ { sub: [1.4, -1.28, 5.0], yaw: 0.25, cam: [-4.5, 5.2, 15.5], look: [-2.2, -1.8, 3.4] }, // 7 book
+ { sub: [1.4, -1.28, 5.0], yaw: 0.25, cam: [6.0, 1.4, 14.0], look: [-4.6, -1.4, 2.6] }, // 8 crew
+ { sub: [1.4, -1.28, 5.0], yaw: 0.25, cam: [-5.5, 0.2, 17.0], look: [-2.6, -0.2, 2.0] }, // 9 surface · beams point home
+];
+if (MOBILE) for (const st of STATIONS) { if (st.cam) { st.cam = [st.cam[0] * 1.1, st.cam[1], st.cam[2] * 1.3]; } }
+// Phones: lens-shift the frame so subjects sit in the upper half, above the copy.
+const LENS = MOBILE ? [0.13, 0.2] : [0, 0];
+function applyLens(cam, w, h, ly = LENS[1]) { if (LENS[0] || LENS[1]) cam.setViewOffset(w, h, w * LENS[0], h * ly, w, h); }
+let lensY = -1;
+
+// ─── Engine ─────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let vol, fx;
+const engine = new Engine({
+ canvas, fov: 40, near: 0.08, far: 260, dpr: 1.5, background: 0x2aa5b4,
+ post: {
+ ao: { aoRadius: 1.3, intensity: 1.9, distanceFalloff: 1.0 },
+ bloom: { intensity: 1.0, luminanceThreshold: 0.62, luminanceSmoothing: 0.32, radius: 0.82 },
+ pre: cam => {
+ vol = new FloodBeamEffect(cam, { density: 0.032, noise: 0.55, noiseScale: 0.7, maxDist: 36, floorY: -1000, wind: V3(0.02, 0.06, 0.01) });
+ fx = new AbyssEffect(cam);
+ return [...(DBG.has('novol') ? [] : [vol]), ...(DBG.has('nofx') ? [] : [fx])];
+ },
+ tone: DBG.get('tone') ?? 'aces',
+ vignette: { offset: 0.22, darkness: 0.72 },
+ noise: 0.055,
+ ca: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+const bloomLum = engine.post?.bloom?.luminanceMaterial ?? null;
+engine.onResize((w, h) => applyLens(camera, w, h));
+scene.background = new THREE.Color(0x2aa5b4);
+scene.fog = DBG.has('nofog') ? null : new THREE.FogExp2(0x2aa5b4, 0.028);
+const envShallow = studioEnvironment(renderer, {
+ top: 0x6fd9e4, bottom: 0x03141d,
+ panels: [{ pos: [0, 10, 0], size: [16, 16], intensity: 5, color: 0xe4fdff }, { pos: [-9, 3, 5], size: [5, 5], intensity: 0.7, color: 0x3fb8d0 }, { pos: [8, 1, -6], size: [3, 8], intensity: 0.5, color: 0x1f7fa8 }],
+});
+const envDeep = studioEnvironment(renderer, {
+ top: 0x1d4f9a, bottom: 0x010308,
+ panels: [{ pos: [0, 10, 0], size: [16, 16], intensity: 2.2, color: 0x5d8fff }],
+});
+const envFlood = studioEnvironment(renderer, {
+ top: 0x05070a, bottom: 0x000000,
+ panels: [{ pos: [0, 7, 6], size: [3, 1.2], intensity: 1.2, color: 0xe6f3ff }, { pos: [-6, 4, -2], size: [1.2, 4], intensity: 0.4, color: 0xbfe9ff }],
+});
+scene.environment = envShallow;
+
+const hemi = new THREE.HemisphereLight(0x9ae9f0, 0x06283a, 1.2);
+scene.add(hemi);
+const sun = new THREE.DirectionalLight(0xfff8ea, 3);
+sun.castShadow = true;
+sun.shadow.mapSize.set(2048, 2048);
+Object.assign(sun.shadow.camera, { left: -6, right: 6, top: 6, bottom: -6, near: 0.5, far: 40 });
+sun.shadow.bias = -0.0004; sun.shadow.normalBias = 0.03;
+scene.add(sun, sun.target);
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 6 });
+
+// ─── Loader ─────────────────────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+const pctEl = loaderEl.querySelector('.scope-pct em');
+const checks = [...loaderEl.querySelectorAll('.checks li')];
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ pctEl.textContent = String(Math.round(v * 100)).padStart(3, '0');
+ for (const li of checks) if (v >= +li.dataset.at && !li.classList.contains('ok')) { li.classList.add('ok'); li.querySelector('b').textContent = 'OK'; }
+ },
+});
+
+// ─── Surface, snow, plankton ───────────────────────────────────────────────
+const surface = waterSurface();
+scene.add(surface);
+const dome = waterDome();
+scene.add(dome);
+const domeTop = new THREE.Color(), domeBot = new THREE.Color();
+const snow = marineSnow({ count: MOBILE ? 3500 : 7500, box: 30 });
+scene.add(snow.points);
+const silt = marineSnow({ count: 1800, fixed: { center: [1.5, FLOOR_Y + 2.2, 3.5], size: [26, 4.4, 20] }, size: 1.3, color: new THREE.Color(0.7, 0.66, 0.6) });
+scene.add(silt.points);
+silt.mat.uniforms.uFloodMul.value = 0.45;
+const plankton = spawner(5000);
+scene.add(plankton.points);
+engine.onResize((w, h, dpr) => {
+ for (const m of [snow.mat, silt.mat, plankton.mat]) m.uniforms.uDpr.value = dpr;
+});
+
+// ─── Terrain ────────────────────────────────────────────────────────────────
+const ground = terrain({ shelfY: SHELF_Y, floorY: FLOOR_Y, edgeZ: EDGE_Z - 8, w: 120, d: 120, seg: MOBILE ? 180 : 280 });
+const groundN = fbmNormal(renderer, { size: 1024, scale: 8, octaves: 7, strength: 2.2 });
+const groundD = fbmTexture(renderer, { size: 512, scale: 6, octaves: 6, contrast: 1.6 });
+const groundMat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.93, metalness: 0, envMapIntensity: 0.3 });
+groundMat.name = 'ground';
+// Triplanar rock/silt: world-space projections so the cliff face never stretches.
+patchWater(groundMat, {
+ caustics: false,
+ extra(sh) {
+ sh.uniforms.uRockN = { value: groundN };
+ sh.uniforms.uRockD = { value: groundD };
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nuniform sampler2D uRockN, uRockD;')
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ vec3 tpN0 = normalize((vec4(normalize(vNormal), 0.0) * viewMatrix).xyz);
+ vec3 tpB = pow(abs(tpN0), vec3(4.0)); tpB /= dot(tpB, vec3(1.0));
+ float det = texture2D(uRockD, vCW.zy * 0.11).r * tpB.x + texture2D(uRockD, vCW.xz * 0.11).r * tpB.y + texture2D(uRockD, vCW.xy * 0.11).r * tpB.z;
+ float det2 = texture2D(uRockD, vCW.xz * 0.9).r;
+ diffuseColor.rgb *= (0.55 + det * 0.9) * (0.85 + det2 * 0.3);`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ vec3 wN = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ vec3 bw = pow(abs(wN), vec3(4.0)); bw /= dot(bw, vec3(1.0));
+ float sc = 0.42;
+ vec3 nx = texture2D(uRockN, vCW.zy * sc).xyz * 2.0 - 1.0;
+ vec3 ny = texture2D(uRockN, vCW.xz * sc).xyz * 2.0 - 1.0;
+ vec3 nz = texture2D(uRockN, vCW.xy * sc).xyz * 2.0 - 1.0;
+ nx = vec3(nx.xy + wN.zy, abs(nx.z) * wN.x);
+ ny = vec3(ny.xy + wN.xz, abs(ny.z) * wN.y);
+ nz = vec3(nz.xy + wN.xy, abs(nz.z) * wN.z);
+ vec3 wn = normalize(nx.zyx * bw.x + ny.xzy * bw.y + nz.xyz * bw.z);
+ normal = normalize((viewMatrix * vec4(wn, 0.0)).xyz);
+ }`);
+ },
+});
+const groundMesh = new THREE.Mesh(ground.geo, groundMat);
+groundMesh.position.set(0, 0, 8);
+groundMesh.receiveShadow = true;
+scene.add(groundMesh);
+const heightAt = (x, z) => ground.heightAt(x, z - 8);
+
+// ─── Submersible ────────────────────────────────────────────────────────────
+const SUB_L = 3.4;
+const sub = new THREE.Group();
+scene.add(sub);
+const subInner = new THREE.Group();
+sub.add(subInner);
+let subScale = 1, subModel = null, anglerModel = null;
+const toWorld = (model, raw, out) => (model ? model.localToWorld(out.copy(raw)) : out.copy(raw));
+const floodCol = new THREE.Color(0xe8f4ff);
+const lampGlow = { value: new THREE.Color(0, 0, 0) };
+const FLOOD_LOCAL = [V3(0.68, 0.33, -0.23), V3(0.68, 0.37, 0), V3(0.68, 0.33, 0.23)];
+const floods = FLOOD_LOCAL.map((p, i) => {
+ const L = new THREE.SpotLight(floodCol, 0, 34, 0.2, 0.24, 1.2);
+ L.castShadow = i === 1 && !DBG.has('noshadow');
+ L.shadow.mapSize.set(1024, 1024);
+ L.shadow.camera.near = 0.3; L.shadow.camera.far = 30;
+ L.shadow.bias = -0.0002; L.shadow.normalBias = 0.02;
+ scene.add(L, L.target);
+ return L;
+});
+for (const L of floods) vol.add(L, { scale: 0.012, range: 0.05, softness: 0.16 });
+const floodState = { power: 0, target: 0, on: false };
+const lampHalos = floods.map(() => { const h = makeGlowSprite(0xeaf6ff, 0.34); scene.add(h); return h; });
+const strobe = new THREE.PointLight(0xffffff, 0, 5, 2);
+scene.add(strobe);
+const strobeDot = makeGlowSprite(0xffffff, 0.22);
+scene.add(strobeDot);
+const fill = new THREE.DirectionalLight(0x3b6a9e, 0);
+scene.add(fill, fill.target);
+
+const subLoad = assets.gltf('models/abyssal/sub.glb').then(g => {
+ const m = g.scene;
+ normalize(m, SUB_L, { ground: false });
+ subScale = m.scale.x;
+ prepModel(m, renderer, {
+ env: 1.1,
+ onMat: mat => {
+ mat.name = 'sub';
+ patchWater(mat, { caustics: !DBG.has("nocaus"), glow: DBG.has("noglow") ? [] : [
+ // object-space (quantized) coordinates: model = obj * 0.9462 + offset
+ { center: V3(0.595, 0.357, -0.233), radius: 0.17, color: lampGlow, lum: 0.5 },
+ { center: V3(0.595, 0.357, 0.233), radius: 0.17, color: lampGlow, lum: 0.5 },
+ ] });
+ },
+ });
+ subInner.add(m);
+ subModel = m;
+});
+
+// ─── Creatures ──────────────────────────────────────────────────────────────
+const nautilus = new THREE.Group();
+scene.add(nautilus);
+const NAUT_BASE = V3(1.6, descY(1) - 0.35, 2.4);
+const nautLoad = assets.gltf('models/abyssal/nautilus.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 1.25, { ground: false });
+ prepModel(m, renderer, { env: 1.0, onMat: mat => { mat.name = 'naut'; patchWater(mat); } });
+ nautilus.add(m);
+});
+
+const school = fishSchool(MOBILE ? 160 : 300);
+scene.add(school.mesh);
+const SCHOOL_C = V3(5.5, descY(0.75), -10);
+
+// Placed in screen space from the twilight camera (x, y in 0..1, distance), so the card and gauge stay clear.
+const JELLIES = [
+ { at: [0.47, 0.24, 13], s: 0.55, a: 0x74e4ff, b: 0xff4f9a },
+ { at: [0.73, 0.2, 15], s: 0.42, a: 0x8f9cff, b: 0x3fffd8 },
+ { at: [0.57, 0.8, 7.5], s: 0.3, a: 0x7fe8ff, b: 0xff6ab0, light: true },
+ { at: [0.69, 0.68, 10], s: 0.46, a: 0x5fd8ff, b: 0xff4f7a, light: true },
+ { at: [0.63, 0.3, 27], s: 0.8, a: 0x6fa8ff, b: 0x40ffe0 },
+ { at: [0.62, 0.06, 11], s: 0.26, a: 0x9ff2ff, b: 0xff7ac0 },
+ { at: [0.42, 0.7, 12], s: 0.4, a: 0x74e4ff, b: 0xb06bff },
+ { at: [0.68, 0.97, 14], s: 0.36, a: 0x8fe0ff, b: 0xff4f9a },
+ { at: [0.54, -0.3, 13], s: 0.5, a: 0x6fd0ff, b: 0x3fffd8 },
+ { at: [0.36, -0.1, 20], s: 0.34, a: 0x9ff2ff, b: 0xff7ac0 },
+ { at: [0.84, 0.88, 18], s: 0.3, a: 0x74e4ff, b: 0x40ffe0 },
+];
+const jellies = JELLIES.map(j => {
+ const g = jellyfish({ scale: j.s, colA: j.a, colB: j.b, rate: rnd(0.4, 0.62), len: rnd(2.4, 3.6) });
+ g.userData.base = V3(0, descY(2), 0);
+ g.userData.at = j.at;
+ g.userData.off = rnd(0, 20);
+ // Lights live in the scene root and never toggle visibility: a changing light count recompiles every material.
+ if (j.light) { const l = new THREE.PointLight(j.a, 0, 5, 1.8); scene.add(l); g.userData.light = l; }
+ scene.add(g);
+ return g;
+});
+
+const angler = new THREE.Group();
+const anglerInner = new THREE.Group();
+angler.add(anglerInner);
+scene.add(angler);
+const ANGLER_BASE = V3(3.3, descY(3) + 0.5, -0.6); // re-placed from screen space at boot
+angler.position.copy(ANGLER_BASE);
+const lureCol = { value: new THREE.Color(0, 0, 0) };
+const LURE_RAW = V3(0.007, 0.478, 0.919); // model space
+const LURE_OBJ = V3(0.008, 0.501, 0.966); // quantized object space
+const lureLight = new THREE.PointLight(0x7fe9ff, 0, 6, 2);
+scene.add(lureLight);
+const lureHalo = makeGlowSprite(0x8ff0ff, 0.9);
+scene.add(lureHalo);
+let anglerScale = 1;
+const angLoad = assets.gltf('models/abyssal/angler.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 3.6, { ground: false });
+ anglerScale = m.scale.x;
+ prepModel(m, renderer, { env: 0.8, onMat: mat => { mat.name = 'angler'; patchWater(mat, { caustics: false, glow: [{ center: LURE_OBJ, radius: 0.07, color: lureCol, inner: 0.2 }] }); } });
+ anglerInner.add(m);
+ anglerModel = m;
+});
+const lureWorld = V3();
+const anglerState = { yaw: 0, lit: 0, look: 0, focus: 0 };
+// She rides with the camera between these stations (screen-locked, distance shrinking), static outside them.
+const RIDE = [2.72, 3.82];
+const anglerEntry = V3(), anglerExit = V3(), idleFocus = V3();
+const rideCam = new THREE.PerspectiveCamera(40, 1, 0.1, 100);
+function rideSpot(s) {
+ const k = smooth(RIDE[0], 3.25, s);
+ // After the zone's centre she lets you pass: drifts up and out through the top of the frame, clear of the gauge.
+ const up = smooth(3.45, RIDE[1], s);
+ return MOBILE ? [0.52, lerp(0.27, 0.02, up), lerp(13, 10, k)] : [lerp(lerp(0.66, 0.6, smooth(RIDE[0], 3.4, s)), 0.54, up), lerp(0.46, 0.08, up), lerp(10.5, 7.4, k)];
+}
+function rideAt(s, out) {
+ // rig is already solved for this frame; use it without the pointer parallax so she keeps some depth.
+ rideCam.fov = camera.fov; rideCam.aspect = camera.aspect;
+ rideCam.updateProjectionMatrix(); applyLens(rideCam, innerWidth, innerHeight, MOBILE ? lensY : undefined);
+ rideCam.position.copy(rig.cam); rideCam.lookAt(rig.look); rideCam.updateMatrixWorld();
+ const [sx, sy, dist] = rideSpot(s);
+ const dir = tmp.c.set(sx * 2 - 1, 1 - sy * 2, 0.5).unproject(rideCam).sub(rideCam.position).normalize();
+ return out.copy(rideCam.position).addScaledVector(dir, dist);
+}
+
+// Vent on the trench lip.
+const vent = new THREE.Group();
+scene.add(vent);
+const VENT_XZ = [-2.3, -5.6];
+const ventGlow = { value: new THREE.Color(0, 0, 0) };
+const ventTop = V3();
+let plume;
+const ventLights = [new THREE.PointLight(0xff6a1e, 0, 11, 1.6), new THREE.PointLight(0xff8a3a, 0, 6, 1.8)];
+for (const l of ventLights) scene.add(l);
+const ventLoad = assets.gltf('models/abyssal/vent.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 5.8, { ground: true });
+ const s = m.scale.x;
+ prepModel(m, renderer, {
+ env: 0.7,
+ onMat: mat => {
+ mat.name = 'vent';
+ patchWater(mat, {
+ caustics: false,
+ extra(sh) {
+ sh.uniforms.uVentGlow = ventGlow;
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nuniform vec3 uVentGlow;')
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ float rust = smoothstep(0.06, 0.26, diffuseColor.r - diffuseColor.b) * smoothstep(0.14, 0.64, vObj.y) * smoothstep(0.32, 0.1, length(vObj.xz - vec2(-0.094, 0.009)));
+ totalEmissiveRadiance += uVentGlow * (rust * 1.5 + smoothstep(0.74, 0.82, vObj.y) * 1.2);`);
+ },
+ });
+ },
+ });
+ const [vx, vz] = VENT_XZ;
+ vent.position.set(vx, heightAt(vx, vz) - 0.9, vz);
+ vent.rotation.y = 0.5;
+ vent.add(m);
+ vent.updateMatrixWorld(true);
+ // Chimney top in world space.
+ ventTop.set(-0.093, 0.793, 0.01);
+ m.updateMatrixWorld(true);
+ m.localToWorld(ventTop);
+ plume = ventPlume({ top: ventTop });
+ scene.add(plume.smoke, plume.sparks);
+ ventLights[0].position.copy(ventTop).add(V3(0, 0.5, 0.4));
+ ventLights[1].position.copy(vent.position).add(V3(0.6, 1.0, 1.2));
+ void s;
+});
+
+// Beacon 07 on the floor.
+const bcn = beacon();
+const BEACON_XZ = [4.3, 3.2];
+bcn.group.position.set(BEACON_XZ[0], heightAt(...BEACON_XZ) - 0.02, BEACON_XZ[1]);
+bcn.group.rotation.y = 0.4;
+scene.add(bcn.group);
+scene.add(bcn.light);
+const beaconHalo = makeGlowSprite(0x5fe6da, 0.7);
+scene.add(beaconHalo);
+// Acoustic ping drawn on the silt: a ring that runs out from the beacon every two seconds.
+const beaconRing = new THREE.Mesh(new THREE.PlaneGeometry(5, 5), new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uP: { value: 0 }, uVis: { value: 1 } },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `uniform float uP, uVis; varying vec2 vUv;
+ void main(){ float d = length(vUv - 0.5) * 2.0; float r = uP;
+ float ring = smoothstep(r - 0.035, r, d) * smoothstep(r + 0.006, r, d);
+ float a = ring * pow(1.0 - uP, 1.6) * smoothstep(0.02, 0.08, d) * 1.4 * uVis;
+ gl_FragColor = vec4(vec3(0.25, 0.9, 0.84) * a, 1.0); }`,
+}));
+beaconRing.rotation.x = -Math.PI / 2;
+beaconRing.position.set(BEACON_XZ[0], heightAt(...BEACON_XZ) + 0.06, BEACON_XZ[1]);
+beaconRing.renderOrder = 4;
+scene.add(beaconRing);
+
+// Companion ROV light for the vessel sections: a soft key from the camera side.
+const rov = new THREE.SpotLight(0xfff1e0, 0, 30, 0.42, 0.9, 1.3);
+scene.add(rov, rov.target);
+
+function makeGlowSprite(color, size) {
+ const c = document.createElement('canvas'); c.width = c.height = 128;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ grd.addColorStop(0, 'rgba(255,255,255,1)'); grd.addColorStop(0.12, 'rgba(255,255,255,.7)'); grd.addColorStop(0.35, 'rgba(255,255,255,.14)'); grd.addColorStop(1, 'rgba(255,255,255,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
+ const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace;
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, color, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true, fog: false }));
+ s.scale.setScalar(size);
+ s.renderOrder = 10;
+ s.userData.size = size;
+ return s;
+}
+
+// ─── Scroll → station ─────────────────────────────────────────────────────────
+const stages = [...document.querySelectorAll('.stage')];
+let anchors = [];
+function measure() {
+ const maxS = document.documentElement.scrollHeight - innerHeight;
+ anchors = stages.map((el, i) => {
+ if (i === 0) return 0;
+ const top = el.getBoundingClientRect().top + scrollY;
+ return Math.min(maxS, top + el.offsetHeight / 2 - innerHeight / 2);
+ });
+ anchors[anchors.length - 1] = maxS;
+}
+function sFromScroll(y) {
+ for (let i = 0; i < anchors.length - 1; i++) if (y <= anchors[i + 1]) return i + clamp((y - anchors[i]) / Math.max(1, anchors[i + 1] - anchors[i]));
+ return anchors.length - 1;
+}
+function scrollFromS(s) {
+ const i = Math.min(anchors.length - 2, Math.floor(s)), f = s - i;
+ return lerp(anchors[i], anchors[i + 1], f);
+}
+measure();
+addEventListener('resize', measure);
+document.fonts?.ready.then(measure);
+
+const lerpA = (a, b, t) => { let d = ((b - a + Math.PI) % (Math.PI * 2) + Math.PI * 2) % (Math.PI * 2) - Math.PI; return a + d * t; };
+const tmp = { sub: V3(), cam: V3(), look: V3(), a: V3(), b: V3(), c: V3() };
+function stationState(i, s, o) {
+ const st = STATIONS[i];
+ o.sub.set(st.sub[0], st.sub[1], st.sub[2]);
+ o.look.set(st.look[0], st.look[1], st.look[2]);
+ if (st.orbit) {
+ const k = clamp(s - 5.4, 0, 1.2);
+ const a = lerp(-0.95, 0.75, smooth(0, 1.2, k));
+ const R = MOBILE ? 9.5 : 7.2;
+ o.cam.set(st.sub[0] + Math.sin(a) * R, st.sub[1] + 1.1 + Math.cos(a * 1.3) * 0.5, st.sub[2] + Math.cos(a) * R);
+ if (!MOBILE) o.look.x -= Math.cos(a) * 1.4, o.look.z += Math.sin(a) * 1.4;
+ } else o.cam.set(st.cam[0], st.cam[1], st.cam[2]);
+ o.yaw = st.yaw;
+ return o;
+}
+const SA = { sub: V3(), cam: V3(), look: V3(), yaw: 0 }, SB = { sub: V3(), cam: V3(), look: V3(), yaw: 0 };
+const rig = { sub: V3(), cam: V3(), look: V3(), yaw: 0 };
+function rigAt(s) {
+ const n = STATIONS.length - 1;
+ const i = Math.min(n - 1, Math.max(0, Math.floor(s)));
+ const f = smooth(0.1, 0.9, clamp(s - i));
+ stationState(i, s, SA); stationState(i + 1, s, SB);
+ const y = descY(s);
+ rig.sub.lerpVectors(SA.sub, SB.sub, f); rig.sub.y += y;
+ rig.cam.lerpVectors(SA.cam, SB.cam, f); rig.cam.y += y;
+ rig.look.lerpVectors(SA.look, SB.look, f); rig.look.y += y;
+ rig.yaw = lerpA(SA.yaw, SB.yaw, f);
+ // Mid-transition swing: the camera drifts out a little so passes feel like a dive, not a dolly.
+ const sw = Math.sin(f * Math.PI);
+ rig.cam.z += sw * 1.2;
+ return rig;
+}
+
+// ─── HUD ────────────────────────────────────────────────────────────────────
+const odo = odometer(document.querySelector('.odo'));
+const rootStyle = document.documentElement.style;
+const gaugeEl = document.querySelector('.gauge');
+const railLis = [...document.querySelectorAll('.rail-zones li')];
+const rTemp = document.querySelector('.r-temp'), rPress = document.querySelector('.r-press'), rLight = document.querySelector('.r-light');
+const markZone = document.querySelector('.mark-zone'), markTime = document.querySelector('.mark-time');
+const logEl = document.querySelector('.divelog');
+const logItems = LOG.map(([d, time, text]) => {
+ const li = document.createElement('li');
+ li.innerHTML = `<time>${time}</time><span>${text}</span>`;
+ li.dataset.d = d;
+ return li;
+});
+const toastEl = document.querySelector('.toast');
+let toastTimer;
+function toast(html, ms = 3200) {
+ toastEl.innerHTML = html;
+ toastEl.classList.add('on');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+const hud = { d: -1, temp: '', press: '', light: '', zone: '', time: '', logN: -1 };
+function updateHud(d, s) {
+ odo.set(d);
+ const rail = clamp(s / 5);
+ gaugeEl.style.setProperty('--d', rail.toFixed(4));
+ for (const li of railLis) li.classList.toggle('near', Math.abs(parseFloat(li.style.getPropertyValue('--p')) - rail) < 0.07);
+ const t = tempAt(d).toFixed(1), p = Math.round(pressureAt(d)).toLocaleString('en-US'), l = fmtLight(lightAt(d)), z = zoneAt(d), tm = fmtTime(d / 1.0);
+ if (t !== hud.temp) rTemp.textContent = hud.temp = t;
+ if (p !== hud.press) rPress.textContent = hud.press = p;
+ if (l !== hud.light) rLight.textContent = hud.light = l;
+ if (z !== hud.zone) markZone.textContent = hud.zone = z;
+ if (tm !== hud.time) markTime.textContent = hud.time = tm;
+ // Dive log: entries up to the current depth, last three visible.
+ const n = logItems.filter(li => d >= +li.dataset.d).length;
+ if (n !== hud.logN) {
+ hud.logN = n;
+ const show = logItems.slice(Math.max(0, n - 3), n);
+ for (const li of logItems) if (!show.includes(li) && li.parentNode) li.remove();
+ for (const li of show) if (!li.parentNode) { logEl.appendChild(li); requestAnimationFrame(() => li.classList.add('on')); }
+ }
+}
+
+// ─── Sonar ping + contacts ───────────────────────────────────────────────────
+const tagsEl = document.querySelector('.tags');
+const CONTACTS = [
+ { key: 'school', name: 'Bigeye scad', latin: 'Selar crumenophthalmus · school of ~300', pos: () => SCHOOL_C },
+ { key: 'naut', name: 'Chambered nautilus', latin: 'Nautilus pompilius', pos: () => nautilus.position },
+ { key: 'jelly', name: 'Crown jellyfish', latin: 'Atolla wyvillei', pos: () => nearestJelly() },
+ { key: 'angler', name: 'Humpback anglerfish', latin: 'Melanocetus johnsonii', pos: () => tmp.c.copy(angler.position).add(V3(0, 0.3, 0)) },
+ { key: 'vent', name: 'Black smoker', latin: 'Sulphide chimney · fluid 380 °C', pos: () => tmp.b.copy(vent.position).add(V3(0, 3.2, 0)) },
+ { key: 'beacon', name: 'Beacon 07', latin: 'Acoustic marker · 12 kHz · placed 2024', pos: () => tmp.a.copy(bcn.group.position).add(V3(0, 1.3, 0)) },
+];
+for (const c of CONTACTS) {
+ c.el = document.createElement('div');
+ c.el.className = 'tag';
+ c.el.innerHTML = `<div class="tag-box"></div><div class="tag-text mono"><b>Contact</b><span class="tag-name"></span><i></i></div>`;
+ tagsEl.appendChild(c.el);
+ c.until = 0; c.hit = false; c.p = V3();
+}
+function nearestJelly() {
+ let best = jellies[0], bd = 1e9;
+ for (const j of jellies) { const dd = j.position.distanceToSquared(camera.position); if (dd < bd) { bd = dd; best = j; } }
+ return best.position;
+}
+const pingState = { t0: -100, origin: V3(), n: 0 };
+function ping() {
+ pingState.t0 = engine.time;
+ toWorld(subModel, V3(0.9, -0.1, 0), pingState.origin);
+ pingState.n++;
+ for (const c of CONTACTS) c.hit = false;
+ sound.ping();
+}
+function updatePing(t) {
+ const age = t - pingState.t0;
+ const R = age * 15;
+ const amt = age < 5 ? Math.exp(-age * 0.45) * smooth(0, 0.05, age) : 0;
+ fx.uniforms.get('uPing').value.set(pingState.origin.x, pingState.origin.y, pingState.origin.z, R);
+ fx.uniforms.get('uPingAmt').value = amt;
+ let k = 0;
+ for (const c of CONTACTS) {
+ const p = c.pos();
+ const dist = p.distanceTo(pingState.origin);
+ if (!c.hit && amt > 0 && R >= dist) {
+ c.hit = true;
+ tmp.a.copy(p).project(camera);
+ const onScreen = Math.abs(tmp.a.x) < 0.92 && Math.abs(tmp.a.y) < 0.9 && tmp.a.z < 1 && p.distanceTo(camera.position) < 42;
+ if (onScreen) {
+ c.until = t + 3.4;
+ c.el.querySelector('.tag-name').textContent = `${c.name} · ${(p.distanceTo(sub.position) * 1.35).toFixed(1)} m`;
+ c.el.querySelector('i').textContent = c.latin;
+ c.el.querySelector('b').textContent = `Sonar contact ${String(++k).padStart(2, '0')}`;
+ }
+ }
+ const on = t < c.until;
+ c.el.classList.toggle('on', on);
+ if (on) {
+ tmp.a.copy(p).project(camera);
+ const x = (tmp.a.x + 1) / 2 * innerWidth, y = (1 - tmp.a.y) / 2 * innerHeight;
+ c.el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0)`;
+ }
+ }
+}
+
+// ─── Vessel hotspots (Pelagia section) ──────────────────────────────────────
+const HOTSPOTS = [
+ { p: V3(0.9, -0.08, -0.16), n: V3(1, 0, -0.35), num: '01', title: 'Crew sphere', sub: 'Titanium · 2.1 m inside', text: 'Forged Ti-6Al-4V, 94 mm thick, three acrylic viewports. At the bottom it shrinks by 1.4 mm. You will not feel it.' },
+ { p: V3(0.62, 0.4, -0.24), n: V3(0.6, 0.6, -0.5), num: '02', title: 'Floodlight array', sub: '6 × 20,000 lm · steerable', text: 'The only light most of what you see has ever received. Below 1,000 m the pilot hands you the joystick.' },
+ { p: V3(-0.15, -0.5, -0.43), n: V3(0, -0.2, -1), num: '03', title: 'Life support', sub: '16 h mission · 96 h reserve', text: 'Oxygen from two banks, CO₂ scrubbed by lithium hydroxide, cabin held at 1 atm and a steady 16 °C.' },
+ { p: V3(0.8, -0.46, -0.3), n: V3(0.7, -0.2, -0.7), num: '04', title: 'Manipulator & basket', sub: '7-function arm · 40 kg', text: 'Takes a core of hadal silt on every dive. The ship’s lab has your sample before you have had lunch.' },
+];
+const hsEl = document.querySelector('.hotspots');
+const hsDetail = document.querySelector('.hs-detail');
+let hsActive = -1;
+for (const h of HOTSPOTS) {
+ h.el = document.createElement('div');
+ h.el.className = 'hs';
+ h.el.innerHTML = `<i class="hs-dot"></i><i class="hs-line"></i><div class="hs-card"><p class="mono">${h.num} · ${h.sub}</p><h3>${h.title}</h3></div>`;
+ hsEl.appendChild(h.el);
+ h.w = V3(); h.nw = V3();
+}
+function updateHotspots(s) {
+ const vis = smooth(5.55, 5.8, s) * (1 - smooth(6.35, 6.6, s));
+ hsEl.style.opacity = vis.toFixed(3);
+ if (vis <= 0.001) return;
+ const toCam = tmp.a;
+ const k = clamp(s - 5.6, 0, 1);
+ tmp.c.copy(sub.position).project(camera);
+ const subScr = { x: (tmp.c.x + 1) / 2 * innerWidth, y: (1 - tmp.c.y) / 2 * innerHeight };
+ const active = Math.min(HOTSPOTS.length - 1, Math.floor(k * 4.4));
+ if (active !== hsActive) {
+ hsActive = active;
+ const h = HOTSPOTS[active];
+ hsDetail.querySelector('.hs-d-num').textContent = h.num;
+ hsDetail.querySelector('.hs-d-sub').textContent = h.sub;
+ hsDetail.querySelector('.hs-d-title').textContent = h.title;
+ hsDetail.querySelector('.hs-d-text').textContent = h.text;
+ gsap.fromTo(hsDetail, { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.6, ease: 'power3.out' });
+ }
+ const copyRight = document.querySelector('.pelagia-copy .specs').getBoundingClientRect().right + 30;
+ HOTSPOTS.forEach((h, i) => {
+ h.el.classList.toggle('active', i === active);
+ toWorld(subModel, h.p, h.w);
+ h.nw.copy(h.n).transformDirection(subInner.matrixWorld);
+ toCam.copy(camera.position).sub(h.w).normalize();
+ const facing = h.nw.dot(toCam) > -0.05;
+ // Reveal one after another as the orbit progresses.
+ const show = facing && k > i * 0.16;
+ h.el.classList.toggle('on', show);
+ tmp.b.copy(h.w).project(camera);
+ const x = (tmp.b.x + 1) / 2 * innerWidth, y = (1 - tmp.b.y) / 2 * innerHeight;
+ const cw = h.el.querySelector('.hs-card').offsetWidth + 110;
+ h.el.classList.toggle('flip', x < subScr.x && x - cw > copyRight || x + cw > innerWidth - 20);
+ h.el.style.transform = `translate3d(${x.toFixed(1)}px, ${y.toFixed(1)}px, 0)`;
+ });
+}
+
+// ─── Sound (optional, off by default) ─────────────────────────────────────────
+const sound = (() => {
+ let ctx = null, master = null, on = false;
+ const btn = document.querySelector('.sound');
+ function init() {
+ ctx = new AudioContext();
+ master = ctx.createGain(); master.gain.value = 0; master.connect(ctx.destination);
+ // Hull rumble: brown noise through a low-pass that breathes.
+ const len = ctx.sampleRate * 4, buf = ctx.createBuffer(1, len, ctx.sampleRate), d = buf.getChannelData(0);
+ let last = 0; for (let i = 0; i < len; i++) { last = (last + 0.02 * (Math.random() * 2 - 1)) / 1.02; d[i] = last * 3.2; }
+ const src = ctx.createBufferSource(); src.buffer = buf; src.loop = true;
+ const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 180;
+ const lfo = ctx.createOscillator(); lfo.frequency.value = 0.07; const lg = ctx.createGain(); lg.gain.value = 60; lfo.connect(lg).connect(lp.frequency); lfo.start();
+ const g = ctx.createGain(); g.gain.value = 0.5;
+ src.connect(lp).connect(g).connect(master); src.start();
+ }
+ function toggle() {
+ on = !on;
+ if (!ctx) init();
+ ctx.resume();
+ master.gain.setTargetAtTime(on ? 0.5 : 0, ctx.currentTime, 0.4);
+ btn.setAttribute('aria-pressed', on);
+ btn.querySelector('span').textContent = on ? 'Sound on' : 'Sound off';
+ }
+ btn.addEventListener('click', toggle);
+ return {
+ ping() {
+ if (!on || !ctx) return;
+ const t = ctx.currentTime;
+ for (const [delay, gain] of [[0, 0.28], [0.42, 0.07], [0.9, 0.025]]) {
+ const o = ctx.createOscillator(); o.type = 'sine'; o.frequency.setValueAtTime(1480, t + delay); o.frequency.exponentialRampToValueAtTime(1320, t + delay + 1.2);
+ const g = ctx.createGain(); g.gain.setValueAtTime(0, t + delay); g.gain.linearRampToValueAtTime(gain, t + delay + 0.01); g.gain.exponentialRampToValueAtTime(0.0001, t + delay + 1.5);
+ o.connect(g).connect(master); o.start(t + delay); o.stop(t + delay + 1.6);
+ }
+ },
+ };
+})();
+
+// ─── Input ──────────────────────────────────────────────────────────────────
+let lastMove = -10;
+pointer.on('move', () => { lastMove = engine.time; });
+const ray = new THREE.Raycaster();
+const aimNdc = new THREE.Vector2();
+const aimPoint = V3(0, -40, -10);
+const prevNdc = new THREE.Vector2();
+// click, not pointerdown: on touch screens a scroll gesture must never fire the sonar.
+addEventListener('click', e => {
+ if (e.button !== 0 || e.target.closest('a,button,.glass,.zone-card,.nav,.pelagia-copy,table')) return;
+ ping();
+});
+const DBG_AIM = DBG.get('aim')?.split(',').map(Number);
+
+// ─── Frame loop ─────────────────────────────────────────────────────────────
+let sNow = 0, sTarget = 0;
+const intro = { k: DBG.has('nointro') ? 1 : 0 };
+const envState = { depth: 0 };
+const fwd = V3(), right = V3(), up = V3(0, 1, 0), dirTmp = V3(), camPrev = V3();
+const cTmp = new THREE.Color();
+const aimSide = V3(1, 0, 0), perpTmp = V3();
+function keepOffAxis(d, axis, minAngle, side) {
+ const cosA = d.dot(axis), cosMin = Math.cos(minAngle);
+ if (cosA <= cosMin) return;
+ perpTmp.copy(d).addScaledVector(axis, -cosA);
+ if (perpTmp.lengthSq() < 1e-3) perpTmp.copy(side).addScaledVector(axis, -side.dot(axis));
+ perpTmp.normalize();
+ d.copy(axis).multiplyScalar(cosMin).addScaledVector(perpTmp, Math.sin(minAngle)).normalize();
+}
+let camVy = 0, lastSpawnDepth = 0;
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ sTarget = sFromScroll(scrollY);
+ sNow = damp(sNow, sTarget, 5, dt);
+ const s = sNow;
+ const d = depthAt(s);
+ envState.depth = d;
+ const dark = smooth(250, 900, d);
+
+ // ── rig
+ if (MOBILE) {
+ // The hero headline owns the lower half of a phone: lift the sub higher there.
+ const ly = Math.round(lerp(0.34, LENS[1], smooth(0.1, 0.9, s)) * 200) / 200;
+ if (ly !== lensY) { lensY = ly; applyLens(camera, innerWidth, innerHeight, ly); }
+ }
+ rigAt(s);
+ const introE = 1 - Math.pow(1 - intro.k, 3);
+ // While the anglerfish is in frame the pilot turns to keep her in the lights.
+ const track = anglerState.focus * smooth(3.15, 3.4, s) * (1 - smooth(3.72, 3.88, s));
+ if (track > 0.001) rig.yaw = lerpA(rig.yaw, Math.atan2(-(angler.position.z - rig.sub.z), angler.position.x - rig.sub.x), track * 0.9);
+ sub.position.copy(rig.sub);
+ sub.position.y += Math.sin(t * 0.55) * 0.07 + (1 - introE) * 4.6;
+ sub.rotation.set(Math.sin(t * 0.4) * 0.025, rig.yaw + Math.sin(t * 0.12) * 0.1 + (1 - introE) * 0.5, Math.sin(t * 0.33) * 0.03);
+ const pAmt = MOBILE ? 0.25 : 1;
+ camera.position.copy(rig.cam).add(tmp.a.set(pointer.sx * 0.35 * pAmt, pointer.sy * 0.18 * pAmt + Math.sin(t * 0.3) * 0.05, 0));
+ camera.position.y += (1 - introE) * 0.8;
+ camera.lookAt(rig.look);
+ camera.updateMatrixWorld();
+ camVy = damp(camVy, (camera.position.y - camPrev.y) / Math.max(dt, 1e-3), 6, dt);
+ camPrev.copy(camera.position);
+
+ // ── water & light by depth
+ waterAt(d, waterCol);
+ scene.background.copy(waterCol);
+ dome.position.copy(camera.position);
+ domeTop.copy(waterCol).multiplyScalar(1.25 + 1.1 * Math.exp(-d / 40));
+ groundMesh.visible = d > 2500;
+ waterAt(d + 160, domeBot).multiplyScalar(0.8);
+ dome.material.uniforms.uTop.value.copy(domeTop);
+ dome.material.uniforms.uMid.value.copy(waterCol);
+ dome.material.uniforms.uBot.value.copy(domeBot);
+ dome.material.uniforms.uSun.value = Math.exp(-d / 60);
+ dome.visible = d < 2400;
+ if (scene.fog) scene.fog.color.copy(waterCol);
+ if (scene.fog) scene.fog.density = lerp(0.03, 0.05, smooth(0, 1200, d));
+ const sunK = Math.exp(-d / 110);
+ const ambK = Math.exp(-d / 330);
+ sun.intensity = 3.4 * sunK;
+ sun.color.setRGB(Math.exp(-d * 0.012), Math.exp(-d * 0.0035), Math.exp(-d * 0.0017));
+ sun.position.copy(sub.position).add(tmp.a.set(-3.5, 14, 4));
+ sun.target.position.copy(sub.position);
+ sun.shadow.autoUpdate = sunK > 0.02;
+ hemi.intensity = 1.25 * ambK;
+ hemi.color.copy(waterCol).multiplyScalar(2.2).lerp(cTmp.setRGB(0.6, 0.95, 1), 0.3 * sunK);
+ hemi.groundColor.copy(waterCol).multiplyScalar(0.25);
+ scene.environment = d < 230 ? envShallow : (d < 1100 ? envDeep : envFlood);
+ scene.environmentIntensity = d < 230 ? 0.9 * ambK + 0.05 : (d < 1100 ? 1.1 * ambK + 0.02 : 0.03 + 0.12 * floodState.power);
+ waterUniforms.uCausT.value = t * 0.55;
+ waterUniforms.uCausAmt.value = 2.8 * Math.exp(-d / 42);
+ surface.material.uniforms.uT.value = t;
+ surface.material.uniforms.uFog.value.copy(domeTop);
+ surface.material.uniforms.uAmt.value = 1;
+ surface.visible = d < 260;
+ fx.uniforms.get('uSun').value = Math.exp(-d / 75) * 1.15;
+ // Bright shallows bloom less; in the dark every living light should bleed.
+ if (bloomLum) bloomLum.threshold = lerp(0.9, 0.55, smooth(40, 500, d));
+ vol.uniforms.get('uDensity').value = lerp(0.05, 0.028, smooth(4.4, 5.2, s));
+ fx.uniforms.get('uSunCol').value.copy(sun.color).multiplyScalar(0.075).lerp(cTmp.setRGB(0.05, 0.14, 0.15), 0.3);
+
+ // ── floodlights: on at 750 m, steered by the pointer
+ const wantOn = d > 740;
+ if (wantOn !== floodState.on) {
+ floodState.on = wantOn;
+ gsap.killTweensOf(floodState);
+ if (wantOn) {
+ gsap.timeline()
+ .to(floodState, { power: 0.8, duration: 0.05 }).to(floodState, { power: 0.05, duration: 0.08, delay: 0.08 })
+ .to(floodState, { power: 1, duration: 0.05, delay: 0.14 }).to(floodState, { power: 0.3, duration: 0.05, delay: 0.05 })
+ .to(floodState, { power: 1, duration: 0.5, ease: 'power2.out', delay: 0.1 });
+ toast('<b>Floodlights on</b> · 750 m · move to steer them');
+ } else gsap.to(floodState, { power: 0, duration: 0.6 });
+ }
+ const fp = floodState.power;
+ const user = DBG_AIM ? 1 : clamp(1 - (t - lastMove - 4) / 2.5);
+ const wx = Math.sin(t * 0.27) * 0.45 + Math.sin(t * 0.61) * 0.12, wy = Math.cos(t * 0.37) * 0.18 - 0.05;
+ const px = DBG_AIM ? DBG_AIM[0] : pointer.sx, py = DBG_AIM ? DBG_AIM[1] : pointer.sy;
+ aimNdc.set(lerp(wx, px, user), lerp(wy, py, user));
+ ray.setFromCamera(aimNdc, camera);
+ // ── anglerfish: rides with the camera through the midnight zone, looming closer as you sink.
+ angler.visible = d > 700 && d < 5200;
+ if (angler.visible) {
+ if (s <= RIDE[0]) angler.position.copy(anglerEntry);
+ else if (s >= RIDE[1]) angler.position.copy(anglerExit);
+ else rideAt(s, angler.position);
+ angler.position.add(tmp.b.set(Math.sin(t * 0.21) * 0.25, Math.sin(t * 0.5) * 0.1, 0));
+ angler.position.addScaledVector(tmp.c.copy(sub.position).sub(angler.position).normalize(), anglerState.lit * 0.5);
+ tmp.b.copy(angler.position).project(camera);
+ anglerState.focus = damp(anglerState.focus, Math.abs(tmp.b.x) < 0.9 && Math.abs(tmp.b.y) < 0.9 && tmp.b.z < 1 ? 1 : 0, 3, dt);
+ } else anglerState.focus = 0;
+ // Where the pointer sits on the plane through the hull (facing the camera), pushed along the sub's heading:
+ // the beams sweep across the frame toward the cursor instead of running down the line of sight.
+ sub.updateMatrixWorld();
+ fwd.set(1, 0, 0).transformDirection(subInner.matrixWorld);
+ camera.getWorldDirection(tmp.c);
+ const tPlane = tmp.b.copy(sub.position).sub(ray.ray.origin).dot(tmp.c) / Math.max(0.2, ray.ray.direction.dot(tmp.c));
+ tmp.a.copy(ray.ray.origin).addScaledVector(ray.ray.direction, tPlane);
+ tmp.b.copy(tmp.a).sub(sub.position);
+ aimSide.copy(tmp.b).lengthSq() < 0.01 && aimSide.copy(right);
+ tmp.a.addScaledVector(tmp.b, 0.6).addScaledVector(fwd, s > 4.6 ? 2.5 : 2);
+ // Hands off the cursor, the pilot keeps the lights on whatever is out there: the anglerfish, then the
+ // chimney, then the beacon — each zone's subject, with a slow searching wobble.
+ const wob = tmp.c.set(Math.sin(t * 0.6) * 0.35, Math.cos(t * 0.45) * 0.25, 0);
+ if (anglerState.focus > 0.01) idleFocus.copy(angler.position).add(wob).y += 0.2;
+ else if (s > 3.7 && s < 4.6) idleFocus.copy(ventTop).add(wob).y -= 1.4;
+ else if (s >= 4.6) idleFocus.copy(bcn.group.position).add(wob).y += 0.3;
+ // Point near her and the lights lock on (a little magnetism makes searching the dark feel skilled, not fiddly).
+ let magnet = 0;
+ if (anglerState.focus > 0.01 || (s > 3.7 && s < 4.6)) {
+ tmp.b.copy(idleFocus).project(camera);
+ const dn = Math.hypot((tmp.b.x - px) * camera.aspect, tmp.b.y - py);
+ magnet = 1 - smooth(0.32, 0.6, dn);
+ }
+ const focusK = Math.max((1 - user) * Math.max(anglerState.focus, smooth(3.7, 3.95, s)), user * magnet);
+ if (focusK > 0.001) tmp.a.lerp(idleFocus, focusK);
+ // On the bottom the beams land where you point on the silt.
+ if (s > 4.5 && ray.ray.direction.y < -0.04) {
+ const tFloor = (FLOOR_Y + 0.3 - ray.ray.origin.y) / ray.ray.direction.y;
+ if (tFloor > 0 && tFloor < 40) tmp.a.lerp(tmp.b.copy(ray.ray.origin).addScaledVector(ray.ray.direction, tFloor), smooth(4.5, 4.9, s) * user);
+ }
+ // At the very end the floodlights turn upward: eleven kilometres of dark between you and the surface.
+ const upK = smooth(8.3, 8.9, s);
+ if (upK > 0) tmp.a.lerp(tmp.b.copy(sub.position).add(tmp.c.set(0.8 + aimNdc.x * 6, 24, -5 - aimNdc.y * 4)), upK);
+ aimPoint.lerp(tmp.a, 1 - Math.exp(-9 * dt));
+ sub.updateMatrixWorld();
+ fwd.set(1, 0, 0).transformDirection(subInner.matrixWorld);
+ right.crossVectors(ray.ray.direction, up).normalize();
+ floods.forEach((L, i) => {
+ toWorld(subModel, FLOOD_LOCAL[i], L.position);
+ dirTmp.copy(aimPoint).addScaledVector(right, (i - 1) * 0.55).sub(L.position).normalize();
+ // Pan/tilt limits: beams cannot swing behind the hull.
+ const dp = dirTmp.dot(fwd);
+ if (dp < 0.2) dirTmp.addScaledVector(fwd, 0.2 - dp).normalize();
+ // Never into the lens, and never straight down the line of sight (the beam collapses into one glaring disc):
+ // keep every beam at least 60° off the viewer and 42° off the view axis, swung toward the cursor's side.
+ tmp.c.copy(camera.position).sub(L.position).normalize();
+ keepOffAxis(dirTmp, tmp.c, 60 * D, aimSide);
+ keepOffAxis(dirTmp, tmp.c.negate(), 42 * D, aimSide);
+ L.target.position.copy(L.position).addScaledVector(dirTmp, 10);
+ L.intensity = fp * (i === 1 ? 110 : 90) * lerp(1, 0.3, smooth(4.4, 5, s)) * lerp(1, 4.2, upK) * (1 + Math.sin(t * 37 + i) * 0.01);
+ });
+ lampGlow.value.copy(floodCol).multiplyScalar(fp * 3.5);
+ floods.forEach((L, i) => {
+ const h = lampHalos[i];
+ h.position.copy(L.position);
+ h.material.opacity = fp * 0.6;
+ h.visible = fp > 0.01;
+ });
+ floodUniforms.uLCos.value = Math.cos(floods[0].angle * 0.92);
+ floodUniforms.uLPow.value = fp * 5;
+ floods.forEach((L, i) => {
+ floodUniforms.uLPos.value[i].copy(L.position);
+ floodUniforms.uLDir.value[i].copy(L.target.position).sub(L.position).normalize();
+ });
+ // Recovery strobe on the sail.
+ const sPh = (t % 2.4);
+ const strobeOn = sPh < 0.04 || (sPh > 0.14 && sPh < 0.17) ? 1 : 0;
+ toWorld(subModel, tmp.a.set(-0.35, 0.66, 0), strobeDot.position);
+ strobe.position.copy(strobeDot.position);
+ strobe.intensity = strobeOn * 3 * dark;
+ strobeDot.material.opacity = strobeOn * dark;
+ strobeDot.scale.setScalar(0.28 * dark + 0.02);
+
+ // ── marine snow & plankton
+ for (const sm of [snow, silt]) {
+ const u = sm.mat.uniforms;
+ u.uT.value = t; u.uCam.value.copy(camera.position);
+ u.uAmb.value = ambK * 0.9;
+ u.uAmbCol.value.copy(waterCol).multiplyScalar(1.6).lerp(cTmp.setRGB(0.85, 0.97, 1), 0.45);
+ u.uFogD.value = lerp(0.03, 0.06, dark);
+ u.uStretch.value = sm === snow ? clamp(Math.abs(camVy) * 0.09, 0, 5) : 0;
+ }
+ silt.points.visible = s > 4.4;
+ plankton.mat.uniforms.uT.value = t;
+ const speed = Math.hypot(pointer.vx, pointer.vy);
+ if (pointer.active && speed > 1.1 && intro.k > 0.9) {
+ const n = Math.min(40, Math.ceil(speed * 5));
+ const bubbles = d < 300;
+ for (let k = 0; k < n; k++) {
+ const f = k / n;
+ tmp.b.set(lerp(prevNdc.x, pointer.x, f) + rnd(-0.012, 0.012), lerp(prevNdc.y, pointer.y, f) + rnd(-0.012, 0.012));
+ ray.setFromCamera(tmp.b, camera);
+ const dist = rnd(2.2, 7.5);
+ const p = tmp.c.copy(ray.ray.origin).addScaledVector(ray.ray.direction, dist);
+ plankton.emit(p.x + rnd(-0.16, 0.16), p.y + rnd(-0.16, 0.16), p.z + rnd(-0.16, 0.16), t - rnd(0, dt), bubbles ? 1 : 0);
+ }
+ }
+ prevNdc.set(pointer.x, pointer.y);
+ // Stirred by the descent: plankton flashes along the hull when you scroll fast in the dark.
+ if (dark > 0.3 && Math.abs(camVy) > 1.2) {
+ const n = Math.min(10, Math.floor(Math.abs(camVy) * 0.8));
+ for (let k = 0; k < n; k++) {
+ tmp.c.set(rnd(-2.2, 2.2), rnd(-1.2, 1.5), rnd(-1.6, 1.6)).add(sub.position);
+ plankton.emit(tmp.c.x, tmp.c.y, tmp.c.z, t, 0);
+ }
+ }
+ // Bubbles from the thrusters near the surface, and the splash on entry.
+ if (d < 120 && Math.random() < 0.5 * (1 - d / 120)) {
+ toWorld(subModel, tmp.a.set(-0.9, rnd(-0.2, 0.2), rnd(-0.4, 0.4)), tmp.c);
+ plankton.emit(tmp.c.x, tmp.c.y, tmp.c.z, t, 1);
+ }
+ plankton.flush();
+ lastSpawnDepth = d;
+
+ // ── creatures
+ if (d < 900) {
+ school.update(t, SCHOOL_C, 3.6);
+ school.mesh.visible = true;
+ } else school.mesh.visible = false;
+ nautilus.visible = d < 1200;
+ if (nautilus.visible) {
+ const jet = Math.pow(0.5 + 0.5 * Math.sin(t * 0.9), 6);
+ nautilus.position.copy(NAUT_BASE).add(tmp.a.set(Math.sin(t * 0.16) * 0.7 - jet * 0.1, Math.sin(t * 0.45) * 0.18, Math.cos(t * 0.13) * 0.45));
+ nautilus.rotation.set(Math.sin(t * 0.4) * 0.08, -1.72 + Math.sin(t * 0.16) * 0.22, Math.sin(t * 0.3) * 0.06);
+ }
+ const jellyOn = d > 80 && d < 2600;
+ for (const j of jellies) {
+ j.visible = jellyOn;
+ if (j.userData.light) { j.userData.light.intensity = jellyOn ? 2.4 * (0.7 + 0.3 * Math.sin(t * 2 + j.userData.off)) : 0; j.userData.light.position.copy(j.position).y -= 0.15; }
+ if (!jellyOn) continue;
+ const u = j.userData;
+ j.position.copy(u.base).add(tmp.a.set(Math.sin(t * 0.1 + u.off) * 0.5, Math.sin(t * u.vel * 2.2 + u.off) * 1.1, Math.cos(t * 0.08 + u.off) * 0.4));
+ j.rotation.set(Math.sin(t * 0.2 + u.off) * 0.18, t * u.spin, Math.cos(t * 0.17 + u.off) * 0.16);
+ const fogD = lerp(0.025, 0.055, dark);
+ for (const m of u.mats) { m.uniforms.uT.value = t; m.uniforms.uGlow.value = lerp(0.35, 1.25, smooth(150, 700, d)); m.uniforms.uFogD.value = fogD; }
+ }
+ // Anglerfish: the lure is always on; she turns toward whichever beam finds her.
+ if (angler.visible) {
+ tmp.a.copy(angler.position).sub(floods[1].position).normalize();
+ const inBeam = fp > 0.2 && tmp.a.angleTo(floodUniforms.uLDir.value[1]) < 0.42 ? 1 : 0;
+ anglerState.lit = damp(anglerState.lit, inBeam, inBeam ? 2.2 : 0.5, dt);
+ const toSub = Math.atan2(sub.position.x - angler.position.x, sub.position.z - angler.position.z);
+ const toCam = Math.atan2(camera.position.x - angler.position.x, camera.position.z - angler.position.z);
+ const idle = toCam + 0.42 + Math.sin(t * 0.18) * 0.22;
+ anglerState.yaw = damp(anglerState.yaw, lerp(idle, toSub, anglerState.lit), 1.4, dt);
+ angler.rotation.set(Math.sin(t * 0.7) * 0.03 - anglerState.lit * 0.08, anglerState.yaw, Math.sin(t * 0.45) * 0.05);
+ anglerInner.rotation.y = Math.sin(t * 2.1) * 0.02;
+ angler.updateMatrixWorld();
+ toWorld(anglerModel, LURE_RAW, lureWorld);
+ const flick = 0.85 + 0.15 * Math.sin(t * 3.1) * Math.sin(t * 1.7);
+ lureCol.value.setRGB(2.2, 5.5, 5.8).multiplyScalar(flick);
+ lureLight.position.copy(lureWorld);
+ lureLight.intensity = 13 * flick;
+ lureHalo.position.copy(lureWorld);
+ lureHalo.material.opacity = 0.75 * flick;
+ }
+ lureHalo.visible = angler.visible;
+ if (!angler.visible) lureLight.intensity = 0;
+ // Vent.
+ const ventOn = d > 3000 && d < 9000;
+ vent.visible = ventOn;
+ if (plume) {
+ plume.smoke.visible = plume.sparks.visible = ventOn;
+ for (const m of plume.mats) { m.uniforms.uT.value = t; }
+ const vf = 0.8 + 0.2 * Math.sin(t * 5.3) * Math.sin(t * 2.1);
+ ventLights[0].intensity = ventOn ? 55 * vf : 0;
+ ventLights[1].intensity = ventOn ? 14 * vf : 0;
+ ventGlow.value.setRGB(1.6, 0.42, 0.08).multiplyScalar(vf);
+ // Heat haze above the chimney.
+ tmp.a.copy(ventTop).add(V3(0, 0.4, 0)).project(camera);
+ const onS = ventOn && tmp.a.z < 1 && Math.abs(tmp.a.x) < 1.3 && Math.abs(tmp.a.y) < 1.3;
+ const distV = camera.position.distanceTo(ventTop);
+ fx.uniforms.get('uHaze').value.set((tmp.a.x + 1) / 2, (tmp.a.y + 1) / 2, clamp(1.6 / distV, 0.02, 0.4), onS ? 1 : 0);
+ }
+ // Beacon: a 12 kHz ping every two seconds, shown as a cyan pulse.
+ const bph = (t % 2.0) / 2.0;
+ const bp = Math.exp(-bph * 9) + 0.12;
+ bcn.glass.emissiveIntensity = bp * 6;
+ bcn.light.intensity = bp * 6 * smooth(6000, 8000, d);
+ bcn.light.position.copy(bcn.group.position).y += 1.33;
+ bcn.group.getWorldPosition(beaconHalo.position); beaconHalo.position.y += 1.33;
+ beaconHalo.material.opacity = bp;
+ beaconHalo.scale.setScalar(0.5 + bp * 0.9);
+ bcn.group.visible = beaconHalo.visible = beaconRing.visible = d > 6000;
+ beaconRing.material.uniforms.uP.value = bph;
+ beaconRing.material.uniforms.uVis.value = smooth(0.1, 0.35, (camera.position.y - beaconRing.position.y) / Math.max(1, camera.position.distanceTo(beaconRing.position)));
+ // Faint cool fill in the dark so the hull separates from the black.
+ fill.intensity = dark * (0.5 + 0.4 * smooth(4.3, 5, s));
+ fill.position.copy(camera.position).add(tmp.a.set(-6, 9, 2));
+ fill.target.position.copy(sub.position);
+ // Companion light: the vessel sections need the sub itself lit.
+ const rovK = smooth(5.3, 5.9, s);
+ rov.intensity = rovK * 60 + smooth(4.6, 5.0, s) * 22;
+ rov.position.copy(camera.position).add(tmp.a.set(-2.5, 3.5, 0));
+ rov.target.position.copy(sub.position);
+
+ // ── post
+ const sonarDark = 1;
+ updatePing(t);
+ void sonarDark;
+
+ // ── HUD & UI state
+ updateHud(Math.abs(sTarget - sNow) < 0.002 ? Math.round(d) : d, s);
+ document.body.classList.toggle('is-dark', d > 700 && s < 5.4);
+ document.body.classList.toggle('is-deep-ui', s > 5.4);
+ document.body.classList.toggle('is-docked', s > 5.3);
+ updateHotspots(s);
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('abyssal', { theme: 'dark' });
+cursor({ color: '#3fd6c9', blend: 'normal', size: 34 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? 0 : document.querySelector(id);
+ if (el === null) return;
+ e.preventDefault();
+ lenis.scrollTo(el === 0 ? 0 : el, { duration: 2.4, offset: 0 });
+}));
+document.querySelector('.ascend').addEventListener('click', () => {
+ lenis.scrollTo(0, { duration: 7, easing: x => (x < 0.5 ? 4 * x * x * x : 1 - Math.pow(-2 * x + 2, 3) / 2) });
+ toast('<b>Ascent</b> · drop weights released · 3 h 02 min to the surface', 4200);
+});
+reveal('.glass h2, .foot-title', { type: 'lines', stagger: 0.08 });
+document.querySelectorAll('.zone-card, .pelagia-copy').forEach(el => {
+ gsap.from(el.querySelectorAll('header, h2, .stats, .see, .eyebrow, .specs'), { y: 40, opacity: 0, duration: 1.3, ease: 'expo.out', stagger: 0.08,
+ scrollTrigger: { trigger: el, start: 'top 82%', once: true } });
+});
+reveal('.zone-card .lede, .pelagia .lede', { type: 'lines', stagger: 0.05, y: '100%' });
+
+// Frame creatures from their station cameras (keeps composition right at any aspect ratio).
+function placeFromStation(s, [sx, sy, dist], out) {
+ rigAt(s);
+ const c = new THREE.PerspectiveCamera(camera.fov, innerWidth / innerHeight, 0.1, 100);
+ applyLens(c, innerWidth, innerHeight);
+ c.position.copy(rig.cam); c.lookAt(rig.look); c.updateMatrixWorld();
+ const dir = V3(sx * 2 - 1, 1 - sy * 2, 0.5).unproject(c).sub(c.position).normalize();
+ return out.copy(c.position).addScaledVector(dir, dist);
+}
+for (const j of jellies) {
+ const [x, y, dd] = j.userData.at;
+ placeFromStation(2, MOBILE ? [0.12 + (x - 0.3) * 1.3, y * 0.72 - 0.04, dd * 1.1] : j.userData.at, j.userData.base);
+}
+placeFromStation(3, MOBILE ? [0.58, 0.27, 12] : [0.67, 0.47, 9.5], ANGLER_BASE);
+placeFromStation(RIDE[0], rideSpot(RIDE[0]), anglerEntry);
+placeFromStation(RIDE[1], rideSpot(RIDE[1]), anglerExit);
+{
+ // Beacon 07 sits in the pool of the floodlights, between the landed sub and the camera.
+ const bp = placeFromStation(5, MOBILE ? [0.36, 0.4, 11] : [0.43, 0.64, 9.2], V3());
+ BEACON_XZ[0] = bp.x; BEACON_XZ[1] = bp.z;
+ bcn.group.position.set(bp.x, heightAt(bp.x, bp.z) - 0.02, bp.z);
+ beaconRing.position.set(bp.x, heightAt(bp.x, bp.z) + 0.06, bp.z);
+ const [sx, , sz] = STATIONS[5].sub;
+ const yawB = Math.atan2(-(bp.z - sz), bp.x - sx) - 0.25;
+ for (const st of STATIONS.slice(5)) st.yaw = yawB;
+}
+
+await Promise.all([subLoad, nautLoad, angLoad, ventLoad].map(p => p.catch(e => console.warn('model missing', e.message))));
+if (DBG.has('s')) {
+ const target = scrollFromS(+DBG.get('s'));
+ lenis.scrollTo(target, { immediate: true });
+ sNow = +DBG.get('s');
+}
+// Warm every program: floodlights, vent and beacon on, every creature visible.
+floodState.power = 1;
+for (const L of floods) L.intensity = 100;
+ventLights[0].intensity = 10; bcn.light.intensity = 1; lureLight.intensity = 1; strobe.intensity = 1; rov.intensity = 1;
+renderer.compile(scene, camera);
+floodState.power = 0;
+engine.start();
+await loader.finish();
+if (!DBG.has('nointro')) {
+ gsap.to(intro, { k: 1, duration: 3.4, ease: 'power2.out' });
+ // Splash: a burst of bubbles around the hull as she enters.
+ for (let i = 0; i < 520; i++) {
+ toWorld(subModel, tmp.a.set(rnd(-1.1, 1.1), rnd(-0.6, 0.7), rnd(-0.6, 0.6)), tmp.c);
+ plankton.emit(tmp.c.x, tmp.c.y, tmp.c.z, engine.time + rnd(0, 1.2), 1);
+ }
+ plankton.flush();
+}
+gsap.from('.hero h1 .l > span', { yPercent: 100, opacity: 0, duration: 1.8, ease: 'expo.out', stagger: 0.1, delay: 0.25 });
+gsap.from('.hero .eyebrow, .hero .sub, .hero .cta, .nav, .gauge, .hint', { opacity: 0, y: 16, duration: 1.4, ease: 'power3.out', stagger: 0.07, delay: 0.7, clearProps: 'opacity,transform' });
+if (DBG.has('ping')) setTimeout(ping, +DBG.get('ping') || 400);
+window.__abyss = { dbg: { lampHalos, floods, lampGlow, strobeDot, beaconHalo, lureHalo, bcn, subInner }, engine, scene, camera, renderer, THREE, ping, get s() { return sNow; }, scrollFromS, depthAt };
diff --git a/examples/abyssal/ocean.js b/examples/abyssal/ocean.js
new file mode 100644
index 0000000..9f85124
--- /dev/null
+++ b/examples/abyssal/ocean.js
@@ -0,0 +1,285 @@
+// The water itself: wavelength-dependent fog, caustics injected into every lit material,
+// a post effect for sun shafts / sonar sweep / vent heat haze, and the surface seen from below.
+import * as THREE from 'three';
+import { Effect, EffectAttribute, BlendFunction } from 'postprocessing';
+
+// Seawater absorbs red first, then green: fog reaches the water colour per channel at different distances.
+THREE.ShaderChunk.fog_fragment = /* glsl */`
+#ifdef USE_FOG
+ #ifdef FOG_EXP2
+ vec3 fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth * vec3( 2.1, 1.1, 0.78 ) );
+ #else
+ vec3 fogFactor = vec3( smoothstep( fogNear, fogFar, vFogDepth ) );
+ #endif
+ gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, clamp( fogFactor, 0.0, 1.0 ) );
+#endif`;
+
+export const CAUSTIC_GLSL = /* glsl */`
+float causticAt(vec2 uv, float time) {
+ // After Dave Hoskins' tileable water caustic.
+ vec2 p = mod(uv * 6.28318, 6.28318) - 250.0;
+ vec2 i = p;
+ float c = 1.0;
+ float inten = 0.005;
+ for (int n = 0; n < 4; n++) {
+ float t = time * (1.0 - (3.5 / float(n + 1)));
+ i = p + vec2(cos(t - i.x) + sin(t + i.y), sin(t - i.y) + cos(t + i.x));
+ c += 1.0 / length(vec2(p.x / (sin(i.x + t) / inten), p.y / (cos(i.y + t) / inten)));
+ }
+ c /= 4.0;
+ c = 1.17 - pow(c, 1.4);
+ return pow(abs(c), 8.0);
+}`;
+
+/** Shared uniforms every patched material reads (updated once per frame by main). */
+export const waterUniforms = {
+ uCausT: { value: 0 },
+ uCausAmt: { value: 1 },
+ uCausCol: { value: new THREE.Color(0.8, 1.0, 0.95) },
+ uCausScale: { value: 0.32 },
+};
+
+/**
+ * Patch a MeshStandardMaterial: world-space caustics falling from above, plus optional emissive masks
+ * in object space (`glow: [{ center, radius, color: Uniform, lum }]`) for lamps and lures baked into the texture.
+ */
+export function patchWater(mat, { caustics = true, glow = [], extra = null } = {}) {
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (sh, r) => {
+ prev?.call(mat, sh, r);
+ Object.assign(sh.uniforms, waterUniforms);
+ glow.forEach((g, k) => {
+ sh.uniforms['uGlowC' + k] = { value: g.center };
+ sh.uniforms['uGlowCol' + k] = g.color;
+ });
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vCW;\nvarying vec3 vObj;')
+ .replace('#include <project_vertex>', `#include <project_vertex>
+ vec4 cwp = vec4(transformed, 1.0);
+ #ifdef USE_INSTANCING
+ cwp = instanceMatrix * cwp;
+ #endif
+ vCW = (modelMatrix * cwp).xyz;
+ vObj = position;`);
+ let glowDecl = '', glowCode = '';
+ glow.forEach((g, k) => {
+ glowDecl += `uniform vec3 uGlowC${k}; uniform vec3 uGlowCol${k};\n`;
+ const lum = g.lum ? `* smoothstep(${g.lum.toFixed(2)}, 1.0, dot(diffuseColor.rgb, vec3(0.3, 0.55, 0.15)))` : '';
+ glowCode += `totalEmissiveRadiance += uGlowCol${k} * smoothstep(${g.radius.toFixed(4)}, ${(g.radius * (g.inner ?? 0.35)).toFixed(4)}, distance(vObj, uGlowC${k})) ${lum};\n`;
+ });
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vCW; varying vec3 vObj;
+ uniform float uCausT, uCausAmt, uCausScale; uniform vec3 uCausCol;
+ ${glowDecl}
+ ${CAUSTIC_GLSL}`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>\n${glowCode}`)
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>
+ ${caustics ? `
+ if (uCausAmt > 0.002) {
+ vec3 cwN = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ float up = clamp(cwN.y * 0.6 + 0.42, 0.0, 1.0);
+ vec2 cuv = (vCW.xz + vec2(0.18, 0.1) * vCW.y) * uCausScale;
+ float cs = causticAt(cuv, uCausT) + causticAt(cuv * 1.37 + 3.1, uCausT * 1.21) * 0.6;
+ reflectedLight.directDiffuse += material.diffuseColor * uCausCol * cs * up * uCausAmt;
+ }` : ''}`);
+ if (extra) extra(sh);
+ };
+ mat.customProgramCacheKey = () => 'water' + (caustics ? 1 : 0) + glow.length + (extra ? 'x' : '') + (mat.name || '');
+ mat.needsUpdate = true;
+ return mat;
+}
+
+// ─── Post: sun shafts, sonar sweep, heat haze ──────────────────────────────
+const frag = /* glsl */`
+uniform mat4 uProjInv;
+uniform mat4 uCamWorld;
+uniform vec3 uCamPos;
+uniform float uT;
+uniform float uSun;
+uniform vec3 uSunCol;
+uniform float uSurfY;
+uniform vec4 uPing; // xyz origin, w radius
+uniform float uPingAmt;
+uniform vec4 uHaze; // xy uv, z radius, w amount
+uniform float uAspect;
+
+float h21(vec2 p) { p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
+float vn2(vec2 p) {
+ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(h21(i), h21(i + vec2(1, 0)), f.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), f.x), f.y);
+}
+float shaft(vec2 q) {
+ float n = vn2(q * 0.36 + vec2(uT * 0.05, uT * 0.03)) * 0.6 + vn2(q * 0.95 - vec2(uT * 0.07, -uT * 0.05)) * 0.4;
+ return pow(smoothstep(0.5, 0.98, n), 2.6);
+}
+
+void mainUv(inout vec2 uv) {
+ if (uHaze.w > 0.001) {
+ vec2 d = (uv - uHaze.xy) * vec2(uAspect, 1.0);
+ float up = d.y / uHaze.z;
+ float w = uHaze.z * (0.35 + max(up, 0.0) * 0.28);
+ float m = exp(-pow(d.x / w, 2.0)) * smoothstep(-0.2, 0.25, up) * exp(-max(up, 0.0) * 0.45);
+ float n1 = sin(uv.y * 150.0 - uT * 7.0 + sin(uv.x * 70.0 + uT * 2.3) * 1.7);
+ float n2 = sin(uv.x * 120.0 + uT * 4.9 + uv.y * 50.0);
+ uv += vec2(n1, n2 * 0.6) * 0.0055 * m * uHaze.w;
+ }
+}
+
+void mainImage(const in vec4 inputColor, const in vec2 uv, const in float depth, out vec4 outputColor) {
+ vec3 col = inputColor.rgb;
+ vec4 clip = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
+ vec4 vp = uProjInv * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vec4(vp.xyz, 1.0)).xyz;
+ vec3 ro = uCamPos;
+ vec3 rd = wp - ro;
+ float dist = length(rd);
+ rd /= dist;
+
+ if (uSun > 0.001) {
+ float len = min(dist, 46.0);
+ const int N = 26;
+ float stepL = len / float(N);
+ float jit = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
+ float acc = 0.0;
+ for (int i = 0; i < N; i++) {
+ float t = (float(i) + jit) * stepL;
+ vec3 p = ro + rd * t;
+ float below = uSurfY - p.y;
+ if (below < 0.0) continue;
+ vec2 q = p.xz + vec2(0.18, 0.1) * below;
+ acc += shaft(q) * exp(-below * 0.06 - t * 0.035) * stepL;
+ }
+ col += uSunCol * acc * uSun;
+ }
+
+ if (uPingAmt > 0.001 && depth < 0.99999) {
+ float d = distance(wp, uPing.xyz);
+ float behind = uPing.w - d;
+ float front = exp(-behind * behind * 5.0);
+ float trail = behind > 0.0 ? exp(-behind * 0.3) : 0.0;
+ float rings = smoothstep(0.93, 1.0, fract(d * 1.1)) * trail;
+ float contour = smoothstep(0.9, 1.0, fract(wp.y * 2.0)) * trail * 0.6;
+ float fadeD = exp(-dist * 0.035);
+ col += vec3(0.22, 0.95, 0.86) * (front * 1.5 + rings * 0.5 + contour * 0.55 + trail * 0.025) * uPingAmt * fadeD;
+ }
+ // The pressure wave itself, seen in open water: an expanding shell with a bright limb.
+ if (uPingAmt > 0.001) {
+ vec3 oc = uPing.xyz - ro;
+ float R = uPing.w;
+ float b = dot(oc, rd);
+ float p = sqrt(max(dot(oc, oc) - b * b, 0.0));
+ float w = 0.1 + R * 0.018;
+ float limb = exp(-pow((R - p) / w, 2.0)) + smoothstep(R, 0.0, p) * 0.015;
+ float vis = step(0.0, b) * step(b - 0.5, dist);
+ float outside = smoothstep(0.0, 3.0, length(oc) - R);
+ col += vec3(0.25, 0.95, 0.88) * limb * vis * outside * uPingAmt * 0.7;
+ }
+ outputColor = vec4(col, inputColor.a);
+}`;
+
+export class AbyssEffect extends Effect {
+ constructor(camera) {
+ super('AbyssEffect', frag, {
+ attributes: EffectAttribute.DEPTH,
+ blendFunction: BlendFunction.NORMAL,
+ uniforms: new Map([
+ ['uProjInv', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamWorld', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamPos', new THREE.Uniform(new THREE.Vector3())],
+ ['uT', new THREE.Uniform(0)],
+ ['uSun', new THREE.Uniform(1)],
+ ['uSunCol', new THREE.Uniform(new THREE.Color(0.1, 0.25, 0.28))],
+ ['uSurfY', new THREE.Uniform(0)],
+ ['uPing', new THREE.Uniform(new THREE.Vector4(0, 0, 0, 0))],
+ ['uPingAmt', new THREE.Uniform(0)],
+ ['uHaze', new THREE.Uniform(new THREE.Vector4(0.5, 0.5, 0.1, 0))],
+ ['uAspect', new THREE.Uniform(1)],
+ ]),
+ });
+ this.camera = camera;
+ }
+ update(renderer, inputBuffer, dt) {
+ const u = this.uniforms, cam = this.camera;
+ u.get('uProjInv').value.copy(cam.projectionMatrixInverse);
+ u.get('uCamWorld').value.copy(cam.matrixWorld);
+ u.get('uCamPos').value.setFromMatrixPosition(cam.matrixWorld);
+ u.get('uT').value += dt;
+ u.get('uAspect').value = cam.aspect;
+ }
+}
+
+// ─── The water around you: brighter toward the surface, darker below ───────
+export function waterDome() {
+ const mat = new THREE.ShaderMaterial({
+ side: THREE.BackSide, depthWrite: false, depthTest: false, fog: false,
+ uniforms: { uTop: { value: new THREE.Color() }, uMid: { value: new THREE.Color() }, uBot: { value: new THREE.Color() }, uSun: { value: 1 }, uT: { value: 0 } },
+ vertexShader: /* glsl */`varying vec3 vD; void main(){ vD = normalize((modelMatrix * vec4(position, 1.0)).xyz - cameraPosition); gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0); gl_Position.z = gl_Position.w; }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uTop, uMid, uBot; uniform float uSun, uT; varying vec3 vD;
+ void main(){
+ vec3 d = normalize(vD);
+ float y = d.y;
+ vec3 col = mix(uMid, uTop, smoothstep(0.0, 0.85, y));
+ col = mix(col, uBot, smoothstep(0.02, -0.7, y));
+ // the sun, smeared by the water above
+ float s = pow(max(dot(d, normalize(vec3(-0.18, 1.0, -0.1))), 0.0), 6.0);
+ col += uTop * s * 0.8 * uSun;
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+ });
+ const m = new THREE.Mesh(new THREE.SphereGeometry(150, 48, 24), mat);
+ m.renderOrder = -10;
+ m.frustumCulled = false;
+ return m;
+}
+
+// ─── The surface, seen from below ──────────────────────────────────────────
+export function waterSurface() {
+ const mat = new THREE.ShaderMaterial({
+ side: THREE.DoubleSide,
+ fog: false, transparent: true, depthWrite: false,
+ uniforms: {
+ uT: { value: 0 }, uAmt: { value: 1 },
+ uSky: { value: new THREE.Color(1.7, 2.6, 2.6) },
+ uDeep: { value: new THREE.Color(0.04, 0.28, 0.34) },
+ uFog: { value: new THREE.Color(0.05, 0.4, 0.45) },
+ },
+ vertexShader: /* glsl */`
+ varying vec3 vW;
+ void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,
+ fragmentShader: /* glsl */`
+ uniform float uT, uAmt; uniform vec3 uSky, uDeep, uFog;
+ varying vec3 vW;
+ ${CAUSTIC_GLSL}
+ vec2 waves(vec2 p) {
+ vec2 g = vec2(0.0);
+ g += vec2(cos(p.x * 0.9 + uT * 1.1), cos(p.y * 0.7 + uT * 0.8)) * 0.16;
+ g += vec2(cos(dot(p, vec2(1.7, 1.1)) - uT * 1.7), cos(dot(p, vec2(-1.3, 1.9)) + uT * 1.4)) * 0.09;
+ g += vec2(cos(dot(p, vec2(4.1, -2.3)) + uT * 2.9), cos(dot(p, vec2(2.7, 3.9)) - uT * 2.5)) * 0.05;
+ return g;
+ }
+ void main() {
+ vec3 v = vW - cameraPosition;
+ float dist = length(v);
+ v /= dist;
+ vec2 g = waves(vW.xz * 0.45);
+ vec3 n = normalize(vec3(g.x, 1.0, g.y));
+ float c = dot(v, n);
+ // Snell's window, widened a touch so the light reaches into a landscape frame.
+ float win = smoothstep(0.3, 0.78, c);
+ float glint = causticAt(vW.xz * 0.11 + g * 0.3, uT * 0.45);
+ float fine = causticAt(vW.xz * 0.29 - g * 0.2, uT * 0.6);
+ float web = smoothstep(0.08, 0.6, fine) * 0.9 + smoothstep(0.1, 0.7, glint) * 0.6;
+ vec3 sky = uSky * (0.32 + 1.6 * web) * (0.8 + 0.6 * smoothstep(0.85, 1.0, c));
+ vec3 refl = uDeep * (0.5 + 1.4 * web + g.x * 0.6);
+ vec3 col = mix(refl, sky, win);
+ col = mix(col, uFog, 1.0 - exp(-dist * 0.006));
+ gl_FragColor = vec4(col * uAmt, exp(-dist * 0.011) * uAmt);
+ }`,
+ });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(700, 700, 1, 1), mat);
+ mesh.rotation.x = Math.PI / 2;
+ mesh.frustumCulled = false;
+ return mesh;
+}
diff --git a/examples/abyssal/style.css b/examples/abyssal/style.css
new file mode 100644
index 0000000..20e8b61
--- /dev/null
+++ b/examples/abyssal/style.css
@@ -0,0 +1,327 @@
+:root {
+ --bg: #02070c;
+ --ink: #e4f1f2;
+ --muted: #7d949b;
+ --dim: rgba(228, 241, 242, .42);
+ --rule: rgba(228, 241, 242, .14);
+ --cyan: #3fd6c9;
+ --orange: #ff6419;
+ --display: 'Space Grotesk', system-ui, sans-serif;
+ --mono: 'IBM Plex Mono', ui-monospace, monospace;
+ --gutter: clamp(16px, 4.4vw, 64px);
+ --gauge-w: clamp(150px, 14vw, 206px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; }
+body { font: 400 16px/1.6 var(--display); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+.mono { font-family: var(--mono); font-size: 11px; letter-spacing: .1em; text-transform: uppercase; font-variant-numeric: tabular-nums; }
+.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+em { font-style: normal; }
+
+/* ─── loader: a sonar scope running the pre-dive checklist ───────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: radial-gradient(90% 70% at 50% 45%, #041219, #010305 70%); display: grid; place-content: center; justify-items: center; gap: 26px; }
+.scope { position: relative; width: 168px; height: 168px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(63,214,201,.35), 0 0 60px rgba(63,214,201,.08); overflow: hidden; }
+.scope-sweep { position: absolute; inset: 0; border-radius: 50%; background: conic-gradient(from 0deg, rgba(63,214,201,.0) 0deg, rgba(63,214,201,.0) 290deg, rgba(63,214,201,.45) 359deg, rgba(63,214,201,0) 360deg); animation: sweep 2.4s linear infinite; }
+.scope-ring { position: absolute; left: 50%; top: 50%; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(63,214,201,.16); transform: translate(-50%, -50%); }
+.r1 { width: 33%; height: 33%; } .r2 { width: 66%; height: 66%; } .r3 { width: 100%; height: 100%; }
+.scope::before, .scope::after { content: ''; position: absolute; background: rgba(63,214,201,.14); }
+.scope::before { left: 50%; top: 0; bottom: 0; width: 1px; } .scope::after { top: 50%; left: 0; right: 0; height: 1px; }
+.scope-blip { position: absolute; left: 64%; top: 30%; width: 6px; height: 6px; border-radius: 50%; background: var(--cyan); box-shadow: 0 0 12px var(--cyan); animation: blip 2.4s linear infinite; }
+.scope-pct { position: absolute; inset: 0; display: grid; place-content: center; font: 400 13px/1 var(--mono); letter-spacing: .08em; color: var(--ink); }
+.scope-pct em { font-size: 26px; font-weight: 400; letter-spacing: 0; }
+@keyframes sweep { to { transform: rotate(360deg); } }
+@keyframes blip { 0%, 18% { opacity: 0; } 20% { opacity: 1; } 60%, 100% { opacity: 0; } }
+.loader-title { color: var(--cyan); }
+.checks { list-style: none; display: grid; gap: 7px; width: 250px; color: var(--muted); }
+.checks li { display: flex; justify-content: space-between; border-bottom: 1px dashed rgba(228,241,242,.1); padding-bottom: 6px; }
+.checks li.ok { color: var(--ink); }
+.checks li.ok b { color: var(--cyan); }
+
+/* ─── nav ───────────────────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 20px var(--gutter); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 11px; text-decoration: none; font: 500 15px/1 var(--display); letter-spacing: .34em; text-transform: uppercase; justify-self: start; }
+.brand svg { width: 26px; height: 26px; color: var(--cyan); }
+.links { display: flex; gap: 6px; padding: 5px; border-radius: 999px; background: rgba(2,10,16,.34); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--rule); }
+.links a { text-decoration: none; font: 500 13px/1 var(--display); color: rgba(228,241,242,.72); padding: 10px 16px; border-radius: 999px; transition: color .3s, background .3s; }
+.links a:hover { color: var(--ink); background: rgba(228,241,242,.08); }
+.nav-end { justify-self: end; display: flex; align-items: center; gap: 12px; }
+.sound { display: flex; align-items: center; gap: 9px; height: 44px; padding: 0 16px; color: var(--muted); border-radius: 999px; transition: color .3s; }
+.sound i { width: 16px; height: 10px; background: repeating-linear-gradient(90deg, currentColor 0 2px, transparent 2px 4px); -webkit-mask: linear-gradient(0deg, #000 30%, transparent 30%) ; mask: linear-gradient(0deg, #000 30%, transparent 30%); }
+.sound[aria-pressed="true"] { color: var(--cyan); }
+.sound[aria-pressed="true"] i { animation: eq .9s steps(3) infinite; -webkit-mask: linear-gradient(0deg, #000 80%, transparent 80%); mask: linear-gradient(0deg, #000 80%, transparent 80%); }
+@keyframes eq { 50% { transform: scaleY(.5); } }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 999px;
+ text-decoration: none; font: 500 14px/1 var(--display); letter-spacing: .01em; transition: background .35s, color .35s, box-shadow .35s; white-space: nowrap; }
+.btn-solid { background: var(--orange); color: #1a0700; }
+.btn-solid:hover { background: #ff8440; box-shadow: 0 0 44px rgba(255,100,25,.4); }
+.btn-ghost { box-shadow: inset 0 0 0 1px rgba(228,241,242,.3); color: var(--ink); background: rgba(2,10,16,.24); backdrop-filter: blur(10px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--cyan); }
+
+/* ─── depth gauge ──────────────────────────────────────────────────────── */
+.gauge { position: fixed; z-index: 20; right: var(--gutter); top: 118px; bottom: 96px; width: var(--gauge-w); pointer-events: none; text-shadow: 0 0 14px rgba(0,10,16,.55); }
+.rail { position: absolute; inset: 0; }
+.rail::before { content: ''; position: absolute; right: 0; top: 0; bottom: 0; width: 9px;
+ background: linear-gradient(90deg, transparent 8px, rgba(228,241,242,.3) 8px) , repeating-linear-gradient(180deg, rgba(228,241,242,.22) 0 1px, transparent 1px 2%);
+ -webkit-mask: linear-gradient(90deg, transparent 4px, #000 4px); mask: linear-gradient(90deg, transparent 4px, #000 4px); }
+.rail-fill { position: absolute; right: 0; top: 0; width: 1px; height: calc(var(--d, 0) * 100%); background: var(--cyan); box-shadow: 0 0 10px var(--cyan); }
+.rail-zones { list-style: none; position: absolute; inset: 0; }
+.rail-zones li { position: absolute; right: 16px; top: calc(var(--p) * 100%); transform: translateY(-50%); display: flex; gap: 10px; align-items: baseline;
+ color: var(--dim); font-size: 9.5px; transition: opacity .4s; white-space: nowrap; }
+.rail-zones li b { font-weight: 500; color: rgba(228,241,242,.62); }
+.rail-zones li::after { content: ''; position: absolute; right: -16px; top: 50%; width: 12px; height: 1px; background: rgba(228,241,242,.55); }
+.rail-zones li.near { opacity: 0; }
+.mark { position: absolute; right: 0; top: calc(var(--d, 0) * 100%); height: 0; width: 100%; }
+.mark-body { position: absolute; right: 24px; top: 0; display: grid; justify-items: end; gap: 6px; transform: translateY(calc(-50% + (0.5 - var(--d, 0)) * 76%)); }
+.mark::after { content: ''; position: absolute; right: 0; top: 50%; width: 18px; height: 1px; background: var(--cyan); box-shadow: 0 0 8px var(--cyan); }
+.mark::before { content: ''; position: absolute; right: -4px; top: 50%; width: 7px; height: 7px; margin-top: -3.5px; border-radius: 50%; background: var(--bg); box-shadow: inset 0 0 0 1.5px var(--cyan), 0 0 10px var(--cyan); }
+.mark-label { display: flex; gap: 12px; color: var(--cyan); font-size: 9.5px; }
+.mark-time { color: var(--muted); }
+.odo { display: flex; align-items: baseline; font: 300 clamp(36px, 3.7vw, 56px)/1 var(--display); letter-spacing: -.02em; color: #f4fbfb; text-shadow: 0 0 30px rgba(0,0,0,.6); }
+.odo .col { display: inline-block; height: 1em; overflow: hidden; width: .62em; text-align: center; }
+.odo .col > span { display: flex; flex-direction: column; will-change: transform; }
+.odo .col > span > i { font-style: normal; height: 1em; line-height: 1; }
+.odo .col.lead { color: rgba(244,251,251,.2); }
+.odo .sep { width: .26em; text-align: center; }
+.odo .sep.lead { color: rgba(244,251,251,.2); }
+.odo .unit { font: 400 13px/1 var(--mono); letter-spacing: .1em; margin-left: 8px; color: var(--muted); align-self: flex-end; padding-bottom: .3em; }
+.reads { display: flex; gap: 14px; color: var(--muted); font-size: 9.5px; }
+.reads div { display: grid; justify-items: end; gap: 3px; }
+.reads dd { color: var(--ink); font-size: 11px; letter-spacing: .04em; }
+.reads b { font-weight: 500; }
+
+/* dive log + hints */
+.divelog { position: fixed; z-index: 20; left: var(--gutter); bottom: 64px; list-style: none; display: grid; gap: 6px; font-size: 10px; color: rgba(228,241,242,.78); pointer-events: none; max-width: 360px; text-shadow: 0 0 12px rgba(0,10,16,.9), 0 0 3px rgba(0,10,16,.8); }
+.divelog li { display: flex; gap: 12px; opacity: 0; transform: translateY(8px); transition: opacity .6s, transform .6s; }
+.divelog li.on { opacity: 1; transform: none; }
+.divelog li time { color: var(--cyan); }
+.divelog li:not(:last-child) { opacity: .5; }
+.divelog li:not(.on) { opacity: 0; }
+.hint { position: fixed; z-index: 20; left: 50%; bottom: 22px; transform: translateX(-50%); pointer-events: none; color: rgba(228,241,242,.8); font-size: 10px; }
+.hint > span { padding: 9px 16px; border-radius: 999px; background: rgba(2,12,18,.42); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px var(--rule); }
+.hint > span { display: flex; gap: 10px; align-items: center; justify-content: center; white-space: nowrap; transition: opacity .6s, transform .6s; }
+.hint-b { position: absolute; left: 50%; top: 0; transform: translate(-50%, 10px); opacity: 0; }
+.hint kbd { font: inherit; color: var(--ink); padding: 4px 7px; border-radius: 4px; box-shadow: inset 0 0 0 1px var(--rule); margin-left: 8px; }
+.hint kbd:first-child { margin-left: 0; }
+.chev { width: 9px; height: 9px; border-right: 1px solid var(--cyan); border-bottom: 1px solid var(--cyan); transform: rotate(45deg); animation: chev 1.8s ease-in-out infinite; margin-right: 4px; }
+@keyframes chev { 50% { transform: translateY(4px) rotate(45deg); } }
+.is-dark .hint-a { opacity: 0; transform: translateY(-10px); }
+.is-dark .hint-b { opacity: 1; transform: translate(-50%, 0); }
+.is-deep-ui .hint { opacity: 0; transition: opacity .6s; }
+.toast { position: fixed; z-index: 25; left: 50%; top: 96px; transform: translate(-50%, -10px); padding: 12px 20px; border-radius: 999px; color: var(--ink);
+ background: rgba(2,12,18,.6); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(63,214,201,.4); opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; white-space: nowrap; }
+.toast b { color: var(--cyan); font-weight: 500; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+/* sonar contacts */
+.tags { position: fixed; inset: 0; z-index: 12; pointer-events: none; }
+.tag { position: absolute; left: 0; top: 0; opacity: 0; transition: opacity .35s; will-change: transform; }
+.tag.on { opacity: 1; }
+.tag-box { position: absolute; left: -26px; top: -26px; width: 52px; height: 52px;
+ background: linear-gradient(var(--cyan), var(--cyan)) 0 0 / 10px 1px, linear-gradient(var(--cyan), var(--cyan)) 0 0 / 1px 10px,
+ linear-gradient(var(--cyan), var(--cyan)) 100% 0 / 10px 1px, linear-gradient(var(--cyan), var(--cyan)) 100% 0 / 1px 10px,
+ linear-gradient(var(--cyan), var(--cyan)) 0 100% / 10px 1px, linear-gradient(var(--cyan), var(--cyan)) 0 100% / 1px 10px,
+ linear-gradient(var(--cyan), var(--cyan)) 100% 100% / 10px 1px, linear-gradient(var(--cyan), var(--cyan)) 100% 100% / 1px 10px;
+ background-repeat: no-repeat; filter: drop-shadow(0 0 4px rgba(63,214,201,.8)); transition: transform .5s cubic-bezier(.2,.9,.2,1); transform: scale(1.8); }
+.tag.on .tag-box { transform: scale(1); }
+.tag-text { position: absolute; left: 36px; top: -24px; display: grid; gap: 4px; white-space: nowrap; font-size: 9.5px; color: var(--ink); text-shadow: 0 0 8px #000; }
+.tag-text b { color: var(--cyan); font-weight: 500; }
+.tag-text i { font-style: normal; color: var(--muted); text-transform: none; letter-spacing: .02em; font-size: 11px; }
+
+/* vessel hotspots */
+.hotspots { position: fixed; inset: 0; z-index: 12; pointer-events: none; }
+.hs { position: absolute; left: 0; top: 0; opacity: 0; transition: opacity .5s; will-change: transform; }
+.hs.on { opacity: 1; }
+.hs-dot { position: absolute; left: -9px; top: -9px; width: 18px; height: 18px; border-radius: 50%; box-shadow: inset 0 0 0 1.5px var(--orange); background: rgba(255,100,25,.18); }
+.hs-dot::after { content: ''; position: absolute; inset: -8px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(255,100,25,.6); animation: ring 2.2s ease-out infinite; }
+@keyframes ring { from { transform: scale(.5); opacity: 1; } to { transform: scale(1.6); opacity: 0; } }
+.hs-line { position: absolute; left: 9px; top: 0; height: 1px; width: 92px; background: linear-gradient(90deg, var(--orange), rgba(255,100,25,.2)); transform-origin: 0 0; }
+.hs-card { position: absolute; left: 106px; top: -18px; width: 244px; padding: 14px 16px 15px; background: rgba(3,10,15,.62); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px rgba(255,100,25,.28); border-radius: 3px; }
+.hs.flip .hs-line { left: auto; right: 9px; transform: scaleX(-1); transform-origin: 100% 0; }
+.hs.flip .hs-card { left: auto; right: 106px; }
+.hs-card .mono { color: var(--orange); font-size: 9.5px; }
+.hs-card h3 { font: 500 17px/1.2 var(--display); margin: 7px 0 6px; letter-spacing: -.01em; }
+.hs-card p { font-size: 12.5px; line-height: 1.5; color: #b4c6ca; }
+
+/* ─── sections ─────────────────────────────────────────────────────────── */
+main { position: relative; z-index: 4; }
+.stage { position: relative; pointer-events: none; }
+.stage a, .stage button, .stage .glass, .stage table { pointer-events: auto; }
+.eyebrow { color: var(--cyan); margin-bottom: 22px; }
+.hero .eyebrow { color: #d9fbf8; text-shadow: 0 0 18px rgba(0,40,50,.6); }
+.hero { height: 118vh; }
+.hero-copy { position: sticky; top: 0; height: 100vh; display: grid; align-content: end; padding: 0 var(--gutter) 15vh; max-width: 60rem; }
+.hero h1 { font: 400 clamp(46px, 6.3vw, 104px)/.95 var(--display); letter-spacing: -.045em; color: #f3fbfb; text-shadow: 0 2px 40px rgba(0,30,40,.35); }
+.hero h1 .l { display: block; overflow: hidden; padding-bottom: .04em; }
+.hero h1 .l > span { display: block; }
+.hero h1 em { color: #fff; font-weight: 500; }
+.hero .sub { max-width: 31em; margin-top: 30px; font-size: clamp(16px, 1.25vw, 19px); line-height: 1.55; color: rgba(236,248,249,.86); text-shadow: 0 1px 20px rgba(0,20,30,.5); }
+.cta { display: flex; gap: 12px; margin-top: 36px; flex-wrap: wrap; }
+
+.zone { height: 220vh; display: flex; align-items: center; padding: 0 var(--gutter); }
+.zone.right { justify-content: flex-end; padding-right: calc(var(--gutter) + var(--gauge-w) + 40px); }
+.zone-card { width: min(440px, 100%); pointer-events: auto; }
+.zone-card header { display: flex; justify-content: space-between; padding-bottom: 14px; border-bottom: 1px solid var(--rule); color: var(--cyan); }
+.zone-card header span:last-child { color: var(--ink); }
+.zone-card h2 { font: 400 clamp(46px, 5.4vw, 86px)/.92 var(--display); letter-spacing: -.045em; margin: 30px 0 26px; display: grid; }
+.zone-card h2 em { font: 400 12px/1 var(--mono); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); margin-top: 16px; }
+.lede { font-size: clamp(15.5px, 1.12vw, 17.5px); line-height: 1.6; color: rgba(228,241,242,.82); }
+.stats { display: grid; grid-template-columns: 1fr 1fr; margin-top: 30px; border-top: 1px solid var(--rule); }
+.stats div { padding: 14px 0 12px; border-bottom: 1px solid var(--rule); }
+.stats div:nth-child(odd) { padding-right: 16px; border-right: 1px solid var(--rule); }
+.stats div:nth-child(even) { padding-left: 16px; }
+.stats dt { color: var(--muted); font-size: 9.5px; }
+.stats dd { color: var(--ink); font-size: 12.5px; letter-spacing: .04em; margin-top: 5px; text-transform: none; }
+.see { margin-top: 22px; font-size: 14px; line-height: 1.55; color: rgba(228,241,242,.7); }
+.see .mono { display: block; color: var(--cyan); font-size: 9.5px; margin-bottom: 6px; }
+/* legibility over bright water */
+#sunlight .zone-card { text-shadow: 0 1px 24px rgba(0, 30, 45, .55); }
+#sunlight .zone-card .lede, #sunlight .zone-card .see { color: rgba(240,250,251,.92); }
+#sunlight .zone-card .stats dt { color: rgba(228,241,242,.7); }
+
+.pelagia { height: 300vh; }
+.pelagia-copy { position: sticky; top: 0; height: 100vh; display: grid; align-content: center; padding: 0 var(--gutter); width: min(560px, 100%); }
+.pelagia h2 { font: 400 clamp(64px, 8vw, 132px)/.9 var(--display); letter-spacing: -.05em; }
+.pelagia .lede { max-width: 25em; margin: 26px 0 30px; }
+.specs { display: grid; border-top: 1px solid var(--rule); max-width: 400px; }
+.specs div { display: flex; justify-content: space-between; padding: 11px 0; border-bottom: 1px solid var(--rule); }
+.specs dt { color: var(--muted); font-size: 9.5px; }
+.specs dd { font-size: 11px; }
+
+.book, .crew { min-height: 170vh; display: flex; align-items: center; padding: 14vh var(--gutter); }
+.glass { width: min(900px, calc(100% - var(--gauge-w) - 60px)); padding: clamp(28px, 3.4vw, 52px); border-radius: 4px;
+ background: linear-gradient(180deg, rgba(3,11,17,.74), rgba(2,8,12,.62)); backdrop-filter: blur(18px) saturate(1.1); box-shadow: inset 0 0 0 1px var(--rule), 0 40px 80px -30px rgba(0,0,0,.8); }
+.glass h2 { font: 400 clamp(38px, 4.4vw, 70px)/.98 var(--display); letter-spacing: -.04em; max-width: 13em; }
+.glass h2 em { color: var(--cyan); }
+.price-row { display: grid; grid-template-columns: 1fr 1.2fr; gap: 40px; margin: 42px 0 36px; align-items: start; }
+.price p { color: var(--muted); }
+.price b { display: block; font: 300 clamp(40px, 4.2vw, 64px)/1 var(--display); letter-spacing: -.03em; margin-top: 12px; color: #fff; }
+.incl { list-style: none; display: grid; gap: 10px; font-size: 14.5px; color: rgba(228,241,242,.8); }
+.incl li { display: grid; grid-template-columns: 18px 1fr; }
+.incl li::before { content: ''; width: 6px; height: 6px; margin-top: 9px; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--cyan); }
+.dates { width: 100%; border-collapse: collapse; font-size: 11px; }
+.dates th { text-align: left; color: var(--muted); font-weight: 400; font-size: 9.5px; padding: 0 0 10px; border-bottom: 1px solid var(--rule); }
+.dates td { padding: 15px 0; border-bottom: 1px solid var(--rule); }
+.dates td:first-child { color: var(--cyan); }
+.dates tr.full td { color: var(--muted); }
+.seats { display: inline-flex; gap: 4px; margin-right: 8px; vertical-align: -1px; }
+.seats i { width: 9px; height: 9px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(228,241,242,.4); }
+.seats i.on { background: var(--orange); box-shadow: 0 0 8px rgba(255,100,25,.7); }
+.book-cta { display: flex; gap: 26px; align-items: center; margin-top: 32px; }
+.book-cta p { color: var(--muted); font-size: 10px; line-height: 1.6; max-width: 36em; text-transform: none; letter-spacing: .03em; }
+.crew { justify-content: flex-start; }
+.crew-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--rule); margin: 40px 0 34px; box-shadow: 0 0 0 1px var(--rule); }
+.crew-grid article { background: rgba(3,10,15,.9); padding: 24px 22px 26px; }
+.crew-grid .mono { color: var(--cyan); font-size: 9.5px; }
+.crew-grid h3 { font: 500 22px/1.1 var(--display); letter-spacing: -.02em; margin: 14px 0 10px; }
+.crew-grid p { font-size: 13.5px; line-height: 1.55; color: rgba(228,241,242,.72); }
+.safety { list-style: none; display: grid; grid-template-columns: repeat(4, 1fr); gap: 22px; }
+.safety b { display: block; font: 300 34px/1 var(--display); letter-spacing: -.02em; color: #fff; margin-bottom: 10px; }
+.safety span { color: var(--muted); font-size: 9.5px; line-height: 1.6; display: block; }
+
+.foot { min-height: 110vh; display: grid; align-content: end; padding: 0 var(--gutter) 70px; }
+.foot-inner { width: calc(100% - var(--gauge-w) - 40px); }
+.foot-title { font: 400 clamp(90px, 17vw, 290px)/.8 var(--display); letter-spacing: -.07em; margin: 0 0 34px -0.04em; color: #f3fbfb; }
+.ascend { pointer-events: auto; }
+.foot-cols { display: grid; grid-template-columns: 1fr 1fr auto; gap: 30px; margin-top: 60px; padding-top: 24px; border-top: 1px solid var(--rule); color: var(--muted); line-height: 2; }
+.foot-cols nav { display: flex; gap: 20px; pointer-events: auto; }
+.foot-cols nav a { text-decoration: none; }
+.foot-cols nav a:hover { color: var(--ink); }
+.fine { margin-top: 30px; color: rgba(125,148,155,.6); font-size: 9.5px; }
+
+/* ─── mobile ───────────────────────────────────────────────────────────── */
+@media (max-width: 900px) {
+ :root { --gauge-w: 118px; }
+ .nav { grid-template-columns: 1fr auto; padding: 14px 16px; }
+ .links, .sound { display: none; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 12.5px; }
+ .brand { font-size: 13px; }
+ .gauge { right: 12px; top: auto; bottom: 64px; height: 38vh; }
+ .rail-zones li span { display: none; }
+ .odo { font-size: 30px; }
+ .reads { gap: 8px; }
+ .reads div:nth-child(3) { display: none; }
+ .mark-label .mark-time { display: none; }
+ .divelog { display: none; }
+ .hint { bottom: auto; top: 120px; left: 50%; transform: translateX(-50%); }
+ .hint-b { left: 50%; transform: translate(-50%, 10px); }
+ .is-dark .hint-b { transform: translate(-50%, 0); }
+ .hint > span { justify-content: flex-start; }
+ .hero-copy { padding-bottom: 20vh; }
+ .zone, .zone.right { justify-content: flex-start; padding: 0 16px; }
+ .zone-card { background: rgba(2,9,14,.55); backdrop-filter: blur(10px); padding: 20px; border-radius: 4px; box-shadow: inset 0 0 0 1px var(--rule); width: calc(100% - 0px); }
+ .zone-card h2 { margin: 20px 0 16px; }
+ .pelagia-copy { align-content: end; padding-bottom: 12vh; }
+ .pelagia .lede { display: none; }
+ .hs-card { width: 170px; padding: 10px 12px; }
+ .hs-card p { display: none; }
+ .glass { width: 100%; }
+ .price-row { grid-template-columns: 1fr; gap: 24px; }
+ .dates th:nth-child(3), .dates td:nth-child(3) { display: none; }
+ .book-cta { flex-direction: column; align-items: flex-start; }
+ .crew-grid, .safety { grid-template-columns: 1fr; }
+ .foot-inner { width: 100%; }
+ .foot-cols { grid-template-columns: 1fr; gap: 12px; }
+ .foot-cols nav { flex-wrap: wrap; }
+ .toast { top: 70px; white-space: normal; text-align: center; width: max-content; max-width: calc(100vw - 32px); }
+}
+
+/* vessel detail (active hotspot) */
+.hs-card { width: auto; white-space: nowrap; padding: 10px 14px 11px; }
+.hs-card h3 { font-size: 15px; margin: 5px 0 0; }
+.hs.active .hs-dot { background: var(--orange); box-shadow: 0 0 16px rgba(255,100,25,.8); }
+.hs.active .hs-card { box-shadow: inset 0 0 0 1px rgba(255,100,25,.7); background: rgba(24,9,2,.66); }
+.hs-detail { margin-top: 30px; max-width: 400px; padding: 16px 0 0 18px; border-left: 1px solid var(--orange); min-height: 124px; }
+.hs-detail .mono { color: var(--orange); font-size: 9.5px; }
+.hs-detail h3 { font: 500 22px/1.15 var(--display); letter-spacing: -.02em; margin: 8px 0 8px; }
+.hs-detail p:last-child { font-size: 14px; line-height: 1.55; color: rgba(228,241,242,.76); }
+.incl li { display: block; position: relative; padding-left: 18px; }
+.incl li::before { position: absolute; left: 0; top: 0; }
+.incl li i { font-style: italic; }
+@media (max-width: 900px) { .hs-detail { display: none; } }
+.divelog { transition: opacity .6s; }
+.is-docked .divelog { opacity: 0; }
+
+/* ─── phone: the gauge becomes an instrument bar, the 3D lives in the upper half ─── */
+.hint-touch { display: none; }
+@media (max-width: 900px) {
+ .gauge { top: 64px; bottom: auto; left: 16px; right: 16px; width: auto; height: 46px; text-shadow: none; }
+ .rail::before, .rail-zones { display: none; }
+ .rail-fill { top: auto; bottom: -5px; right: auto; left: 18px; height: 1px; width: calc(var(--d, 0) * (100% - 36px)); }
+ .mark { position: static; height: auto; width: auto; }
+ .mark::before, .mark::after { display: none; }
+ .mark-body { position: static; transform: none; display: flex; align-items: center; justify-content: space-between; gap: 10px;
+ padding: 7px 14px; border-radius: 999px; background: rgba(2,10,16,.5); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--rule); }
+ .mark-label { flex-direction: column; gap: 2px; font-size: 8.5px; min-width: 72px; }
+ .odo { font-size: 25px; }
+ .odo .unit { font-size: 10px; margin-left: 4px; }
+ .reads { gap: 10px; }
+ .reads dd { font-size: 10px; }
+ .toast { top: 164px; }
+ .zone { align-items: center; }
+ .zone-card { margin-top: 46vh; padding: 18px 18px 16px; }
+ .zone-card h2 { font-size: 40px; margin: 14px 0 12px; }
+ .zone-card h2 em { margin-top: 10px; }
+ .zone-card .lede { font-size: 14.5px; }
+ .zone-card .see { display: none; }
+ .stats { margin-top: 16px; }
+ .stats div { padding: 9px 0 8px; }
+ .hint-mouse { display: none; }
+ .hint-touch { display: inline-flex; gap: 8px; align-items: center; }
+ .hs:not(.active) .hs-card { display: none; }
+ .hs:not(.active) .hs-line { display: none; }
+ .hero-copy { padding-bottom: 12vh; }
+ .hero h1 { font-size: 44px; }
+ .hero .sub { font-size: 15px; margin-top: 18px; }
+ .hero .eyebrow { margin-bottom: 14px; }
+ .pelagia-copy { padding-bottom: 8vh; }
+ .pelagia h2 { font-size: 64px; }
+ .specs div { padding: 8px 0; }
+ .dates td:first-child, .dates th:first-child { display: none; }
+ .glass { padding: 22px 18px; }
+ .foot-title { font-size: 84px; }
+}
diff --git a/examples/artemis/astronaut.js b/examples/artemis/astronaut.js
new file mode 100644
index 0000000..d626bee
--- /dev/null
+++ b/examples/artemis/astronaut.js
@@ -0,0 +1,219 @@
+// The walker. Scroll sets a target distance along the traverse; the astronaut follows it with a soft speed cap.
+// The gait phase is advanced by *distance* (not time), so planted boots never slide at any scroll speed:
+// walk → lunar lope (the run clip, slowed, with extra 1/6 g flight) → "time-lapse" when you scroll hard.
+// Idle is synthesised (the Meshy idle preset is broken): suit rest pose, arms eased down, breathing.
+import { THREE, damp, clamp, smooth, lerp } from '../../src/core/engine.js';
+
+const V = () => new THREE.Vector3();
+
+function analyse(model, mixer, clip, bones) {
+ const act = mixer.clipAction(clip);
+ mixer.stopAllAction();
+ act.reset().play().setEffectiveWeight(1);
+ const N = 96, rows = [];
+ const a = V(), b = V();
+ for (let i = 0; i <= N; i++) {
+ act.time = (clip.duration * i) / N; mixer.update(0); model.updateMatrixWorld(true);
+ bones.lf.getWorldPosition(a); bones.rf.getWorldPosition(b);
+ rows.push({ t: act.time, ly: a.y, lz: a.z, ry: b.y, rz: b.z });
+ }
+ act.stop();
+ const minL = Math.min(...rows.map(r => r.ly)), minR = Math.min(...rows.map(r => r.ry));
+ // stance velocity: foot low and moving backwards relative to the hips
+ let vs = 0, vn = 0;
+ for (let i = 1; i < rows.length; i++) {
+ const p = rows[i - 1], q = rows[i], dt = q.t - p.t;
+ if (p.ly < minL + 0.012 && q.ly < minL + 0.012) { vs += -(q.lz - p.lz) / dt; vn++; }
+ if (p.ry < minR + 0.012 && q.ry < minR + 0.012) { vs += -(q.rz - p.rz) / dt; vn++; }
+ }
+ const speed = vs / Math.max(1, vn);
+ // left heel strike phase
+ let contact = 0;
+ for (let i = 1; i < rows.length; i++) if (rows[i].ly < minL + 0.014 && rows[i - 1].ly >= minL + 0.014) { contact = i / N; break; }
+ // flight: both feet clearly off the ground
+ const air = rows.map(r => (r.ly > minL + 0.03 && r.ry > minR + 0.03 ? 1 : 0));
+ const lift = new Float32Array(N + 1);
+ for (let i = 0; i <= N; i++) {
+ if (!air[i]) continue;
+ let s = i, e = i;
+ while (s > 0 && air[s - 1]) s--;
+ while (e < N && air[e + 1]) e++;
+ lift[i] = Math.sin(Math.PI * (i - s + 0.5) / (e - s + 1));
+ }
+ return { speed, stride: speed * clip.duration, contact, lift, footY: (minL + minR) / 2 };
+}
+
+function idleClip(model, bones) {
+ // Rest pose tracks for every animated bone, with the arms lowered and a slow breathing cycle.
+ model.updateMatrixWorld(true);
+ const rest = new Map();
+ model.traverse(o => { if (o.isBone) rest.set(o, { q: o.quaternion.clone(), p: o.position.clone() }); });
+ const worldQ = o => o.getWorldQuaternion(new THREE.Quaternion());
+ const lowerArm = (arm, fore, down, fwd) => {
+ const d = fore.getWorldPosition(V()).sub(arm.getWorldPosition(V())).normalize();
+ const axis = V().crossVectors(d, V().set(0, -1, 0)).normalize();
+ const qW = new THREE.Quaternion().setFromAxisAngle(axis, down);
+ const newW = qW.multiply(worldQ(arm));
+ const parentW = worldQ(arm.parent);
+ arm.quaternion.copy(parentW.invert().multiply(newW));
+ arm.updateMatrixWorld(true);
+ // bend the elbow forward a touch
+ const d2 = fore.children[0]?.getWorldPosition(V()).sub(fore.getWorldPosition(V())).normalize() ?? V(0, -1, 0);
+ const ax2 = V().crossVectors(d2, V().set(0, 0, 1)).normalize();
+ const q2 = new THREE.Quaternion().setFromAxisAngle(ax2, fwd).multiply(worldQ(fore));
+ fore.quaternion.copy(worldQ(fore.parent).invert().multiply(q2));
+ fore.updateMatrixWorld(true);
+ };
+ lowerArm(bones.la, bones.lfa, 0.36, 0.3);
+ lowerArm(bones.ra, bones.rfa, 0.36, 0.3);
+ const pose = new Map();
+ model.traverse(o => { if (o.isBone) pose.set(o, { q: o.quaternion.clone(), p: o.position.clone() }); });
+ // restore rest so the mixer's bindings see the true bind pose
+ for (const [o, r] of rest) { o.quaternion.copy(r.q); o.position.copy(r.p); }
+ const T = 4.8, times = [0, 1.2, 2.4, 3.6, 4.8];
+ const tracks = [];
+ const breathe = [0, 1, 0, -1, 0];
+ for (const [o, s] of pose) {
+ const vals = [];
+ for (let k = 0; k < times.length; k++) {
+ const q = s.q.clone();
+ const b = breathe[k];
+ if (o === bones.spine) q.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(b * 0.018, 0, 0)));
+ if (o === bones.head) q.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(0.03 + b * 0.01, Math.sin(k / 4 * Math.PI * 2) * 0.05, 0)));
+ if (o === bones.la || o === bones.ra) q.multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(b * 0.02, 0, 0)));
+ vals.push(q.x, q.y, q.z, q.w);
+ }
+ tracks.push(new THREE.QuaternionKeyframeTrack(`${o.name}.quaternion`, times, vals));
+ if (o === bones.hips) {
+ const pv = [];
+ for (let k = 0; k < times.length; k++) pv.push(s.p.x, s.p.y + breathe[k] * 0.35 - 0.6, s.p.z);
+ tracks.push(new THREE.VectorKeyframeTrack(`${o.name}.position`, times, pv));
+ }
+ }
+ return new THREE.AnimationClip('idle-synth', T, tracks);
+}
+
+export class Astronaut {
+ constructor(gltf, H, { onStep, onLift } = {}) {
+ this.H = H; this.onStep = onStep; this.onLift = onLift;
+ this.root = new THREE.Group();
+ this.model = gltf.scene;
+ this.root.add(this.model);
+ const get = n => this.model.getObjectByName(n);
+ this.bones = { hips: get('Hips'), lf: get('LeftFoot'), rf: get('RightFoot'), lt: get('LeftToeBase'), rt: get('RightToeBase'),
+ spine: get('Spine01'), head: get('Head'), la: get('LeftArm'), ra: get('RightArm'), lfa: get('LeftForeArm'), rfa: get('RightForeArm') };
+ this.model.traverse(o => { if (o.isSkinnedMesh) { o.frustumCulled = false; this.mesh = o; } });
+ this.mixer = new THREE.AnimationMixer(this.model);
+ const clip = n => gltf.animations.find(a => a.name === n);
+ this.walkClip = clip('walk'); this.runClip = clip('run');
+ this.walkInfo = analyse(this.model, this.mixer, this.walkClip, this.bones);
+ this.runInfo = analyse(this.model, this.mixer, this.runClip, this.bones);
+ this.idle = idleClip(this.model, this.bones);
+ this.mixer.stopAllAction();
+ this.aWalk = this.mixer.clipAction(this.walkClip).play();
+ this.aRun = this.mixer.clipAction(this.runClip).play();
+ this.aIdle = this.mixer.clipAction(this.idle).play();
+ this.aWalk.timeScale = 0; this.aRun.timeScale = 0;
+ this.runOffset = this.runInfo.contact - this.walkInfo.contact;
+ // state
+ this.curve = H.curve; this.len = this.curve.getLength();
+ this.d = 0; this.v = 0; this.phase = 0.12; this.moveW = 0; this.runW = 0; this.yaw = 0;
+ this.stillT = 10; this.steps = 0; this.lift = 0;
+ this.feet = [
+ { ankle: this.bones.lf, toe: this.bones.lt, down: false, side: 'L' },
+ { ankle: this.bones.rf, toe: this.bones.rt, down: false, side: 'R' },
+ ];
+ this.pos = V(); this.fwd = V(1, 0, 0); this.side = V(0, 0, 1);
+ this._a = V(); this._b = V(); this._t = V();
+ this.pose(0, 0);
+ console.info(`[artemis] walk ${this.walkInfo.speed.toFixed(2)} m/s stride ${this.walkInfo.stride.toFixed(2)} m · run ${this.runInfo.speed.toFixed(2)} m/s stride ${this.runInfo.stride.toFixed(2)} m · offset ${this.runOffset.toFixed(3)}`);
+ }
+
+ get stride() { return lerp(this.walkInfo.stride, this.runInfo.stride, this.runW); }
+
+ // Place root on the path at distance d and evaluate the blended pose at the current phase.
+ pose(dt, idleDt) {
+ const u = clamp(this.d / this.len, 0, 1);
+ const p = this.curve.getPointAt(u), tg = this.curve.getTangentAt(u);
+ const yaw = Math.atan2(tg.x, tg.z);
+ this.yaw = this.yawInit ? yaw : yaw; this.yawInit = true;
+ const ph = ((this.phase % 1) + 1) % 1;
+ const rph = (((this.phase + this.runOffset) % 1) + 1) % 1;
+ const li = this.runInfo.lift, n = li.length - 1, fi = rph * n, i0 = Math.floor(fi);
+ const lift = (li[i0] + (li[Math.min(n, i0 + 1)] - li[i0]) * (fi - i0)) * this.runW * this.moveW;
+ this.lift = lift;
+ this.root.position.set(p.x, this.H.heightAt(p.x, p.z) + lift * 0.3 - 0.004, p.z);
+ this.root.rotation.y = this.yaw + (this.yawOffset || 0);
+ this.fwd.set(Math.sin(this.yaw), 0, Math.cos(this.yaw));
+ this.side.set(this.fwd.z, 0, -this.fwd.x).negate();
+ this.pos.copy(this.root.position);
+ const w = this.moveW;
+ this.aWalk.setEffectiveWeight(w * (1 - this.runW));
+ this.aRun.setEffectiveWeight(w * this.runW);
+ this.aIdle.setEffectiveWeight(1 - w);
+ this.aWalk.time = ph * this.walkClip.duration;
+ this.aRun.time = rph * this.runClip.duration;
+ this.mixer.update(idleDt);
+ this.root.updateMatrixWorld(true);
+ }
+
+ detect(emit, time) {
+ const moving = this.moveW > 0.55 && this.v > 0.04;
+ for (const f of this.feet) {
+ const a = f.ankle.getWorldPosition(this._a), t = f.toe.getWorldPosition(this._b);
+ const h = a.y - this.root.position.y;
+ const low = this.walkInfo.footY + 0.016, high = this.walkInfo.footY + 0.05;
+ if (!f.down && h < low && (moving || !emit)) {
+ f.down = true;
+ if (moving && emit) {
+ const dir = this._t.copy(t).sub(a); dir.y = 0; dir.normalize();
+ const cx = a.x + dir.x * 0.07, cz = a.z + dir.z * 0.07;
+ this.steps++;
+ this.onStep?.({ x: cx, z: cz, yaw: Math.atan2(dir.x, dir.z), foot: f.side, speed: this.v, lope: this.runW, time, toe: t.clone() });
+ }
+ } else if (f.down && h > high) {
+ f.down = false;
+ if (moving && emit) this.onLift?.({ toe: t.clone(), fwd: this.fwd.clone(), speed: this.v, lope: this.runW, time });
+ }
+ }
+ }
+
+ // Jump straight to distance d, stamping every print along the way (reload mid-page, nav links).
+ simulateTo(d, stamp) {
+ const saveOn = this.onLift; this.onLift = null;
+ this.moveW = 1; this.runW = 0; this.v = 1;
+ while (this.d < d - 0.05) {
+ const s = Math.min(0.08, d - this.d);
+ this.d += s; this.phase += s / this.stride;
+ this.pose(0, 0);
+ this.detect(stamp, 0);
+ }
+ this.onLift = saveOn;
+ this.v = 0; this.moveW = 0;
+ }
+
+ update(dt, target, time) {
+ target = clamp(target, 0, this.len - 0.4);
+ const gap = target - this.d;
+ const vmax = 2.5 + Math.max(0, Math.abs(gap) - 5) * 1.4;
+ const vDes = clamp(gap * 2.1, -vmax, vmax);
+ this.v = damp(this.v, vDes, 3.2, dt);
+ if (Math.abs(gap) < 0.004 && Math.abs(this.v) < 0.02) this.v = 0;
+ const sp = Math.abs(this.v);
+ this.stillT = sp > 0.05 ? 0 : this.stillT + dt;
+ this.moveW = damp(this.moveW, this.stillT < 0.18 ? 1 : 0, this.stillT < 0.18 ? 5 : 3, dt);
+ this.runW = damp(this.runW, smooth(1.6, 2.8, sp), 2.5, dt);
+ // never walk past the ends of the traverse (the damped velocity would otherwise overshoot)
+ const dMax = this.len - 0.4;
+ if (this.d + this.v * dt > dMax) this.v = Math.max(0, (dMax - this.d) / dt);
+ if (this.d + this.v * dt < 0) this.v = Math.min(0, -this.d / dt);
+ const ds = this.v * dt;
+ const n = Math.min(24, Math.max(1, Math.ceil(Math.abs(ds) / 0.09)));
+ for (let k = 1; k <= n; k++) {
+ this.d += ds / n;
+ this.phase += ds / n / this.stride;
+ this.pose(k === n ? dt : 0, k === n ? dt : 0);
+ this.detect(true, time - dt * (1 - k / n));
+ }
+ }
+}
diff --git a/examples/artemis/dust.js b/examples/artemis/dust.js
new file mode 100644
index 0000000..fe4f0bd
--- /dev/null
+++ b/examples/artemis/dust.js
@@ -0,0 +1,74 @@
+// Kicked regolith: every grain is a closed-form ballistic arc under lunar gravity. No air, so no drag and no
+// billowing — the spray rises, falls on a clean parabola and stops dead when it meets the ground.
+import { THREE } from '../../src/core/engine.js';
+import { mulberry32 } from './noise.js';
+
+export const G_MOON = 1.62;
+
+export class Dust {
+ constructor(max = 6000) {
+ this.max = max; this.head = 0;
+ this.rnd = mulberry32(99);
+ const geo = new THREE.BufferGeometry();
+ this.a0 = new Float32Array(max * 4); // p0.xyz, t0
+ this.a1 = new Float32Array(max * 4); // v.xyz, life
+ this.a2 = new Float32Array(max); // size/brightness seed
+ for (let i = 0; i < max; i++) { this.a0[i * 4 + 3] = -100; this.a1[i * 4 + 3] = 0; this.a2[i] = this.rnd(); }
+ this.b0 = new THREE.BufferAttribute(this.a0, 4).setUsage(THREE.DynamicDrawUsage);
+ this.b1 = new THREE.BufferAttribute(this.a1, 4).setUsage(THREE.DynamicDrawUsage);
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(max * 3), 3));
+ geo.setAttribute('a0', this.b0); geo.setAttribute('a1', this.b1); geo.setAttribute('seed', new THREE.BufferAttribute(this.a2, 1));
+ this.mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { uTime: { value: 0 }, uG: { value: G_MOON }, uDpr: { value: 1 }, uBright: { value: 1.5 }, uH: { value: 900 } },
+ vertexShader: /* glsl */`
+ attribute vec4 a0; attribute vec4 a1; attribute float seed;
+ uniform float uTime, uG, uDpr, uH; varying float vA; varying float vS;
+ void main(){
+ float t = uTime - a0.w;
+ if (t < 0. || t > a1.w + 0.35) { gl_Position = vec4(2., 2., 2., 1.); gl_PointSize = 0.; return; }
+ float tf = min(t, a1.w);
+ vec3 p = a0.xyz + a1.xyz * tf + vec3(0., -0.5 * uG * tf * tf, 0.);
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ float sz = mix(0.004, 0.02, seed * seed * seed);
+ gl_PointSize = max(1.3, sz * uH * projectionMatrix[1][1] * 0.5 / -mv.z) * uDpr;
+ vA = (t > a1.w ? 1. - (t - a1.w) / 0.35 : 1.) * smoothstep(0., 0.05, t);
+ vS = seed;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform float uBright; varying float vA; varying float vS;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ float a = smoothstep(0.5, 0.2, d) * vA;
+ if (a < 0.01) discard;
+ gl_FragColor = vec4(vec3(0.6, 0.59, 0.57) * uBright * (0.55 + vS * 0.5), a * 0.85);
+ }`,
+ });
+ this.points = new THREE.Points(geo, this.mat);
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 2;
+ }
+ // Launch n grains from p with directions around `dir` (unit, horizontal), speed range and elevation range (radians).
+ kick(p, dir, n, { speed = [0.5, 1.4], elev = [0.35, 1.0], spread = 0.8, time, ground = p.y, jitter = 0.05 }) {
+ const r = this.rnd;
+ let lo = this.head, cnt = 0;
+ for (let k = 0; k < n; k++) {
+ const i = this.head; this.head = (this.head + 1) % this.max; cnt++;
+ const yaw = Math.atan2(dir.x, dir.z) + (r() - 0.5) * spread * 2;
+ const el = elev[0] + (elev[1] - elev[0]) * r();
+ const s = speed[0] + (speed[1] - speed[0]) * Math.pow(r(), 1.6);
+ const vx = Math.sin(yaw) * Math.cos(el) * s, vz = Math.cos(yaw) * Math.cos(el) * s, vy = Math.sin(el) * s;
+ const px = p.x + (r() - 0.5) * jitter * 2, py = p.y + r() * 0.02, pz = p.z + (r() - 0.5) * jitter * 2;
+ const h0 = Math.max(0, py - ground);
+ const life = (vy + Math.sqrt(vy * vy + 2 * G_MOON * h0)) / G_MOON;
+ this.a0.set([px, py, pz, time + r() * 0.05], i * 4);
+ this.a1.set([vx, vy, vz, life], i * 4);
+ }
+ // upload the touched range (handles wrap-around by uploading everything in that case)
+ if (lo + cnt <= this.max) {
+ this.b0.addUpdateRange(lo * 4, cnt * 4); this.b1.addUpdateRange(lo * 4, cnt * 4);
+ } else { this.b0.clearUpdateRanges(); this.b1.clearUpdateRanges(); }
+ this.b0.needsUpdate = true; this.b1.needsUpdate = true;
+ }
+}
diff --git a/examples/artemis/index.html b/examples/artemis/index.html
new file mode 100644
index 0000000..32a69fc
--- /dev/null
+++ b/examples/artemis/index.html
@@ -0,0 +1,219 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Artemis — Seven days at the lunar south pole</title>
+ <meta name="description" content="Artemis Surface Stays: a seven-day stay at an outpost on the rim of Shackleton crater. Twelve guests a season. $4.2M, all-inclusive.">
+ <meta name="theme-color" content="#000000">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Barlow+Condensed:wght@400;500;600&family=Space+Grotesk:wght@300;400;500;600&display=swap" rel="stylesheet">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Ccircle cx='16' cy='16' r='11' fill='none' stroke='%23fff' stroke-width='2'/%3E%3Cpath d='M16 5a11 11 0 0 0 0 22 7.5 11 0 0 1 0-22Z' fill='%23fff'/%3E%3C/svg%3E">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="grain" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-frame">
+ <p class="rd loader-top"><span>Artemis · Powered descent</span><span>LM-7 “Tranquil”</span></p>
+ <div class="loader-alt"><span class="loader-num">15,000</span><em>m</em></div>
+ <div class="loader-bar"><i></i></div>
+ <p class="rd loader-bottom"><span class="loader-call">Braking phase</span><span><span class="loader-pct">0</span>%</span></p>
+ </div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Artemis home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="10.5" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M16 5.5a10.5 10.5 0 0 0 0 21 7.2 10.5 0 0 1 0-21Z" fill="currentColor"/><path d="M2 22.5h28" stroke="currentColor" stroke-width="1.4"/></svg>
+ <span>Artemis</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#walk" data-jump="walk">The walk</a>
+ <a href="#outpost" data-jump="outpost">Outpost</a>
+ <a href="#days" data-jump="days">Seven days</a>
+ <a href="#training" data-jump="training">Training</a>
+ <a href="#price" data-jump="price">Price</a>
+ </nav>
+ <a class="btn btn-solid" href="#reserve" data-magnetic>Reserve a seat</a>
+ </header>
+
+ <!-- mission readouts, pinned to the frame like film-edge data -->
+ <div class="hud" aria-hidden="true">
+ <div class="hud-tl rd"><span>89.94°S&nbsp;&nbsp;0.12°E</span><span>Shackleton rim · site A</span></div>
+ <div class="hud-tr rd"><span class="hud-sun">Sun az 218.0° · el 7.2°</span><span>Earth el 11.4°</span></div>
+ <div class="hud-bl rd"><span>MET <b class="hud-met">000:00:00:00</b></span></div>
+ <div class="hud-br rd"><span class="hud-frame">Frame 0001</span><span>AS-31 · 70mm</span></div>
+ <i class="hud-c hud-c1"></i><i class="hud-c hud-c2"></i><i class="hud-c hud-c3"></i><i class="hud-c hud-c4"></i>
+ </div>
+
+ <div class="telemetry rd" aria-hidden="true">
+ <div><em>Distance</em><b class="tm-dist">0.0</b><small>m</small></div>
+ <div><em>Steps</em><b class="tm-steps">0</b></div>
+ <div><em>Gait</em><b class="tm-gait">Standing</b></div>
+ <div><em>Prints left</em><b class="tm-prints">0</b></div>
+ <div class="tm-rate"><em>Playback</em><b class="tm-rate-v">×1.0</b></div>
+ </div>
+
+ <main id="top">
+ <section class="hero" aria-labelledby="hero-title">
+ <div class="hero-inner">
+ <p class="eyebrow rd">Artemis Surface Stays <span>—</span> Season 2031 <span>—</span> 12 seats</p>
+ <h1 id="hero-title" class="hero-title">
+ <span class="ln"><span>One small step,</span></span>
+ <span class="ln"><span>repeated <em>40,000</em> times.</span></span>
+ </h1>
+ <p class="hero-sub">Seven days at an outpost on the rim of Shackleton crater, where the Sun never sets and nothing you leave behind ever blows away. Bring good boots. We supply the rest.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#reserve" data-magnetic>Reserve a seat</a>
+ <a class="btn btn-ghost" href="#days" data-jump="days" data-magnetic>See the itinerary</a>
+ </div>
+ </div>
+ <div class="scroll-hint rd" aria-hidden="true">
+ <span class="boot"><i></i><i></i></span>
+ <span><b>Scroll to walk</b> · stop to rest · scroll back to retrace</span>
+ </div>
+ </section>
+
+ <section class="walk" id="walk" aria-label="The walk">
+ <div class="walk-sticky">
+ <p class="sec-tag rd"><b>01</b> The walk <span class="sec-sub">EVA 1 · rim traverse · 38 m · he walks as fast as you scroll</span></p>
+ <article class="cap cap-a" data-from="0.5" data-to="8">
+ <p class="rd">00 m · Regolith</p>
+ <h3>It isn’t sand.</h3>
+ <p>It’s volcanic glass, shattered by four billion years of impacts and never weathered smooth. It holds a bootprint the way plaster holds a hand.</p>
+ </article>
+ <article class="cap cap-b" data-from="8.5" data-to="15">
+ <p class="rd">09 m · 1.62 m/s²</p>
+ <h3>You weigh a sixth. Your mass doesn’t.</h3>
+ <p>Starting is effortless. Stopping takes planning. By the second hour you stop walking and start to lope.</p>
+ </article>
+ <article class="cap cap-c" data-from="15.5" data-to="23">
+ <p class="rd">17 m · No air</p>
+ <h3>Every grain flies the same arc.</h3>
+ <p>With nothing to slow it, kicked dust rises on a perfect parabola and lands at the same instant as the pebble next to it. No cloud. No drift. Just geometry.</p>
+ </article>
+ <article class="cap cap-d" data-from="23.5" data-to="30.5">
+ <p class="rd">25 m · Look back</p>
+ <h3>These will outlast the pyramids.</h3>
+ <p>No wind, no rain, no frost. Your prints will stay exactly like this until a micrometeorite finds them, in about ten million years.</p>
+ </article>
+ <article class="cap cap-e" data-from="31" data-to="40">
+ <p class="rd">36 m · Home</p>
+ <h3>The gold one is yours.</h3>
+ <p>A guest walks thirty-one kilometres in a week, about forty thousand steps. Your suit counts every one of them.</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="outpost" id="outpost" aria-labelledby="outpost-title">
+ <div class="sticky">
+ <div class="panel panel-left">
+ <p class="sec-tag rd"><b>02</b> The outpost</p>
+ <h2 id="outpost-title">Built on a ridge that almost never sees night.</h2>
+ <p class="lede">Shackleton Rim is one of the Moon’s peaks of near-eternal light. The Sun circles the horizon instead of setting, and our arrays turn to follow it. Two hundred metres away, the crater floor hasn’t seen sunlight in two billion years.</p>
+ <ul class="specs rd">
+ <li><b>38 m³</b><span>pressurised, per guest pair</span></li>
+ <li><b>−173 °C</b><span>in the crater, 400 m below</span></li>
+ <li><b>1.3 s</b><span>to call home, each way</span></li>
+ </ul>
+ <figure class="plate">
+ <img src="/img/artemis/habitat.webp" alt="Four curtained berths inside the habitat, with a porthole showing Earth above the lunar horizon" loading="lazy" width="1000" height="1250">
+ <figcaption class="rd">Hab 2, berth deck. The window faces Earth.</figcaption>
+ </figure>
+ </div>
+ </div>
+ </section>
+
+ <section class="days" id="days" aria-labelledby="days-title">
+ <div class="sticky">
+ <div class="panel panel-left">
+ <p class="sec-tag rd"><b>03</b> The seven days</p>
+ <h2 id="days-title">At the pole, the Sun doesn’t set. It walks around you.</h2>
+ <p class="lede small">Scroll through the week. The Sun travels eighty-five degrees around the horizon, and every shadow on the rim turns with it like the hand of a clock.</p>
+ <ol class="itinerary">
+ <li data-day="0"><span class="rd">Day 1</span><div><h3>Touchdown</h3><p>Twelve minutes of powered descent from lunar orbit. Suit checks, then your first step onto the rim.</p></div></li>
+ <li data-day="1"><span class="rd">Day 2</span><div><h3>The long walk</h3><p>A guided four-kilometre traverse along the ridge. You learn the lope, the slow bounding gait the Moon rewards.</p></div></li>
+ <li data-day="2"><span class="rd">Day 3</span><div><h3>Into the dark</h3><p>A lamp-lit descent into a permanently shadowed crater, where water ice has waited since before the dinosaurs.</p></div></li>
+ <li data-day="3"><span class="rd">Day 4</span><div><h3>Earth day</h3><p>Rest in the cabin. Call home, then watch the continents turn slowly in the window.</p></div></li>
+ <li data-day="4"><span class="rd">Day 5</span><div><h3>De Gerlache rim</h3><p>Pressurised rover to the neighbouring crater. Lunch looking down four kilometres of cliff.</p></div></li>
+ <li data-day="5"><span class="rd">Day 6</span><div><h3>Leave one thing</h3><p>Bury a sealed capsule in the regolith. We log the coordinates. It will outlive every city on Earth.</p></div></li>
+ <li data-day="6"><span class="rd">Day 7</span><div><h3>Ascent</h3><p>Liftoff, rendezvous, three days drifting home. The prints stay.</p></div></li>
+ </ol>
+ </div>
+ </div>
+ </section>
+
+ <section class="training" id="training" aria-labelledby="training-title">
+ <div class="sticky">
+ <div class="panel panel-left wide">
+ <p class="sec-tag rd"><b>04</b> Training &amp; medical</p>
+ <h2 id="training-title">Six weeks on Earth for seven days up there.</h2>
+ <p class="lede small">No flying experience required. Fitness matters more than age: our oldest guest was seventy-one. You train in Houston and Cologne, alongside the crew who will fly you.</p>
+ <div class="cards">
+ <article class="tcard">
+ <img src="/img/artemis/training.webp" alt="A suited trainee walking on simulated regolith under a harsh spotlight, a support cable rising from the suit" loading="lazy" width="1000" height="1250">
+ <p class="rd">Weeks 1–2</p><h3>Partial gravity</h3><p>A harness carries five-sixths of your weight while you learn to walk, lope, and fall on simulant regolith.</p>
+ </article>
+ <article class="tcard">
+ <img src="/img/artemis/centrifuge.webp" alt="A human centrifuge: a long steel arm with a capsule sweeping around a circular concrete hall" loading="lazy" width="1000" height="1250">
+ <p class="rd">Weeks 3–4</p><h3>Launch loads</h3><p>Four centrifuge sessions building to 4 g, so the ride up feels like something you have already done.</p>
+ </article>
+ <article class="tcard tcard-text">
+ <ul class="med rd" aria-label="Medical clearance checklist">
+ <li><span>Suit scan</span><b>±0.4 mm</b></li>
+ <li><span>Cardiac stress</span><b>Cleared</b></li>
+ <li><span>Bone density</span><b>Cleared</b></li>
+ <li><span>Vestibular</span><b>Cleared</b></li>
+ <li><span>Radiation baseline</span><b>Logged</b></li>
+ </ul>
+ <p class="rd">Weeks 5–6</p><h3>Suit &amp; surgeon</h3><p>Your suit is cut to a 3D scan of your body. Cardiac, bone-density and vestibular screening, and a flight surgeon on every stay.</p>
+ </article>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <section class="price" id="price" aria-labelledby="price-title">
+ <div class="sticky">
+ <div class="panel panel-price">
+ <p class="sec-tag rd"><b>05</b> Price</p>
+ <h2 id="price-title"><span class="big">$4.2M</span><span class="all">all-inclusive.</span></h2>
+ <ul class="incl">
+ <li>Launch from LC-39B and the return home</li>
+ <li>Six weeks of training, medical and lodging</li>
+ <li>A suit cut to your body. It’s yours to keep.</li>
+ <li>Seven days, every EVA, every meal</li>
+ <li>Insurance, flight surgeon, one call home a day</li>
+ <li>Your footprints, which are permanent</li>
+ </ul>
+ <div class="price-cta" id="reserve">
+ <a class="btn btn-solid" href="#reserve" data-magnetic>Reserve with $250,000</a>
+ <a class="btn btn-ghost" href="#reserve" data-magnetic>Talk to a flight planner</a>
+ </div>
+ <p class="fine rd">Deposit fully refundable until training begins · next window October 2031 · 4 of 12 seats remain</p>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot" aria-labelledby="foot-title">
+ <div class="foot-inner">
+ <p class="rd foot-exp">Exposure +6 EV · shutter open · the stars were there the whole time</p>
+ <h2 id="foot-title" class="foot-title">Leave something<br>that lasts.</h2>
+ <div class="foot-cols">
+ <div class="rd"><b>Artemis Surface Stays</b><br>Launch: Kennedy Space Center, FL<br>Training: Houston · Cologne</div>
+ <div class="rd"><b>Site A</b><br>Shackleton Rim, 89.94°S 0.12°E<br>Sunlight 91% of the lunar year</div>
+ <a class="btn btn-solid" href="#reserve" data-magnetic>Reserve a seat</a>
+ </div>
+ <p class="rd legal">© 2031 Artemis Surface Stays — a fictional company. Not affiliated with NASA or any space agency.</p>
+ </div>
+ </footer>
+ </main>
+
+ <div class="hotspots" aria-hidden="true"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/artemis/main.js b/examples/artemis/main.js
new file mode 100644
index 0000000..a8c7cb2
--- /dev/null
+++ b/examples/artemis/main.js
@@ -0,0 +1,441 @@
+import { Engine, THREE, damp, clamp, smooth, lerp } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, elementProgress } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { TUNE, buildHeight, HF, LAYOUT, regolithTextures, heightTexture, patchRegolith, sunUniform, nearTerrain, farTerrain, farHeightfield, rocks } from './terrain.js';
+import { Prints } from './prints.js';
+import { Dust } from './dust.js';
+import { Astronaut } from './astronaut.js';
+import { makeEarth, makeSun, makeStars } from './sky.js';
+import { buildOutpost } from './outpost.js';
+
+const DBG = new URLSearchParams(location.search);
+const D2R = Math.PI / 180;
+const V3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const mobile = matchMedia('(max-width: 640px)').matches;
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 32, near: 0.08, far: 20000, dpr: mobile ? 1.5 : 1.5, background: 0x000000,
+ post: {
+ ao: { aoRadius: 0.8, intensity: 2.4, distanceFalloff: 0.5 },
+ bloom: { intensity: 0.42, luminanceThreshold: 2.4, luminanceSmoothing: 0.45, radius: 0.72 },
+ tone: 'agx',
+ vignette: { offset: 0.34, darkness: 0.5 },
+ noise: 0.045,
+ ca: 0.0005,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.shadowMap.type = THREE.PCFShadowMap;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 4 });
+
+// ─── Loader: powered descent ──────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+const numEl = loaderEl.querySelector('.loader-num'), pctEl = loaderEl.querySelector('.loader-pct'), callEl = loaderEl.querySelector('.loader-call');
+const CALLS = [[0, 'Braking phase'], [0.45, 'Pitchover'], [0.75, 'Approach'], [0.93, 'Landing phase'], [1, 'Contact light']];
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ const alt = Math.round(15000 * Math.pow(1 - v, 1.7));
+ numEl.textContent = alt.toLocaleString('en-US');
+ pctEl.textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ callEl.textContent = CALLS.filter(c => v >= c[0]).pop()[1];
+ },
+ exit: async () => {
+ callEl.textContent = 'Contact light';
+ await new Promise(r => setTimeout(r, 420));
+ callEl.textContent = 'Engine stop';
+ await new Promise(r => setTimeout(r, 380));
+ await gsap.to(loaderEl, { autoAlpha: 0, duration: 1.1, ease: 'power2.inOut' });
+ },
+});
+
+// ─── Assets (downloads run while the rim is generated on the CPU) ─────────────
+const pAstro = assets.gltf('models/artemis/astro-rig.glb');
+const pEarth = assets.texture('img/artemis/earth.webp');
+await new Promise(r => setTimeout(r, 60));
+const H = buildHeight();
+
+// ─── Lights ───────────────────────────────────────────────────────────────────
+const SUN0 = LAYOUT.toSun.clone();
+const sun = new THREE.DirectionalLight(0xfffcf6, 10);
+sun.castShadow = true;
+sun.shadow.mapSize.set(4096, 4096);
+Object.assign(sun.shadow.camera, { left: -24, right: 24, top: 13, bottom: -13, near: 1, far: 320 });
+sun.shadow.bias = -0.00018; sun.shadow.normalBias = 0.022;
+scene.add(sun, sun.target);
+const earthshine = new THREE.HemisphereLight(0x4a6aa8, 0x000000, 0.1);
+scene.add(earthshine);
+
+// A cheap starting environment (replaced by a capture of the real scene once it exists).
+{
+ const s = new THREE.Scene();
+ s.add(new THREE.Mesh(new THREE.SphereGeometry(10, 32, 16), new THREE.ShaderMaterial({ side: THREE.BackSide,
+ vertexShader: 'varying vec3 p; void main(){ p = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.); }',
+ fragmentShader: 'varying vec3 p; void main(){ gl_FragColor = vec4(vec3(0.42) * smoothstep(0.05, -0.3, p.y), 1.); }' })));
+ const pm = new THREE.PMREMGenerator(renderer);
+ scene.environment = pm.fromScene(s, 0.04).texture;
+ pm.dispose();
+}
+
+// ─── Terrain ──────────────────────────────────────────────────────────────────
+const tex = regolithTextures(renderer);
+const hfTex = heightTexture(H.data, HF.N + 1, renderer);
+const farHF = farHeightfield(H, 512, 16000);
+const farTex = heightTexture(farHF.data, farHF.n, renderer);
+const midHF = farHeightfield(H, 512, 1600);
+const midTex = heightTexture(midHF.data, midHF.n, renderer);
+const regCtx = { tex, hf: { tex: hfTex, x0: H.x0, z0: H.z0, size: HF.half * 2 } };
+const GROUND = 0x5d5c59;
+const groundMat = patchRegolith(new THREE.MeshStandardMaterial({ color: GROUND, roughness: 1, metalness: 0, envMapIntensity: 0.4 }), regCtx);
+const farMat = patchRegolith(new THREE.MeshStandardMaterial({ color: GROUND, roughness: 1, metalness: 0, envMapIntensity: 0.4 }),
+ { tex, hf: { tex: farTex, x0: farHF.x0, z0: farHF.z0, size: farHF.size }, far: { tex: midTex, x0: midHF.x0, z0: midHF.z0, size: midHF.size }, fill: { value: 0.11 } });
+const near = nearTerrain(H, groundMat);
+const farMesh = farTerrain(H, farMat);
+scene.add(near, farMesh);
+const rockMat = patchRegolith(new THREE.MeshStandardMaterial({ color: 0x55534f, roughness: 0.94, metalness: 0, envMapIntensity: 0.6 }), { ...regCtx, rock: true, ls: 0.3 });
+const rockGroup = rocks(H, rockMat);
+scene.add(rockGroup);
+
+const prints = new Prints(H, { ...regCtx, color: new THREE.Color(GROUND) });
+scene.add(prints.mesh);
+const dust = new Dust(mobile ? 3000 : 6000);
+scene.add(dust.points);
+
+// ─── Sky ──────────────────────────────────────────────────────────────────────
+const SITE = V3(HF.cx, 0, HF.cz);
+const earthTex = await pEarth;
+earthTex.anisotropy = 8;
+const earth = makeEarth(earthTex, { dist: 11500, ang: 5.4 });
+earth.position.copy(SITE).addScaledVector(LAYOUT.toEarth, 11500);
+scene.add(earth);
+const sunDisc = makeSun();
+scene.add(sunDisc);
+const stars = makeStars(mobile ? 2500 : 5000);
+stars.position.copy(SITE);
+scene.add(stars);
+
+// ─── Astronaut ────────────────────────────────────────────────────────────────
+let simulating = false;
+const gltf = await pAstro;
+const tmp = V3(), tmp2 = V3();
+const astro = new Astronaut(gltf, H, {
+ onStep: e => {
+ prints.stamp(e.x, e.z, e.yaw);
+ if (simulating) return;
+ const g = H.heightAt(e.x, e.z);
+ dust.kick(tmp.set(e.x, g + 0.02, e.z), tmp2.set(Math.sin(e.yaw), 0, Math.cos(e.yaw)), Math.round(26 + e.lope * 50),
+ { speed: [0.12, 0.45 + e.lope * 0.7], elev: [0.35, 1.2], spread: 1.7, time: engine.time, ground: g, jitter: 0.07 });
+ },
+ onLift: e => {
+ if (simulating) return;
+ const g = H.heightAt(e.toe.x, e.toe.z);
+ dust.kick(tmp.set(e.toe.x, g + 0.03, e.toe.z), e.fwd, Math.round(70 + e.lope * 110),
+ { speed: [0.45, 1.25 + e.lope * 1.1], elev: [0.3, 0.95], spread: 0.42, time: engine.time, ground: g, jitter: 0.05 });
+ },
+});
+scene.add(astro.root);
+astro.model.traverse(o => {
+ if (!o.isMesh) return;
+ o.castShadow = true; o.receiveShadow = true;
+ const m = o.material;
+ m.envMapIntensity = 0.6;
+ m.color.setScalar(0.7);
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap']) if (m[k]) m[k].anisotropy = 8;
+ m.onBeforeCompile = sh => {
+ sh.fragmentShader = sh.fragmentShader.replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment>
+ float gRatio = diffuseColor.g / max(diffuseColor.r, 1e-3);
+ float visor = step(0.6, gRatio) * step(gRatio, 0.86) * smoothstep(0.05, 0.12, diffuseColor.r - diffuseColor.b) * step(0.06, diffuseColor.r);
+ metalnessFactor = max(metalnessFactor, visor);
+ roughnessFactor = mix(max(roughnessFactor, 0.6), min(roughnessFactor, 0.14), max(smoothstep(0.35, 0.8, metalnessFactor), visor));
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(1.0, 0.72, 0.36), visor * 0.6);`);
+ };
+});
+
+// ─── Outpost ──────────────────────────────────────────────────────────────────
+const outpost = await buildOutpost({ assets, renderer, H, scene });
+outpost.group.traverse(o => { if (o.isMesh && o.material?.envMapIntensity !== undefined) o.material.envMapIntensity = Math.max(o.material.envMapIntensity, 1); });
+
+// ─── Sun control (the week turns the Sun around the horizon) ──────────────────
+const sunState = { az: 0, envAz: -99 };
+const toSun = V3();
+function applySun(az) {
+ toSun.copy(SUN0).applyAxisAngle(V3(0, 1, 0), -az);
+ sunUniform.value.copy(toSun);
+ earth.userData.uniforms.uSun.value.copy(toSun);
+ sunDisc.position.copy(SITE).addScaledVector(toSun, 12000);
+ outpost.trackSun(toSun);
+}
+applySun(0);
+
+// Environment = a capture of the actual scene (sunlit regolith below, black sky, Earth), so the gold visor and foil
+// reflect the rim they stand on.
+const cubeRT = new THREE.WebGLCubeRenderTarget(256, { type: THREE.HalfFloatType, generateMipmaps: false });
+const cubeCam = new THREE.CubeCamera(0.5, 16000, cubeRT);
+const pmrem = new THREE.PMREMGenerator(renderer);
+let envRT = null;
+function captureEnv() {
+ astro.root.visible = false; dust.points.visible = false; prints.mesh.visible = false; stars.visible = false;
+ cubeCam.position.copy(astro.root.position).add(V3(0, 1.6, 0));
+ cubeCam.update(renderer, scene);
+ astro.root.visible = true; dust.points.visible = true; prints.mesh.visible = true; stars.visible = true;
+ const rt = pmrem.fromCubemap(cubeRT.texture);
+ envRT?.dispose();
+ envRT = rt;
+ scene.environment = rt.texture;
+ sunState.envAz = sunState.az;
+}
+
+// ─── Sections & camera choreography ───────────────────────────────────────────
+const $ = s => document.querySelector(s);
+const secs = { hero: $('.hero'), walk: $('.walk'), outpost: $('.outpost'), days: $('.days'), training: $('.training'), price: $('.price'), foot: $('.foot') };
+const measure = el => ({ top: el.offsetTop, span: Math.max(1, el.offsetHeight - innerHeight) });
+const RC = new Map(); // section ranges, measured on resize only (no layout reads inside the frame loop)
+const range = el => RC.get(el) ?? measure(el);
+const prog = el => { const r = range(el); return clamp((scrollY - r.top) / r.span); };
+const A = V3(), F = V3(), S = V3(), L = outpost.center.clone();
+const rel = (f, s, y, out = V3()) => out.copy(A).addScaledVector(F, f).addScaledVector(S, s).setY(A.y + y);
+const toEarthFlat = V3(LAYOUT.toEarth.x, 0, LAYOUT.toEarth.z).normalize();
+const siteC = V3(30, 0, -7);
+// Portrait screens: centre the subject, pull back and widen, so the same choreography reads on a phone.
+let portrait = innerWidth / innerHeight < 0.9;
+addEventListener('resize', () => { portrait = innerWidth / innerHeight < 0.9; });
+const shot = (pos, look, fov, subj, lift = 0.2) => {
+ if (portrait && subj) { look.lerp(subj, 0.8); pos.sub(subj).multiplyScalar(1.22).add(subj); fov *= 1.32; look.y -= lift * pos.distanceTo(subj); }
+ else if (portrait) fov *= 1.25;
+ return { pos, look, fov };
+};
+const subA = (y = 0.95) => V3(A.x, A.y + y, A.z);
+const at = (x, y, z) => V3(A.x + x, A.y + y, A.z + z);
+const aroundL = (az, r, y) => V3(L.x + Math.sin(az * D2R) * r, L.y + y, L.z + Math.cos(az * D2R) * r);
+const UP = V3(0, 1, 0);
+const earthRight = V3(-toEarthFlat.z, 0, toEarthFlat.x);
+const earthLook = V3().copy(toEarthFlat).applyAxisAngle(UP, 7.4 * D2R);
+earthLook.y = Math.tan(3.6 * D2R);
+const SHOTS = {
+ hero: () => shot(at(1.35, 1.55, 7.2), at(-1.9, 1.2, -3.0), 30, portrait ? at(-0.2, 0.62, -0.4) : null, 0),
+ side: () => shot(rel(-0.9, 6.4, 1.35), rel(0.3, 0, 1.05), 32, subA()),
+ side3: () => shot(rel(0.2, 6.3, 1.4), rel(-1.2, 0, 1.1), 32, subA()),
+ side2: () => shot(rel(-3.0, 3.0, 0.75), rel(0.7, -0.3, 0.7), 36, subA()),
+ behind: () => shot(rel(-7.0, 2.2, 3.4), rel(5, -0.8, 0.5), 38, subA(0.3)),
+ over: () => shot(rel(-2.4, 4.8, 8.4), rel(1.4, -0.3, 0), 36, subA(0)),
+ front: () => shot(rel(4.2, 3.2, 1.1), rel(0, -0.2, 0.95), 34, subA()),
+ boot: () => shot(rel(3.9, 1.7, 0.3), rel(0, 0, 0.92), 40, subA(0.9)),
+ approach: () => shot(rel(-6.2, 3.8, 2.5), V3(L.x - 1.5, L.y + 2.9, L.z), 38, V3((A.x + L.x) / 2, L.y + 2, (A.z + L.z) / 2)),
+ outA: () => shot(aroundL(-30, 15.5, 2.4), V3(L.x - 3.4, L.y + 2.9, L.z + 1.8), 36, V3(L.x, L.y + 3.4, L.z)),
+ outB: () => shot(aroundL(6, 14.5, 3.4), V3(L.x - 3.6, L.y + 2.7, L.z + 0.4), 38, V3(L.x, L.y + 3.4, L.z)),
+ daysA: () => shot(V3(43, 7.5, 23), V3(39.5, 5.2, -9.8), 38, V3(46, 2, -8)),
+ daysB: () => shot(V3(39, 9.0, 20), V3(40.2, 4.6, -13), 40, V3(46, 2, -8)),
+ portraitA: () => shot(rel(3.0, -0.3, 1.45), V3().copy(A).addScaledVector(S, 0.62).setY(A.y + 1.22), 28, subA(1.45)),
+ portraitB: () => shot(rel(2.4, -1.5, 1.0), V3().copy(A).addScaledVector(S, 0.5).addScaledVector(F, 0.3).setY(A.y + 1.2), 30, subA(1.45)),
+ earth: () => { const c = V3(A.x, A.y + 0.7, A.z).addScaledVector(toEarthFlat, -12).addScaledVector(earthRight, -0.62); return shot(c, c.clone().addScaledVector(earthLook, 40), 20); },
+ foot: () => shot(V3(L.x - 22, L.y + 3.2, L.z + 16), V3(L.x - 6, L.y + 5.5, L.z - 4), 38),
+};
+let KEYS = [];
+function layoutKeys() {
+ RC.clear(); for (const el of Object.values(secs)) RC.set(el, measure(el));
+ const k = (el, t, name) => { const r = range(el); return { y: r.top + t * r.span, name }; };
+ KEYS = [
+ { y: 0, name: 'hero' },
+ k(secs.walk, 0.0, 'side'), k(secs.walk, 0.16, 'side2'), k(secs.walk, 0.32, 'behind'), k(secs.walk, 0.48, 'over'),
+ k(secs.walk, 0.62, 'front'), k(secs.walk, 0.76, 'boot'), k(secs.walk, 0.88, 'side3'), k(secs.walk, 1.0, 'approach'),
+ k(secs.outpost, 0.15, 'outA'), k(secs.outpost, 0.9, 'outB'),
+ k(secs.days, 0.08, 'daysA'), k(secs.days, 0.92, 'daysB'),
+ k(secs.training, 0.12, 'portraitA'), k(secs.training, 0.9, 'portraitB'),
+ k(secs.price, 0.2, 'earth'), k(secs.price, 0.85, 'earth'),
+ k(secs.foot, 0, 'foot'),
+ ].sort((a, b) => a.y - b.y);
+}
+layoutKeys();
+addEventListener('resize', () => setTimeout(layoutKeys, 50));
+document.fonts?.ready.then(layoutKeys);
+addEventListener('load', layoutKeys);
+
+const camT = { pos: V3(), look: V3(), fov: 32 };
+function evalCam(y) {
+ let i = 0;
+ while (i < KEYS.length - 2 && y >= KEYS[i + 1].y) i++;
+ const a = KEYS[i], b = KEYS[i + 1];
+ const f = smooth(0, 1, clamp((y - a.y) / Math.max(1, b.y - a.y)));
+ const sa = SHOTS[a.name](), sb = SHOTS[b.name]();
+ camT.pos.lerpVectors(sa.pos, sb.pos, f);
+ camT.look.lerpVectors(sa.look, sb.look, f);
+ camT.fov = lerp(sa.fov, sb.fov, f);
+}
+
+// ─── HTML bindings ────────────────────────────────────────────────────────────
+const caps = [...document.querySelectorAll('.cap')].map(el => ({ el, from: +el.dataset.from, to: +el.dataset.to }));
+const days = [...document.querySelectorAll('.itinerary li')];
+const tm = { dist: $('.tm-dist'), steps: $('.tm-steps'), gait: $('.tm-gait'), prints: $('.tm-prints'), rate: $('.tm-rate'), rateV: $('.tm-rate-v') };
+const hud = { sun: $('.hud-sun'), met: $('.hud-met'), frame: $('.hud-frame') };
+const navLinks = [...document.querySelectorAll('.links a')];
+const hsEl = $('.hotspots');
+const HOTSPOTS = [
+ { title: 'Crew cabin', text: 'Four berths, one Earth-facing window, 38 m³ per guest pair.', at: () => V3(0, 4.9, 0).applyAxisAngle(V3(0, 1, 0), LAYOUT.lander.yaw).add(L) },
+ { title: 'Descent stage', text: 'Lands you, then stays behind as four tonnes of radiation shielding.', at: () => V3(0, 2.2, 0).add(L) },
+ { title: 'Solar mast', text: 'Fifteen metres tall. Turns a full circle every lunar day. 48 kW.', at: () => V3(LAYOUT.mast.x, H.heightAt(LAYOUT.mast.x, LAYOUT.mast.z) + 11.5, LAYOUT.mast.z) },
+ { title: 'Hab 2', text: 'Galley, gym, and the only shower within 384,000 km.', at: () => V3(LAYOUT.hab.x, H.heightAt(LAYOUT.hab.x, LAYOUT.hab.z) + 4.4, LAYOUT.hab.z) },
+].map(h => { const el = document.createElement('div'); el.className = 'hs'; el.innerHTML = `<i></i><div><b>${h.title}</b><span>${h.text}</span></div>`; hsEl.appendChild(el); return { ...h, el }; });
+
+document.querySelectorAll('a[href^="#"]:not([data-jump])').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href').slice(1);
+ const el = id === 'top' ? null : document.getElementById(id);
+ e.preventDefault();
+ if (id === 'reserve') { const r = range(secs.price); lenis.scrollTo(r.top + r.span * 0.5, { duration: 2.4 }); return; }
+ lenis.scrollTo(el ?? 0, { duration: 2.2 });
+}));
+navLinks.concat([...document.querySelectorAll('[data-jump]')]).forEach(a => a.addEventListener('click', e => {
+ const id = a.dataset.jump; if (!id || !secs[id]) return;
+ e.preventDefault();
+ const r = range(secs[id]);
+ lenis.scrollTo(r.top + (id === 'walk' ? 0 : r.span * 0.12), { duration: 2.2 });
+}));
+
+// ─── Frame loop ───────────────────────────────────────────────────────────────
+const state = { intro: 0, walkP: 0, target: 0, dayP: 0, starAmt: 0, lastHud: 0, frame: 0, par: V3() };
+const camPos = V3(), camLook = V3();
+let camInit = false;
+const dbgCam = DBG.get('pos') ? { pos: V3(...DBG.get('pos').split(',').map(Number)), look: V3(...DBG.get('look').split(',').map(Number)), fov: +(DBG.get('fov') ?? 30) } : null;
+const proj = V3();
+const fmt = (n, w) => String(Math.floor(n)).padStart(w, '0');
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ const y = scrollY;
+ // astronaut target from the pinned walk
+ state.walkP = prog(secs.walk);
+ const target = clamp((state.walkP - 0.015) / 0.95) * (astro.len - 0.45);
+ {
+ const pr = range(secs.price);
+ const want = smooth(pr.top - innerHeight * 0.8, pr.top + pr.span * 0.2, y);
+ const dyaw = Math.atan2(toEarthFlat.x, toEarthFlat.z) - Math.atan2(astro.fwd.x, astro.fwd.z);
+ const wrap = Math.atan2(Math.sin(dyaw), Math.cos(dyaw));
+ astro.yawOffset = damp(astro.yawOffset || 0, wrap * want * 0.8, 1.6, dt);
+ }
+ astro.update(dt, target, t);
+ A.copy(astro.pos); F.copy(astro.fwd); S.copy(astro.side);
+ dust.mat.uniforms.uTime.value = t;
+ earth.userData.earth.rotation.y += dt * 0.006;
+
+ // week → sun azimuth
+ const dp = prog(secs.days);
+ state.dayP = damp(state.dayP, dp, 3, dt);
+ sunState.az = state.dayP * 85 * D2R;
+ applySun(sunState.az);
+ if (Math.abs(sunState.az - sunState.envAz) > 0.14) captureEnv();
+
+ // camera
+ evalCam(y);
+ if (dbgCam) { camT.pos.copy(dbgCam.pos); camT.look.copy(dbgCam.look); camT.fov = dbgCam.fov; }
+ // feed-forward so the damped follow camera doesn't trail a loping astronaut out of frame
+ if (state.walkP > 0 && state.walkP < 1) { tmp.copy(F).multiplyScalar(astro.v / 5.5); camT.pos.add(tmp); camT.look.add(tmp); }
+ // hand-held 70 mm: a breath of drift
+ camT.pos.x += Math.sin(t * 0.43) * 0.012; camT.pos.y += Math.sin(t * 0.61 + 1) * 0.008;
+ if (state.intro < 1) {
+ const f = 1 - state.intro;
+ camT.pos.add(tmp.set(-6 * f * f, 26 * f * f * f + 2 * f, 10 * f * f));
+ camT.look.y += 0.6 * f;
+ }
+ state.par.set(pointer.sx * 0.22, pointer.sy * 0.12, 0).applyQuaternion(camera.quaternion);
+ if (!camInit) { camPos.copy(camT.pos); camLook.copy(camT.look); camInit = true; }
+ const k = dbgCam ? 50 : 5.5;
+ camPos.set(damp(camPos.x, camT.pos.x, k, dt), damp(camPos.y, camT.pos.y, k, dt), damp(camPos.z, camT.pos.z, k, dt));
+ camLook.set(damp(camLook.x, camT.look.x, k, dt), damp(camLook.y, camT.look.y, k, dt), damp(camLook.z, camT.look.z, k, dt));
+ camera.position.copy(camPos).add(state.par);
+ const gmin = H.heightAt(camera.position.x, camera.position.z) + 0.14;
+ if (camera.position.y < gmin) camera.position.y = gmin;
+ camera.lookAt(camLook);
+ if (Math.abs(camera.fov - camT.fov) > 0.01) { camera.fov = damp(camera.fov, camT.fov, k, dt); camera.updateProjectionMatrix(); }
+
+ // shadow frustum follows what we look at
+ const focus = tmp.copy(camLook).lerp(camera.position, 0.25);
+ focus.y = H.heightAt(focus.x, focus.z);
+ sun.target.position.copy(focus);
+ sun.position.copy(focus).addScaledVector(toSun, 160);
+ sun.target.updateMatrixWorld();
+
+ // stars open up at the very end
+ const fr = range(secs.foot);
+ state.starAmt = damp(state.starAmt, smooth(fr.top - innerHeight * 0.9, fr.top, y), 3, dt);
+ stars.material.uniforms.uAmount.value = state.starAmt;
+
+ // UI
+ const walking = state.walkP > 0.004 && state.walkP < 0.999;
+ document.body.classList.toggle('is-walking', walking);
+ for (const c of caps) c.el.classList.toggle('on', walking && astro.d >= c.from && astro.d < c.to);
+ for (const [name, el] of Object.entries(secs)) {
+ if (name === 'hero' || name === 'walk' || name === 'foot') continue;
+ const r = range(el);
+ el.classList.toggle('in', y > r.top - innerHeight * 0.35 && y < r.top + r.span + innerHeight * 0.2);
+ }
+ const di = clamp(Math.floor(dp * 7), 0, 6);
+ days.forEach((li, i) => li.classList.toggle('on', i === di));
+ const outR = range(secs.outpost), outOn = y > outR.top - innerHeight * 0.1 && y < outR.top + outR.span;
+ for (const h of HOTSPOTS) {
+ proj.copy(h.at()).project(camera);
+ const sy = (1 - proj.y) / 2 * innerHeight;
+ const vis = outOn && proj.z < 1 && Math.abs(proj.x) < 0.85 && sy > 150 && sy < innerHeight - 140;
+ h.el.classList.toggle('on', vis);
+ if (vis) h.el.style.transform = `translate3d(${((proj.x + 1) / 2 * innerWidth).toFixed(1)}px, ${((1 - proj.y) / 2 * innerHeight).toFixed(1)}px, 0)`;
+ }
+ $('.hero').style.opacity = 1 - smooth(innerHeight * 0.05, innerHeight * 0.55, y);
+
+ if (t - state.lastHud > 0.08) {
+ state.lastHud = t;
+ tm.dist.textContent = astro.d.toFixed(1);
+ tm.steps.textContent = astro.steps;
+ tm.gait.textContent = astro.v < -0.06 ? 'Retracing' : astro.moveW < 0.35 ? 'Standing' : astro.runW > 0.55 ? 'Lope' : 'Walk';
+ tm.prints.textContent = prints.count;
+ const rate = Math.abs(astro.v) / 1.35;
+ tm.rate.classList.toggle('on', rate > 1.9);
+ tm.rateV.textContent = rate > 1.9 ? `×${rate.toFixed(1)}` : '×1.0';
+ const az = (218 + sunState.az / D2R) % 360;
+ hud.sun.textContent = `Sun az ${az.toFixed(1)}° · el 7.2°`;
+ const met = t + 0.0;
+ hud.met.textContent = `${fmt(met / 86400, 3)}:${fmt((met / 3600) % 24, 2)}:${fmt((met / 60) % 60, 2)}:${fmt(met % 60, 2)}`;
+ const sec = Object.entries(secs).filter(([n, el]) => n !== 'hero' && n !== 'foot' && y >= range(el).top - innerHeight * 0.5).pop()?.[0];
+ navLinks.forEach(a => a.classList.toggle('on', a.dataset.jump === sec));
+ }
+ hud.frame.textContent = `Frame ${fmt(++state.frame % 10000, 4)}`;
+});
+engine.onResize((w, h, dpr) => {
+ dust.mat.uniforms.uDpr.value = dpr; dust.mat.uniforms.uH.value = h;
+ stars.material.uniforms.uDpr.value = dpr;
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+gsap.set('.hero-title .ln > span', { yPercent: 105 });
+gsap.set('.eyebrow, .hero-sub, .hero-cta, .scroll-hint, .nav, .hud', { opacity: 0, y: 12 });
+worldNav('artemis', { theme: 'dark', corner: 'bl' });
+cursor({ color: '#ffffff', blend: 'difference', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+window.__art = { captureEnv, sun, TUNE, groundMat, farMat, farMesh, near, earth, astro, prints, dust, engine, H, state, sunState, lenis, camera,
+ jump(sec, p = 0) {
+ const r = range(secs[sec]);
+ lenis.scrollTo(r.top + p * r.span, { immediate: true, force: true });
+ const target = clamp((prog(secs.walk) - 0.015) / 0.95) * (astro.len - 0.45);
+ if (target > astro.d + 0.3) { simulating = true; astro.simulateTo(target, true); simulating = false; }
+ else if (target < astro.d - 0.3) astro.d = target;
+ state.intro = 1; camInit = false;
+ } };
+
+// Reloaded mid-page? Put the walker (and every print behind him) where the scroll says he should be.
+{
+ const target = clamp((prog(secs.walk) - 0.015) / 0.95) * (astro.len - 0.45);
+ if (target > 0.5) { simulating = true; astro.simulateTo(target, true); simulating = false; }
+}
+astro.update(0.016, astro.d, 0);
+captureEnv();
+renderer.compile(scene, camera);
+engine.start();
+await loader.finish();
+gsap.to(state, { intro: 1, duration: 3.4, ease: 'power3.inOut' });
+gsap.to('.hero-title .ln > span', { yPercent: 0, duration: 1.6, ease: 'expo.out', stagger: 0.12, delay: 0.9 });
+gsap.to('.eyebrow, .hero-sub, .hero-cta, .scroll-hint, .nav, .hud', { opacity: 1, y: 0, duration: 1.4, ease: 'power3.out', stagger: 0.08, delay: 1.3 });
diff --git a/examples/artemis/noise.js b/examples/artemis/noise.js
new file mode 100644
index 0000000..abfd3cc
--- /dev/null
+++ b/examples/artemis/noise.js
@@ -0,0 +1,61 @@
+// Seeded RNG + gradient noise used to build the regolith on the CPU (heights must match what the feet stand on).
+export function mulberry32(a) {
+ return () => {
+ a |= 0; 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;
+ };
+}
+
+export function makeNoise(seed = 1) {
+ const rnd = mulberry32(seed);
+ const p = new Uint8Array(256);
+ for (let i = 0; i < 256; i++) p[i] = i;
+ for (let i = 255; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); const t = p[i]; p[i] = p[j]; p[j] = t; }
+ const perm = new Uint8Array(512);
+ for (let i = 0; i < 512; i++) perm[i] = p[i & 255];
+ const gx = new Float32Array(256), gy = new Float32Array(256);
+ for (let i = 0; i < 256; i++) { const a = rnd() * Math.PI * 2; gx[i] = Math.cos(a); gy[i] = Math.sin(a); }
+ const fade = t => t * t * t * (t * (t * 6 - 15) + 10);
+
+ function noise2(x, y) {
+ const xi = Math.floor(x), yi = Math.floor(y);
+ const xf = x - xi, yf = y - yi;
+ const X = xi & 255, Y = yi & 255;
+ const a = perm[X + perm[Y]], b = perm[X + 1 + perm[Y]], c = perm[X + perm[Y + 1]], d = perm[X + 1 + perm[Y + 1]];
+ const u = fade(xf), v = fade(yf);
+ const n00 = gx[a] * xf + gy[a] * yf;
+ const n10 = gx[b] * (xf - 1) + gy[b] * yf;
+ const n01 = gx[c] * xf + gy[c] * (yf - 1);
+ const n11 = gx[d] * (xf - 1) + gy[d] * (yf - 1);
+ const nx0 = n00 + (n10 - n00) * u, nx1 = n01 + (n11 - n01) * u;
+ return (nx0 + (nx1 - nx0) * v) * 1.41;
+ }
+ function fbm2(x, y, oct = 4, gain = 0.5, lac = 2.03) {
+ let s = 0, a = 0.5, f = 1;
+ for (let i = 0; i < oct; i++) { s += a * noise2(x * f + i * 17.3, y * f - i * 9.1); f *= lac; a *= gain; }
+ return s;
+ }
+ function ridge2(x, y, oct = 5) {
+ let s = 0, a = 0.5, f = 1, w = 1;
+ for (let i = 0; i < oct; i++) {
+ let n = 1 - Math.abs(noise2(x * f + i * 31.7, y * f + i * 11.3));
+ n *= n; n *= w; w = Math.min(1, n * 2);
+ s += a * n; f *= 2.1; a *= 0.5;
+ }
+ return s;
+ }
+ // 3D value noise for rock displacement
+ const h3 = (x, y, z) => { let n = (x * 374761393 + y * 668265263 + z * 1274126177 + seed * 97) | 0; n = Math.imul(n ^ (n >>> 13), 1274126177); return ((n ^ (n >>> 16)) >>> 0) / 4294967296; };
+ function noise3(x, y, z) {
+ const xi = Math.floor(x), yi = Math.floor(y), zi = Math.floor(z);
+ const xf = x - xi, yf = y - yi, zf = z - zi;
+ const u = xf * xf * (3 - 2 * xf), v = yf * yf * (3 - 2 * yf), w = zf * zf * (3 - 2 * zf);
+ const l = (a, b, t) => a + (b - a) * t;
+ return l(
+ l(l(h3(xi, yi, zi), h3(xi + 1, yi, zi), u), l(h3(xi, yi + 1, zi), h3(xi + 1, yi + 1, zi), u), v),
+ l(l(h3(xi, yi, zi + 1), h3(xi + 1, yi, zi + 1), u), l(h3(xi, yi + 1, zi + 1), h3(xi + 1, yi + 1, zi + 1), u), v), w) * 2 - 1;
+ }
+ return { noise2, fbm2, ridge2, noise3, rnd };
+}
diff --git a/examples/artemis/outpost.js b/examples/artemis/outpost.js
new file mode 100644
index 0000000..0a7f614
--- /dev/null
+++ b/examples/artemis/outpost.js
@@ -0,0 +1,130 @@
+// The outpost at the end of the traverse: the Meshy lander, a regolith-shielded habitat, a vertical solar mast
+// that turns to follow the low sun, and orange trail beacons along the walk.
+import { THREE, normalize, prepModel } from '../../src/core/engine.js';
+import { fbmNormal } from '../../src/core/textures.js';
+import { LAYOUT } from './terrain.js';
+
+export function paintedMetalFix(mat) {
+ // Meshy marks the white cabin panels as metal; treat bright, unsaturated texels as painted aluminium.
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (sh, r) => {
+ prev?.(sh, r);
+ sh.fragmentShader = sh.fragmentShader.replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ float pLum = dot(diffuseColor.rgb, vec3(0.333));
+ float pSat = max(diffuseColor.r, max(diffuseColor.g, diffuseColor.b)) - min(diffuseColor.r, min(diffuseColor.g, diffuseColor.b));
+ float paint = smoothstep(0.32, 0.6, pLum) * (1.0 - smoothstep(0.05, 0.14, pSat));
+ roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.55), paint);`)
+ .replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment>
+ metalnessFactor *= 1.0 - paint * 0.93;`);
+ };
+ mat.customProgramCacheKey = () => 'painted-metal';
+}
+
+export async function buildOutpost({ assets, renderer, H, scene }) {
+ const group = new THREE.Group();
+ scene.add(group);
+ const L = LAYOUT.lander;
+ const g = await assets.gltf('models/artemis/lander.glb');
+ const lander = g.scene;
+ normalize(lander, 6.6, { axis: 'y' });
+ prepModel(lander, renderer, { env: 1.0, onMat: m => paintedMetalFix(m) });
+ const lg = new THREE.Group();
+ lg.add(lander);
+ lg.position.set(L.x, H.heightAt(L.x, L.z) - 0.04, L.z);
+ lg.rotation.y = L.yaw;
+ group.add(lg);
+
+ const white = new THREE.MeshStandardMaterial({ color: 0xd8d6d0, roughness: 0.72, metalness: 0, normalMap: fbmNormal(renderer, { size: 512, scale: 12, octaves: 5, strength: 0.6 }) });
+ white.normalMap.repeat.set(4, 2);
+ const band = new THREE.MeshStandardMaterial({ color: 0x9a9892, roughness: 0.5, metalness: 0.6 });
+ const orange = new THREE.MeshStandardMaterial({ color: 0xff5a14, roughness: 0.45, metalness: 0, emissive: 0xff4a0a, emissiveIntensity: 0.08 });
+ const dark = new THREE.MeshStandardMaterial({ color: 0x1a1b1e, roughness: 0.6, metalness: 0.5 });
+
+ // Habitat: a long pressurised can on low legs, with shielding bands and a suitport end.
+ {
+ const hb = LAYOUT.hab;
+ const hab = new THREE.Group();
+ const body = new THREE.Mesh(new THREE.CapsuleGeometry(1.9, 6.4, 16, 48).rotateZ(Math.PI / 2), white);
+ body.position.y = 2.35;
+ hab.add(body);
+ for (let i = -3; i <= 3; i++) {
+ const r = new THREE.Mesh(new THREE.TorusGeometry(1.93, 0.05, 8, 64).rotateY(Math.PI / 2), band);
+ r.position.set(i * 1.05, 2.35, 0); hab.add(r);
+ }
+ for (const s of [-1, 1]) for (const e of [-1, 1]) {
+ const leg = new THREE.Mesh(new THREE.CylinderGeometry(0.08, 0.1, 1.2, 10), band);
+ leg.position.set(e * 2.6, 0.6, s * 1.25); hab.add(leg);
+ const pad = new THREE.Mesh(new THREE.CylinderGeometry(0.34, 0.38, 0.06, 20), band);
+ pad.position.set(e * 2.6, 0.03, s * 1.25); hab.add(pad);
+ }
+ const port = new THREE.Mesh(new THREE.CylinderGeometry(0.62, 0.62, 0.35, 32).rotateZ(Math.PI / 2), dark);
+ port.position.set(-5.1, 2.2, 0); hab.add(port);
+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.64, 0.05, 10, 40).rotateY(Math.PI / 2), orange);
+ ring.position.set(-5.28, 2.2, 0); hab.add(ring);
+ const win = new THREE.Mesh(new THREE.CircleGeometry(0.28, 32), new THREE.MeshStandardMaterial({ color: 0x05070a, roughness: 0.05, metalness: 0.9 }));
+ win.position.set(1.2, 3.1, 1.86); win.rotation.x = -0.35; hab.add(win);
+ hab.position.set(hb.x, H.heightAt(hb.x, hb.z), hb.z);
+ hab.rotation.y = 0.5;
+ hab.traverse(o => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ group.add(hab);
+ }
+
+ // Vertical solar array mast: truss + two rolled-out wings, yawed to face the sun.
+ let wings;
+ {
+ const ms = LAYOUT.mast;
+ const mast = new THREE.Group();
+ const h = 15;
+ const strut = new THREE.CylinderGeometry(0.035, 0.035, h, 6);
+ for (let k = 0; k < 3; k++) {
+ const a = (k / 3) * Math.PI * 2;
+ const s = new THREE.Mesh(strut, band); s.position.set(Math.cos(a) * 0.28, h / 2, Math.sin(a) * 0.28); mast.add(s);
+ }
+ for (let y = 0.5; y < h; y += 0.7) {
+ const r = new THREE.Mesh(new THREE.TorusGeometry(0.28, 0.018, 4, 3).rotateX(Math.PI / 2), band); r.position.y = y; mast.add(r);
+ }
+ const base = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 1.1, 0.5, 6), white); base.position.y = 0.25; mast.add(base);
+ const c = document.createElement('canvas'); c.width = 256; c.height = 1024;
+ const cx = c.getContext('2d');
+ cx.fillStyle = '#0a1226'; cx.fillRect(0, 0, 256, 1024);
+ cx.strokeStyle = '#7a8090'; cx.lineWidth = 1.2;
+ for (let x = 0; x <= 256; x += 32) { cx.beginPath(); cx.moveTo(x, 0); cx.lineTo(x, 1024); cx.stroke(); }
+ for (let y = 0; y <= 1024; y += 32) { cx.beginPath(); cx.moveTo(0, y); cx.lineTo(256, y); cx.stroke(); }
+ cx.strokeStyle = '#c9a15a'; cx.lineWidth = 6; cx.strokeRect(3, 3, 250, 1018);
+ const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace; tex.anisotropy = 8;
+ const cell = new THREE.MeshStandardMaterial({ map: tex, roughness: 0.92, metalness: 0, envMapIntensity: 0.12 });
+ wings = new THREE.Group();
+ for (const s of [-1, 1]) {
+ const w = new THREE.Mesh(new THREE.BoxGeometry(2.6, 8.5, 0.05), cell);
+ w.position.set(s * 1.75, h - 5.2, 0); wings.add(w);
+ }
+ const boom = new THREE.Mesh(new THREE.BoxGeometry(6.4, 0.1, 0.1), band); boom.position.y = h - 0.9; wings.add(boom);
+ const boom2 = boom.clone(); boom2.position.y = h - 9.5; wings.add(boom2);
+ mast.add(wings);
+ const tip = new THREE.Mesh(new THREE.SphereGeometry(0.16, 16, 12), orange); tip.position.y = h + 0.1; mast.add(tip);
+ mast.position.set(ms.x, H.heightAt(ms.x, ms.z), ms.z);
+ mast.traverse(o => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ group.add(mast);
+ }
+
+ // Trail beacons: thin white poles with retro-reflective orange caps, alternating sides of the path.
+ {
+ const n = 7;
+ const poleGeo = new THREE.CylinderGeometry(0.012, 0.016, 1.15, 6).translate(0, 0.575, 0);
+ const capGeo = new THREE.CylinderGeometry(0.032, 0.032, 0.11, 12).translate(0, 1.2, 0);
+ const poles = new THREE.InstancedMesh(poleGeo, band, n), caps = new THREE.InstancedMesh(capGeo, orange, n);
+ const m = new THREE.Matrix4();
+ for (let i = 0; i < n; i++) {
+ const u = (i + 0.6) / (n + 0.4);
+ const p = H.curve.getPointAt(u), t = H.curve.getTangentAt(u);
+ const s = i % 2 ? 1 : -1;
+ const x = p.x - t.z * 2.9 * s, z = p.z + t.x * 2.9 * s;
+ m.makeRotationY(i * 1.3).setPosition(x, H.heightAt(x, z) - 0.05, z);
+ poles.setMatrixAt(i, m); caps.setMatrixAt(i, m);
+ }
+ for (const im of [poles, caps]) { im.castShadow = true; im.receiveShadow = true; im.computeBoundingSphere(); group.add(im); }
+ }
+
+ const trackSun = toSun => { wings.rotation.y = Math.atan2(toSun.x, toSun.z); };
+ return { group, lander: lg, trackSun, center: new THREE.Vector3(L.x, lg.position.y, L.z) };
+}
diff --git a/examples/artemis/prints.js b/examples/artemis/prints.js
new file mode 100644
index 0000000..944bd2b
--- /dev/null
+++ b/examples/artemis/prints.js
@@ -0,0 +1,93 @@
+// Bootprints: a canvas-baked cleated sole (height → normal + depression mask + alpha), stamped as instanced decals
+// that reuse the regolith shader, so their albedo, micro-normals and raymarched shadows match the ground exactly.
+import { THREE } from '../../src/core/engine.js';
+import { patchRegolith } from './terrain.js';
+import { mulberry32 } from './noise.js';
+
+function bootTexture() {
+ const W = 128, H = 256;
+ const c = document.createElement('canvas'); c.width = W; c.height = H;
+ const g = c.getContext('2d', { willReadFrequently: true });
+ const read = () => { const d = g.getImageData(0, 0, W, H).data; const o = new Float32Array(W * H); for (let i = 0; i < W * H; i++) o[i] = d[i * 4] / 255; return o; };
+ const sole = blur => {
+ g.filter = 'none'; g.fillStyle = '#000'; g.fillRect(0, 0, W, H);
+ g.filter = `blur(${blur}px)`; g.fillStyle = '#fff';
+ g.beginPath(); g.ellipse(W * 0.5, H * 0.33, W * 0.33, H * 0.165, 0, 0, Math.PI * 2); g.fill(); // forefoot (toe at top)
+ g.beginPath(); g.ellipse(W * 0.5, H * 0.72, W * 0.275, H * 0.13, 0, 0, Math.PI * 2); g.fill(); // heel
+ g.fillRect(W * 0.24, H * 0.32, W * 0.52, H * 0.4); // waist
+ return read();
+ };
+ const m = sole(1.2), wide = sole(9), mid = sole(3.5);
+ const rnd = mulberry32(5);
+ const h = new Float32Array(W * H);
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ const i = y * W + x;
+ // Chevron cleats across the sole, a smooth instep band, and crumbs.
+ const u = (x / W - 0.5), v = y / H;
+ const chev = Math.cos(((v + Math.abs(u) * 0.35) * H) / 13 * Math.PI * 2) * 0.5 + 0.5;
+ const instep = v > 0.5 && v < 0.58 ? 0 : 1;
+ const cleat = Math.pow(chev, 2.2) * instep;
+ const rim = Math.max(0, wide[i] - mid[i] * 0.95);
+ h[i] = -m[i] * (0.9 + cleat * 0.2) + rim * 0.5 + (rnd() - 0.5) * 0.07 * (m[i] + rim);
+ }
+ // Raw bytes (a canvas would premultiply and destroy RGB wherever alpha is 0); rows flipped so the toe is +v.
+ const px = new Uint8Array(W * H * 4);
+ const k = 3.2;
+ for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
+ const i = y * W + x, o = ((H - 1 - y) * W + x) * 4;
+ const l = h[y * W + Math.max(0, x - 1)], r = h[y * W + Math.min(W - 1, x + 1)];
+ const t = h[Math.max(0, y - 1) * W + x], bt = h[Math.min(H - 1, y + 1) * W + x];
+ let nx = (l - r) * k, ny = (bt - t) * k, nz = 1;
+ const len = Math.hypot(nx, ny, nz); nx /= len; ny /= len;
+ px[o] = (nx * 0.5 + 0.5) * 255;
+ px[o + 1] = (ny * 0.5 + 0.5) * 255;
+ px[o + 2] = Math.min(1, Math.max(0, (h[i] + 1.3) / 2)) * 255;
+ px[o + 3] = Math.min(1, wide[i] * 1.6) * 255;
+ }
+ const tex = new THREE.DataTexture(px, W, H, THREE.RGBAFormat);
+ tex.colorSpace = THREE.NoColorSpace;
+ tex.magFilter = THREE.LinearFilter; tex.minFilter = THREE.LinearMipmapLinearFilter; tex.generateMipmaps = true;
+ tex.anisotropy = 8;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+export class Prints {
+ constructor(H, ctx, max = 900) {
+ this.H = H; this.max = max; this.count = 0; this.list = [];
+ const tex = bootTexture();
+ const geo = new THREE.PlaneGeometry(0.25, 0.5).rotateX(-Math.PI / 2);
+ const mat = new THREE.MeshStandardMaterial({ color: ctx.color, roughness: 1, metalness: 0, transparent: true, depthWrite: false,
+ polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -6 });
+ mat.defines = { USE_UV: '' };
+ patchRegolith(mat, { ...ctx, print: tex });
+ this.mesh = new THREE.InstancedMesh(geo, mat, max);
+ this.mesh.count = 0;
+ this.mesh.receiveShadow = true;
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 1;
+ this._m = new THREE.Matrix4(); this._up = new THREE.Vector3(); this._f = new THREE.Vector3(); this._x = new THREE.Vector3(); this._z = new THREE.Vector3();
+ }
+ near(x, z, r = 0.14) {
+ for (let i = this.list.length - 1; i >= Math.max(0, this.list.length - 60); i--) { const p = this.list[i]; if ((p.x - x) ** 2 + (p.z - z) ** 2 < r * r) return true; }
+ return false;
+ }
+ stamp(x, z, yaw) {
+ if (this.near(x, z)) return false;
+ const up = this.H.normalAt(x, z, this._up, 0.12);
+ const f = this._f.set(Math.sin(yaw), 0, Math.cos(yaw));
+ f.addScaledVector(up, -f.dot(up)).normalize();
+ const zA = this._z.copy(f).negate(); // plane's local -Z is the toe
+ const xA = this._x.crossVectors(up, zA).normalize();
+ const y = this.H.heightAt(x, z) + 0.008;
+ this._m.makeBasis(xA, up, zA).setPosition(x, y, z);
+ const i = this.count % this.max;
+ this.mesh.setMatrixAt(i, this._m);
+ this.mesh.instanceMatrix.needsUpdate = true;
+ this.count++;
+ this.mesh.count = Math.min(this.count, this.max);
+ this.list.push({ x, z });
+ if (this.list.length > this.max) this.list.shift();
+ return true;
+ }
+}
diff --git a/examples/artemis/sky.js b/examples/artemis/sky.js
new file mode 100644
index 0000000..f0b60cc
--- /dev/null
+++ b/examples/artemis/sky.js
@@ -0,0 +1,81 @@
+// Earth over the horizon (NB2 Blue-Marble plate on a sphere, lit by our own sun so its phase is honest),
+// a thin atmosphere shell, a sun disc for the rare reverse angle, and a star field that only appears
+// when the "camera" opens up its exposure near the end of the page.
+import { THREE } from '../../src/core/engine.js';
+import { mulberry32 } from './noise.js';
+
+export function makeEarth(map, { dist = 11500, ang = 5.2 } = {}) {
+ const R = dist * Math.tan((ang * Math.PI) / 360);
+ const group = new THREE.Group();
+ const uniforms = { uMap: { value: map }, uSun: { value: new THREE.Vector3(1, 0, 0) }, uGain: { value: 1.25 } };
+ const earth = new THREE.Mesh(new THREE.SphereGeometry(R, 96, 64), new THREE.ShaderMaterial({
+ uniforms,
+ vertexShader: /* glsl */`
+ varying vec3 vN; varying vec3 vP; varying vec2 vUv;
+ void main(){ vUv = uv; vN = normalize(mat3(modelMatrix) * normal); vec4 w = modelMatrix * vec4(position, 1.); vP = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,
+ fragmentShader: /* glsl */`
+ uniform sampler2D uMap; uniform vec3 uSun; uniform float uGain;
+ varying vec3 vN; varying vec3 vP; varying vec2 vUv;
+ void main(){
+ vec3 n = normalize(vN), V = normalize(cameraPosition - vP);
+ vec3 day = texture2D(uMap, vUv).rgb;
+ float ndl = dot(n, uSun);
+ float lit = smoothstep(-0.08, 0.22, ndl) * (0.35 + 0.65 * clamp(ndl, 0., 1.));
+ float ocean = smoothstep(0.02, 0.12, day.b - max(day.r, day.g) * 0.9) * (1. - smoothstep(0.55, 0.8, dot(day, vec3(.33))));
+ float spec = pow(max(dot(reflect(-uSun, n), V), 0.), 36.) * ocean * 1.6 * step(0., ndl);
+ float fres = pow(1. - max(dot(n, V), 0.), 2.4);
+ vec3 atm = vec3(0.32, 0.56, 1.0) * fres * smoothstep(-0.25, 0.5, ndl) * 1.4;
+ vec3 col = day * lit * uGain + atm + vec3(0.9, 0.95, 1.) * spec;
+ col = mix(col, col * vec3(0.8, 0.9, 1.15), fres * 0.6);
+ gl_FragColor = vec4(col * 2.2, 1.);
+ }`,
+ }));
+ const halo = new THREE.Mesh(new THREE.SphereGeometry(R * 1.045, 64, 48), new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, side: THREE.BackSide, blending: THREE.AdditiveBlending,
+ vertexShader: `varying vec3 vN; varying vec3 vP; void main(){ vN = normalize(mat3(modelMatrix) * normal); vec4 w = modelMatrix * vec4(position,1.); vP = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,
+ fragmentShader: `uniform vec3 uSun; varying vec3 vN; varying vec3 vP;
+ void main(){ vec3 n = normalize(vN), V = normalize(cameraPosition - vP);
+ float rim = pow(clamp(1. - abs(dot(n, V)) , 0., 1.), 5.0);
+ float day = smoothstep(-0.35, 0.6, dot(n, uSun));
+ gl_FragColor = vec4(vec3(0.3, 0.55, 1.0) * rim * day * 2.2, 1.); }`,
+ }));
+ group.add(earth, halo);
+ earth.rotation.set(0.35, -2.1, 0.18);
+ group.userData = { earth, halo, uniforms, R, dist };
+ return group;
+}
+
+export function makeSun() {
+ const c = document.createElement('canvas'); c.width = c.height = 256;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(128, 128, 0, 128, 128, 128);
+ grd.addColorStop(0, '#fff'); grd.addColorStop(0.12, '#fff'); grd.addColorStop(0.16, 'rgba(255,250,240,.35)');
+ grd.addColorStop(0.4, 'rgba(255,245,230,.06)'); grd.addColorStop(1, 'rgba(0,0,0,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, 256, 256);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace;
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, color: new THREE.Color(40, 39, 37), depthWrite: false, blending: THREE.AdditiveBlending, fog: false }));
+ s.scale.setScalar(900);
+ return s;
+}
+
+export function makeStars(n = 5000, r = 14000) {
+ const rnd = mulberry32(8);
+ const pos = new Float32Array(n * 3), mag = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ const u = rnd() * 2 - 1, a = rnd() * Math.PI * 2, s = Math.sqrt(1 - u * u);
+ pos.set([Math.cos(a) * s * r, Math.abs(u) * r * (u > -0.2 ? 1 : 0.2), Math.sin(a) * s * r], i * 3);
+ mag[i] = Math.pow(rnd(), 6);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('mag', new THREE.BufferAttribute(mag, 1));
+ const m = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uAmount: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: `attribute float mag; uniform float uDpr; varying float vM; void main(){ vM = mag; vec4 mv = modelViewMatrix * vec4(position,1.); gl_Position = projectionMatrix * mv; gl_PointSize = (1. + mag * 2.4) * uDpr; }`,
+ fragmentShader: `uniform float uAmount; varying float vM; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, 0., d); gl_FragColor = vec4(vec3(0.85, 0.9, 1.) * a * (0.25 + vM * 3.) * uAmount, 1.); }`,
+ });
+ const p = new THREE.Points(g, m);
+ p.frustumCulled = false;
+ return p;
+}
diff --git a/examples/artemis/style.css b/examples/artemis/style.css
new file mode 100644
index 0000000..0e542fe
--- /dev/null
+++ b/examples/artemis/style.css
@@ -0,0 +1,267 @@
+:root {
+ --bg: #000;
+ --ink: #f4f3f0;
+ --dim: rgba(244, 243, 240, .62);
+ --faint: rgba(244, 243, 240, .16);
+ --hair: rgba(244, 243, 240, .28);
+ --accent: #ff5b14;
+ --sans: 'Space Grotesk', system-ui, sans-serif;
+ --cond: 'Barlow Condensed', 'Arial Narrow', sans-serif;
+ --gut: clamp(16px, 4vw, 56px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 16px/1.55 var(--sans); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+img { display: block; max-width: 100%; }
+.rd { font-family: var(--cond); font-weight: 500; font-size: 12px; letter-spacing: .16em; text-transform: uppercase; font-variant-numeric: tabular-nums; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+.grain { position: fixed; inset: 0; z-index: 1; pointer-events: none; opacity: .0; }
+
+/* ── loader: powered descent ─────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: #000; display: grid; place-items: center; }
+.loader-frame { width: min(520px, 84vw); display: grid; gap: 18px; }
+.loader-top, .loader-bottom { display: flex; justify-content: space-between; color: var(--dim); }
+.loader-alt { display: flex; align-items: baseline; gap: 10px; font: 300 clamp(64px, 12vw, 132px)/.9 var(--sans); letter-spacing: -.04em; font-variant-numeric: tabular-nums; }
+.loader-alt em { font: 500 18px/1 var(--cond); letter-spacing: .14em; color: var(--dim); font-style: normal; }
+.loader-bar { height: 1px; background: var(--faint); position: relative; overflow: hidden; }
+.loader-bar i { position: absolute; inset: 0; background: var(--ink); transform-origin: left; transform: scaleX(var(--p, 0)); }
+.loader-call { color: var(--accent); }
+
+/* ── nav ─────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 24px;
+ padding: 26px calc(var(--gut) + 14px) 0; pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 500 15px/1 var(--sans); letter-spacing: .34em; text-transform: uppercase; }
+.brand svg { width: 26px; height: 26px; }
+.links { display: flex; gap: clamp(18px, 2.4vw, 38px); margin-left: auto; }
+.links a { text-decoration: none; font: 500 13px/1 var(--sans); color: var(--dim); transition: color .3s; letter-spacing: .01em; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: -7px; height: 1px; background: var(--accent); transform: scaleX(0); transform-origin: left; transition: transform .45s cubic-bezier(.2,.8,.2,1); }
+.links a:hover, .links a.on { color: var(--ink); }
+.links a.on::after { transform: scaleX(1); }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 22px; border-radius: 3px;
+ text-decoration: none; font: 500 14px/1 var(--sans); letter-spacing: .01em; transition: background .35s, color .35s, box-shadow .35s; white-space: nowrap; }
+.btn-solid { background: var(--accent); color: #000; }
+.btn-solid:hover { background: #ff7a3d; box-shadow: 0 0 0 6px rgba(255, 91, 20, .16); }
+.btn-ghost { box-shadow: inset 0 0 0 1px var(--hair); color: var(--ink); background: rgba(0, 0, 0, .25); backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--ink); }
+.nav .btn { height: 40px; padding: 0 18px; font-size: 13px; }
+
+/* ── HUD: film-edge data ─────────────────────────────────── */
+.hud { position: fixed; inset: var(--gut); z-index: 6; pointer-events: none; color: var(--dim); transition: opacity .6s; }
+.hud > div { position: absolute; display: grid; gap: 4px; padding: 14px; font-size: 11px; }
+.hud-tl { left: calc(12px - var(--gut)); top: 50%; writing-mode: vertical-rl; transform: translateY(-50%) rotate(180deg); display: flex !important; gap: 18px !important; }
+.hud-tr { right: calc(12px - var(--gut)); top: 50%; writing-mode: vertical-rl; transform: translateY(-50%); display: flex !important; gap: 18px !important; }
+.hud-bl { left: 0; bottom: 0; padding-bottom: 12px !important; }
+.hud-bl { left: 150px; }
+.hud-br { right: 0; bottom: 0; text-align: right; }
+.hud b { color: var(--ink); font-weight: 500; }
+.hud-c { position: absolute; width: 14px; height: 14px; border-color: var(--hair); border-style: solid; border-width: 0; }
+.hud-c1 { left: 0; top: 0; border-left-width: 1px; border-top-width: 1px; }
+.hud-c2 { right: 0; top: 0; border-right-width: 1px; border-top-width: 1px; }
+.hud-c3 { left: 0; bottom: 0; border-left-width: 1px; border-bottom-width: 1px; }
+.hud-c4 { right: 0; bottom: 0; border-right-width: 1px; border-bottom-width: 1px; }
+
+.telemetry { position: fixed; left: 50%; bottom: calc(var(--gut) + 8px); transform: translate(-50%, 16px); z-index: 7; display: flex; gap: 0; pointer-events: none;
+ opacity: 0; transition: opacity .6s, transform .6s; }
+.is-walking .telemetry { opacity: 1; transform: translate(-50%, 0); }
+.telemetry > div { display: grid; gap: 2px; padding: 0 20px; border-left: 1px solid var(--faint); min-width: 104px; }
+.telemetry > div:first-child { border-left: 0; }
+.telemetry em { font-style: normal; color: var(--dim); font-size: 11px; }
+.telemetry b { font: 500 26px/1 var(--cond); letter-spacing: .02em; color: var(--ink); }
+.telemetry small { font-size: 11px; color: var(--dim); margin-left: 3px; }
+.telemetry > div:first-child { grid-template-columns: auto auto; align-items: baseline; }
+.telemetry > div:first-child em { grid-column: 1 / -1; }
+.tm-rate { opacity: .35; transition: opacity .3s; }
+.tm-rate.on { opacity: 1; }
+.tm-rate.on b { color: var(--accent); }
+
+/* ── hero ────────────────────────────────────────────────── */
+.hero { position: relative; z-index: 4; height: 100vh; min-height: 620px; pointer-events: none; }
+.hero-inner { position: absolute; left: calc(var(--gut) + 14px); bottom: calc(var(--gut) + 64px); max-width: min(760px, 58vw); }
+.eyebrow { color: var(--dim); margin-bottom: 26px; }
+.eyebrow span { color: var(--accent); margin: 0 .5em; }
+.hero-title { font: 400 clamp(46px, 6.3vw, 112px)/.94 var(--sans); letter-spacing: -.042em; }
+.hero-title .ln { display: block; overflow: hidden; padding-bottom: .06em; }
+.hero-title .ln > span { display: block; }
+.hero-title em { font-style: normal; color: var(--accent); }
+.hero-sub { max-width: 31em; margin-top: 28px; font-size: clamp(16px, 1.25vw, 19px); line-height: 1.5; color: var(--dim); }
+.hero-cta { display: flex; gap: 12px; margin-top: 34px; pointer-events: auto; flex-wrap: wrap; }
+.scroll-hint { position: absolute; left: 50%; transform: translateX(-50%); bottom: calc(var(--gut) + 22px); white-space: nowrap; display: flex; align-items: center; gap: 14px; color: var(--dim); }
+.scroll-hint b { color: var(--ink); font-weight: 600; }
+.boot { position: relative; width: 16px; height: 28px; }
+.boot i { position: absolute; width: 6px; height: 11px; border-radius: 3px 3px 2px 2px; background: var(--accent); animation: step 1.6s infinite cubic-bezier(.5,0,.3,1); }
+.boot i:first-child { left: 0; top: 14px; }
+.boot i:last-child { right: 0; top: 2px; animation-delay: .8s; }
+@keyframes step { 0%, 100% { opacity: .25; transform: translateY(4px); } 30%, 60% { opacity: 1; transform: none; } }
+
+/* ── walk ────────────────────────────────────────────────── */
+.walk { position: relative; z-index: 4; height: 900vh; pointer-events: none; }
+.walk-sticky { position: sticky; top: 0; height: 100vh; }
+.sec-tag { color: var(--dim); display: flex; gap: 12px; align-items: baseline; }
+.sec-tag b { color: var(--accent); font-weight: 600; }
+.sec-sub { color: var(--faint); color: rgba(244,243,240,.38); margin-left: 8px; }
+.walk .sec-tag { position: absolute; left: calc(var(--gut) + 14px); top: 132px; opacity: 0; transition: opacity .6s; }
+.is-walking .walk .sec-tag { opacity: 1; }
+.cap { position: absolute; width: min(390px, 80vw); opacity: 0; transform: translateY(18px); transition: opacity .8s ease, transform 1s cubic-bezier(.2,.8,.2,1); }
+.cap.on { opacity: 1; transform: none; }
+.cap::before { content: ''; display: block; width: 36px; height: 2px; background: var(--accent); margin-bottom: 18px; }
+.cap .rd { color: var(--dim); margin-bottom: 10px; }
+.cap h3 { font: 400 clamp(26px, 2.5vw, 38px)/1.05 var(--sans); letter-spacing: -.03em; margin-bottom: 14px; }
+.cap p:last-child { color: var(--dim); font-size: 15.5px; line-height: 1.55; }
+.cap-a { left: calc(var(--gut) + 14px); bottom: 24vh; }
+.cap-b { right: calc(var(--gut) + 14px); top: 22vh; }
+.cap-c { left: calc(var(--gut) + 14px); top: 24vh; }
+.cap-d { right: calc(var(--gut) + 14px); bottom: 24vh; }
+.cap-e { left: calc(var(--gut) + 14px); top: 24vh; }
+
+/* ── sticky sections ─────────────────────────────────────── */
+.outpost, .days, .training, .price { position: relative; z-index: 4; pointer-events: none; }
+.outpost { height: 260vh; } .days { height: 380vh; } .training { height: 240vh; } .price { height: 200vh; }
+.sticky { position: sticky; top: 0; height: 100vh; overflow: hidden; }
+.panel { position: absolute; top: 0; bottom: 0; display: flex; flex-direction: column; justify-content: center; gap: 0; padding: 120px 0 100px; width: min(520px, 42vw); }
+.panel-left { left: calc(var(--gut) + 14px); }
+.panel-right { right: calc(var(--gut) + 14px); }
+.panel.wide { width: min(1120px, calc(100vw - 2 * var(--gut) - 28px)); }
+.panel h2 { font: 400 clamp(34px, 3.7vw, 62px)/1 var(--sans); letter-spacing: -.04em; margin: 22px 0 22px; }
+.lede { color: var(--dim); font-size: clamp(15px, 1.12vw, 18px); line-height: 1.58; max-width: 34em; }
+.lede.small { max-width: 38em; }
+.panel > * { opacity: 0; transform: translateY(26px); transition: opacity .9s ease, transform 1.1s cubic-bezier(.2,.8,.2,1); }
+.in .panel > * { opacity: 1; transform: none; }
+.in .panel > *:nth-child(2) { transition-delay: .08s; } .in .panel > *:nth-child(3) { transition-delay: .16s; }
+.in .panel > *:nth-child(4) { transition-delay: .24s; } .in .panel > *:nth-child(5) { transition-delay: .32s; }
+.specs { list-style: none; display: grid; grid-template-columns: repeat(3, 1fr); margin-top: 34px; border-top: 1px solid var(--faint); }
+.specs li { padding: 16px 16px 0 0; display: grid; gap: 6px; color: var(--dim); }
+.specs b { font: 400 30px/1 var(--sans); letter-spacing: -.03em; color: var(--ink); text-transform: none; }
+.plate { margin-top: 34px; width: 210px; pointer-events: auto; }
+.plate img { width: 100%; height: auto; aspect-ratio: 4 / 3; object-fit: cover; filter: saturate(.45) contrast(1.05); border-radius: 2px; }
+.plate figcaption { color: var(--dim); margin-top: 10px; font-size: 11px; }
+
+/* hotspots on the outpost */
+.hotspots { position: fixed; inset: 0; z-index: 5; pointer-events: none; }
+.hs { position: absolute; left: 0; top: 0; opacity: 0; transition: opacity .6s; will-change: transform; }
+.hs.on { opacity: 1; }
+.hs i { position: absolute; left: -5px; top: -5px; width: 10px; height: 10px; border-radius: 50%; box-shadow: 0 0 0 1px var(--ink); }
+.hs i::after { content: ''; position: absolute; inset: 3px; border-radius: 50%; background: var(--accent); }
+.hs div { position: absolute; left: 18px; top: -12px; width: 230px; padding: 9px 12px 10px; border-left: 1px solid var(--accent); background: rgba(0,0,0,.62); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); border-radius: 0 2px 2px 0; }
+.hs b { display: block; font: 500 12px/1.2 var(--cond); letter-spacing: .16em; text-transform: uppercase; }
+.hs span { display: block; font-size: 13px; line-height: 1.45; color: var(--dim); margin-top: 4px; }
+
+/* itinerary */
+.itinerary { list-style: none; margin-top: 30px; border-top: 1px solid var(--faint); }
+.itinerary li { display: grid; grid-template-columns: 64px 1fr; gap: 14px; padding: 12px 0; border-bottom: 1px solid var(--faint); opacity: .32; transition: opacity .5s; }
+.itinerary li.on { opacity: 1; }
+.itinerary li .rd { color: var(--accent); padding-top: 3px; }
+.itinerary h3 { font: 500 17px/1.2 var(--sans); letter-spacing: -.01em; }
+.itinerary p { font-size: 14px; line-height: 1.45; color: var(--dim); max-height: 0; overflow: hidden; transition: max-height .6s ease, margin .6s; }
+.itinerary li.on p { max-height: 80px; margin-top: 6px; }
+
+/* training */
+.cards { display: grid; grid-template-columns: repeat(3, minmax(0, 250px)); gap: 20px; margin-top: 38px; }
+.tcard { display: grid; gap: 8px; align-content: start; }
+.tcard img { width: 100%; height: auto; aspect-ratio: 4 / 3.2; object-fit: cover; filter: grayscale(1) contrast(1.1) brightness(.92); border-radius: 2px; margin-bottom: 10px; }
+.tcard .rd { color: var(--accent); }
+.tcard h3 { font: 500 20px/1.1 var(--sans); letter-spacing: -.02em; }
+.tcard p:last-child { color: var(--dim); font-size: 14px; line-height: 1.5; }
+.suit-diagram { aspect-ratio: 4 / 3.2; margin-bottom: 10px; border-radius: 2px; box-shadow: inset 0 0 0 1px var(--faint); position: relative; overflow: hidden;
+ background: repeating-linear-gradient(0deg, transparent 0 19px, rgba(244,243,240,.06) 19px 20px), repeating-linear-gradient(90deg, transparent 0 19px, rgba(244,243,240,.06) 19px 20px); }
+.suit-diagram span { position: absolute; border: 1px solid var(--hair); border-radius: 50%; }
+.suit-diagram span:nth-child(1) { width: 30%; aspect-ratio: 1; left: 35%; top: 12%; }
+.suit-diagram span:nth-child(2) { width: 46%; height: 52%; left: 27%; top: 42%; border-radius: 40% 40% 12% 12%; }
+.suit-diagram span:nth-child(3) { width: 6px; height: 6px; background: var(--accent); border: 0; left: calc(50% - 3px); top: 58%; box-shadow: 0 0 0 6px rgba(255,91,20,.18); }
+
+/* price */
+.panel-price { left: calc(var(--gut) + 14px); width: min(560px, 46vw); }
+.price h2 { display: grid; gap: 0; margin-top: 18px; }
+.price .big { font: 300 clamp(84px, 11vw, 196px)/.84 var(--sans); letter-spacing: -.06em; }
+.price .all { font: 400 clamp(26px, 2.6vw, 42px)/1 var(--sans); letter-spacing: -.03em; color: var(--accent); margin-top: 14px; }
+.incl { list-style: none; margin-top: 26px; border-top: 1px solid var(--faint); }
+.incl li { padding: 11px 0; border-bottom: 1px solid var(--faint); font-size: 15px; color: var(--dim); display: flex; gap: 14px; }
+.incl li::before { content: '+'; color: var(--accent); font-family: var(--cond); font-weight: 600; }
+.price-cta { display: flex; gap: 12px; margin-top: 30px; pointer-events: auto; flex-wrap: wrap; }
+.fine { color: rgba(244,243,240,.42); margin-top: 18px; font-size: 11px; }
+
+/* footer */
+.foot { position: relative; z-index: 4; min-height: 100vh; display: grid; align-content: end; padding: 0 calc(var(--gut) + 14px) calc(var(--gut) + 60px);
+ background: linear-gradient(180deg, transparent, rgba(0,0,0,.2) 40%, rgba(0,0,0,.75)); }
+.foot-exp { color: var(--accent); margin-bottom: 26px; }
+.foot-title { font: 400 clamp(56px, 9.4vw, 170px)/.9 var(--sans); letter-spacing: -.05em; }
+.foot-cols { display: grid; grid-template-columns: 1fr 1fr auto; gap: 40px; align-items: end; margin-top: 70px; padding-top: 26px; border-top: 1px solid var(--faint); }
+.foot-cols .rd { color: var(--dim); line-height: 1.9; }
+.foot-cols b { color: var(--ink); font-weight: 600; }
+.legal { color: rgba(244,243,240,.36); margin-top: 40px; font-size: 11px; }
+
+@media (max-width: 1000px) {
+ .links { display: none; }
+ .hud-tl, .hud-tr, .hud-bl { display: none !important; }
+ .panel, .panel-price { width: calc(100vw - 2 * var(--gut) - 8px); left: calc(var(--gut) + 4px); right: auto; justify-content: flex-end; padding-bottom: 96px; }
+ .cards { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 10px; }
+ .tcard p:last-child { display: none; }
+}
+@media (max-width: 640px) {
+ :root { --gut: 14px; }
+ .nav { padding: 18px 20px 0; }
+ .brand { font-size: 13px; letter-spacing: .28em; }
+ .nav .btn { height: 36px; padding: 0 14px; font-size: 12px; }
+ .hud-br { display: none !important; }
+ .hero-inner { left: 20px; right: 20px; max-width: none; bottom: 104px; }
+ .hotspots { display: none; }
+ .training .lede { display: none; }
+ .hero-sub { font-size: 14.5px; margin-top: 18px; }
+ .eyebrow { margin-bottom: 16px; font-size: 11px; }
+ .hero-title { font-size: clamp(38px, 11vw, 56px); }
+ .hero-sub { font-size: 15px; }
+ .scroll-hint { left: 20px; right: auto; bottom: 64px; transform: none; }
+ .scroll-hint span:last-child { font-size: 11px; }
+ .cap { width: calc(100vw - 40px); left: 20px !important; right: auto !important; top: auto !important; bottom: 150px !important; }
+ .cap h3 { font-size: 25px; }
+ .cap p:last-child { font-size: 14px; }
+ .walk .sec-tag { top: 84px; left: 20px; }
+ .sec-sub { display: none; }
+ .telemetry { bottom: 62px; }
+ .telemetry > div { padding: 0 9px; min-width: 0; }
+ .telemetry > div:nth-child(4), .telemetry .tm-rate { display: none; }
+ .telemetry b { font-size: 19px; }
+ .panel h2 { font-size: 30px; margin: 14px 0; }
+ .lede { font-size: 14.5px; }
+ .specs b { font-size: 22px; }
+ .plate { display: none; }
+ .itinerary li { grid-template-columns: 52px 1fr; padding: 8px 0; }
+ .itinerary h3 { font-size: 15px; }
+ .itinerary li:not(.on) { display: none; }
+ .itinerary li.on p { max-height: 100px; }
+ .cards { grid-template-columns: 1fr 1fr; }
+ .tcard-text { display: none; }
+ .tcard h3 { font-size: 16px; }
+ .price .big { font-size: 84px; }
+ .incl li { font-size: 13.5px; padding: 8px 0; }
+ .incl li:nth-child(n+5) { display: none; }
+ .foot-cols { grid-template-columns: 1fr; gap: 20px; margin-top: 40px; }
+ .foot-title { font-size: 54px; }
+}
+
+/* legibility: soft scrims that belong to the photograph, not boxes */
+.panel::before { content: ''; position: absolute; top: -20vh; bottom: -20vh; width: 170%; z-index: -1; pointer-events: none;
+ opacity: 0; transition: opacity 1s ease; }
+.panel-left::before, .panel-price::before { left: -60%; background: radial-gradient(closest-side, rgba(0,0,0,.78), rgba(0,0,0,.5) 55%, transparent); }
+.panel-right::before { right: -60%; background: radial-gradient(closest-side, rgba(0,0,0,.78), rgba(0,0,0,.5) 55%, transparent); }
+.in .panel::before { opacity: 1; }
+.cap::after { content: ''; position: absolute; inset: -90px -140px -90px -160px; z-index: -1; pointer-events: none;
+ background: radial-gradient(closest-side, rgba(0,0,0,.62), rgba(0,0,0,.34) 60%, transparent); }
+.cap h3, .cap p, .panel h2, .panel .lede { text-shadow: 0 1px 18px rgba(0,0,0,.5); }
+.telemetry::before { content: ''; position: absolute; inset: -40px -80px -30px; z-index: -1; background: radial-gradient(closest-side, rgba(0,0,0,.55), transparent); }
+.panel.wide { width: min(780px, 58vw); }
+.cards { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+
+.hero-inner::before { content: ''; position: absolute; inset: -18vh -30vw -14vh -14vw; z-index: -1; pointer-events: none;
+ background: radial-gradient(closest-side, rgba(0,0,0,.6), rgba(0,0,0,.32) 60%, transparent); }
+.hero-sub { color: rgba(244,243,240,.78); }
+
+.med { list-style: none; aspect-ratio: 4 / 3.2; margin-bottom: 10px; border-radius: 2px; box-shadow: inset 0 0 0 1px var(--faint); padding: 12px 14px;
+ display: grid; align-content: space-evenly; background: linear-gradient(180deg, rgba(255,91,20,.06), transparent 60%); }
+.med li { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; color: var(--dim); font-size: 11px; border-bottom: 1px dashed rgba(244,243,240,.1); padding-bottom: 5px; }
+.med li:last-child { border-bottom: 0; }
+.med li span::before { content: ''; display: inline-block; width: 5px; height: 5px; border-radius: 50%; background: var(--accent); margin-right: 8px; vertical-align: 1px; }
+.med b { color: var(--ink); font-weight: 600; }
+html, body { overflow-x: clip; }
+main { overflow-x: clip; }
diff --git a/examples/artemis/terrain.js b/examples/artemis/terrain.js
new file mode 100644
index 0000000..3059fef
--- /dev/null
+++ b/examples/artemis/terrain.js
@@ -0,0 +1,455 @@
+// The south-pole rim: CPU heightfield (so boots, rocks and the lander sit exactly on it), a warped near mesh,
+// a polar far mesh with massifs and a crater that never sees the Sun, and the regolith shader:
+// world-space albedo + micro-crater normals, raymarched heightfield shadows with a physically sized penumbra,
+// and a partial Lommel–Seeliger term (the reason the Moon looks flat and bright under a grazing sun).
+import { THREE, smooth } from '../../src/core/engine.js';
+import { bakeTexture, fbmTexture } from '../../src/core/textures.js';
+import { makeNoise, mulberry32 } from './noise.js';
+
+export const HF = { cx: 22, cz: -4, half: 64, N: 1024 };
+
+// Walk path (x, z), the outpost pads and the sky directions.
+export const LAYOUT = {
+ path: [[-1.5, 0.4], [0, 0], [7, 0.6], [14, 0.1], [21, -1.3], [28, -3.2], [34, -4.8], [38.6, -6.1]],
+ lander: { x: 45.2, z: -9.2, r: 6.5, yaw: -2.2 },
+ hab: { x: 57, z: 8, r: 5 },
+ mast: { x: 58, z: -21, r: 3 },
+ toSun: new THREE.Vector3(-0.84, 0.123, 0.52).normalize(),
+ toEarth: new THREE.Vector3(-0.05, 0.108, -1).normalize(),
+};
+
+const ss = (a, b, v) => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); };
+
+export function buildHeight() {
+ const nz = makeNoise(11);
+ const rnd = mulberry32(2031);
+ const { cx, cz, half, N } = HF;
+ const x0 = cx - half, z0 = cz - half, step = (half * 2) / N;
+
+ // Path as a dense polyline + distance lookup grid (1 m).
+ const curve = new THREE.CatmullRomCurve3(LAYOUT.path.map(([x, z]) => new THREE.Vector3(x, 0, z)), false, 'centripetal');
+ const samples = curve.getSpacedPoints(160).map(v => [v.x, v.z]);
+ const DG = 129, dd = (half * 2) / (DG - 1);
+ const distGrid = new Float32Array(DG * DG);
+ for (let j = 0; j < DG; j++) for (let i = 0; i < DG; i++) {
+ const x = x0 + i * dd, z = z0 + j * dd;
+ let m = 1e9;
+ for (let k = 0; k < samples.length - 1; k++) {
+ const [ax, az] = samples[k], [bx, bz] = samples[k + 1];
+ const vx = bx - ax, vz = bz - az, wx = x - ax, wz = z - az;
+ const t = Math.min(1, Math.max(0, (wx * vx + wz * vz) / (vx * vx + vz * vz)));
+ const ex = wx - vx * t, ez = wz - vz * t;
+ m = Math.min(m, ex * ex + ez * ez);
+ }
+ distGrid[j * DG + i] = Math.sqrt(m);
+ }
+ const pathDist = (x, z) => {
+ const fx = Math.min(DG - 1.001, Math.max(0, (x - x0) / dd)), fz = Math.min(DG - 1.001, Math.max(0, (z - z0) / dd));
+ const i = Math.floor(fx), j = Math.floor(fz), u = fx - i, v = fz - j;
+ const a = distGrid[j * DG + i], b = distGrid[j * DG + i + 1], c = distGrid[(j + 1) * DG + i], d = distGrid[(j + 1) * DG + i + 1];
+ return (a + (b - a) * u) + ((c + (d - c) * u) - (a + (b - a) * u)) * v;
+ };
+ const pads = [LAYOUT.lander, LAYOUT.hab, LAYOUT.mast];
+ const padMask = (x, z, pad = 4) => {
+ let m = 1;
+ for (const p of pads) m = Math.min(m, ss(p.r, p.r + pad, Math.hypot(x - p.x, z - p.z)));
+ return m;
+ };
+
+ // Large undulation shared with the far field.
+ const base0 = (x, z) => nz.fbm2(x / 150, z / 150, 3) * 4.2 + nz.fbm2(x / 34 + 3.1, z / 34, 3) * 0.75;
+ const padH = pads.map(p => base0(p.x, p.z));
+ const base = (x, z) => {
+ let b = base0(x, z);
+ pads.forEach((p, k) => { const w = 1 - ss(p.r * 0.6, p.r + 7, Math.hypot(x - p.x, z - p.z)); b += (padH[k] - b) * w; });
+ return b;
+ };
+
+ // Craters: a spatial hash keeps per-vertex cost low.
+ const craters = [];
+ const addCraters = (n, rMin, rMax, pow, clear, depthK, focus) => {
+ let tries = 0;
+ while (n > 0 && tries++ < n * 40) {
+ const r = rMin + (rMax - rMin) * Math.pow(rnd(), pow);
+ const fx = focus ? (rnd() * 2 - 1) * focus[0] + focus[1] : x0 + rnd() * half * 2;
+ const fz = focus ? (rnd() * 2 - 1) * focus[2] + focus[3] : z0 + rnd() * half * 2;
+ if (Math.abs(fx - cx) > half - 2 || Math.abs(fz - cz) > half - 2) continue;
+ if (pathDist(fx, fz) < r + clear) continue;
+ if (padMask(fx, fz, r + 2) < 1) continue;
+ const depth = r * depthK * (0.55 + rnd() * 0.6);
+ const fresh = rnd() < 0.3;
+ craters.push({ x: fx, z: fz, r, depth: fresh ? depth : depth * 0.45, rim: depth * (fresh ? 0.3 + rnd() * 0.15 : 0.08 + rnd() * 0.1), infl: r * 2.2 });
+ n--;
+ }
+ };
+ addCraters(9, 7, 20, 1.3, 4, 0.17);
+ addCraters(120, 1.2, 5.5, 2.2, 1.6, 0.2);
+ addCraters(90, 0.8, 3, 2, 1.2, 0.22, [30, 20, 18, -3]);
+ addCraters(520, 0.2, 1.1, 2.6, 0.55, 0.2, [36, 20, 22, -3]);
+ addCraters(380, 0.25, 1.3, 2.4, 0.55, 0.16);
+ const CELL = 4, GC = Math.ceil((half * 2) / CELL);
+ const cells = Array.from({ length: GC * GC }, () => []);
+ for (const c of craters) {
+ const i0 = Math.max(0, Math.floor((c.x - c.infl - x0) / CELL)), i1 = Math.min(GC - 1, Math.floor((c.x + c.infl - x0) / CELL));
+ const j0 = Math.max(0, Math.floor((c.z - c.infl - z0) / CELL)), j1 = Math.min(GC - 1, Math.floor((c.z + c.infl - z0) / CELL));
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) cells[j * GC + i].push(c);
+ }
+ const K = Math.pow(2.2, -4);
+ const craterH = (x, z) => {
+ const i = Math.floor((x - x0) / CELL), j = Math.floor((z - z0) / CELL);
+ if (i < 0 || j < 0 || i >= GC || j >= GC) return 0;
+ let h = 0;
+ for (const c of cells[j * GC + i]) {
+ const dx = x - c.x, dz = z - c.z, d2 = dx * dx + dz * dz;
+ if (d2 > c.infl * c.infl) continue;
+ const u = Math.sqrt(d2) / c.r;
+ if (u < 1) h += -c.depth + (c.depth + c.rim) * Math.pow(u, 2.3);
+ else { const q = u * u; h += c.rim * (1 / (q * q) - K) / (1 - K); }
+ }
+ return h;
+ };
+
+ const H = (x, z) => {
+ const edge = 1 - ss(half - 16, half - 3, Math.max(Math.abs(x - cx), Math.abs(z - cz)));
+ const pm = ss(0.45, 2.6, pathDist(x, z));
+ const pads_ = padMask(x, z);
+ const detail = nz.fbm2(x / 5.2, z / 5.2, 4, 0.5) * 0.022 + nz.noise2(x / 1.3 + 7, z / 1.3) * 0.007;
+ return base(x, z) + (detail * (0.25 + 0.75 * pm) * pads_ + craterH(x, z)) * edge;
+ };
+
+ const data = new Float32Array((N + 1) * (N + 1));
+ for (let j = 0; j <= N; j++) {
+ const z = z0 + j * step;
+ for (let i = 0; i <= N; i++) data[j * (N + 1) + i] = H(x0 + i * step, z);
+ }
+ const heightAt = (x, z) => {
+ const fx = Math.min(N - 0.0001, Math.max(0, (x - x0) / step)), fz = Math.min(N - 0.0001, Math.max(0, (z - z0) / step));
+ const i = Math.floor(fx), j = Math.floor(fz), u = fx - i, v = fz - j, W = N + 1;
+ const a = data[j * W + i], b = data[j * W + i + 1], c = data[(j + 1) * W + i], d = data[(j + 1) * W + i + 1];
+ return (a + (b - a) * u) * (1 - v) + (c + (d - c) * u) * v;
+ };
+ const normalAt = (x, z, out = new THREE.Vector3(), e = step) => {
+ const hx = heightAt(x + e, z) - heightAt(x - e, z), hz = heightAt(x, z + e) - heightAt(x, z - e);
+ return out.set(-hx, 2 * e, -hz).normalize();
+ };
+
+ // Far field: same undulation + massifs + a deep crater towards -Z, lunar curvature.
+ const crater = { x: 1400, z: -4600, r: 2100, depth: 650, rim: 140 };
+ const farH = (x, z) => {
+ const dx = x - cx, dz = z - cz, r = Math.hypot(dx, dz);
+ let h = base0(x, z);
+ const far = ss(1800, 6500, r);
+ const m = nz.fbm2(x / 3600 + 1.7, z / 3600 - 4.2, 5, 0.5);
+ h += Math.max(0, m + 0.06) * 560 * far;
+ h += nz.fbm2(x / 520, z / 520, 4) * 20 * ss(150, 900, r);
+ // two named massifs on the horizon: a big one under the Earth, a lower one to the east
+ for (const [mx, mz, mh, mw] of [[-900, -7600, 820, 2600], [5200, -5600, 430, 1900], [-6200, -2600, 380, 1700]]) {
+ const d2 = ((x - mx) ** 2 + (z - mz) ** 2) / (mw * mw);
+ if (d2 < 9) h += mh * Math.exp(-d2) * (0.72 + 0.28 * nz.ridge2(x / 900 + mx, z / 900, 5));
+ }
+ const u = Math.hypot(x - crater.x, z - crater.z) / crater.r;
+ if (u < 1) h += -crater.depth + (crater.depth + crater.rim) * Math.pow(u, 2.0);
+ else if (u < 1.7) h += crater.rim * Math.pow(1 - (u - 1) / 0.7, 2);
+ h -= (r * r) / (2 * 1737400);
+ return h;
+ };
+
+ return { data, step, x0, z0, heightAt, normalAt, farH, pathDist, curve, craters };
+}
+
+// ─── Textures ───────────────────────────────────────────────────────────────
+const CRATER_GLSL = /* glsl */`
+ float h21(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
+ float craterField(vec2 uv, float per, float dens){
+ vec2 g = uv * per; vec2 id = floor(g); float h = 0.;
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
+ vec2 c = id + vec2(float(i), float(j)); vec2 cw = mod(c, per);
+ if (h21(cw) > dens) continue;
+ vec2 ctr = c + vec2(h21(cw + 3.1), h21(cw + 7.7));
+ float rad = mix(0.1, 0.5, pow(h21(cw + 1.3), 2.2));
+ float u = length(g - ctr) / rad;
+ if (u < 1.) h += (-1. + 1.32 * pow(u, 2.2)) * rad;
+ else if (u < 2.) h += 0.32 * rad * pow(2. - u, 2.);
+ }
+ return h / per;
+ }
+ float H(vec2 uv){
+ return craterField(uv, 22., 0.26) * 0.75 + craterField(uv + 0.37, 61., 0.3) * 0.55 + craterField(uv + 0.71, 131., 0.32) * 0.4
+ + fbm(uv * 24., 24., 6, 0.55) * 0.012 + fbm(uv * 96., 96., 3, 0.5) * 0.003;
+ }`;
+
+export function regolithTextures(renderer) {
+ const size = 1024;
+ const detail = bakeTexture(renderer, size, `${CRATER_GLSL}
+ void main(){
+ float e = 1.0 / ${size.toFixed(1)};
+ float hx = H(vUv + vec2(e, 0.)) - H(vUv - vec2(e, 0.));
+ float hy = H(vUv + vec2(0., e)) - H(vUv - vec2(0., e));
+ vec3 n = normalize(vec3(-hx * ${size.toFixed(1)} * 0.5, -hy * ${size.toFixed(1)} * 0.5, 1.));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.);
+ }`);
+ const albedo = fbmTexture(renderer, { size: 512, scale: 5, octaves: 6, gain: 0.55, contrast: 1.4, bias: 0.5 });
+ const speck = bakeTexture(renderer, 512, `
+ void main(){
+ float n = fbm(vUv * 64., 64., 3, 0.5);
+ float s = step(0.965, fract(sin(dot(floor(vUv * 512.), vec2(12.9898, 78.233))) * 43758.5453));
+ gl_FragColor = vec4(vec3(0.5 + n * 0.5 + s * 0.6), 1.);
+ }`);
+ for (const t of [detail, albedo, speck]) t.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return { detail, albedo, speck };
+}
+
+export function heightTexture(data, n, renderer) {
+ const tex = new THREE.DataTexture(data, n, n, THREE.RedFormat, THREE.FloatType);
+ const lin = renderer.extensions.has('OES_texture_float_linear');
+ tex.magFilter = tex.minFilter = lin ? THREE.LinearFilter : THREE.NearestFilter;
+ tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.generateMipmaps = false;
+ tex.needsUpdate = true;
+ return tex;
+}
+
+// ─── Regolith shader patch (terrain, far field, bootprints, rocks) ───────────
+export const sunUniform = { value: LAYOUT.toSun.clone() };
+export const TUNE = { ls: { value: 0.35 }, detail: { value: 0.5 }, fill: { value: 0.09 } };
+export function patchRegolith(mat, { tex, hf, far = false, print = null, albedo = true, ls = 0.55, detailK = 1, rock = false, fill = null }) {
+ mat.onBeforeCompile = sh => {
+ mat.userData.sh = sh;
+ Object.assign(sh.uniforms, {
+ uHF: { value: hf.tex }, uHFMin: { value: new THREE.Vector2(hf.x0, hf.z0) }, uHFSize: { value: hf.size },
+ ...(far ? { uMid: { value: far.tex }, uMidMin: { value: new THREE.Vector2(far.x0, far.z0) }, uMidSize: { value: far.size } } : {}),
+ uRay: { value: far ? new THREE.Vector4(4, 1.15, 0.25, 1.5) : new THREE.Vector4(0.12, 1.14, 0.014, 0.035) },
+ uRayBias: { value: far ? 2.5 : (rock ? 0.004 : 0.03) },
+ uSun: sunUniform, uDetail: { value: tex.detail }, uAlb: { value: tex.albedo }, uSpeck: { value: tex.speck },
+ uFill: fill ?? TUNE.fill, uLS: rock || print ? { value: print ? 0.12 : ls } : TUNE.ls, uDetailK: rock ? { value: detailK } : TUNE.detail,
+ });
+ if (print) Object.assign(sh.uniforms, { uPrint: { value: print } });
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWPos;' + (print ? '\nvarying vec3 vPT, vPB;' : ''))
+ .replace('#include <worldpos_vertex>', `#include <worldpos_vertex>
+ vec4 wpA = vec4(transformed, 1.0);
+ #ifdef USE_INSTANCING
+ wpA = instanceMatrix * wpA;
+ #endif
+ vWPos = (modelMatrix * wpA).xyz;
+ ${print ? `vPT = normalize((modelMatrix * instanceMatrix * vec4(1., 0., 0., 0.)).xyz);
+ vPB = normalize((modelMatrix * instanceMatrix * vec4(0., 0., -1., 0.)).xyz);` : ''}`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vWPos;
+ uniform sampler2D uHF, uDetail, uAlb, uSpeck; uniform vec2 uHFMin; uniform float uHFSize, uLS, uDetailK, uRayBias, uFill; uniform vec4 uRay; uniform vec3 uSun;
+ ${print ? `uniform sampler2D uPrint; varying vec3 vPT, vPB;
+ float printShadow(float ph, vec2 puv){
+ vec3 nP = normalize(cross(vPT, vPB));
+ vec3 s = vec3(dot(uSun, vPT), dot(uSun, vPB), dot(uSun, nP));
+ if (s.z <= 0.0) return 0.0;
+ float hl = max(length(s.xy), 1e-4);
+ vec2 duv = (s.xy / hl) / vec2(0.25, 0.5);
+ float slope = s.z / hl;
+ float h0 = ph * 0.015, sh = 1.0;
+ for (int i = 1; i <= 14; i++) {
+ float dist = float(i) * 0.012;
+ float hs = (texture2D(uPrint, puv + duv * dist).b * 2.0 - 1.3) * 0.015;
+ sh = min(sh, smoothstep(-0.0015, 0.0015, h0 + dist * slope - hs));
+ }
+ return sh;
+ }` : ''}
+ ${far ? 'uniform sampler2D uMid; uniform vec2 uMidMin; uniform float uMidSize;' : ''}
+ float terrainVis(vec3 p, vec3 L){
+ float vis = 1.0; float t = uRay.x;
+ for (int i = 0; i < 34; i++) {
+ vec3 q = p + L * t;
+ vec2 uv = (q.xz - uHFMin) / uHFSize;
+ if (uv.x < 0. || uv.y < 0. || uv.x > 1. || uv.y > 1.) break;
+ ${far ? `vec2 uvm = (q.xz - uMidMin) / uMidSize;
+ bool inMid = uvm.x > 0. && uvm.y > 0. && uvm.x < 1. && uvm.y < 1.;
+ float h = inMid ? textureLod(uMid, uvm, 0.0).r : textureLod(uHF, uv, 0.0).r;
+ float bias = inMid ? 0.35 + t * 0.002 : uRayBias + t * 0.003;` : `float h = textureLod(uHF, uv, 0.0).r;
+ float bias = uRayBias;`}
+ float k = uRay.z + t * 0.0094;
+ vis = min(vis, smoothstep(-k, k, q.y + bias - h));
+ if (vis < 0.005) break;
+ t = t * uRay.y + uRay.w;
+ }
+ return vis;
+ }`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ vec2 wxz = vWPos.xz;
+ ${albedo ? `
+ float a1 = texture2D(uAlb, wxz / 41.0).r, a2 = texture2D(uAlb, wxz / 6.1 + 0.37).r, a3 = texture2D(uAlb, wxz / 233.0 + 0.1).r;
+ float sp = texture2D(uSpeck, wxz / 1.9).r;
+ diffuseColor.rgb *= (0.66 + a1 * 0.5) * (0.86 + a2 * 0.26) * (0.72 + a3 * 0.5) * (0.82 + sp * 0.3);` : ''}
+ ${print ? `
+ vec4 pr = texture2D(uPrint, vUv);
+ float ph = pr.b * 2.0 - 1.3;
+ float inside = smoothstep(-0.2, -0.6, ph);
+ diffuseColor.rgb *= mix(1.0, 0.6, inside) * (1.0 + smoothstep(0.05, 0.3, ph) * 0.16);
+ diffuseColor.a *= pr.a;` : ''}`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ vec3 nW = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ vec3 T = normalize(vec3(1., 0., 0.) - nW * nW.x); vec3 B = normalize(cross(nW, T)) * -1.0;
+ vec2 pert = vec2(0.);
+ ${rock ? `
+ vec3 an = abs(nW);
+ vec2 tuv = an.y > max(an.x, an.z) ? vWPos.xz : (an.x > an.z ? vWPos.zy : vWPos.xy);
+ pert += (texture2D(uDetail, tuv / 0.9).xy * 2. - 1.) * 0.9 + (texture2D(uDetail, tuv / 0.23 + .3).xy * 2. - 1.) * 0.5;` : `
+ float fade = 1.0 - smoothstep(20.0, 90.0, length(vWPos - cameraPosition));
+ pert += (texture2D(uDetail, wxz / 5.3).xy * 2. - 1.) * 0.95 * mix(0.5, 1.0, fade);
+ pert += (texture2D(uDetail, wxz / 23.0 + 0.5).xy * 2. - 1.) * 0.8;
+ pert += (texture2D(uDetail, wxz / 1.37 + 0.21).xy * 2. - 1.) * 0.6 * fade;`}
+ ${print ? 'pert *= 1.0 - inside * 0.85;' : ''}
+ pert *= uDetailK;
+ // micro-relief self-occludes at grazing view angles: fade it (kills moiré and backlit 'sand ripples')
+ pert *= mix(0.28, 1.0, smoothstep(0.03, 0.32, dot(nW, normalize(cameraPosition - vWPos))));
+ nW = normalize(nW + T * pert.x + B * pert.y);
+ ${print ? 'vec2 pn = pr.rg * 2. - 1.; nW = normalize(nW + (vPT * pn.x + vPB * pn.y) * 3.0);' : ''}
+ normal = normalize((viewMatrix * vec4(nW, 0.0)).xyz);
+ }`)
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>
+ {
+ vec3 nW2 = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ float vis = terrainVis(vWPos + nW2 * ${far ? '1.5' : '0.02'}, uSun)${print ? ' * printShadow(ph, vUv)' : ''};
+ float mu0 = max(dot(nW2, uSun), 0.0);
+ float mu = max(dot(nW2, normalize(cameraPosition - vWPos)), 0.0);
+ float lsK = mix(1.0, 2.0 / (mu0 + mu + 0.08), uLS);
+ reflectedLight.directDiffuse *= vis * lsK;
+ reflectedLight.directSpecular *= vis;
+ reflectedLight.indirectDiffuse += diffuseColor.rgb * uFill * (0.6 + 0.4 * nW2.y);
+ }`);
+ };
+ mat.customProgramCacheKey = () => `regolith-${far}-${!!print}-${albedo}-${rock}`;
+ return mat;
+}
+
+// ─── Meshes ───────────────────────────────────────────────────────────────────
+export function nearTerrain(H, material) {
+ const { cx, cz, half } = HF;
+ const S = 560;
+ const warp = u => half * (0.55 * u + 0.45 * u * u * u);
+ const pos = new Float32Array((S + 1) * (S + 1) * 3), nor = new Float32Array((S + 1) * (S + 1) * 3);
+ const n = new THREE.Vector3();
+ let k = 0;
+ for (let j = 0; j <= S; j++) {
+ const z = cz + warp(j / S * 2 - 1);
+ for (let i = 0; i <= S; i++) {
+ const x = cx + warp(i / S * 2 - 1);
+ pos[k] = x; pos[k + 1] = H.heightAt(x, z); pos[k + 2] = z;
+ H.normalAt(x, z, n);
+ nor[k] = n.x; nor[k + 1] = n.y; nor[k + 2] = n.z;
+ k += 3;
+ }
+ }
+ const idx = new Uint32Array(S * S * 6);
+ k = 0;
+ for (let j = 0; j < S; j++) for (let i = 0; i < S; i++) {
+ const a = j * (S + 1) + i, b = a + 1, c = a + S + 1, d = c + 1;
+ idx[k++] = a; idx[k++] = c; idx[k++] = b; idx[k++] = b; idx[k++] = c; idx[k++] = d;
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ g.setIndex(new THREE.BufferAttribute(idx, 1));
+ g.computeBoundingSphere();
+ const m = new THREE.Mesh(g, material);
+ m.receiveShadow = true;
+ return m;
+}
+
+export function farTerrain(H, material) {
+ const { cx, cz, half } = HF;
+ const A = 420, R = 170, r0 = 40, r1 = 16000;
+ const pos = new Float32Array((A + 1) * (R + 1) * 3);
+ let k = 0;
+ for (let j = 0; j <= R; j++) {
+ const r = r0 * Math.pow(r1 / r0, j / R);
+ for (let i = 0; i <= A; i++) {
+ const a = (i / A) * Math.PI * 2;
+ const x = cx + Math.cos(a) * r, z = cz + Math.sin(a) * r;
+ const cheb = Math.max(Math.abs(x - cx), Math.abs(z - cz));
+ pos[k] = x; pos[k + 1] = H.farH(x, z) - 6 * (1 - ss(half - 12, half, cheb)); pos[k + 2] = z;
+ k += 3;
+ }
+ }
+ const idx = [];
+ for (let j = 0; j < R; j++) for (let i = 0; i < A; i++) {
+ const a = j * (A + 1) + i, b = a + 1, c = a + A + 1, d = c + 1;
+ idx.push(a, b, c, b, d, c);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setIndex(idx);
+ g.computeVertexNormals();
+ g.computeBoundingSphere();
+ const m = new THREE.Mesh(g, material);
+ m.receiveShadow = true;
+ return m;
+}
+
+export function farHeightfield(H, n = 512, extent = 16000) {
+ const data = new Float32Array(n * n);
+ const x0 = HF.cx - extent, z0 = HF.cz - extent, st = (extent * 2) / (n - 1);
+ for (let j = 0; j < n; j++) for (let i = 0; i < n; i++) data[j * n + i] = H.farH(x0 + i * st, z0 + j * st);
+ return { data, n, x0, z0, size: (n - 1) * st };
+}
+
+// ─── Rocks ────────────────────────────────────────────────────────────────────
+function rockGeometry(seed, detail, rough = 1) {
+ const nz = makeNoise(seed);
+ const g = new THREE.IcosahedronGeometry(1, detail);
+ const p = g.attributes.position;
+ const v = new THREE.Vector3();
+ const sx = 0.8 + nz.rnd() * 0.5, sy = 0.45 + nz.rnd() * 0.35, sz = 0.7 + nz.rnd() * 0.5;
+ for (let i = 0; i < p.count; i++) {
+ v.fromBufferAttribute(p, i);
+ let d = 1 + nz.noise3(v.x * 1.4 + seed, v.y * 1.4, v.z * 1.4) * 0.28 * rough + nz.noise3(v.x * 4, v.y * 4 + seed, v.z * 4) * 0.08 * rough
+ + nz.noise3(v.x * 11, v.y * 11, v.z * 11 + seed) * 0.025 * rough;
+ // facet it a little: planar chips
+ const f = Math.abs(nz.noise3(v.x * 2.2 - seed, v.y * 2.2, v.z * 2.2));
+ d -= f * 0.12 * rough;
+ v.multiplyScalar(d);
+ v.x *= sx; v.y *= sy; v.z *= sz;
+ if (v.y < -0.15) v.y = -0.15 + (v.y + 0.15) * 0.25;
+ p.setXYZ(i, v.x, v.y, v.z);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+export function rocks(H, material, rnd = mulberry32(77)) {
+ const group = new THREE.Group();
+ const place = (geo, count, sizeFn, spot, clear, castShadow) => {
+ const im = new THREE.InstancedMesh(geo, material, count);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), s = new THREE.Vector3(), p = new THREE.Vector3(), e = new THREE.Euler();
+ let n = 0, tries = 0;
+ while (n < count && tries++ < count * 30) {
+ const [x, z] = spot();
+ const size = sizeFn();
+ if (H.pathDist(x, z) < clear + size) continue;
+ const pads = [LAYOUT.lander, LAYOUT.hab, LAYOUT.mast];
+ if (pads.some(pd => Math.hypot(x - pd.x, z - pd.z) < pd.r * 0.9)) continue;
+ e.set((rnd() - 0.5) * 0.5, rnd() * Math.PI * 2, (rnd() - 0.5) * 0.5);
+ q.setFromEuler(e);
+ s.setScalar(size).multiply(new THREE.Vector3(1, 0.8 + rnd() * 0.5, 1));
+ p.set(x, H.heightAt(x, z) - size * 0.12, z);
+ m.compose(p, q, s);
+ im.setMatrixAt(n++, m);
+ }
+ im.count = n;
+ im.castShadow = castShadow; im.receiveShadow = true;
+ im.instanceMatrix.needsUpdate = true;
+ im.computeBoundingSphere();
+ group.add(im);
+ return im;
+ };
+ const { cx, cz, half } = HF;
+ const anywhere = () => [cx + (rnd() * 2 - 1) * (half - 4), cz + (rnd() * 2 - 1) * (half - 4)];
+ const nearPath = () => { const t = rnd(); const pt = H.curve.getPointAt(t); const a = rnd() * Math.PI * 2, r = 0.6 + Math.pow(rnd(), 1.6) * 16; return [pt.x + Math.cos(a) * r, pt.z + Math.sin(a) * r]; };
+ const big = [rockGeometry(3, 5), rockGeometry(9, 5), rockGeometry(21, 5, 1.2)];
+ const mid = [rockGeometry(5, 3), rockGeometry(13, 3, 1.3)];
+ const small = [rockGeometry(17, 1, 1.2), rockGeometry(29, 1)];
+ big.forEach(g => place(g, 3, () => 0.9 + Math.pow(rnd(), 2) * 2.2, anywhere, 5, true));
+ mid.forEach(g => place(g, 40, () => 0.18 + Math.pow(rnd(), 2.5) * 0.7, () => (rnd() < 0.6 ? nearPath() : anywhere()), 1.5, true));
+ small.forEach(g => place(g, 1100, () => 0.02 + Math.pow(rnd(), 3) * 0.16, nearPath, 0.25, true));
+ return group;
+}
diff --git a/examples/artemis/tools/build-astro.mjs b/examples/artemis/tools/build-astro.mjs
new file mode 100644
index 0000000..58dec69
--- /dev/null
+++ b/examples/artemis/tools/build-astro.mjs
@@ -0,0 +1,41 @@
+// Build the web astronaut: Meshy rigged mesh + PBR maps from the static Meshy model (same UV atlas)
+// + walk / run / idle clips merged from the separate Meshy animation exports.
+// node examples/artemis/tools/build-astro.mjs <out.glb>
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+const out = process.argv[2];
+const R = 'assets/raw/artemis-astro.';
+const doc = await io.read(R + 'rigged_character_glb.glb');
+const root = doc.getRoot();
+const stat = await io.read(R + 'glb');
+const sm = stat.getRoot().listMaterials()[0];
+const mat = root.listMaterials()[0];
+const copyTex = (t, name) => { const n = doc.createTexture(name).setImage(t.getImage().slice()).setMimeType(t.getMimeType()); return n; };
+mat.setNormalTexture(copyTex(sm.getNormalTexture(), 'normal'));
+mat.setMetallicRoughnessTexture(copyTex(sm.getMetallicRoughnessTexture(), 'mr'));
+mat.setMetallicFactor(1).setRoughnessFactor(1);
+console.log('static mat', sm.getName(), 'normalScale', sm.getNormalScale());
+for (const a of root.listAnimations()) a.dispose();
+const byName = new Map(root.listNodes().map(n => [n.getName(), n]));
+const srcs = [['walk', R + 'walking_armature_glb.glb'], ['run', R + 'running_armature_glb.glb'], ['idle', R + 'animation_glb.glb']];
+const buf = root.listBuffers()[0];
+for (const [name, file] of srcs) {
+ const s = await io.read(file);
+ for (const a of s.getRoot().listAnimations()) {
+ const na = doc.createAnimation(name);
+ for (const c of a.listChannels()) {
+ const node = byName.get(c.getTargetNode().getName());
+ if (!node) { console.log('missing node', c.getTargetNode().getName()); continue; }
+ const path = c.getTargetPath();
+ if (name === 'idle' && c.getTargetNode().getName() === 'Hips' && path === 'scale') continue;
+ const sp = c.getSampler();
+ const cp = acc => doc.createAccessor().setArray(acc.getArray().slice()).setType(acc.getType()).setNormalized(acc.getNormalized()).setBuffer(buf);
+ const samp = doc.createAnimationSampler().setInput(cp(sp.getInput())).setOutput(cp(sp.getOutput())).setInterpolation(sp.getInterpolation());
+ na.addSampler(samp).addChannel(doc.createAnimationChannel().setTargetNode(node).setTargetPath(path).setSampler(samp));
+ }
+ console.log('clip', name, na.listChannels().length);
+ }
+}
+await io.write(out, doc);
+console.log('wrote', out);
diff --git a/examples/artemis/tools/inspect.mjs b/examples/artemis/tools/inspect.mjs
new file mode 100644
index 0000000..6792875
--- /dev/null
+++ b/examples/artemis/tools/inspect.mjs
@@ -0,0 +1,21 @@
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { MeshoptDecoder } from 'meshoptimizer';
+await MeshoptDecoder.ready;
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.decoder': MeshoptDecoder });
+for (const f of process.argv.slice(2)) {
+ const doc = await io.read(f);
+ const r = doc.getRoot();
+ console.log('==', f);
+ console.log(' meshes', r.listMeshes().map(m => m.getName() + ':' + m.listPrimitives().map(p => (p.getIndices()?.getCount() / 3) + 'tris attrs=' + p.listSemantics().join(',')).join('|')));
+ console.log(' skins', r.listSkins().map(s => s.getName() + ' joints=' + s.listJoints().length));
+ console.log(' joints', r.listSkins()[0]?.listJoints().map(j => j.getName()).join(' '));
+ console.log(' anims', r.listAnimations().map(a => a.getName() + ' ch=' + a.listChannels().length + ' dur=' + Math.max(...a.listSamplers().map(s => { const i = s.getInput(); return i.getElement(i.getCount() - 1, [])[0]; })).toFixed(3)));
+ console.log(' mats', r.listMaterials().map(m => m.getName() + ' base=' + !!m.getBaseColorTexture() + ' n=' + !!m.getNormalTexture() + ' mr=' + !!m.getMetallicRoughnessTexture() + ' metal=' + m.getMetallicFactor() + ' rough=' + m.getRoughnessFactor()));
+ console.log(' tex', r.listTextures().map(t => t.getMimeType() + ' ' + t.getSize()?.join('x')));
+ console.log(' nodes', r.listNodes().length, r.listNodes().slice(0,5).map(n => n.getName() + ' s=' + n.getScale().map(v=>v.toFixed(3)) + ' r=' + n.getRotation().map(v=>v.toFixed(3)) + ' t=' + n.getTranslation().map(v=>v.toFixed(3))));
+ const a = r.listAnimations()[0];
+ if (a) { const ch = a.listChannels().slice(0, 4).map(c => c.getTargetNode().getName() + '.' + c.getTargetPath() + ' n=' + c.getSampler().getInput().getCount()); console.log(' ch0', ch); }
+ const acc = r.listMeshes()[0]?.listPrimitives()[0]?.getAttribute('POSITION');
+ if (acc) console.log(' posMin', acc.getMin([]).map(v=>v.toFixed(3)), 'posMax', acc.getMax([]).map(v=>v.toFixed(3)));
+}
diff --git a/examples/atlas/airship.js b/examples/atlas/airship.js
new file mode 100644
index 0000000..d9b4b86
--- /dev/null
+++ b/examples/atlas/airship.js
@@ -0,0 +1,202 @@
+// The Zephyrine: a procedural storybook airship — striped lathe envelope, tail fins, a timber gondola with
+// lit windows, rigging, twin propellers and a pennant. Forward is +Z.
+import { THREE } from '../../src/core/engine.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { patchAtmosphere } from './sky.js';
+
+function envelopeTexture({ a = '#f7eedf', b = '#f2a484', name: title = 'ZEPHYRINE' } = {}) {
+ const W = 2048, H = 1024;
+ const c = document.createElement('canvas'); c.width = W; c.height = H;
+ const g = c.getContext('2d');
+ const gores = 16;
+ for (let i = 0; i < gores; i++) {
+ g.fillStyle = i % 2 ? b : a;
+ g.fillRect((i / gores) * W, 0, W / gores + 1, H);
+ }
+ // seams
+ g.globalAlpha = 0.35; g.fillStyle = '#9a6a52';
+ for (let i = 0; i <= gores; i++) g.fillRect((i / gores) * W - 1.5, 0, 3, H);
+ // hoops along the length
+ g.globalAlpha = 0.18;
+ for (let j = 1; j < 14; j++) g.fillRect(0, (j / 14) * H - 1, W, 2);
+ g.globalAlpha = 1;
+ // navy belly band, nose and tail caps
+ g.fillStyle = '#28365a';
+ g.fillRect(0, H * 0.965, W, H * 0.04);
+ g.fillRect(0, 0, W, H * 0.03);
+ g.fillStyle = '#e9c07a';
+ g.fillRect(0, H * 0.955, W, H * 0.01);
+ g.fillRect(0, H * 0.03, W, H * 0.008);
+ // name on both flanks
+ const name = (u, flip) => {
+ g.save();
+ g.translate(u * W, H * 0.52);
+ g.rotate(flip ? Math.PI / 2 : -Math.PI / 2);
+ g.fillStyle = 'rgba(247,238,223,.96)';
+ g.beginPath(); g.roundRect(-300, -62, 600, 124, 62); g.fill();
+ g.strokeStyle = '#28365a'; g.lineWidth = 5; g.stroke();
+ g.fillStyle = '#28365a';
+ g.font = '64px "Young Serif", Georgia, serif';
+ g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.fillText(title, 0, 4);
+ g.restore();
+ };
+ name(0.25, true); name(0.75, false);
+ // painterly grain
+ const img = g.getImageData(0, 0, W, H), d = img.data;
+ for (let i = 0; i < d.length; i += 4) { const n = (Math.random() - 0.5) * 14; d[i] += n; d[i + 1] += n; d[i + 2] += n; }
+ g.putImageData(img, 0, 0);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8;
+ return t;
+}
+
+function woodTexture() {
+ const c = document.createElement('canvas'); c.width = 512; c.height = 256;
+ const g = c.getContext('2d');
+ g.fillStyle = '#8a5a36'; g.fillRect(0, 0, 512, 256);
+ for (let j = 0; j < 8; j++) {
+ g.fillStyle = `hsl(${24 + Math.random() * 6}, ${38 + Math.random() * 10}%, ${30 + Math.random() * 10}%)`;
+ g.fillRect(0, j * 32 + 1, 512, 30);
+ g.fillStyle = 'rgba(40,22,10,.55)'; g.fillRect(0, j * 32, 512, 2);
+ for (let k = 0; k < 40; k++) { g.fillStyle = `rgba(255,220,180,${Math.random() * 0.06})`; g.fillRect(Math.random() * 512, j * 32 + Math.random() * 30, 40 + Math.random() * 120, 1); }
+ }
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8;
+ t.wrapS = t.wrapT = THREE.RepeatWrapping;
+ return t;
+}
+
+export function buildAirship(pal = {}) {
+ const ship = new THREE.Group();
+ const body = new THREE.Group(); // bobs and pitches inside the ship frame
+ ship.add(body);
+ const L = 6.4, R = 1.15;
+ const std = (o) => { const m = new THREE.MeshStandardMaterial({ roughness: 0.72, metalness: 0, envMapIntensity: 0.5, ...o }); patchAtmosphere(m); return m; };
+
+ // Envelope
+ const pts = [];
+ const N = 72;
+ for (let j = 0; j <= N; j++) {
+ const t = j / N;
+ const r = R * Math.pow(Math.sin(Math.PI * Math.pow(t, 1.35)), 0.62);
+ pts.push(new THREE.Vector2(Math.max(r, 0.0001), (t - 0.5) * L));
+ }
+ const envGeo = new THREE.LatheGeometry(pts, 64);
+ envGeo.rotateX(Math.PI / 2);
+ const envMat = std({ map: envelopeTexture(pal), roughness: 0.62 });
+ const envelope = new THREE.Mesh(envGeo, envMat);
+ envelope.castShadow = envelope.receiveShadow = true;
+ body.add(envelope);
+
+ // Tail fins (cross)
+ const finShape = new THREE.Shape();
+ finShape.moveTo(0, 0); finShape.lineTo(1.35, 0); finShape.quadraticCurveTo(1.25, 0.6, 1.05, 1.05); finShape.lineTo(0.45, 1.0); finShape.quadraticCurveTo(0.2, 0.5, 0, 0);
+ const finGeo = new THREE.ExtrudeGeometry(finShape, { depth: 0.05, bevelEnabled: true, bevelSize: 0.025, bevelThickness: 0.02, bevelSegments: 2, curveSegments: 10 });
+ finGeo.translate(0, 0, -0.025);
+ const finMat = std({ color: pal.fin ?? '#e9866a', roughness: 0.6 });
+ const trimMat = std({ color: '#28365a', roughness: 0.55 });
+ for (let k = 0; k < 4; k++) {
+ const fin = new THREE.Mesh(finGeo, k % 2 ? finMat : trimMat);
+ const holder = new THREE.Group();
+ holder.rotation.z = k * Math.PI / 2;
+ fin.rotation.y = Math.PI / 2; // shape x → -z (backwards along the hull)
+ fin.position.set(0, R * 0.34, -L * 0.36);
+ fin.scale.setScalar(1.05);
+ fin.castShadow = true;
+ holder.add(fin);
+ body.add(holder);
+ }
+
+ // Gondola
+ const wood = woodTexture();
+ const gondY = -R - 0.62;
+ const hull = new THREE.Mesh(new RoundedBoxGeometry(0.95, 0.52, 2.3, 4, 0.16), std({ map: wood, roughness: 0.8 }));
+ hull.position.set(0, gondY, 0.15);
+ hull.castShadow = hull.receiveShadow = true;
+ body.add(hull);
+ const keel = new THREE.Mesh(new RoundedBoxGeometry(0.62, 0.22, 2.0, 3, 0.1), std({ map: wood, color: '#b98a66' }));
+ keel.position.set(0, gondY - 0.3, 0.15);
+ body.add(keel);
+ const roof = new THREE.Mesh(new RoundedBoxGeometry(1.08, 0.08, 2.44, 2, 0.035), trimMat);
+ roof.position.set(0, gondY + 0.3, 0.15);
+ roof.castShadow = true;
+ body.add(roof);
+ const brass = std({ color: '#e0b36a', metalness: 0.85, roughness: 0.35, envMapIntensity: 1.2 });
+ const winMat = new THREE.MeshStandardMaterial({ color: '#2c1e10', emissive: '#ffc27a', emissiveIntensity: 2.2, roughness: 0.3 });
+ patchAtmosphere(winMat);
+ const winGeo = new THREE.BoxGeometry(0.02, 0.17, 0.2);
+ for (const s of [-1, 1]) for (let i = 0; i < 6; i++) {
+ const w = new THREE.Mesh(winGeo, winMat);
+ w.position.set(s * 0.482, gondY + 0.06, -0.72 + i * 0.3);
+ body.add(w);
+ }
+ const bowLamp = new THREE.Mesh(new THREE.SphereGeometry(0.06, 12, 8), new THREE.MeshBasicMaterial({ color: new THREE.Color('#ffd49a').multiplyScalar(6) }));
+ bowLamp.position.set(0, gondY + 0.05, 1.36);
+ body.add(bowLamp);
+
+ // Rigging
+ const rigMat = std({ color: '#3b2f28', roughness: 0.9 });
+ const rigGeo = new THREE.CylinderGeometry(0.01, 0.01, 1, 4, 1, true);
+ const up = new THREE.Vector3(0, 1, 0);
+ const addRig = (a, b) => {
+ const m = new THREE.Mesh(rigGeo, rigMat);
+ const d = new THREE.Vector3().subVectors(b, a);
+ m.scale.y = d.length();
+ m.position.copy(a).addScaledVector(d, 0.5);
+ m.quaternion.setFromUnitVectors(up, d.normalize());
+ body.add(m);
+ };
+ for (const s of [-1, 1]) for (const z of [-0.9, 0.2, 1.2]) {
+ addRig(new THREE.Vector3(s * 0.46, gondY + 0.32, z), new THREE.Vector3(s * R * 0.55, -R * 0.83, z * 1.35));
+ addRig(new THREE.Vector3(s * 0.46, gondY + 0.32, z), new THREE.Vector3(s * R * 0.2, -R * 0.97, z * 1.35 + 0.5));
+ }
+
+ // Propellers on outrigger struts
+ const props = [];
+ const bladeGeo = new RoundedBoxGeometry(0.1, 0.62, 0.025, 2, 0.012);
+ bladeGeo.translate(0, 0.3, 0);
+ for (const s of [-1, 1]) {
+ const strut = new THREE.Mesh(new THREE.CylinderGeometry(0.03, 0.03, 0.9, 6), brass);
+ strut.rotation.z = Math.PI / 2;
+ strut.position.set(s * 0.9, gondY + 0.05, -0.85);
+ body.add(strut);
+ const pod = new THREE.Mesh(new THREE.CapsuleGeometry(0.1, 0.3, 4, 10), trimMat);
+ pod.rotation.x = Math.PI / 2;
+ pod.position.set(s * 1.35, gondY + 0.05, -0.85);
+ body.add(pod);
+ const hub = new THREE.Group();
+ hub.position.set(s * 1.35, gondY + 0.05, -1.12);
+ for (let k = 0; k < 3; k++) { const b = new THREE.Mesh(bladeGeo, brass); b.rotation.z = k * Math.PI * 2 / 3; hub.add(b); }
+ body.add(hub);
+ props.push(hub);
+ }
+
+ // Pennant flying from the top fin
+ const flagGeo = new THREE.PlaneGeometry(1.1, 0.26, 16, 1);
+ flagGeo.translate(-0.55, 0, 0);
+ const flagBase = flagGeo.attributes.position.array.slice();
+ const flag = new THREE.Mesh(flagGeo, std({ color: '#f07f5f', side: THREE.DoubleSide, roughness: 0.8 }));
+ flag.rotation.y = Math.PI / 2;
+ flag.position.set(0, R * 0.34 + 1.12, -L * 0.36 - 1.1);
+ body.add(flag);
+ const mast = new THREE.Mesh(new THREE.CylinderGeometry(0.015, 0.015, 0.5, 5), brass);
+ mast.position.set(0, R * 0.34 + 1.0, -L * 0.36 - 1.1);
+ body.add(mast);
+
+ ship.traverse(o => { if (o.isMesh) { o.layers.enable(1); } });
+
+ ship.userData.update = (dt, t) => {
+ for (const p of props) p.rotation.z += dt * 14;
+ body.position.y = Math.sin(t * 0.7) * 0.12;
+ body.rotation.x = Math.sin(t * 0.5) * 0.02;
+ const a = flag.geometry.attributes.position;
+ for (let i = 0; i < a.count; i++) {
+ const x = flagBase[i * 3];
+ a.array[i * 3 + 2] = Math.sin(x * 5 + t * 7) * 0.08 * (-x);
+ a.array[i * 3 + 1] = flagBase[i * 3 + 1] * (1 + x * 0.35);
+ }
+ a.needsUpdate = true;
+ };
+ ship.userData.length = L;
+ ship.userData.refreshName = () => { const old = envMat.map; envMat.map = envelopeTexture(pal); envMat.needsUpdate = true; old.dispose(); };
+ return ship;
+}
diff --git a/examples/atlas/birds.js b/examples/atlas/birds.js
new file mode 100644
index 0000000..b0608d1
--- /dev/null
+++ b/examples/atlas/birds.js
@@ -0,0 +1,118 @@
+// A flock of swifts: CPU boids steering toward a roost that migrates from island to island,
+// drawn as one instanced mesh whose wings flap in the vertex shader.
+import { THREE } from '../../src/core/engine.js';
+import { patchAtmosphere } from './sky.js';
+
+const ZERO = new THREE.Vector3(), ZAX = new THREE.Vector3(0, 0, 1);
+
+function birdGeometry() {
+ // body + two swept wings; attribute `wing` = signed span position for flapping
+ const P = [], W = [];
+ const tri = (a, b, c, wa, wb, wc) => { P.push(...a, ...b, ...c); W.push(wa, wb, wc); };
+ // body (a thin diamond, both faces)
+ const nose = [0, 0, 0.32], tail = [0, 0, -0.3], top = [0, 0.05, 0], bot = [0, -0.04, 0], l = [-0.05, 0, 0.02], r = [0.05, 0, 0.02];
+ tri(nose, l, top, 0, 0, 0); tri(nose, top, r, 0, 0, 0); tri(tail, top, l, 0, 0, 0); tri(tail, r, top, 0, 0, 0);
+ tri(nose, bot, l, 0, 0, 0); tri(nose, r, bot, 0, 0, 0); tri(tail, l, bot, 0, 0, 0); tri(tail, bot, r, 0, 0, 0);
+ // wings: scythe shape
+ for (const s of [-1, 1]) {
+ const root0 = [s * 0.04, 0, 0.1], root1 = [s * 0.04, 0, -0.08], mid = [s * 0.34, 0.01, -0.02], tip = [s * 0.62, 0.0, -0.22];
+ tri(root0, mid, root1, 0, s * 0.55, 0); tri(root1, mid, tip, 0, s * 0.55, s * 1);
+ tri(root0, root1, mid, 0, 0, s * 0.55); tri(root1, tip, mid, 0, s * 1, s * 0.55);
+ }
+ // tail fork
+ tri([0, 0, -0.26], [-0.1, 0, -0.44], [0, 0, -0.32], 0, 0, 0); tri([0, 0, -0.26], [0, 0, -0.32], [0.1, 0, -0.44], 0, 0, 0);
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ g.setAttribute('wing', new THREE.Float32BufferAttribute(W, 1));
+ g.computeVertexNormals();
+ return g;
+}
+
+export class Flock {
+ constructor(count = 70) {
+ this.n = count;
+ this.pos = []; this.vel = [];
+ for (let i = 0; i < count; i++) {
+ this.pos.push(new THREE.Vector3((Math.random() - 0.5) * 12, 6 + Math.random() * 4, (Math.random() - 0.5) * 12));
+ this.vel.push(new THREE.Vector3(Math.random() - 0.5, 0, Math.random() - 0.5).normalize().multiplyScalar(3));
+ }
+ this.target = new THREE.Vector3();
+ this.roost = new THREE.Vector3();
+ this.roostR = 7;
+ const mat = new THREE.MeshStandardMaterial({ color: '#2d3654', roughness: 0.9, side: THREE.DoubleSide });
+ const u = patchAtmosphere(mat);
+ const flap = { value: 0 };
+ mat.onBeforeCompile = (orig => sh => {
+ orig(sh);
+ sh.uniforms.uFlapT = flap;
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute float wing; attribute float phase; uniform float uFlapT;')
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ float fl = sin(uFlapT * (11.0 + phase * 4.0) + phase * 40.0);
+ float glide = smoothstep(0.2, 0.8, sin(uFlapT * 0.7 + phase * 17.0) * 0.5 + 0.5);
+ transformed.y += abs(wing) * fl * 0.32 * (1.0 - glide * 0.85);
+ transformed.x *= 1.0 - abs(wing) * abs(fl) * 0.12 * (1.0 - glide);`);
+ })(mat.onBeforeCompile);
+ mat.customProgramCacheKey = () => 'atlas-bird';
+ this.flap = flap;
+ const geo = birdGeometry();
+ this.mesh = new THREE.InstancedMesh(geo, mat, count);
+ const ph = new Float32Array(count); for (let i = 0; i < count; i++) ph[i] = Math.random();
+ geo.setAttribute('phase', new THREE.InstancedBufferAttribute(ph, 1));
+ this.mesh.frustumCulled = false;
+ this.mesh.castShadow = false;
+ this._m = new THREE.Matrix4(); this._q = new THREE.Quaternion(); this._s = new THREE.Vector3(1, 1, 1);
+ this._side = new THREE.Vector3(); this._bq = new THREE.Quaternion(); this._a = new THREE.Vector3(); this._b = new THREE.Vector3(); this._c = new THREE.Vector3();
+ this.scale = 0.9;
+ }
+
+ setRoost(v, r = 7) { this.roost.copy(v); this.roostR = r; }
+
+ update(dt, t) {
+ this.flap.value = t;
+ const { pos, vel, n } = this;
+ // the flock circles its roost; the circling point leads the birds around
+ const ang = t * 0.35;
+ this.target.set(this.roost.x + Math.cos(ang) * this.roostR, this.roost.y + Math.sin(t * 0.5) * 1.5, this.roost.z + Math.sin(ang) * this.roostR);
+ const sep = this._a, ali = this._b, coh = this._c;
+ const acc = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ sep.set(0, 0, 0); ali.set(0, 0, 0); coh.set(0, 0, 0);
+ let k = 0;
+ const p = pos[i];
+ for (let j = 0; j < n; j++) {
+ if (i === j) continue;
+ const q = pos[j];
+ const dx = p.x - q.x, dy = p.y - q.y, dz = p.z - q.z;
+ const d2 = dx * dx + dy * dy + dz * dz;
+ if (d2 > 9) continue;
+ k++;
+ ali.add(vel[j]); coh.add(q);
+ if (d2 < 1.4) { const inv = 1 / (d2 + 0.05); sep.x += dx * inv; sep.y += dy * inv; sep.z += dz * inv; }
+ }
+ acc.set(0, 0, 0);
+ if (k) {
+ ali.divideScalar(k).sub(vel[i]).multiplyScalar(0.9);
+ coh.divideScalar(k).sub(p).multiplyScalar(0.3);
+ acc.add(ali).add(coh).addScaledVector(sep, 1.6);
+ }
+ const tx = this.target.x - p.x, ty = this.target.y - p.y, tz = this.target.z - p.z;
+ const td = Math.hypot(tx, ty, tz) || 1;
+ acc.x += tx / td * 2.2; acc.y += ty / td * 2.2; acc.z += tz / td * 2.2;
+ const v = vel[i];
+ v.addScaledVector(acc, dt);
+ const sp = v.length();
+ const lim = sp > 6.5 ? 6.5 / sp : sp < 2.6 ? 2.6 / sp : 1;
+ v.multiplyScalar(lim);
+ p.addScaledVector(v, dt);
+ // orient along velocity, bank into the turn
+ this._m.lookAt(v, ZERO, THREE.Object3D.DEFAULT_UP);
+ this._q.setFromRotationMatrix(this._m);
+ const bank = THREE.MathUtils.clamp(acc.dot(this._side.set(-v.z, 0, v.x).normalize()) * 0.12, -0.8, 0.8);
+ this._q.multiply(this._bq.setFromAxisAngle(ZAX, bank));
+ this._m.compose(p, this._q, this._s.setScalar(this.scale));
+ this.mesh.setMatrixAt(i, this._m);
+ }
+ this.mesh.instanceMatrix.needsUpdate = true;
+ }
+}
diff --git a/examples/atlas/clouds.js b/examples/atlas/clouds.js
new file mode 100644
index 0000000..3665096
--- /dev/null
+++ b/examples/atlas/clouds.js
@@ -0,0 +1,189 @@
+// Soft volumetric-looking clouds: one instanced draw of world-up billboards, each sampling a GPU-baked
+// cumulus atlas (density + self-shadowing from above), lit in three tones, hazed by the shared sky and
+// depth-faded against the islands (soft particles), then depth-sorted on the CPU every frame.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture } from '../../src/core/textures.js';
+import { sky, SKY_GLSL } from './sky.js';
+
+function bakeAtlas(renderer) {
+ // pass 1: cumulus density per tile
+ const density = bakeTexture(renderer, 1024, /* glsl */`
+ float h1(float n){ return fract(sin(n) * 43758.5453123); }
+ float puff(vec2 p, float id){
+ float f = -1.0;
+ float flt = step(2.5, id); // tile 3: long, low stratus for the cloud sea
+ for (int i = 0; i < 11; i++){
+ float fi = float(i);
+ float a = h1(fi * 12.7 + id * 91.3), b = h1(fi * 3.9 + id * 17.1), c = h1(fi * 7.3 + id * 33.7);
+ float spread = mix(0.5, 0.66, flt);
+ float x = 0.5 + (a - 0.5) * spread;
+ float edge = 1.0 - abs(x - 0.5) * mix(1.5, 1.2, flt);
+ float r = mix(0.075, 0.19, c) * edge * mix(1.0, 0.72, flt);
+ float y = mix(0.34, 0.36, flt) + r * 0.75 + b * mix(0.13, 0.05, flt) * edge;
+ vec2 dp = (p - vec2(x, y)) * vec2(1.0, 1.08);
+ f = max(f, (r - length(dp)) / r);
+ }
+ return f;
+ }
+ void main(){
+ vec2 tile = floor(vUv * 2.0);
+ vec2 p = fract(vUv * 2.0);
+ float id = tile.x + tile.y * 2.0;
+ float n = fbm(p * 4.0 + id * 3.7, 64.0, 6, 0.55);
+ float n2 = fbm(p * 14.0 + id * 1.3, 64.0, 4, 0.5);
+ float f = puff(p + vec2(n, n * 0.8) * 0.07, id);
+ float d = smoothstep(-0.12, 0.6, f + n * 0.45 + n2 * 0.18);
+ d *= smoothstep(0.24, 0.42, p.y + n * 0.06 + n2 * 0.02);
+ d *= smoothstep(0.5, 0.38, max(abs(p.x - 0.5), abs(p.y - 0.5)));
+ gl_FragColor = vec4(d, 0.0, 0.0, 1.0);
+ }`);
+ density.generateMipmaps = false;
+ // pass 2: light transmitted from above (self-shadowing), marched through the density texture
+ return bakeTexture(renderer, 1024, /* glsl */`
+ uniform sampler2D uDen;
+ float den(vec2 p, vec2 tile){ p = clamp(p, 0.0, 1.0); return texture2D(uDen, (p + tile) * 0.5).r; }
+ void main(){
+ vec2 tile = floor(vUv * 2.0);
+ vec2 p = fract(vUv * 2.0);
+ float d = den(p, tile);
+ float acc = 0.0;
+ for (int i = 1; i <= 16; i++) acc += den(p + vec2(0.01, 0.024) * float(i), tile);
+ float acc2 = 0.0;
+ for (int i = 1; i <= 6; i++) acc2 += den(p + vec2(0.0, 0.07) * float(i), tile);
+ float T = exp(-acc * 0.15), T2 = exp(-acc2 * 0.22);
+ gl_FragColor = vec4(d, T * 0.7 + T2 * 0.3, 0.0, 1.0);
+ }`, { uDen: { value: density } });
+}
+
+export class Clouds {
+ constructor(renderer, { max = 1400 } = {}) {
+ this.max = max;
+ this.items = [];
+ this.tex = bakeAtlas(renderer);
+ const base = new THREE.PlaneGeometry(1, 1);
+ const geo = new THREE.InstancedBufferGeometry();
+ geo.index = base.index;
+ geo.setAttribute('position', base.getAttribute('position'));
+ geo.setAttribute('uv', base.getAttribute('uv'));
+ this.a = new Float32Array(max * 4);
+ this.b = new Float32Array(max * 4);
+ this.attrA = new THREE.InstancedBufferAttribute(this.a, 4).setUsage(THREE.DynamicDrawUsage);
+ this.attrB = new THREE.InstancedBufferAttribute(this.b, 4).setUsage(THREE.DynamicDrawUsage);
+ this.c = new Float32Array(max * 2);
+ this.attrC = new THREE.InstancedBufferAttribute(this.c, 2).setUsage(THREE.DynamicDrawUsage);
+ geo.setAttribute('iA', this.attrA);
+ geo.setAttribute('iB', this.attrB);
+ geo.setAttribute('iC', this.attrC);
+ geo.instanceCount = 0;
+ this.uniforms = {
+ ...sky,
+ uTex: { value: this.tex },
+ uDepth: { value: null },
+ uRes: { value: new THREE.Vector2(1, 1) },
+ uNear: { value: 0.1 }, uFar: { value: 1000 },
+ uLitC: { value: new THREE.Color('#fffaf2').multiplyScalar(1.12) },
+ uMidC: { value: new THREE.Color('#fae5d9') },
+ uShadowC: { value: new THREE.Color('#a6bade') },
+ uNearFade: { value: new THREE.Vector2(0.4, 1.5) },
+ uCloudFog: { value: 0.0034 },
+ uSoftOn: { value: 1 },
+ };
+ this.material = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, depthTest: true,
+ uniforms: this.uniforms,
+ vertexShader: /* glsl */`
+ attribute vec4 iA; attribute vec4 iB; attribute vec2 iC;
+ uniform float uTime;
+ varying vec2 vUv; varying float vViewZ; varying vec3 vWorld; varying vec4 vB; varying float vSize;
+ void main(){
+ vec3 c = iA.xyz;
+ float seed = fract(iA.x * 0.1373 + iA.z * 0.0711 + iA.y * 0.031);
+ c += vec3(sin(uTime * 0.045 + seed * 30.0), sin(uTime * 0.03 + seed * 11.0) * 0.25, cos(uTime * 0.04 + seed * 20.0)) * (0.4 + iA.w * 0.025);
+ vec3 toCam = normalize(cameraPosition - c);
+ vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), toCam));
+ vec3 up = cross(toCam, right);
+ vec2 q = position.xy * vec2(1.0, iB.w);
+ float cr = cos(iC.x), sr = sin(iC.x);
+ q = vec2(cr * q.x - sr * q.y, sr * q.x + cr * q.y);
+ vec3 wp = c + (right * q.x + up * q.y) * iA.w;
+ vUv = vec2(iC.y > 0.5 ? 1.0 - uv.x : uv.x, uv.y); vWorld = wp; vB = iB; vSize = iA.w;
+ vec4 mv = viewMatrix * vec4(wp, 1.0);
+ vViewZ = -mv.z;
+ gl_Position = projectionMatrix * mv;
+ }`,
+ fragmentShader: /* glsl */`
+ #include <packing>
+ ${SKY_GLSL}
+ uniform sampler2D uTex, uDepth; uniform vec2 uRes; uniform float uNear, uFar; uniform vec2 uNearFade;
+ uniform vec3 uLitC, uMidC, uShadowC; uniform float uCloudFog, uSoftOn;
+ varying vec2 vUv; varying float vViewZ; varying vec3 vWorld; varying vec4 vB; varying float vSize;
+ void main(){
+ float id = floor(vB.x + 0.5); float ty = floor((id + 0.5) * 0.5); vec2 tile = vec2(id - ty * 2.0, ty);
+ vec4 t = texture2D(uTex, (clamp(vUv, 0.004, 0.996) + tile) * 0.5);
+ float d = t.r * vB.z;
+ if (d < 0.004) discard;
+ float L = clamp((0.3 + 0.7 * t.g) * vB.y, 0.0, 1.25);
+ vec3 col = mix(uShadowC, uMidC, smoothstep(0.0, 0.38, L));
+ col = mix(col, uLitC, smoothstep(0.3, 0.85, L));
+ vec3 dir = normalize(vWorld - cameraPosition);
+ float s = max(dot(dir, uSunDir), 0.0);
+ col += mix(uSunCol, vec3(1.0), 0.5) * (pow(s, 4.0) * (1.0 - t.r) * 0.4 + pow(s, 16.0) * 0.25);
+ float fz = uCloudFog * vViewZ; float f = 1.0 - exp(-fz * fz);
+ col = mix(col, skyColor(dir), clamp(f, 0.0, 0.97));
+ float sceneZ = -perspectiveDepthToViewZ(texture2D(uDepth, gl_FragCoord.xy / uRes).x, uNear, uFar);
+ float soft = mix(1.0, clamp((sceneZ - vViewZ) / (vSize * 0.28), 0.0, 1.0), uSoftOn);
+ float nearF = smoothstep(vSize * 0.06 + uNearFade.x, vSize * 0.42 + uNearFade.y, vViewZ);
+ gl_FragColor = vec4(col, d * soft * nearF);
+ }`,
+ });
+ this.mesh = new THREE.Mesh(geo, this.material);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 5;
+ this.geo = geo;
+ this._order = [];
+ }
+
+ /** tile 0-3, shade (lighting multiplier), alpha, aspect (h/w). Returns the item so callers can animate it. */
+ add(x, y, z, size, { tile = 0, shade = 1, alpha = 1, aspect = 1, rot = (Math.random() - 0.5) * 0.3, flip = Math.random() < 0.5 ? 1 : 0 } = {}) {
+ if (this.items.length >= this.max) return null;
+ const it = { x, y, z, size, tile, shade, alpha, aspect, rot, flip };
+ this.items.push(it);
+ return it;
+ }
+
+ update(camera) {
+ const n = this.items.length;
+ const cp = camera.position;
+ const fx = -camera.matrixWorld.elements[8], fy = -camera.matrixWorld.elements[9], fz = -camera.matrixWorld.elements[10];
+ const order = this._order;
+ order.length = 0;
+ for (let i = 0; i < n; i++) {
+ const it = this.items[i];
+ if (it.alpha <= 0.001) continue;
+ it._d = (it.x - cp.x) * fx + (it.y - cp.y) * fy + (it.z - cp.z) * fz;
+ if (it._d < -it.size) continue; // fully behind the camera
+ order.push(it);
+ }
+ order.sort((p, q) => q._d - p._d);
+ const a = this.a, b = this.b;
+ for (let k = 0; k < order.length; k++) {
+ const it = order[k];
+ a[k * 4] = it.x; a[k * 4 + 1] = it.y; a[k * 4 + 2] = it.z; a[k * 4 + 3] = it.size;
+ b[k * 4] = it.tile; b[k * 4 + 1] = it.shade; b[k * 4 + 2] = it.alpha; b[k * 4 + 3] = it.aspect;
+ this.c[k * 2] = it.rot; this.c[k * 2 + 1] = it.flip;
+ }
+ this.attrC.needsUpdate = true;
+ this.attrC.addUpdateRange(0, order.length * 2);
+ this.geo.instanceCount = order.length;
+ this.attrA.needsUpdate = true; this.attrB.needsUpdate = true;
+ this.attrA.addUpdateRange(0, order.length * 4);
+ this.attrB.addUpdateRange(0, order.length * 4);
+ this.uniforms.uNear.value = camera.near; this.uniforms.uFar.value = camera.far;
+ }
+}
+
+/** Seeded RNG so the sky is the same sky every visit. */
+export function rng(seed = 1) {
+ let s = seed >>> 0;
+ return () => { s = (s + 0x6D2B79F5) >>> 0; let t = s; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
+}
diff --git a/examples/atlas/index.html b/examples/atlas/index.html
new file mode 100644
index 0000000..64958b4
--- /dev/null
+++ b/examples/atlas/index.html
@@ -0,0 +1,221 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Atlas of Drifting Isles — Airship passage above the cloud sea</title>
+ <meta name="description" content="Four islands adrift above the cloud sea, reachable only by airship. Daily departures from Port Aubade since 1887.">
+ <meta name="theme-color" content="#8cc9ff">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Nunito+Sans:ital,opsz,wght@0,6..12,300..900;1,6..12,300..700&family=Young+Serif&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-card">
+ <p class="loader-mark">Atlas <i>of Drifting Isles</i></p>
+ <svg class="loader-route" viewBox="0 0 360 130" aria-hidden="true">
+ <path id="route" d="M24 104 C 90 20, 250 10, 336 88" fill="none" stroke="currentColor" stroke-width="1.4" stroke-dasharray="2 7" stroke-linecap="round"/>
+ <path class="route-done" d="M24 104 C 90 20, 250 10, 336 88" fill="none" stroke="#ef7d5c" stroke-width="2" stroke-linecap="round"/>
+ <circle cx="24" cy="104" r="4.5" fill="#1d2742"/>
+ <g class="route-isles" fill="#fff8ee" stroke="#1d2742" stroke-width="1.3">
+ <ellipse cx="336" cy="92" rx="13" ry="5"/><path d="M325 92 l11 14 l11 -14" /><path d="M334 86 v-9 l5 3 l-5 2" fill="#ef7d5c" stroke="none"/>
+ </g>
+ <g class="loader-ship">
+ <ellipse cx="0" cy="0" rx="17" ry="7" fill="#f7eedf" stroke="#1d2742" stroke-width="1.3"/>
+ <path d="M-9 -6.3 C-3 -7.4 3 -7.4 9 -6.3 M-9 6.3 C-3 7.4 3 7.4 9 6.3" stroke="#ef7d5c" stroke-width="2" fill="none"/>
+ <path d="M-17 0 l-6 -6 v12 z" fill="#ef7d5c"/>
+ <rect x="-5" y="8" width="10" height="4" rx="1.5" fill="#1d2742"/>
+ </g>
+ <text x="24" y="124" class="loader-label">Port Aubade</text>
+ <text x="336" y="124" text-anchor="end" class="loader-label">The Drift</text>
+ </svg>
+ <p class="loader-line">Charting the drift <span class="loader-pct">0</span>%</p>
+ <p class="loader-sub">Wind WSW, 12 knots · visibility excellent · all four isles in range</p>
+ </div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Atlas of Drifting Isles, home">
+ <svg viewBox="0 0 40 40" aria-hidden="true"><circle cx="20" cy="20" r="18.5" fill="none" stroke="currentColor" stroke-width="1.2"/><path d="M20 4 L23 20 L20 36 L17 20 Z" fill="currentColor"/><path d="M4 20 L20 17.5 L36 20 L20 22.5 Z" fill="currentColor" opacity=".35"/><ellipse cx="20" cy="13" rx="6.5" ry="3" fill="#ef7d5c"/></svg>
+ <span class="brand-words"><b>Atlas</b><i>of Drifting Isles</i></span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#lanternholm" data-go="1">Destinations</a>
+ <a href="#fleet" data-go="5">The fleet</a>
+ <a href="#book" data-go="6">Timetable &amp; fares</a>
+ </nav>
+ <a class="btn btn-coral" href="#book" data-go="6" data-magnetic>Book a crossing</a>
+ </header>
+
+ <main class="track">
+ <!-- 0 · Hero -->
+ <section class="stop stop-hero" id="top" data-st="0" aria-label="Welcome">
+ <div class="panel hero" data-panel="0">
+ <p class="kicker" data-rise>Sky passage since 1887 <span>·</span> Daily departures from Port Aubade</p>
+ <h1 class="hero-title">
+ <span class="hero-line1" data-rise>The map is not the territory.</span>
+ <span class="hero-line2" data-rise>The territory<br><em>floats.</em></span>
+ </h1>
+ <p class="hero-sub" data-rise>Four islands adrift above the cloud sea, reachable only by airship. We keep the timetable. The wind keeps the rest.</p>
+ <div class="hero-cta" data-rise>
+ <a class="btn btn-ink" href="#lanternholm" data-go="1" data-magnetic>Take the grand tour</a>
+ <span class="hint"><i class="hint-ring" aria-hidden="true"></i>Click any island to fly there</span>
+ </div>
+ </div>
+ </section>
+
+ <!-- 1 · Lanternholm -->
+ <section class="stop" id="lanternholm" data-st="1" aria-label="Lanternholm">
+ <article class="panel ticket t-left" data-panel="1">
+ <header class="t-head" data-rise><span class="t-num">I</span><span class="t-route">Port Aubade <i>⟶</i> Lanternholm</span><span class="t-code">AD&nbsp;101</span></header>
+ <h2 class="t-name" data-rise>Lanternholm</h2>
+ <p class="t-meta" data-rise><b>3 h</b> from Port Aubade <span>·</span> the lighthouse isle</p>
+ <p class="t-lede" data-rise>The only lighthouse in the world that has never seen the sea. Keeper Oona Brisk lights the lamp at dusk anyway — for airships, for swifts, and for anyone who has lost their bearings above the clouds.</p>
+ <ul class="t-list" data-rise>
+ <li>Climb the 112 steps to the lamp room at dusk</li>
+ <li>Seed cake and strong tea in the keeper’s cottage</li>
+ <li>Lupin meadows in flower from May to August</li>
+ </ul>
+ <dl class="t-facts" data-rise><div><dt>Altitude</dt><dd>1,900 m</dd></div><div><dt>Drift</dt><dd>4 km/day NNE</dd></div><div><dt>Islanders</dt><dd>2 and a cat</dd></div></dl>
+ <footer class="t-stub" data-rise>
+ <p class="t-price"><small>Return from</small><b>180</b><span>crowns</span></p>
+ <p class="t-when">Daily · 07:40</p>
+ <a class="btn btn-coral" href="#book" data-go="6" data-dest="lanternholm">Reserve a berth</a>
+ </footer>
+ </article>
+ </section>
+
+ <!-- 2 · Amberlea -->
+ <section class="stop" id="amberlea" data-st="2" aria-label="Amberlea">
+ <article class="panel ticket t-right" data-panel="2">
+ <header class="t-head" data-rise><span class="t-num">II</span><span class="t-route">Port Aubade <i>⟶</i> Amberlea</span><span class="t-code">AD&nbsp;204</span></header>
+ <h2 class="t-name" data-rise>Amberlea</h2>
+ <p class="t-meta" data-rise><b>4½ h</b> from Port Aubade <span>·</span> the drifting farm</p>
+ <p class="t-lede" data-rise>The breadbasket of the archipelago: wheat that grows in thin air, a mill that has not stopped turning since 1904, and a river that runs off the end of the farm into nothing at all.</p>
+ <ul class="t-list" data-rise>
+ <li>Bring in the July harvest with the Amberlea families</li>
+ <li>Row the mill-river right to the edge of the world</li>
+ <li>A warm loaf from the mill with every return berth</li>
+ </ul>
+ <dl class="t-facts" data-rise><div><dt>Altitude</dt><dd>1,650 m</dd></div><div><dt>Drift</dt><dd>2 km/day E</dd></div><div><dt>Islanders</dt><dd>31</dd></div></dl>
+ <footer class="t-stub" data-rise>
+ <p class="t-price"><small>Return from</small><b>150</b><span>crowns</span></p>
+ <p class="t-when">Mon · Wed · Sat</p>
+ <a class="btn btn-coral" href="#book" data-go="6" data-dest="amberlea">Reserve a berth</a>
+ </footer>
+ </article>
+ </section>
+
+ <!-- 3 · Hollowmere -->
+ <section class="stop" id="hollowmere" data-st="3" aria-label="Hollowmere">
+ <article class="panel ticket t-left" data-panel="3">
+ <header class="t-head" data-rise><span class="t-num">III</span><span class="t-route">Port Aubade <i>⟶</i> Hollowmere</span><span class="t-code">AD&nbsp;316</span></header>
+ <h2 class="t-name" data-rise>Hollowmere</h2>
+ <p class="t-meta" data-rise><b>6 h</b> from Port Aubade <span>·</span> the endless falls</p>
+ <p class="t-lede" data-rise>A forest lake that never empties, pouring over the island’s lip into two thousand metres of air. Nobody has found where the water comes from. Everybody agrees it tastes of rain.</p>
+ <ul class="t-list" data-rise>
+ <li>Swim the pool a stone’s throw from the edge</li>
+ <li>Cross the moss bridge to the Wayfinder Stones</li>
+ <li>Canopy hammocks, with rainbows at breakfast</li>
+ </ul>
+ <dl class="t-facts" data-rise><div><dt>Altitude</dt><dd>2,300 m</dd></div><div><dt>Drift</dt><dd>6 km/day S</dd></div><div><dt>Islanders</dt><dd>None, officially</dd></div></dl>
+ <footer class="t-stub" data-rise>
+ <p class="t-price"><small>Return from</small><b>260</b><span>crowns</span></p>
+ <p class="t-when">Tue · Fri</p>
+ <a class="btn btn-coral" href="#book" data-go="6" data-dest="hollowmere">Reserve a berth</a>
+ </footer>
+ </article>
+ </section>
+
+ <!-- 4 · Hanakumo -->
+ <section class="stop" id="hanakumo" data-st="4" aria-label="Hanakumo">
+ <article class="panel ticket t-right" data-panel="4">
+ <header class="t-head" data-rise><span class="t-num">IV</span><span class="t-route">Port Aubade <i>⟶</i> Hanakumo</span><span class="t-code">AD&nbsp;409</span></header>
+ <h2 class="t-name" data-rise>Hanakumo</h2>
+ <p class="t-meta" data-rise><b>9 h</b> from Port Aubade <span>·</span> overnight, by sleeper</p>
+ <p class="t-lede" data-rise>A three-tiered temple whose cherry trees bloom every month the island drifts south. The monks ring the wind bells by hand when a ship comes in — you will hear Hanakumo an hour before you see it.</p>
+ <ul class="t-list" data-rise>
+ <li>The dawn bell ceremony on the upper gallery</li>
+ <li>The lantern stair: through the torii, up 208 steps</li>
+ <li>Petal season — we will wake you when it starts</li>
+ </ul>
+ <dl class="t-facts" data-rise><div><dt>Altitude</dt><dd>2,800 m</dd></div><div><dt>Drift</dt><dd>3 km/day SW</dd></div><div><dt>Islanders</dt><dd>12 monks</dd></div></dl>
+ <footer class="t-stub" data-rise>
+ <p class="t-price"><small>Return from</small><b>340</b><span>crowns</span></p>
+ <p class="t-when">Thursdays · sleeper</p>
+ <a class="btn btn-coral" href="#book" data-go="6" data-dest="hanakumo">Reserve a berth</a>
+ </footer>
+ </article>
+ </section>
+
+ <!-- 5 · Fleet -->
+ <section class="stop" id="fleet" data-st="5" aria-label="The airship fleet">
+ <div class="panel fleet" data-panel="5">
+ <p class="kicker" data-rise>The fleet</p>
+ <h2 class="fleet-title" data-rise>Three ships, each named for a kind of weather.</h2>
+ <p class="fleet-lede" data-rise>Every Atlas ship is built in Port Aubade from spruce, copper rivets and eleven thousand square metres of waxed silk. They are not fast. That is rather the point.</p>
+ <ul class="ships">
+ <li class="ship is-here" data-rise><span class="ship-tag">You are looking at her</span><h3>Zephyrine</h3><p>Flagship · 24 berths</p><p class="ship-note">Observation deck, dining saloon, a piano that is only slightly out of tune.</p></li>
+ <li class="ship" data-rise><span class="ship-tag">Overnight</span><h3>Halcyon</h3><p>Sleeper · 12 cabins</p><p class="ship-note">The Hanakumo run. Linen sheets, porthole bunks, cocoa at 2,800 m.</p></li>
+ <li class="ship" data-rise><span class="ship-tag">Charter</span><h3>Little Squall</h3><p>Six seats · any isle</p><p class="ship-note">Goes wherever the wind is going, which is usually somewhere good.</p></li>
+ </ul>
+ <dl class="fleet-stats" data-rise><div><dt>38 kn</dt><dd>cruising, with a tailwind</dd></div><div><dt>2,900 m</dt><dd>service ceiling</dd></div><div><dt>137 yrs</dt><dd>no passenger lost (one umbrella)</dd></div></dl>
+ </div>
+ </section>
+
+ <!-- 6 · Booking -->
+ <section class="stop stop-book" id="book" data-st="6" aria-label="Book a crossing">
+ <div class="panel book" data-panel="6">
+ <p class="kicker" data-rise>Timetable &amp; fares</p>
+ <h2 class="book-title" data-rise>Pack light. Everything up here already floats.</h2>
+ <p class="book-lede" data-rise>Berths open ninety days ahead. Every fare includes breakfast aboard, a wool blanket and a window seat.</p>
+ <form class="booking" data-rise onsubmit="return false">
+ <label class="field"><span>From</span><input value="Port Aubade" readonly></label>
+ <label class="field"><span>To</span>
+ <select name="dest">
+ <option value="lanternholm">Lanternholm · 3 h</option>
+ <option value="amberlea">Amberlea · 4½ h</option>
+ <option value="hollowmere">Hollowmere · 6 h</option>
+ <option value="hanakumo">Hanakumo · 9 h</option>
+ </select>
+ </label>
+ <label class="field"><span>Depart</span><input type="date" name="date"></label>
+ <label class="field field-small"><span>Travellers</span>
+ <select name="pax"><option>1</option><option selected>2</option><option>3</option><option>4</option><option>5</option><option>6</option></select>
+ </label>
+ <button class="btn btn-coral btn-big" type="submit" data-magnetic>Find a berth</button>
+ </form>
+ <p class="book-note" data-rise>Crossings are subject to wind. If your island drifts out of range, we refund in full and send a postcard.</p>
+ </div>
+ </section>
+ </main>
+
+ <footer class="foot">
+ <div class="foot-cloud" aria-hidden="true"></div>
+ <div class="foot-inner">
+ <p class="foot-mark">Atlas <i>of Drifting Isles</i></p>
+ <div class="foot-cols">
+ <div><h4>Harbour Master’s Office</h4><p>Pier 9, Port Aubade<br>Open daily 06:00 – 22:00<br>Last boarding call 21:40</p></div>
+ <div><h4>Destinations</h4><p><a href="#lanternholm" data-go="1">Lanternholm</a><br><a href="#amberlea" data-go="2">Amberlea</a><br><a href="#hollowmere" data-go="3">Hollowmere</a><br><a href="#hanakumo" data-go="4">Hanakumo</a></p></div>
+ <div><h4>Aboard</h4><p><a href="#fleet" data-go="5">The fleet</a><br><a href="#book" data-go="6">Timetable &amp; fares</a><br>Gift berths<br>Lost umbrellas</p></div>
+ <div><h4>Est. 1887</h4><p>Member of the Guild of Lighter-than-Air Carriers. Weather permitting, always.</p></div>
+ </div>
+ <p class="foot-small"><span>© 1887–2026 Atlas of Drifting Isles</span><span>Timetables subject to wind</span></p>
+ </div>
+ </footer>
+
+ <!-- chrome over the world -->
+ <div class="pins" aria-hidden="true"></div>
+ <aside class="chart" aria-label="Chart of the drift">
+ <p class="chart-title"><span>The drift chart</span><em class="chart-where">Port Aubade approaches</em></p>
+ <div class="chart-map"><canvas class="chart-canvas"></canvas><div class="chart-dots"></div></div>
+ </aside>
+ <div class="toast" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/atlas/main.js b/examples/atlas/main.js
new file mode 100644
index 0000000..5466d6d
--- /dev/null
+++ b/examples/atlas/main.js
@@ -0,0 +1,760 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { sky, skyDome, patchAtmosphere } from './sky.js';
+import { Clouds, rng } from './clouds.js';
+import { buildAirship } from './airship.js';
+import { Flock } from './birds.js';
+import { fallStream, petals, lighthouseLamp, pointU, motes } from './water.js';
+
+// ─── The archipelago ──────────────────────────────────────────────────────────
+const V3 = THREE.Vector3;
+const UP = new V3(0, 1, 0);
+const TAU = Math.PI * 2;
+const DBG = new URLSearchParams(location.search);
+const portrait = () => innerWidth < innerHeight * 0.95;
+const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+// side: -1 → the ticket sits left and the island is framed right of centre; +1 the opposite.
+const ISLES = [
+ { key: 'lighthouse', id: 'lanternholm', name: 'Lanternholm', num: 'I', time: '3 h', s: 1.25, pos: [6.4, 0.6, 7], yaw: -0.55,
+ az: 0.62, sweep: 0.6, dist: 15.5, h: 2.6, side: -1 },
+ { key: 'windmill', id: 'amberlea', name: 'Amberlea', num: 'II', time: '4½ h', s: 1.2, pos: [22, -4, -14], yaw: -0.35,
+ az: -0.5, sweep: 0.6, dist: 16.5, h: 3.4, side: 1,
+ fall: { a: [-0.4, 1.5, 2.18], b: [-0.13, 1.5, 2.18], boxA: [-0.5, 0.0, 1.98], boxB: [-0.05, 4.3, 2.42], drop: 18 } },
+ { key: 'falls', id: 'hollowmere', name: 'Hollowmere', num: 'III', time: '6 h', s: 1.15, pos: [-1, 12, -32], yaw: 0.1,
+ az: 0.42, sweep: 0.55, dist: 16, h: 2.0, side: -1,
+ fall: { a: [0.45, 1.5, 1.98], b: [0.85, 1.5, 1.98], boxA: [0.36, 0.05, 1.76], boxB: [0.95, 4.35, 2.26], drop: 25 } },
+ { key: 'pagoda', id: 'hanakumo', name: 'Hanakumo', num: 'IV', time: '9 h', s: 1.1, pos: [30, 16, -56], yaw: -0.3,
+ az: -0.5, sweep: 0.55, dist: 14.5, h: 3.0, side: 1 },
+];
+const ARCH = new V3(12, 6, -24); // archipelago centre
+const HERO_POS0 = new THREE.Vector3(0, 6.5, 31), HERO_LOOK0 = new THREE.Vector3(1, 5.2, 0), BOOK_POS0 = new THREE.Vector3(-10, 16, 54);
+const tmp = new V3(), tmp2 = new V3(), tmp3 = new V3(), tmp4 = new V3();
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 40, near: 0.3, far: 2600, dpr: 1.5, background: 0x9fd0ff,
+ post: {
+ ao: DBG.has('noao') ? false : { aoRadius: 1.4, intensity: 1.6, distanceFalloff: 0.5 },
+ bloom: { intensity: 0.55, luminanceThreshold: 1.25, luminanceSmoothing: 0.35, radius: 0.8 },
+ tone: DBG.get('tone') ?? 'neutral',
+ vignette: { offset: 0.42, darkness: 0.34 },
+ noise: 0.028,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.shadowMap.autoUpdate = false;
+scene.environment = studioEnvironment(renderer, {
+ top: 0x7fb8ec, bottom: 0xf4dccb,
+ panels: [
+ { pos: [-6, 7, 6], size: [9, 4], intensity: 2.6, color: 0xfff0dc },
+ { pos: [7, 2, -5], size: [4, 7], intensity: 1.1, color: 0xcfe6ff },
+ { pos: [0, -6, 0], size: [12, 12], intensity: 0.8, color: 0xffe2cc },
+ ],
+});
+scene.environmentIntensity = 0.55;
+
+const hemi = new THREE.HemisphereLight('#d9ecff', '#ffdcc8', 1.35);
+scene.add(hemi);
+const sun = new THREE.DirectionalLight('#fff0dc', 2.5);
+sun.castShadow = true;
+sun.shadow.mapSize.set(4096, 4096);
+Object.assign(sun.shadow.camera, { left: -46, right: 46, top: 46, bottom: -46, near: 1, far: 260 });
+sun.shadow.bias = -0.0003; sun.shadow.normalBias = 0.05; sun.shadow.radius = 2.5;
+scene.add(sun, sun.target);
+
+const DAY = { dir: new V3(-0.55, 0.62, 0.56).normalize(), skyDir: new V3(-0.337, 0.174, -0.925).normalize(), sun: new THREE.Color('#fff0dc'), sunI: 2.5, hemiI: 1.35,
+ zenith: new THREE.Color('#3f8fe0'), mid: new THREE.Color('#7cc4ff'), horizon: new THREE.Color('#ffe7d2'), below: new THREE.Color('#f0e8e8'), glow: new THREE.Color('#ffd9ae'),
+ lit: new THREE.Color('#fffaf3').multiplyScalar(1.12), midC: new THREE.Color('#fae5d9'), shadow: new THREE.Color('#a6bade') };
+const DUSK = { dir: new V3(-0.72, 0.16, 0.68).normalize(), skyDir: new V3(0.616, 0.075, -0.784).normalize(), sun: new THREE.Color('#ffb07a'), sunI: 2.2, hemiI: 1.05,
+ zenith: new THREE.Color('#4f79c4'), mid: new THREE.Color('#c2c3e0'), horizon: new THREE.Color('#ffcb92'), below: new THREE.Color('#f4d8c2'), glow: new THREE.Color('#ffae64'),
+ lit: new THREE.Color('#fff0da').multiplyScalar(1.15), midC: new THREE.Color('#ffd2ac'), shadow: new THREE.Color('#a8a4cb') };
+
+const dome = skyDome();
+scene.add(dome);
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+const loaderEl = document.querySelector('.loader');
+const routePath = loaderEl.querySelector('#route');
+const routeDone = loaderEl.querySelector('.route-done');
+const loaderShip = loaderEl.querySelector('.loader-ship');
+const routeLen = routePath.getTotalLength();
+routeDone.style.strokeDasharray = `${routeLen} ${routeLen}`;
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ const p = routePath.getPointAtLength(v * routeLen), q = routePath.getPointAtLength(Math.min(routeLen, v * routeLen + 2));
+ loaderShip.setAttribute('transform', `translate(${p.x} ${p.y - 12}) rotate(${Math.atan2(q.y - p.y, q.x - p.x) * 57.3})`);
+ routeDone.style.strokeDashoffset = routeLen * (1 - v);
+ },
+ exit: () => gsap.timeline()
+ .to('.loader-card', { y: -30, opacity: 0, duration: 0.6, ease: 'power2.in' })
+ .add(() => beginIntro(), '-=0.1')
+ .to(loaderEl, { yPercent: -112, duration: 1.5, ease: 'expo.inOut' }, '-=0.2'),
+});
+
+// ─── Clouds ────────────────────────────────────────────────────────────────────
+const clouds = new Clouds(renderer, { max: 1800 });
+scene.add(clouds.mesh);
+if (DBG.has('nosoft')) clouds.uniforms.uSoftOn.value = 0;
+if (DBG.has('noclouds')) clouds.mesh.visible = false;
+if (DBG.has('nobloom')) engine.post.bloom.intensity = 0;
+{
+ const R = rng(11);
+ // The cloud sea: a deep undulating floor that runs to the horizon — fine puffs near, broad banks far.
+ const sea = (n, r0, r1, s0, s1) => {
+ for (let i = 0; i < n; i++) {
+ const r = r0 + Math.sqrt(R()) * (r1 - r0), a = R() * TAU;
+ const x = ARCH.x + Math.cos(a) * r * 1.1, z = ARCH.z + Math.sin(a) * r;
+ const far = r / 340;
+ const dip = R();
+ const y = -11 + Math.sin(x * 0.035) * 2.5 + Math.cos(z * 0.045 + 1) * 2.5 - dip * 4 - far * 10;
+ clouds.add(x, y, z, lerp(s0, s1, R()), { tile: R() < 0.55 ? 3 : Math.floor(R() * 3), shade: 0.7 + (1 - dip) * 0.48, alpha: 0.95, aspect: 0.45 + R() * 0.22 });
+ }
+ };
+ sea(300, 0, 95, 14, 34);
+ sea(230, 95, 340, 40, 110);
+ // Horizon banks: towering far cumulus that give the sky its depth.
+ for (let i = 0; i < 46; i++) {
+ const a = R() * TAU, r = 420 + R() * 260;
+ clouds.add(ARCH.x + Math.cos(a) * r, -30 + R() * 30, ARCH.z + Math.sin(a) * r, 140 + R() * 160, { tile: Math.floor(R() * 3), shade: 1 + R() * 0.2, alpha: 0.85, aspect: 0.6 + R() * 0.3 });
+ }
+ // Mid-level cumulus drifting between the islands: flat bases, heaped tops, kept out of every sightline the tour uses.
+ const cluster = (cx, cy, cz, rad, n, shade = 1) => {
+ for (let k = 0; k < n; k++) {
+ const h = Math.pow(R(), 1.4); // most puffs sit low, a few heap up
+ const spread = 1 - h * 0.55;
+ const ox = (R() - 0.5) * 2.2 * rad * spread, oz = (R() - 0.5) * 1.5 * rad * spread;
+ const oy = h * rad * 0.9;
+ clouds.add(cx + ox, cy + oy, cz + oz, rad * (0.55 + R() * 0.55) * (1 - h * 0.3), { tile: Math.floor(R() * 3), shade: (0.8 + h * 0.4) * shade, alpha: 0.96, aspect: 0.75 + R() * 0.2 });
+ }
+ };
+ // A towering cumulus: flat base on the sea, heaped cauliflower crown.
+ const sunH = new V3(DAY.dir.x, 0, DAY.dir.z).normalize();
+ const tower = (x, z, base, height, width, n) => {
+ for (let k = 0; k < n; k++) {
+ const h = Math.pow(R(), 0.75);
+ const w = width * (1 - h * 0.45) * (h > 0.82 ? 1.2 : 1);
+ const ox = (R() - 0.5) * w, oz = (R() - 0.5) * w * 0.7;
+ const sunSide = (ox * sunH.x + oz * sunH.z) / (w * 0.5 + 1e-3);
+ clouds.add(x + ox, base + h * height, z + oz, width * (0.46 + R() * 0.3) * (1 - h * 0.3),
+ { tile: Math.floor(R() * 3), shade: (0.7 + h * 0.5) * (1 + sunSide * 0.14), alpha: 0.97, aspect: 0.82 + R() * 0.18 });
+ }
+ };
+ const segs = [];
+ const heroP = HERO_POS0;
+ for (const I of ISLES) {
+ const c = new V3(I.pos[0], I.pos[1] + 3.5 * I.s, I.pos[2]);
+ segs.push([heroP, c], [BOOK_POS0, c]);
+ for (const da of [-0.35, 0, 0.35]) {
+ const az = I.yaw + I.az + da;
+ segs.push([new V3(c.x + Math.sin(az) * I.dist, c.y + I.h, c.z + Math.cos(az) * I.dist), c]);
+ }
+ }
+ const segDist = (p, a, b) => { const ab = tmp2.subVectors(b, a); const t = clamp(tmp3.subVectors(p, a).dot(ab) / ab.lengthSq()); return p.distanceTo(tmp4.copy(a).addScaledVector(ab, t)); };
+ let placed = 0, tries = 0;
+ while (placed < 16 && tries++ < 4000) {
+ const x = (R() - 0.5) * 150, z = 30 - R() * 150, y = -9 + R() * 22;
+ const rad = 7 + R() * 9;
+ const c = new V3(x, y, z);
+ const reach = rad * 2 + 3;
+ if (segs.some(([a, b]) => segDist(c, a, b) < reach)) continue;
+ if (ISLES.some(I => c.distanceTo(tmp.set(I.pos[0], I.pos[1] + 3, I.pos[2])) < reach + 6)) continue;
+ // nothing between the hero camera and the archipelago
+ const toC = tmp.subVectors(c, heroP), dC = toC.length();
+ if (dC < 70 && toC.normalize().dot(tmp2.subVectors(HERO_LOOK0, heroP).normalize()) > 0.55 && y + rad > -4) continue;
+ cluster(x, y, z, rad, 12 + Math.floor(R() * 10));
+ placed++;
+ }
+ // Set-piece cumulus: towers behind each island (seen from its orbit), a bed of cloud beneath it,
+ // and a few big towers on the hero horizon.
+ for (const I of ISLES) {
+ const c = new V3(I.pos[0], I.pos[1] + 3.5 * I.s, I.pos[2]);
+ const az = I.yaw + I.az;
+ const camP = new V3(c.x + Math.sin(az) * I.dist, c.y + I.h, c.z + Math.cos(az) * I.dist);
+ const d = tmp.subVectors(c, camP).setY(0).normalize().clone();
+ const side = new V3().crossVectors(d, UP).normalize();
+ const t1 = c.clone().addScaledVector(d, 70).addScaledVector(side, -I.side * 30);
+ tower(t1.x, t1.z, -10, c.y + 12, 24, 13);
+ const t2 = c.clone().addScaledVector(d, 110).addScaledVector(side, I.side * 38);
+ tower(t2.x, t2.z, -12, c.y + 18, 32, 14);
+ const bed = c.clone().addScaledVector(d, 18).add(new V3(0, -13 * I.s, 0));
+ cluster(bed.x, bed.y, bed.z, 10, 16, 0.95);
+ }
+ // towers on the hero horizon, behind the archipelago
+ for (const [x, z, h, w, n] of [[-70, -170, 52, 50, 18], [92, -190, 60, 56, 20], [-190, -120, 40, 50, 14], [200, -150, 44, 54, 14]]) tower(x, z, -12, h, w, n);
+ // Mist skirts hugging each island's roots.
+ for (const I of ISLES) {
+ for (let k = 0; k < 8; k++) {
+ const a = (k / 8) * TAU + R() * 0.5, r = (2.4 + R() * 2.2) * I.s;
+ clouds.add(I.pos[0] + Math.cos(a) * r, I.pos[1] + (0.1 + R() * 1.4) * I.s, I.pos[2] + Math.sin(a) * r, (3 + R() * 2.5) * I.s,
+ { tile: Math.floor(R() * 3), shade: 1 + R() * 0.2, alpha: 0.38, aspect: 0.6 });
+ }
+ }
+}
+// Fly-through wisps, re-seeded along every flight path.
+const wisps = [];
+for (let k = 0; k < 36; k++) { const w = clouds.add(0, -999, 0, 6, { alpha: 0 }); w.peak = 0.8; wisps.push(w); }
+let wispT = 99, wispDur = 3;
+
+// ─── Islands ──────────────────────────────────────────────────────────────────
+const pinsEl = document.querySelector('.pins');
+for (const I of ISLES) {
+ I.root = new THREE.Group();
+ I.root.position.set(...I.pos);
+ I.root.rotation.y = I.yaw;
+ I.root.scale.setScalar(I.s);
+ I.bob = new THREE.Group();
+ I.root.add(I.bob);
+ scene.add(I.root);
+ I.center = new V3(I.pos[0], I.pos[1] + 3.9 * I.s, I.pos[2]);
+ I.top = new V3(I.pos[0], I.pos[1] + 6.35 * I.s, I.pos[2]);
+ I.sphere = new THREE.Sphere(new V3(I.pos[0], I.pos[1] + 3.4 * I.s, I.pos[2]), 3.1 * I.s);
+ I.hover = { value: 0 };
+ I.hot = false;
+ I.phase = Math.random() * TAU;
+ const pin = document.createElement('div');
+ pin.className = 'pin';
+ pin.innerHTML = `<div class="pin-card"><em>${I.num}</em><b>${I.name}</b><span>${I.time}</span></div><i class="pin-stem"></i><i class="pin-dot"></i>`;
+ pinsEl.appendChild(pin);
+ I.pin = pin;
+}
+const loads = ISLES.map(I => assets.gltf(`models/atlas/${I.key}.glb`).then(g => {
+ const m = g.scene;
+ normalize(m, 6, { axis: 'y' });
+ m.updateMatrixWorld(true);
+ const mesh = firstMesh(m);
+ const rel = { value: mesh.matrixWorld.clone() };
+ prepModel(m, renderer, {
+ env: 0.5, metal: 0,
+ onMat: mat => patchAtmosphere(mat, {
+ hover: I.hover, rel,
+ fallA: I.fall ? new V3(...I.fall.boxA) : undefined, fallB: I.fall ? new V3(...I.fall.boxB) : undefined,
+ }),
+ });
+ m.traverse(o => { if (o.isMesh) o.layers.enable(1); });
+ I.bob.add(m);
+ I.model = m;
+ if (I.fall) I.bob.add(fallStream({ a: I.fall.a, b: I.fall.b, drop: I.fall.drop }));
+}));
+// Island life
+const hana = ISLES[3], lantern = ISLES[0];
+hana.bob.add(petals({ box: [[-1.5, 4.0, -1.7], [1.4, 4.9, 0.6]] }));
+const lamp = lighthouseLamp();
+lamp.position.set(0.67, 5.5, -1.1);
+lantern.bob.add(lamp);
+
+// ─── Airship & birds ─────────────────────────────────────────────────────────
+const ship = buildAirship();
+scene.add(ship);
+const SHIP = { c: new V3(12, 18, -26), rx: 52, rz: 54, w: 0.011, a: -Math.PI / 2 - 0.62 };
+const shipFwd = new V3(), shipPos = new V3();
+function placeShip(dt) {
+ SHIP.a += SHIP.w * dt;
+ const a = SHIP.a;
+ shipPos.set(SHIP.c.x + Math.cos(a) * SHIP.rx, SHIP.c.y + Math.sin(a * 2) * 2.5, SHIP.c.z + Math.sin(a) * SHIP.rz);
+ shipFwd.set(-Math.sin(a) * SHIP.rx, Math.cos(a * 2) * 5, Math.cos(a) * SHIP.rz).normalize();
+ ship.position.copy(shipPos);
+ ship.lookAt(tmp.copy(shipPos).add(shipFwd));
+ ship.rotateZ(-0.06); // leaning gently into its endless turn
+}
+// The Halcyon, the overnight sleeper, forever setting off toward the sunset.
+const halcyon = buildAirship({ a: '#f4ecdf', b: '#33436e', fin: '#ef7d5c', name: 'HALCYON' });
+halcyon.scale.setScalar(0.8);
+scene.add(halcyon);
+const HAL = { a: new V3(150, 12, -40), b: new V3(-120, 19, -95), period: 110, u: 0.3 };
+function placeHalcyon(dt, active) {
+ // it only sails while the evening is up, and always sets off from beside the sun
+ if (active) HAL.u = (HAL.u + dt / HAL.period) % 1; else HAL.u = 0.3;
+ const u = HAL.u;
+ halcyon.position.lerpVectors(HAL.a, HAL.b, u);
+ halcyon.lookAt(tmp.copy(halcyon.position).add(tmp2.subVectors(HAL.b, HAL.a)));
+}
+const dust = motes();
+scene.add(dust);
+const flock = new Flock(DBG.has('nobirds') ? 0 : 56);
+flock.scale = 0.38;
+scene.add(flock.mesh);
+
+// ─── Soft-particle depth: islands + airship only (layer 1), half resolution ─────
+const depthRT = new THREE.WebGLRenderTarget(4, 4, { depthBuffer: true });
+depthRT.depthTexture = new THREE.DepthTexture(4, 4);
+depthRT.texture.generateMipmaps = false;
+const depthMat = new THREE.MeshBasicMaterial({ colorWrite: false });
+clouds.uniforms.uDepth.value = depthRT.depthTexture;
+engine.onResize((w, h, dpr) => {
+ depthRT.setSize(Math.ceil(w * dpr * 0.5), Math.ceil(h * dpr * 0.5));
+ clouds.uniforms.uRes.value.set(w * dpr, h * dpr);
+ pointU.uResY.value = h * dpr;
+});
+function depthPass() {
+ const mask = camera.layers.mask;
+ camera.layers.set(1);
+ scene.overrideMaterial = depthMat;
+ renderer.setRenderTarget(depthRT);
+ renderer.clear();
+ renderer.render(scene, camera);
+ renderer.setRenderTarget(null);
+ scene.overrideMaterial = null;
+ camera.layers.mask = mask;
+}
+
+// ─── Stations & camera poses ─────────────────────────────────────────────────
+// 0 hero · 1–4 islands · 5 fleet · 6 booking
+const HERO = { pos: new V3(0, 6.5, 31), look: new V3(1, 5.2, 0), mpos: new V3(3, 7, 46), mlook: new V3(6, 0.5, 0) };
+if (DBG.get('hero')) { const v = DBG.get('hero').split(',').map(Number); HERO.pos.set(v[0], v[1], v[2]); HERO.look.set(v[3], v[4], v[5]); }
+const BOOK = { pos: new V3(-10, 16, 54), look: new V3(16, 9, -40), mpos: new V3(-2, 19, 76), mlook: new V3(14, 5, -40) };
+function tanHalf(fov) { return Math.tan(fov * Math.PI / 360); }
+function baseFov() { return portrait() ? 56 : 40; }
+
+function poseOf(st, t, local, out) {
+ const P = portrait();
+ out.fov = baseFov();
+ if (st === 0) {
+ out.pos.copy(P ? HERO.mpos : HERO.pos).add(tmp.set(Math.sin(t * 0.06) * 1.6, Math.sin(t * 0.045) * 0.5 - local * 1.5, -local * 5));
+ out.look.copy(P ? HERO.mlook : HERO.look);
+ } else if (st >= 1 && st <= 4) {
+ const I = ISLES[st - 1];
+ const R = I.dist * (P ? 1.45 : 1);
+ const az = I.yaw + I.az + (local - 0.5) * I.sweep + Math.sin(t * 0.09) * 0.22;
+ out.pos.set(I.center.x + Math.sin(az) * R, I.center.y + I.h * (P ? 1.25 : 1), I.center.z + Math.cos(az) * R);
+ const fwd = tmp.subVectors(I.center, out.pos).normalize();
+ const right = tmp2.crossVectors(fwd, UP).normalize();
+ out.look.copy(I.center);
+ if (P) out.look.addScaledVector(UP, -R * tanHalf(out.fov) * 0.36);
+ else out.look.addScaledVector(right, I.side * R * tanHalf(out.fov) * camera.aspect * 0.3);
+ } else if (st === 5) {
+ const off = tmp.set(P ? -15 : -13.5, P ? -0.6 : -1.2, P ? 6 : 5.5).applyQuaternion(ship.quaternion);
+ out.pos.copy(shipPos).add(off);
+ const right = tmp2.set(1, 0, 0).applyQuaternion(ship.quaternion);
+ out.look.copy(shipPos).addScaledVector(shipFwd, 0.4).addScaledVector(UP, P ? -3.6 : -0.9);
+ const toShip = tmp3.subVectors(shipPos, out.pos).normalize();
+ const camRight = tmp4.crossVectors(toShip, UP).normalize();
+ if (!P) out.look.addScaledVector(camRight, -4.2);
+ } else {
+ out.pos.copy(P ? BOOK.mpos : BOOK.pos).add(tmp.set(Math.sin(t * 0.05) * 1.2, local * 3, 0));
+ out.look.copy(P ? BOOK.mlook : BOOK.look);
+ }
+ return out;
+}
+
+// ─── Flight ────────────────────────────────────────────────────────────────────
+const cam = { pos: new V3().copy(HERO.pos).add(new V3(0, -16, 16)), look: HERO.look.clone(), fov: 40, roll: 0,
+ vel: new V3(), acc: new V3(), prev: new V3(), prevVel: new V3() };
+const pose = { pos: new V3(), look: new V3(), fov: 40 };
+const fl = { on: false, u: 0, dur: 3, st: 0, p0: new V3(), p1: new V3(), look0: new V3(), lat: new V3(), dip: new V3(), dist: 1, fov0: 40, side: 1 };
+let station = -1;
+const R2 = rng(5);
+const ease = u => u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2;
+function bez(a, b, c, d, t, out) {
+ const s = 1 - t;
+ return out.set(0, 0, 0).addScaledVector(a, s * s * s).addScaledVector(b, 3 * s * s * t).addScaledVector(c, 3 * s * t * t).addScaledVector(d, t * t * t);
+}
+function bezD(a, b, c, d, t, out) {
+ const s = 1 - t;
+ return out.set(0, 0, 0).addScaledVector(tmp4.subVectors(b, a), 3 * s * s).addScaledVector(tmp4.subVectors(c, b), 6 * s * t).addScaledVector(tmp4.subVectors(d, c), 3 * t * t);
+}
+const P1 = new V3(), P2 = new V3(), P3 = new V3(), BP = new V3(), BT = new V3();
+function controls(t) {
+ poseOf(fl.st, t, stLocal(fl.st), pose);
+ P3.copy(pose.pos);
+ const back = tmp.subVectors(pose.pos, pose.look).normalize();
+ P2.copy(P3).addScaledVector(back, fl.dist * 0.3).add(fl.lat).add(fl.dip).addScaledVector(UP, fl.dist * 0.05);
+ P1.copy(fl.p1).addScaledVector(fl.lat, 0.55).add(fl.dip);
+}
+function fly(st, { dur, intro = false } = {}) {
+ const t = engine.time;
+ fl.intro = intro;
+ poseOf(st, t, stLocal(st), pose);
+ fl.on = true; fl.u = 0; fl.st = st;
+ fl.p0.copy(cam.pos); fl.look0.copy(cam.look); fl.fov0 = cam.fov;
+ const d = tmp2.subVectors(pose.pos, cam.pos);
+ fl.dist = Math.max(d.length(), 6);
+ fl.dur = (dur ?? clamp(2.4 + fl.dist * 0.02, 2.8, 4.4)) * (REDUCED ? 0.5 : 1);
+ const dir = d.normalize();
+ if (cam.vel.length() > 2) fl.p1.copy(cam.pos).addScaledVector(cam.vel, fl.dur / 3 * 0.6);
+ else fl.p1.copy(cam.pos).addScaledVector(dir, fl.dist * 0.2).addScaledVector(UP, fl.dist * 0.06);
+ // sweep out to one side so the ship-of-a-camera banks through the turn; alternate sides
+ const lateralSign = Math.sign(tmp3.crossVectors(tmp.subVectors(cam.look, cam.pos), dir).y || 1);
+ fl.side = lateralSign;
+ fl.lat.crossVectors(dir, UP).normalize().multiplyScalar(fl.dist * 0.26 * fl.side);
+ fl.dip.set(0, -fl.dist * 0.045, 0);
+ controls(t);
+ // seed the cloud wisps along the route so every flight threads through weather
+ for (let k = 0; k < wisps.length; k++) {
+ const w = wisps[k];
+ const u = 0.16 + (k / wisps.length) * 0.46 + (R2() - 0.5) * 0.04;
+ bez(fl.p0, P1, P2, P3, u, BP);
+ bezD(fl.p0, P1, P2, P3, u, BT).normalize();
+ const side = tmp.crossVectors(BT, UP).normalize(), upv = tmp3.crossVectors(side, BT);
+ const ang = R2() * TAU, rad = k % 9 === 0 ? 0.8 + R2() * 1.2 : 2.5 + R2() * 8;
+ w.x = BP.x + side.x * Math.cos(ang) * rad + upv.x * Math.sin(ang) * rad * 0.55;
+ w.y = BP.y + side.y * Math.cos(ang) * rad + upv.y * Math.sin(ang) * rad * 0.55 - 0.6;
+ w.z = BP.z + side.z * Math.cos(ang) * rad + upv.z * Math.sin(ang) * rad * 0.55;
+ w.size = 3.5 + R2() * 7; w.tile = k % 3; w.shade = 0.95 + R2() * 0.22; w.aspect = 0.62 + R2() * 0.25;
+ w.peak = k % 9 === 0 ? 0.5 : 0.45 + R2() * 0.4;
+ }
+ wispT = 0; wispDur = fl.dur;
+ document.body.classList.add('is-flying');
+}
+
+// ─── Scroll → stations ────────────────────────────────────────────────────────
+const stops = [...document.querySelectorAll('.stop')];
+const panels = stops.map(s => s.querySelector('.panel'));
+panels.forEach(p => p.querySelectorAll('[data-rise]').forEach((el, i) => el.style.setProperty('--i', i)));
+const footEl = document.querySelector('.foot');
+const navLinks = [...document.querySelectorAll('.links a')];
+let lock = null, lockTimer = 0;
+const locals = new Array(stops.length).fill(0.5);
+function stLocal(st) { return locals[st] ?? 0.5; }
+function readScroll() {
+ const mid = innerHeight * 0.5;
+ let st = 0;
+ for (let k = 0; k < stops.length; k++) {
+ const r = stops[k].getBoundingClientRect();
+ locals[k] = clamp((mid - r.top) / r.height);
+ if (r.top <= mid) st = k;
+ }
+ return st;
+}
+const lenis = smoothScroll({ lerp: 0.08 });
+function goTo(st) {
+ if (st === fl.st && (fl.on || station === st)) return;
+ lock = st;
+ fly(st);
+ const el = stops[st];
+ const y = st === 0 ? 0 : el.offsetTop - innerHeight * 0.5 + el.offsetHeight * 0.32;
+ lenis.scrollTo(y, { duration: fl.dur * 0.85, easing: ease, onComplete: () => { lock = null; } });
+ clearTimeout(lockTimer);
+ lockTimer = setTimeout(() => { lock = null; }, fl.dur * 1000 + 700);
+}
+document.querySelectorAll('[data-go]').forEach(a => a.addEventListener('click', e => {
+ e.preventDefault();
+ const dest = a.dataset.dest;
+ if (dest) document.querySelector('.booking select[name=dest]').value = dest;
+ goTo(+a.dataset.go);
+}));
+
+// ─── Hover, pins & click-to-fly ──────────────────────────────────────────────
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+let hovered = null, overUI = false;
+const cur = cursor({ color: '#1d2742', blend: 'normal', size: 30 });
+const UI_SEL = 'a,button,input,select,label,.panel.is-on,.chart,.nav,.foot,.toast';
+addEventListener('pointerover', e => { overUI = !!e.target.closest?.(UI_SEL); });
+function pick(x, y) {
+ ndc.set(x / innerWidth * 2 - 1, -(y / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ let best = null, bd = Infinity;
+ for (const I of ISLES) {
+ if (!I.model) continue;
+ const hit = ray.ray.intersectSphere(I.sphere, tmp3);
+ if (hit) { const d = hit.distanceTo(camera.position); if (d < bd) { bd = d; best = I; } }
+ }
+ return best;
+}
+let downAt = null;
+addEventListener('pointerdown', e => { downAt = { x: e.clientX, y: e.clientY, t: performance.now(), ui: !!e.target.closest(UI_SEL) }; });
+addEventListener('pointerup', e => {
+ if (!downAt || downAt.ui || !started) return;
+ const moved = Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y);
+ downAt = null;
+ if (moved > 10) return;
+ const I = pick(e.clientX, e.clientY);
+ if (I) goTo(ISLES.indexOf(I) + 1);
+});
+
+// ─── Chart of the drift ─────────────────────────────────────────────────────
+const chartCanvas = document.querySelector('.chart-canvas');
+const cx = chartCanvas.getContext('2d');
+const chartDots = document.querySelector('.chart-dots');
+const whereEl = document.querySelector('.chart-where');
+const WHERE = ['Port Aubade', 'I · Lanternholm', 'II · Amberlea', 'III · Hollowmere', 'IV · Hanakumo', 'Zephyrine', 'Golden hour'];
+const MAPB = { z0: 22, z1: -78, x0: -30, x1: 30 };
+let CW = 248, CH = 136;
+function toMap(x, z) {
+ if (portrait()) return [0, 0];
+ return [CW * 0.07 + (MAPB.z0 - z) / (MAPB.z0 - MAPB.z1) * CW * 0.86, CH * 0.12 + (x - MAPB.x0) / (MAPB.x1 - MAPB.x0) * CH * 0.76];
+}
+ISLES.forEach((I, k) => {
+ const b = document.createElement('button');
+ b.className = 'chart-dot';
+ b.type = 'button';
+ b.setAttribute('aria-label', `Fly to ${I.name}`);
+ b.innerHTML = `<i></i><b>${I.num}</b>`;
+ b.addEventListener('click', () => goTo(k + 1));
+ b.addEventListener('pointerenter', () => { I.hot = true; });
+ b.addEventListener('pointerleave', () => { I.hot = false; });
+ chartDots.appendChild(b);
+ I.dot = b;
+});
+function layoutChart() {
+ const r = chartCanvas.getBoundingClientRect();
+ CW = r.width || 248; CH = r.height || 136;
+ chartCanvas.width = CW * 2; chartCanvas.height = CH * 2;
+ ISLES.forEach((I, k) => {
+ if (portrait()) { I.dot.style.left = `${22 + k * 42}px`; I.dot.style.top = '50%'; return; }
+ const [u, v] = toMap(I.pos[0], I.pos[2]);
+ I.dot.style.left = `${u}px`; I.dot.style.top = `${v}px`;
+ });
+}
+function drawChart(t) {
+ if (portrait()) return;
+ const g = cx;
+ g.setTransform(2, 0, 0, 2, 0, 0);
+ g.clearRect(0, 0, CW, CH);
+ // paper, latitude lines
+ g.strokeStyle = 'rgba(29,39,66,.07)'; g.lineWidth = 1;
+ for (let x = 0; x < CW; x += 24) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, CH); g.stroke(); }
+ for (let y = 0; y < CH; y += 24) { g.beginPath(); g.moveTo(0, y); g.lineTo(CW, y); g.stroke(); }
+ // airship loop
+ g.setLineDash([2, 4]); g.strokeStyle = 'rgba(239,125,92,.45)'; g.beginPath();
+ for (let k = 0; k <= 64; k++) { const a = k / 64 * TAU; const [u, v] = toMap(SHIP.c.x + Math.cos(a) * SHIP.rx, SHIP.c.z + Math.sin(a) * SHIP.rz); k ? g.lineTo(u, v) : g.moveTo(u, v); }
+ g.stroke();
+ // the tour route
+ g.setLineDash([3, 4]); g.strokeStyle = 'rgba(29,39,66,.5)'; g.lineWidth = 1.2; g.beginPath();
+ const [su, sv] = toMap(0, 26); g.moveTo(su - 16, sv);
+ ISLES.forEach(I => { const [u, v] = toMap(I.pos[0], I.pos[2]); g.lineTo(u, v); });
+ g.stroke(); g.setLineDash([]);
+ // soft island halos
+ ISLES.forEach(I => { const [u, v] = toMap(I.pos[0], I.pos[2]); const grd = g.createRadialGradient(u, v, 2, u, v, 20); grd.addColorStop(0, 'rgba(140,201,255,.55)'); grd.addColorStop(1, 'rgba(140,201,255,0)'); g.fillStyle = grd; g.beginPath(); g.arc(u, v, 20, 0, TAU); g.fill(); });
+ // the airship
+ const [au, av] = toMap(shipPos.x, shipPos.z);
+ if (au > 0 && au < CW && av > 0 && av < CH) {
+ const [bu, bv] = toMap(shipPos.x + shipFwd.x, shipPos.z + shipFwd.z);
+ g.save(); g.translate(au, av); g.rotate(Math.atan2(bv - av, bu - au));
+ g.fillStyle = '#ef7d5c'; g.beginPath(); g.ellipse(0, 0, 6, 2.6, 0, 0, TAU); g.fill(); g.restore();
+ }
+ // you are here
+ const [cu, cv] = toMap(camera.position.x, camera.position.z);
+ const dir = tmp.set(0, 0, -1).applyQuaternion(camera.quaternion);
+ const [du, dv] = toMap(camera.position.x + dir.x, camera.position.z + dir.z);
+ const ang = Math.atan2(dv - cv, du - cu);
+ g.save(); g.translate(clamp(cu, 6, CW - 6), clamp(cv, 6, CH - 6)); g.rotate(ang);
+ g.fillStyle = 'rgba(29,39,66,.12)'; g.beginPath(); g.moveTo(0, 0); g.arc(0, 0, 26, -0.45, 0.45); g.closePath(); g.fill();
+ g.fillStyle = '#1d2742'; g.beginPath(); g.moveTo(7, 0); g.lineTo(-5, -4.5); g.lineTo(-2.5, 0); g.lineTo(-5, 4.5); g.closePath(); g.fill();
+ g.restore();
+ // compass
+ g.fillStyle = 'rgba(29,39,66,.55)'; g.font = '700 8px "Nunito Sans", sans-serif'; g.fillText('N ↑', CW - 22, 12);
+}
+engine.onResize(() => layoutChart());
+
+// ─── Toast & booking ─────────────────────────────────────────────────────────
+const toastEl = document.querySelector('.toast');
+let toastTimer;
+function toast(msg, ms = 3600) { toastEl.textContent = msg; toastEl.classList.add('on'); clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms); }
+const form = document.querySelector('.booking');
+const dateIn = form.querySelector('input[type=date]');
+{ const d = new Date(Date.now() + 21 * 864e5); dateIn.value = d.toISOString().slice(0, 10); }
+form.addEventListener('submit', e => {
+ e.preventDefault();
+ const sel = form.querySelector('select[name=dest]');
+ const name = sel.options[sel.selectedIndex].text.split(' · ')[0];
+ const pax = form.querySelector('select[name=pax]').value;
+ toast(`${pax} ${pax === '1' ? 'berth' : 'berths'} to ${name} held for twenty minutes. (A demonstration — no airships were harmed.)`);
+});
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+let started = false;
+let dusk = 0;
+let shownPanel = -1;
+const shadowSize = 46;
+const vtmp = new V3(), lightDir = new V3();
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ sky.uTime.value = t;
+ renderer.shadowMap.needsUpdate = true;
+ if (!started) return;
+
+ // scroll → station
+ const want = readScroll();
+ const target = lock ?? want;
+ if (target !== (fl.on ? fl.st : station)) fly(target);
+
+ // time of day: morning over the islands, golden hour by the time you book
+ const footIn = footEl.getBoundingClientRect().top < innerHeight * 0.72;
+ document.body.classList.toggle('is-foot', footIn);
+ const duskT = (fl.on ? fl.st : station) >= 6 ? 1 : (fl.on ? fl.st : station) === 5 ? 0.3 : 0;
+ dusk = damp(dusk, duskT, 0.9, dt);
+ const e = smooth(0, 1, dusk);
+ sky.uSunDir.value.lerpVectors(DAY.skyDir, DUSK.skyDir, e).normalize();
+ const sd = lightDir.lerpVectors(DAY.dir, DUSK.dir, e).normalize();
+ sky.uZenith.value.lerpColors(DAY.zenith, DUSK.zenith, e);
+ sky.uMid.value.lerpColors(DAY.mid, DUSK.mid, e);
+ sky.uHorizon.value.lerpColors(DAY.horizon, DUSK.horizon, e);
+ sky.uBelow.value.lerpColors(DAY.below, DUSK.below, e);
+ sky.uSunCol.value.lerpColors(DAY.glow, DUSK.glow, e);
+ clouds.uniforms.uLitC.value.lerpColors(DAY.lit, DUSK.lit, e);
+ clouds.uniforms.uMidC.value.lerpColors(DAY.midC, DUSK.midC, e);
+ clouds.uniforms.uShadowC.value.lerpColors(DAY.shadow, DUSK.shadow, e);
+ sun.color.lerpColors(DAY.sun, DUSK.sun, e);
+ sun.intensity = lerp(DAY.sunI, DUSK.sunI, e);
+ hemi.intensity = lerp(DAY.hemiI, DUSK.hemiI, e);
+ sky.uFogDensity.value = lerp(0.0032, 0.0022, e);
+ sun.target.position.copy(ARCH);
+ sun.position.copy(ARCH).addScaledVector(sd, 120);
+
+ // camera
+ placeShip(dt);
+ if (fl.on) {
+ fl.u = Math.min(1, fl.u + dt / fl.dur);
+ const u = fl.u, k = ease(u);
+ controls(t);
+ bez(fl.p0, P1, P2, P3, k, cam.pos);
+ bezD(fl.p0, P1, P2, P3, k, BT).normalize();
+ // path curvature in the horizontal plane → how hard the ship-of-a-camera is turning
+ const k2 = Math.min(1, k + 0.02);
+ bezD(fl.p0, P1, P2, P3, k2, BP).normalize();
+ let dpsi = Math.atan2(BP.x, -BP.z) - Math.atan2(BT.x, -BT.z); dpsi = Math.atan2(Math.sin(dpsi), Math.cos(dpsi));
+ const kdot = (ease(Math.min(1, u + 0.005)) - ease(Math.max(0, u - 0.005))) / 0.01 / fl.dur;
+ fl.turn = (k2 > k ? dpsi / (k2 - k) : 0) * kdot;
+ const dOld = tmp.subVectors(fl.look0, cam.pos).normalize();
+ const dNew = tmp2.subVectors(pose.look, cam.pos).normalize();
+ const dir = fl.intro ? vtmp.copy(dOld).lerp(dNew, smooth(0.0, 0.7, u)).normalize()
+ : vtmp.copy(dOld).lerp(BT, smooth(0.0, 0.35, u) * 0.85).lerp(dNew, smooth(0.42, 0.92, u)).normalize();
+ // keep the horizon in frame while swooping low over the cloud sea
+ const minY = lerp(-0.12, dNew.y, smooth(0.55, 0.95, u));
+ if (dir.y < minY) { const h = Math.hypot(dir.x, dir.z) || 1, ny = minY, nh = Math.sqrt(1 - ny * ny); dir.set(dir.x / h * nh, ny, dir.z / h * nh); }
+ cam.look.copy(cam.pos).addScaledVector(dir, 14);
+ cam.fov = lerp(fl.fov0, pose.fov, k) + Math.pow(Math.sin(Math.PI * u), 2) * (REDUCED ? 0 : 13);
+ if (u >= 1) {
+ fl.on = false; station = fl.st;
+ window.__atlasReady = true;
+ cam.look.copy(pose.look);
+ document.body.classList.remove('is-flying');
+ }
+ } else if (station >= 0) {
+ poseOf(station, t, stLocal(station), pose);
+ const lam = station === 5 ? 6 : 3;
+ cam.pos.x = damp(cam.pos.x, pose.pos.x, lam, dt); cam.pos.y = damp(cam.pos.y, pose.pos.y, lam, dt); cam.pos.z = damp(cam.pos.z, pose.pos.z, lam, dt);
+ cam.look.x = damp(cam.look.x, pose.look.x, lam, dt); cam.look.y = damp(cam.look.y, pose.look.y, lam, dt); cam.look.z = damp(cam.look.z, pose.look.z, lam, dt);
+ cam.fov = damp(cam.fov, pose.fov, 3, dt);
+ }
+ // bank from lateral acceleration
+ if (dt > 0) {
+ const v = tmp.subVectors(cam.pos, cam.prev).divideScalar(dt);
+ cam.vel.lerp(v, 1 - Math.exp(-10 * dt));
+ const a = tmp2.subVectors(cam.vel, cam.prevVel).divideScalar(dt);
+ cam.acc.lerp(a, 1 - Math.exp(-5 * dt));
+ cam.prevVel.copy(cam.vel);
+ }
+ cam.prev.copy(cam.pos);
+ const fwd = tmp3.subVectors(cam.look, cam.pos).normalize();
+ const right = tmp4.crossVectors(fwd, UP).normalize();
+ const yaw = Math.atan2(fwd.x, -fwd.z);
+ let dyaw = yaw - (cam.yaw ?? yaw); dyaw = Math.atan2(Math.sin(dyaw), Math.cos(dyaw));
+ cam.yaw = yaw;
+ cam.yawRate = damp(cam.yawRate ?? 0, dt > 0 ? dyaw / dt : 0, 4, dt);
+ const bankEnv = fl.on ? Math.pow(Math.sin(Math.PI * clamp(fl.u * 1.15)), 0.7) : 0;
+ const rollT = fl.on ? clamp((cam.yawRate * 0.45 + (fl.turn ?? 0) * 0.55) * bankEnv, -0.5, 0.5) : Math.sin(t * 0.3) * 0.008;
+ cam.roll = damp(cam.roll, REDUCED ? 0 : rollT, 3.2, dt);
+ const par = fl.on ? 0.15 : 1;
+ camera.position.copy(cam.pos).addScaledVector(right, pointer.sx * 0.5 * par).addScaledVector(UP, pointer.sy * 0.3 * par);
+ camera.up.copy(UP);
+ camera.lookAt(cam.look);
+ camera.rotateZ(cam.roll);
+ if (Math.abs(camera.fov - cam.fov) > 0.01) { camera.fov = cam.fov; camera.updateProjectionMatrix(); }
+ camera.updateMatrixWorld();
+ dome.position.copy(camera.position);
+ dust.material.uniforms.uCam.value.copy(camera.position);
+
+ // wisps
+ wispT += dt;
+ const wa = smooth(0, 0.35, wispT) * (1 - smooth(wispDur * 0.72, wispDur + 0.6, wispT));
+ for (const w of wisps) w.alpha = w.peak * wa;
+
+ // islands: bob, hover glow, pins
+ const cur0 = fl.on ? fl.st : station;
+ let hit = null;
+ if (!overUI && pointer.active && !portrait()) hit = pick(pointer.px, pointer.py);
+ if (hit !== hovered) { hovered = hit; cur?.set(hit ? 'label' : '', hit ? 'Fly' : ''); }
+ for (let k = 0; k < ISLES.length; k++) {
+ const I = ISLES[k];
+ I.bob.position.y = Math.sin(t * 0.42 + I.phase) * 0.22;
+ I.bob.rotation.z = Math.sin(t * 0.31 + I.phase) * 0.012;
+ I.bob.rotation.x = Math.sin(t * 0.27 + I.phase * 2) * 0.01;
+ const hot = hovered === I || I.hot;
+ I.hover.value = damp(I.hover.value, hot ? 1 : 0, 6, dt);
+ const showAll = cur0 === 0 && !fl.on && !footIn;
+ const on = !!I.model && (showAll || (hot && cur0 !== k + 1)) && !(fl.on && fl.u < 0.9);
+ tmp.copy(I.top); tmp.y += I.bob.position.y * I.s;
+ tmp.project(camera);
+ const vis = tmp.z < 1 && Math.abs(tmp.x) < 1.05 && Math.abs(tmp.y) < 1.05;
+ I.pin.classList.toggle('on', on && vis);
+ I.pin.classList.toggle('hot', hot);
+ if (vis) {
+ const hw = (I.pinW ??= I.pin.offsetWidth || 160) / 2 + 8;
+ const px = clamp((tmp.x + 1) / 2 * innerWidth, hw, innerWidth - hw);
+ const py = Math.max((1 - tmp.y) / 2 * innerHeight, portrait() ? 190 : 150);
+ I.pin.style.transform = `translate3d(${px.toFixed(1)}px, ${py.toFixed(1)}px, 0) translate(-50%, -100%)`;
+ }
+ I.dot.classList.toggle('on', cur0 === k + 1);
+ }
+ whereEl.textContent = WHERE[cur0] ?? WHERE[0];
+ const navOn = cur0 >= 1 && cur0 <= 4 ? 0 : cur0 === 5 ? 1 : cur0 === 6 ? 2 : -1;
+ navLinks.forEach((a, i) => a.classList.toggle('is-active', i === navOn));
+
+ // birds roost around whichever island you are visiting
+ const roostI = cur0 >= 1 && cur0 <= 4 ? ISLES[cur0 - 1] : cur0 === 0 ? ISLES[0] : ISLES[2];
+ flock.setRoost(tmp.copy(roostI.center).add(tmp2.set(0, 3.5, 0)), 7 * roostI.s);
+ flock.update(Math.min(dt, 1 / 30), t);
+ ship.userData.update(dt, t);
+ placeHalcyon(dt, e > 0.5); halcyon.visible = e > 0.05; halcyon.userData.update(dt, t + 3);
+ lamp.userData.update(t, 0.12 + e * 0.9);
+
+ // panels: the destination ticket slides in as the camera settles into orbit
+ // reveal early enough that the ticket is crisp by the time the camera settles: ~40% in, never later than 1.1 s
+ let wantPanel = fl.on ? (fl.u * fl.dur > Math.min(fl.dur * 0.4, 1.1) ? fl.st : -1) : station;
+ if (footIn && wantPanel === 6) wantPanel = -1;
+ if (wantPanel !== shownPanel) {
+ panels[shownPanel]?.classList.remove('is-on');
+ panels[wantPanel]?.classList.add('is-on');
+ shownPanel = wantPanel;
+ }
+
+ drawChart(t);
+ clouds.update(camera);
+ depthPass();
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('atlas', { theme: 'light', corner: 'bl' });
+magnetic();
+layoutChart();
+window.__atlas = { fly: i => goTo(i), flyOnly: i => { lock = i; fly(i); }, engine, cam, ISLES, debug: () => ({ t: +engine.time.toFixed(2), fl: { on: fl.on, u: +fl.u.toFixed(2), dur: +fl.dur.toFixed(2), st: fl.st }, station, fps: window.__fps, lock, cam: cam.pos.toArray().map(v => +v.toFixed(1)) }) };
+
+await Promise.all(loads);
+placeShip(0);
+placeHalcyon(0, false);
+flock.setRoost(ISLES[0].center, 7);
+for (let k = 0; k < 90; k++) flock.update(1 / 30, k / 30);
+// compile everything so the first frames do not hitch, then hold the camera down in the cloud sea
+poseOf(0, 0, 0, pose);
+camera.position.copy(pose.pos); camera.lookAt(pose.look); camera.updateMatrixWorld();
+clouds.update(camera);
+renderer.compile(scene, camera);
+depthPass();
+if (portrait()) cam.pos.copy(HERO.mpos).add(new V3(0, -18, 18));
+camera.position.copy(cam.pos); camera.lookAt(cam.look); camera.updateMatrixWorld();
+clouds.update(camera);
+depthPass();
+let introDone = false;
+function beginIntro() {
+ if (introDone) return;
+ introDone = true;
+ started = true;
+ window.__atlasIntro = performance.now();
+ cam.prev.copy(cam.pos);
+ readScroll();
+ fly(readScroll(), { dur: 5.2, intro: true });
+}
+engine.start();
+document.fonts?.load('64px "Young Serif"').then(() => { ship.userData.refreshName?.(); halcyon.userData.refreshName?.(); });
+await loader.finish();
+beginIntro();
diff --git a/examples/atlas/sky.js b/examples/atlas/sky.js
new file mode 100644
index 0000000..796e774
--- /dev/null
+++ b/examples/atlas/sky.js
@@ -0,0 +1,116 @@
+// Sky dome, the shared sky-colour function and the aerial-perspective patch used by every material in the world,
+// so islands, clouds and birds all melt into exactly the colour of the sky behind them.
+import { THREE } from '../../src/core/engine.js';
+
+export const sky = {
+ uZenith: { value: new THREE.Color('#3f8fe0') },
+ uMid: { value: new THREE.Color('#7cc4ff') },
+ uHorizon: { value: new THREE.Color('#ffe4cc') },
+ uBelow: { value: new THREE.Color('#f3e4dc') },
+ uSunCol: { value: new THREE.Color('#ffd2a4') },
+ uSunDir: { value: new THREE.Vector3(-0.337, 0.174, -0.925).normalize() },
+ uFogDensity: { value: 0.0032 },
+ uFogLow: { value: new THREE.Vector3(-2, -13, 0.8) }, // start y, full y, max amount
+ uTime: { value: 0 },
+};
+
+export const SKY_GLSL = /* glsl */`
+ uniform vec3 uZenith, uMid, uHorizon, uBelow, uSunCol, uSunDir;
+ uniform float uFogDensity; uniform vec3 uFogLow; uniform float uTime;
+ vec3 skyColor(vec3 d){
+ float y = d.y;
+ vec3 c = mix(uMid, uZenith, smoothstep(0.08, 0.75, y));
+ c = mix(c, uHorizon, pow(1.0 - clamp(y + 0.02, 0.0, 1.0), 7.0));
+ c = mix(c, uBelow, smoothstep(-0.01, -0.22, y));
+ float s = max(dot(d, uSunDir), 0.0);
+ c += uSunCol * (pow(s, 5.0) * 0.22 + pow(s, 40.0) * 0.5);
+ return c;
+ }
+ vec3 atmosphere(vec3 col, vec3 worldPos){
+ vec3 dv = worldPos - cameraPosition; float dist = length(dv); vec3 dir = dv / max(dist, 1e-4);
+ float f = 1.0 - exp(-uFogDensity * dist);
+ f = max(f, smoothstep(uFogLow.x, uFogLow.y, worldPos.y) * uFogLow.z);
+ return mix(col, skyColor(dir), clamp(f, 0.0, 1.0));
+ }
+`;
+
+export function skyDome() {
+ const mat = new THREE.ShaderMaterial({
+ side: THREE.BackSide, depthWrite: false, depthTest: false, fog: false,
+ uniforms: { ...sky },
+ vertexShader: /* glsl */`varying vec3 vDir; void main(){ vDir = normalize((modelMatrix * vec4(position, 0.0)).xyz); vec4 p = projectionMatrix * viewMatrix * vec4((modelMatrix * vec4(position,1.)).xyz, 1.); gl_Position = p.xyww; }`,
+ fragmentShader: /* glsl */`${SKY_GLSL}
+ varying vec3 vDir;
+ void main(){
+ vec3 d = normalize(vDir);
+ vec3 c = skyColor(d);
+ float s = max(dot(d, uSunDir), 0.0);
+ vec3 warm = mix(uSunCol, vec3(1.0, 0.97, 0.9), 0.7);
+ c += warm * smoothstep(0.99972, 0.99988, s) * 8.0; // the disc (HDR, catches the bloom)
+ c += warm * (pow(s, 260.0) * 0.8 + pow(s, 28.0) * 0.22);
+ gl_FragColor = vec4(c, 1.0);
+ }`,
+ });
+ const dome = new THREE.Mesh(new THREE.SphereGeometry(900, 48, 24), mat);
+ dome.renderOrder = -10;
+ dome.frustumCulled = false;
+ return dome;
+}
+
+/**
+ * Patch a standard material with sky-matched aerial perspective (distance + low mist),
+ * an optional hover rim, and a waterfall flow overlay inside an island-space box.
+ */
+export function patchAtmosphere(mat, extra = {}) {
+ const u = {
+ uHover: extra.hover ?? { value: 0 },
+ uRimCol: { value: new THREE.Color('#ffd28a') },
+ uRel: extra.rel ?? { value: new THREE.Matrix4() },
+ uFallA: { value: extra.fallA ?? new THREE.Vector3(9, 9, 9) },
+ uFallB: { value: extra.fallB ?? new THREE.Vector3(9, 9, 9) },
+ uLit: extra.lit ?? { value: 0 },
+ };
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, sky, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vAtmoW; varying vec3 vIsl; uniform mat4 uRel;')
+ .replace('#include <fog_vertex>', `#include <fog_vertex>
+ vec4 aw = vec4(transformed, 1.0);
+ #ifdef USE_INSTANCING
+ aw = instanceMatrix * aw;
+ #endif
+ vAtmoW = (modelMatrix * aw).xyz; vIsl = (uRel * vec4(transformed, 1.0)).xyz;`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 vAtmoW; varying vec3 vIsl; uniform float uHover, uLit; uniform vec3 uRimCol, uFallA, uFallB;\n${SKY_GLSL}
+ float h21(vec2 p){ return fract(sin(dot(p, vec2(41.3, 289.1))) * 43758.5453); }
+ float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f*f*(3.-2.*f);
+ return mix(mix(h21(i), h21(i+vec2(1,0)), f.x), mix(h21(i+vec2(0,1)), h21(i+vec2(1,1)), f.x), f.y); }`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ // waterfall flow: bright streaks sliding down inside the sheet
+ vec3 q = vIsl;
+ float inFall = step(uFallA.x, q.x) * step(q.x, uFallB.x) * step(uFallA.y, q.y) * step(q.y, uFallB.y) * step(uFallA.z, q.z) * step(q.z, uFallB.z);
+ if (inFall > 0.5) {
+ // dissolve the sculpted sheet where it ends; the particle stream takes over from here
+ float cut = smoothstep(uFallA.y + 1.3, uFallA.y + 0.15, q.y);
+ if (h21(gl_FragCoord.xy + fract(uTime) * 17.0) < cut) discard;
+ float s1 = vn(vec2(q.x * 26.0, q.y * 1.6 + uTime * 2.6));
+ float s2 = vn(vec2(q.x * 61.0 + 3.0, q.y * 3.1 + uTime * 4.1));
+ float streak = smoothstep(0.55, 0.95, s1 * 0.6 + s2 * 0.5);
+ totalEmissiveRadiance += vec3(0.55, 0.68, 0.78) * streak * 0.6;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.78, 0.9, 1.0), 0.25);
+ }
+ }`)
+ .replace('#include <fog_fragment>', `
+ {
+ float ndv = clamp(dot(normal, normalize(vViewPosition)), 0.0, 1.0);
+ float fr = pow(1.0 - ndv, 2.6), frT = pow(1.0 - ndv, 5.0);
+ gl_FragColor.rgb += uRimCol * (fr * 0.07 + frT * uHover * 2.2);
+ gl_FragColor.rgb *= 1.0 + uHover * 0.1;
+ gl_FragColor.rgb = atmosphere(gl_FragColor.rgb, vAtmoW);
+ }`);
+ };
+ mat.customProgramCacheKey = () => 'atlas-atmo';
+ mat.userData.atmo = u;
+ return u;
+}
diff --git a/examples/atlas/style.css b/examples/atlas/style.css
new file mode 100644
index 0000000..43baf2d
--- /dev/null
+++ b/examples/atlas/style.css
@@ -0,0 +1,287 @@
+:root {
+ --sky: #7cc4ff;
+ --sky-deep: #2f6fb5;
+ --ink: #1d2742;
+ --ink-soft: #4d5a7c;
+ --ink-faint: rgba(29, 39, 66, .14);
+ --cream: #fff8ee;
+ --paper: #fbf2e4;
+ --peach: #ffcfb0;
+ --coral: #ef7d5c;
+ --coral-deep: #d9603f;
+ --gold: #d9a45a;
+ --serif: 'Young Serif', 'Iowan Old Style', Georgia, serif;
+ --sans: 'Nunito Sans', system-ui, sans-serif;
+ --ease: cubic-bezier(.2, .8, .2, 1);
+ --pad: clamp(18px, 4vw, 56px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: #9fd0ff; color: var(--ink); -webkit-font-smoothing: antialiased; }
+body { font: 400 16px/1.55 var(--sans); font-optical-sizing: auto; background: #9fd0ff; overflow-x: hidden; }
+a { color: inherit; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+
+/* ── loader ─────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; display: grid; place-items: center;
+ background: radial-gradient(120% 90% at 50% 0%, #fffaf2 0%, #fbf0e1 60%, #f6e3cf 100%); }
+.loader::after { content: ''; position: absolute; left: -2%; right: -2%; bottom: -54px; height: 110px; pointer-events: none;
+ background:
+ radial-gradient(60px 50px at 4% 20%, #f6e3cf 98%, #0000) ,
+ radial-gradient(80px 64px at 16% 30%, #f6e3cf 98%, #0000),
+ radial-gradient(70px 56px at 29% 18%, #f6e3cf 98%, #0000),
+ radial-gradient(90px 70px at 43% 34%, #f6e3cf 98%, #0000),
+ radial-gradient(70px 56px at 57% 20%, #f6e3cf 98%, #0000),
+ radial-gradient(84px 66px at 70% 30%, #f6e3cf 98%, #0000),
+ radial-gradient(64px 52px at 83% 18%, #f6e3cf 98%, #0000),
+ radial-gradient(80px 64px at 96% 28%, #f6e3cf 98%, #0000); }
+.loader-card { display: grid; justify-items: center; gap: 18px; color: var(--ink); text-align: center; padding: 0 16px; }
+.loader-mark { font: 400 clamp(44px, 6vw, 76px)/.9 var(--serif); letter-spacing: -.025em; margin-bottom: 18px; }
+.loader-mark i { display: block; font: 800 11px/1 var(--sans); letter-spacing: .32em; text-transform: uppercase; color: var(--ink-soft); margin-top: 14px; font-style: normal; }
+.loader-sub { font: 700 10.5px/1.5 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--ink-soft); opacity: .8; }
+.loader::before { content: ''; position: absolute; left: 50%; top: 50%; width: min(760px, 120vw); aspect-ratio: 1; transform: translate(-50%, -50%); opacity: .07; pointer-events: none;
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 200'%3E%3Cg fill='none' stroke='%231d2742' stroke-width='.6'%3E%3Ccircle cx='100' cy='100' r='96'/%3E%3Ccircle cx='100' cy='100' r='80'/%3E%3Ccircle cx='100' cy='100' r='40'/%3E%3Cpath d='M100 4v192M4 100h192M32 32l136 136M168 32L32 168'/%3E%3C/g%3E%3Cpath d='M100 10l8 90-8 90-8-90z' fill='%231d2742'/%3E%3C/svg%3E") center / contain no-repeat; }
+.loader-route { width: min(440px, 84vw); height: auto; color: rgba(29, 39, 66, .45); overflow: visible; }
+.loader-label { font: 700 9px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; fill: var(--ink-soft); }
+.loader-line { font: 400 21px/1 var(--serif); letter-spacing: .005em; }
+.loader-pct { font-variant-numeric: tabular-nums; display: inline-block; min-width: 2ch; text-align: right; }
+
+/* ── nav ────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between;
+ padding: 20px var(--pad); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; color: var(--ink); }
+.brand svg { width: 38px; height: 38px; }
+.brand-words { display: grid; line-height: 1; }
+.brand-words b { font: 400 23px/1 var(--serif); letter-spacing: .01em; }
+.brand-words i { font: 700 9.5px/1.2 var(--sans); letter-spacing: .24em; text-transform: uppercase; font-style: normal; color: var(--ink-soft); margin-top: 4px; }
+.links { display: flex; gap: 6px; padding: 6px; border-radius: 999px; background: rgba(255, 250, 242, .42); backdrop-filter: blur(12px) saturate(1.3);
+ box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .55); }
+.links a { text-decoration: none; font: 700 13px/1 var(--sans); padding: 10px 16px; border-radius: 999px; color: var(--ink); transition: background .3s, color .3s; }
+.links a:hover { background: rgba(255, 255, 255, .7); }
+.links a.is-active { background: var(--ink); color: var(--cream); }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 999px; border: 0; cursor: pointer;
+ text-decoration: none; font: 800 14px/1 var(--sans); letter-spacing: .01em; transition: background .35s, color .35s, box-shadow .35s, transform .35s; white-space: nowrap; }
+.btn-coral { background: var(--coral); color: #fff; box-shadow: 0 10px 24px -10px rgba(217, 96, 63, .8), inset 0 -2px 0 rgba(0, 0, 0, .12); }
+.btn-coral:hover { background: var(--coral-deep); }
+.btn-ink { background: var(--ink); color: var(--cream); box-shadow: 0 14px 30px -14px rgba(29, 39, 66, .9); }
+.btn-ink:hover { background: #2c3a60; }
+.btn-ink::after { content: '↓'; font-size: 15px; transition: transform .4s var(--ease); }
+.btn-ink:hover::after { transform: translateY(3px); }
+
+/* ── scroll track: each stop is a spacer, its panel is fixed and switched on by the camera ─────── */
+.track { position: relative; z-index: 2; }
+.stop { position: relative; height: 175vh; }
+.stop-hero { height: 150vh; }
+.stop-book { height: 150vh; }
+
+.panel { position: fixed; z-index: 10; pointer-events: none; visibility: hidden; }
+.panel.is-on { visibility: visible; pointer-events: auto; }
+.panel [data-rise] { opacity: 0; transform: translate3d(0, 18px, 0); filter: blur(3px);
+ transition: opacity .3s ease, transform .4s var(--ease), filter .3s ease; transition-delay: 0s; }
+.panel.is-on [data-rise] { opacity: 1; transform: none; filter: none; transition: opacity .5s ease, transform .7s var(--ease), filter .35s ease;
+ transition-delay: calc(var(--i, 0) * 40ms + 60ms); }
+.panel.is-leaving { visibility: visible; }
+
+.kicker { font: 800 11.5px/1.3 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--ink-soft); }
+.kicker span { color: var(--coral); margin: 0 .5em; }
+
+/* hero */
+.hero { left: var(--pad); bottom: 11vh; max-width: min(1000px, 70vw); }
+.hero .kicker { margin-bottom: 22px; }
+.hero-title { font-weight: 400; display: grid; gap: .1em; }
+.hero-line1 { font: 400 clamp(24px, 2.5vw, 40px)/1.05 var(--serif); letter-spacing: -.005em; color: var(--ink-soft); }
+.hero-line2 { font: 400 clamp(52px, min(6.6vw, 12.5vh), 118px)/.92 var(--serif); letter-spacing: -.028em; color: var(--ink); }
+.hero-line2 em { font-style: normal; color: var(--coral); position: relative; white-space: nowrap; }
+.hero-line2 em::after { content: ''; position: absolute; left: .02em; right: .1em; bottom: .02em; height: .14em;
+ background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 200 20' preserveAspectRatio='none'%3E%3Cpath d='M2 12 C 30 2, 50 2, 70 10 S 110 18, 130 9 S 175 2, 198 10' fill='none' stroke='%23ef7d5c' stroke-width='4' stroke-linecap='round'/%3E%3C/svg%3E") center / 100% 100% no-repeat; opacity: .8; }
+.hero-sub { max-width: 30em; margin-top: 26px; font: 500 clamp(16px, 1.25vw, 19px)/1.55 var(--sans); color: var(--ink); }
+.hero-cta { display: flex; align-items: center; gap: 26px; margin-top: 32px; flex-wrap: wrap; }
+.hint { display: inline-flex; align-items: center; gap: 12px; font: 700 13px/1 var(--sans); color: var(--ink); padding: 11px 16px 11px 12px; border-radius: 999px;
+ background: rgba(255, 250, 242, .55); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .6); }
+.hint-ring { position: relative; width: 14px; height: 14px; border-radius: 50%; background: var(--coral); }
+.hint-ring::before, .hint-ring::after { content: ''; position: absolute; inset: 0; border-radius: 50%; border: 2px solid var(--coral); animation: ping 2.2s var(--ease) infinite; }
+.hint-ring::after { animation-delay: 1.1s; }
+@keyframes ping { from { transform: scale(1); opacity: .9; } to { transform: scale(3.2); opacity: 0; } }
+
+/* destination tickets */
+.ticket { top: 50%; width: min(440px, 36vw); transform: translateY(-46%); padding: 26px 30px 0; border-radius: 22px;
+ background: linear-gradient(180deg, rgba(255, 251, 245, .9), rgba(252, 244, 232, .86)); backdrop-filter: blur(16px) saturate(1.25);
+ box-shadow: 0 40px 80px -40px rgba(36, 64, 120, .55), 0 2px 0 rgba(255, 255, 255, .7) inset, 0 0 0 1px rgba(255, 255, 255, .5) inset;
+ opacity: 0; clip-path: inset(0 0 100% 0 round 22px); transition: opacity .4s ease, transform .9s var(--ease), clip-path .5s cubic-bezier(.6, 0, .9, .4);
+ /* punched ticket notches at the perforation */
+ -webkit-mask: radial-gradient(circle 11px at 0 calc(100% - 89px), #0000 97%, #000) left / 51% 100% no-repeat,
+ radial-gradient(circle 11px at 100% calc(100% - 89px), #0000 97%, #000) right / 51% 100% no-repeat;
+ mask: radial-gradient(circle 11px at 0 calc(100% - 89px), #0000 97%, #000) left / 51% 100% no-repeat,
+ radial-gradient(circle 11px at 100% calc(100% - 89px), #0000 97%, #000) right / 51% 100% no-repeat; }
+.ticket.is-on { opacity: 1; clip-path: inset(0 0 0 0 round 22px); transition: opacity .25s ease, transform .7s var(--ease), clip-path .6s var(--ease); }
+.t-left { left: var(--pad); }
+.t-right { right: var(--pad); top: auto; bottom: 236px; transform: none; }
+@media (max-height: 880px) and (min-width: 761px) { .ticket .t-facts { display: none; } .ticket { width: min(420px, 36vw); } }
+@media (max-height: 760px) and (min-width: 761px) { .ticket .t-list { display: none; } }
+.t-left:not(.is-on) { transform: translate(-30px, -46%); }
+.t-right:not(.is-on) { transform: translate(30px, 0); }
+.t-head { display: flex; align-items: center; gap: 12px; font: 800 10.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink-soft);
+ padding-bottom: 16px; border-bottom: 1px solid var(--ink-faint); }
+.t-num { display: grid; place-items: center; min-width: 30px; height: 30px; padding: 0 6px; border-radius: 999px; background: var(--ink); color: var(--cream); font: 400 13px/1 var(--serif); letter-spacing: 0; }
+.t-route i { font-style: normal; color: var(--coral); margin: 0 .3em; }
+.t-code { margin-left: auto; color: var(--coral); }
+.t-name { font: 400 clamp(40px, 4.2vw, 64px)/1 var(--serif); letter-spacing: -.02em; margin-top: 22px; }
+.t-meta { margin-top: 10px; font: 600 15px/1.3 var(--sans); color: var(--ink-soft); }
+.t-meta b { color: var(--ink); font-weight: 900; }
+.t-meta span { color: var(--coral); margin: 0 .35em; }
+.t-lede { margin-top: 16px; font: 400 16px/1.6 var(--sans); color: var(--ink); }
+.t-list { list-style: none; margin-top: 16px; display: grid; gap: 7px; }
+.t-list li { position: relative; padding-left: 24px; font: 600 14.5px/1.4 var(--sans); color: var(--ink); }
+.t-list li::before { content: ''; position: absolute; left: 2px; top: .38em; width: 11px; height: 11px; border-radius: 50%;
+ background: radial-gradient(circle at 50% 50%, var(--coral) 0 35%, #0000 38%), radial-gradient(circle, #0000 58%, rgba(239, 125, 92, .45) 60% 72%, #0000 74%); }
+.t-facts { display: grid; grid-template-columns: repeat(3, 1fr); margin-top: 20px; border-top: 1px solid var(--ink-faint); padding-top: 14px; gap: 8px; }
+.t-facts dt { font: 800 9.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink-soft); }
+.t-facts dd { margin-top: 6px; font: 400 15px/1.2 var(--serif); }
+.t-stub { position: relative; display: flex; align-items: center; gap: 16px; height: 88px; margin: 22px -30px 0; padding: 0 30px;
+ border-top: 2px dashed rgba(29, 39, 66, .2); background: rgba(255, 207, 176, .22); border-radius: 0 0 22px 22px; }
+.t-price { display: grid; grid-template-columns: auto auto; align-items: baseline; column-gap: 6px; line-height: 1; }
+.t-price small { grid-column: 1 / -1; font: 800 9.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink-soft); margin-bottom: 6px; }
+.t-price b { font: 400 40px/1 var(--serif); letter-spacing: -.02em; }
+.t-price span { font: 700 13px/1 var(--sans); color: var(--ink-soft); }
+.t-when { font: 700 12px/1.3 var(--sans); color: var(--ink-soft); margin-left: auto; text-align: right; }
+.t-stub .btn { height: 44px; padding: 0 20px; }
+
+/* fleet */
+.fleet { left: var(--pad); top: max(96px, 14vh); width: min(560px, 42vw); }
+.fleet-title { font: 400 clamp(32px, min(3.9vw, 6.8vh), 62px)/1.02 var(--serif); letter-spacing: -.02em; margin-top: 14px; }
+.fleet-lede { margin-top: 18px; font: 500 17px/1.55 var(--sans); max-width: 30em; }
+.ships { list-style: none; display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 28px; width: min(760px, 60vw); }
+.ship { padding: 18px 18px 20px; border-radius: 18px; background: rgba(255, 250, 242, .72); backdrop-filter: blur(14px); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .6); }
+.ship.is-here { background: rgba(255, 250, 242, .92); box-shadow: inset 0 0 0 1.5px var(--coral); }
+.ship-tag { font: 800 9.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--coral); }
+.ship h3 { font: 400 26px/1 var(--serif); margin-top: 12px; }
+.ship p { font: 700 12.5px/1.35 var(--sans); color: var(--ink-soft); margin-top: 6px; }
+.ship .ship-note { font: 500 13.5px/1.45 var(--sans); color: var(--ink); margin-top: 10px; }
+.fleet-stats { display: flex; gap: 34px; margin-top: 26px; }
+.fleet-stats dt { font: 400 28px/1 var(--serif); }
+.fleet-stats dd { font: 700 12px/1.3 var(--sans); color: var(--ink-soft); margin-top: 6px; max-width: 12em; }
+
+/* booking */
+.book { left: var(--pad); top: max(96px, calc(50% - 340px)); width: min(620px, 48vw); }
+@media (max-height: 780px) and (min-width: 761px) { .book-lede, .book-note { display: none; } .booking { margin-top: 20px; } }
+.book-title { font: 400 clamp(38px, min(4.9vw, 8.4vh), 82px)/.98 var(--serif); letter-spacing: -.025em; margin-top: 14px; color: var(--ink); }
+.book-lede { margin-top: 20px; font: 500 17px/1.55 var(--sans); max-width: 28em; }
+.booking { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 30px; padding: 14px; border-radius: 22px;
+ background: rgba(255, 250, 242, .82); backdrop-filter: blur(16px) saturate(1.2); box-shadow: 0 30px 60px -30px rgba(80, 50, 60, .5), inset 0 0 0 1px rgba(255, 255, 255, .6); }
+.field { display: grid; gap: 6px; padding: 12px 16px; border-radius: 14px; background: rgba(255, 255, 255, .7); box-shadow: inset 0 0 0 1px var(--ink-faint); }
+.field span { font: 800 9.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink-soft); }
+.field input, .field select { font: 400 18px/1.2 var(--serif); color: var(--ink); background: none; border: 0; outline: none; width: 100%; appearance: none; -webkit-appearance: none; }
+.field select { cursor: pointer; padding-right: 20px; text-overflow: ellipsis; background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' fill='none' stroke='%231d2742' stroke-width='1.6'/%3E%3C/svg%3E") right 2px center / 12px no-repeat; }
+.field:focus-within { box-shadow: inset 0 0 0 1.5px var(--coral); }
+.btn-big { grid-column: 1 / -1; height: 56px; font-size: 15px; border-radius: 14px; }
+.book-note { margin-top: 16px; font: 600 12.5px/1.5 var(--sans); color: var(--ink-soft); max-width: 36em; }
+
+/* ── footer ─────────────────────────────────────────── */
+.foot { position: relative; z-index: 12; background: var(--paper); color: var(--ink); padding: 40px var(--pad) 90px; }
+.foot-cloud { position: absolute; left: 0; right: 0; top: -58px; height: 60px; pointer-events: none;
+ background:
+ radial-gradient(70px 52px at 3% 100%, var(--paper) 98%, #0000), radial-gradient(90px 60px at 13% 100%, var(--paper) 98%, #0000),
+ radial-gradient(64px 44px at 22% 100%, var(--paper) 98%, #0000), radial-gradient(110px 58px at 33% 100%, var(--paper) 98%, #0000),
+ radial-gradient(70px 40px at 45% 100%, var(--paper) 98%, #0000), radial-gradient(96px 56px at 56% 100%, var(--paper) 98%, #0000),
+ radial-gradient(76px 46px at 67% 100%, var(--paper) 98%, #0000), radial-gradient(104px 60px at 79% 100%, var(--paper) 98%, #0000),
+ radial-gradient(70px 42px at 90% 100%, var(--paper) 98%, #0000), radial-gradient(84px 56px at 99% 100%, var(--paper) 98%, #0000); }
+.foot-inner { max-width: 1320px; margin: 0 auto; }
+.foot-mark { font: 400 clamp(64px, 11vw, 190px)/.9 var(--serif); letter-spacing: -.035em; }
+.foot-mark i { font-style: normal; display: block; font-size: .32em; letter-spacing: -.01em; color: var(--ink-soft); margin-top: .2em; }
+.foot-cols { display: grid; grid-template-columns: repeat(4, 1fr); gap: 40px; margin-top: 70px; padding-top: 34px; border-top: 1px solid var(--ink-faint); }
+.foot-cols h4 { font: 800 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--coral); margin-bottom: 14px; }
+.foot-cols p { font: 500 15px/1.8 var(--sans); color: var(--ink); }
+.foot-cols a { text-decoration: none; border-bottom: 1px solid var(--ink-faint); transition: border-color .3s; }
+.foot-cols a:hover { border-color: var(--coral); }
+.foot-small { display: flex; justify-content: space-between; gap: 20px; margin-top: 60px; font: 700 11px/1.4 var(--sans); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-soft); padding-left: 190px; }
+
+/* ── pins over islands ──────────────────────────────── */
+.pins { position: fixed; inset: 0; z-index: 8; pointer-events: none; }
+.pin { position: absolute; left: 0; top: 0; display: grid; justify-items: center; opacity: 0; transition: opacity .45s ease; will-change: transform; }
+.pin.on { opacity: 1; }
+.pin-card { display: flex; align-items: baseline; gap: 8px; padding: 8px 13px 9px; border-radius: 999px; background: rgba(255, 250, 242, .88); backdrop-filter: blur(8px);
+ box-shadow: 0 10px 24px -12px rgba(29, 39, 66, .55), inset 0 0 0 1px rgba(255, 255, 255, .7); white-space: nowrap; transform-origin: 50% 100%; transition: transform .45s var(--ease), background .3s; }
+.pin-card b { font: 400 16px/1 var(--serif); }
+.pin-card span { font: 800 10px/1 var(--sans); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-soft); }
+.pin-card em { font: 400 11px/1 var(--serif); font-style: normal; color: var(--coral); }
+.pin-stem { width: 1.5px; height: 30px; background: linear-gradient(rgba(29, 39, 66, .6), rgba(29, 39, 66, 0)); }
+.pin-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink); margin-top: -3px; box-shadow: 0 0 0 4px rgba(255, 250, 242, .5); }
+.pin.hot .pin-card { transform: scale(1.12); background: #fff; }
+.pin.hot .pin-card::after { content: 'Fly there →'; font: 800 10px/1 var(--sans); letter-spacing: .12em; text-transform: uppercase; color: var(--coral); margin-left: 4px; }
+
+/* ── chart of the drift ─────────────────────────────── */
+.chart { position: fixed; right: var(--pad); bottom: 22px; z-index: 20; width: 272px; padding: 12px 12px 12px; border-radius: 20px;
+ background: rgba(255, 250, 242, .78); backdrop-filter: blur(14px) saturate(1.2); box-shadow: 0 24px 50px -28px rgba(29, 39, 66, .6), inset 0 0 0 1px rgba(255, 255, 255, .65);
+ transition: opacity .6s, transform .6s var(--ease); }
+.chart-title { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; padding: 2px 6px 10px; }
+.chart-title span { font: 800 9.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink-soft); }
+.chart-where { font: 400 13px/1 var(--serif); font-style: normal; color: var(--ink); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.chart-map { position: relative; height: 136px; border-radius: 12px; overflow: hidden; background: #f7ecdb; }
+.chart-canvas { position: absolute; inset: 0; width: 100%; height: 100%; }
+.chart-dots { position: absolute; inset: 0; }
+.chart-dot { position: absolute; width: 30px; height: 30px; margin: -15px 0 0 -15px; border-radius: 50%; border: 0; background: none; cursor: pointer;
+ display: grid; place-items: center; font: 400 11px/1 var(--serif); color: var(--ink); }
+.chart-dot i { position: absolute; inset: 7px; border-radius: 50%; background: var(--cream); box-shadow: 0 0 0 1.5px var(--ink); transition: transform .35s var(--ease), background .3s; }
+.chart-dot b { position: relative; font-weight: 400; }
+.chart-dot:hover i { transform: scale(1.25); }
+.chart-dot.on i { background: var(--coral); box-shadow: 0 0 0 1.5px var(--coral-deep), 0 0 0 6px rgba(239, 125, 92, .25); }
+.chart-dot.on b { color: #fff; }
+.is-foot .chart { opacity: 0; transform: translateY(20px); pointer-events: none; }
+
+.toast { position: fixed; left: 50%; bottom: 28px; transform: translate(-50%, 16px); z-index: 40; padding: 14px 22px; border-radius: 999px; background: var(--ink); color: var(--cream);
+ font: 700 14px/1.3 var(--sans); opacity: 0; pointer-events: none; transition: opacity .45s, transform .45s var(--ease); box-shadow: 0 20px 40px -18px rgba(29, 39, 66, .8); max-width: calc(100vw - 32px); text-align: center; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+.is-flying .hint { opacity: .0; }
+
+/* ── mobile ─────────────────────────────────────────── */
+@media (max-width: 760px) {
+ .nav { padding: 14px 16px; }
+ .brand svg { width: 32px; height: 32px; }
+ .brand-words b { font-size: 20px; }
+ .brand-words i { font-size: 8.5px; letter-spacing: .2em; }
+ .links { display: none; }
+ .nav .btn { height: 38px; padding: 0 15px; font-size: 12.5px; }
+ .hero { left: 16px; right: 16px; bottom: 76px; max-width: none; }
+ .hero .kicker { font-size: 10px; margin-bottom: 14px; }
+ .hero-line1 { font-size: 22px; }
+ .hero-line2 { font-size: 50px; }
+ .hero-sub { font-size: 15px; margin-top: 16px; }
+ .hero-cta { gap: 12px; margin-top: 20px; }
+ .hero-cta .btn { height: 42px; }
+ .hint { font-size: 12px; padding: 9px 12px 9px 10px; }
+ .ticket { top: auto; bottom: 62px; left: 12px; right: 12px; width: auto; transform: none; padding: 18px 20px 0; border-radius: 18px; }
+ .t-left:not(.is-on), .t-right:not(.is-on) { transform: translateY(30px); }
+ .t-name { font-size: 38px; margin-top: 14px; }
+ .t-lede { font-size: 14px; margin-top: 10px; line-height: 1.5; }
+ .t-list, .t-facts, .t-when { display: none; }
+ .t-head { font-size: 9px; padding-bottom: 12px; }
+ .t-stub { margin: 14px -20px 0; padding: 14px 20px 16px; border-radius: 0 0 18px 18px; }
+ .t-price b { font-size: 32px; }
+ .t-stub .btn { margin-left: auto; height: 40px; }
+ .fleet { left: 16px; right: 16px; top: auto; bottom: 62px; width: auto; }
+ .fleet-title { font-size: 32px; }
+ .fleet-lede { font-size: 14.5px; }
+ .ships { grid-template-columns: 1fr; width: auto; gap: 8px; margin-top: 16px; }
+ .ship:not(.is-here) { display: none; }
+ .ship .ship-note { display: none; }
+ .fleet-stats { display: none; }
+ .book { left: 16px; right: 16px; top: auto; bottom: 62px; transform: none; width: auto; }
+ .book-title { font-size: 36px; }
+ .book-lede { font-size: 14.5px; }
+ .booking { grid-template-columns: 1fr 1fr; margin-top: 18px; padding: 10px; gap: 8px; }
+ .field { padding: 10px 12px; }
+ .field input, .field select { font-size: 15px; }
+ .book-note { display: none; }
+ .chart { right: auto; left: 50%; top: 66px; bottom: auto; transform: translateX(-50%); width: auto; padding: 5px; border-radius: 999px; }
+ .chart-title { display: none; }
+ .chart-map { height: 34px; width: 170px; background: none; overflow: visible; }
+ .chart-canvas { display: none; }
+ .is-foot .chart { transform: translate(-50%, -10px); }
+ .foot-cols { grid-template-columns: 1fr 1fr; gap: 28px; }
+ .foot-small { flex-direction: column; padding-left: 0; padding-bottom: 40px; }
+ .pin-card span, .pin-card em { display: none; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .panel [data-rise], .panel.is-on [data-rise] { transition: opacity .4s ease; transform: none; filter: none; }
+}
diff --git a/examples/atlas/water.js b/examples/atlas/water.js
new file mode 100644
index 0000000..29f7696
--- /dev/null
+++ b/examples/atlas/water.js
@@ -0,0 +1,183 @@
+// Particle life on the islands: waterfall streams that keep falling where the sculpted sheet ends,
+// drifting blossom from Hanakumo, and the lighthouse lamp.
+import { THREE } from '../../src/core/engine.js';
+import { sky, SKY_GLSL } from './sky.js';
+
+export const pointU = { uResY: { value: 900 }, uDpr: { value: 1 } };
+
+/** A waterfall continuing from a lip segment (island-local space) down into the cloud sea. */
+export function fallStream({ a, b, drop = 16, count = 5000, push = 1 }) {
+ const seed = new Float32Array(count * 4);
+ for (let i = 0; i < count; i++) seed.set([Math.random(), Math.random(), Math.random(), Math.random()], i * 4);
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3));
+ geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 4));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { ...sky, ...pointU, uA: { value: new THREE.Vector3(...a) }, uB: { value: new THREE.Vector3(...b) }, uDrop: { value: drop }, uPush: { value: push } },
+ vertexShader: /* glsl */`
+ uniform float uTime, uResY, uDpr, uDrop, uPush; uniform vec3 uA, uB;
+ attribute vec4 aSeed;
+ varying float vA; varying vec3 vW; varying float vLife;
+ void main(){
+ float life = fract(uTime * (0.1 + aSeed.z * 0.06) + aSeed.y);
+ vec3 p = mix(uA, uB, aSeed.x);
+ float f = life;
+ p.y -= f * f * uDrop * 0.7 + f * uDrop * 0.3;
+ p.z += (f * (0.35 + aSeed.w * 0.9) + f * f * 1.5) * uPush;
+ p.x += (aSeed.x - 0.5) * f * 1.8 + sin(uTime * 1.3 + aSeed.y * 20.0) * f * 0.35;
+ vec4 w = modelMatrix * vec4(p, 1.0);
+ vW = w.xyz;
+ vec4 mv = viewMatrix * w;
+ gl_Position = projectionMatrix * mv;
+ float sz = mix(0.16, 2.2, pow(f, 1.5)) * (0.5 + aSeed.w);
+ gl_PointSize = sz * projectionMatrix[1][1] * uResY * 0.5 / -mv.z;
+ vA = smoothstep(0.0, 0.03, f) * pow(1.0 - f, 1.1) * mix(1.0, 0.35, smoothstep(0.1, 0.6, f));
+ vLife = f;
+ }`,
+ fragmentShader: /* glsl */`
+ ${SKY_GLSL}
+ varying float vA; varying vec3 vW; varying float vLife;
+ void main(){
+ vec2 c = gl_PointCoord - 0.5;
+ float d = length(c);
+ // early on each drop is a vertical streak, later a soft ball of spray
+ float stretch = mix(3.2, 1.0, smoothstep(0.0, 0.45, vLife));
+ float a = smoothstep(0.5, 0.0, length(c * vec2(stretch, 1.0)));
+ vec3 col = mix(vec3(0.86, 0.95, 1.05), vec3(1.0, 0.98, 0.96), vLife);
+ col = atmosphere(col, vW);
+ gl_FragColor = vec4(col, a * vA * 0.7);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 4;
+ return pts;
+}
+
+/** Blossom that lifts off Hanakumo's cherry trees and drifts away on the wind. */
+export function petals({ box, count = 700, wind = [3.2, -0.25, 1.4] }) {
+ const seed = new Float32Array(count * 4), base = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) {
+ seed.set([Math.random(), Math.random(), Math.random(), Math.random()], i * 4);
+ base.set([THREE.MathUtils.lerp(box[0][0], box[1][0], Math.random()), THREE.MathUtils.lerp(box[0][1], box[1][1], Math.random()), THREE.MathUtils.lerp(box[0][2], box[1][2], Math.random())], i * 3);
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(base, 3));
+ geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 4));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { ...sky, ...pointU, uWind: { value: new THREE.Vector3(...wind) } },
+ vertexShader: /* glsl */`
+ uniform float uTime, uResY; uniform vec3 uWind;
+ attribute vec4 aSeed;
+ varying float vA; varying vec3 vW; varying float vRot;
+ void main(){
+ float life = fract(uTime * (0.045 + aSeed.z * 0.03) + aSeed.y);
+ vec3 p = position;
+ float T = life * 9.0;
+ p += uWind * T;
+ p.y -= T * T * 0.05;
+ p.x += sin(uTime * 1.7 + aSeed.x * 30.0) * 0.25 * life;
+ p.z += cos(uTime * 1.3 + aSeed.w * 30.0) * 0.25 * life;
+ vec4 w = modelMatrix * vec4(p, 1.0);
+ vW = w.xyz;
+ vec4 mv = viewMatrix * w;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (0.07 + aSeed.w * 0.05) * projectionMatrix[1][1] * uResY * 0.5 / -mv.z;
+ vA = smoothstep(0.0, 0.08, life) * (1.0 - smoothstep(0.7, 1.0, life));
+ vRot = uTime * (1.5 + aSeed.x * 3.0) + aSeed.z * 6.28;
+ }`,
+ fragmentShader: /* glsl */`
+ ${SKY_GLSL}
+ varying float vA; varying vec3 vW; varying float vRot;
+ void main(){
+ vec2 c = gl_PointCoord - 0.5;
+ float cr = cos(vRot), sr = sin(vRot);
+ c = mat2(cr, -sr, sr, cr) * c;
+ c.x *= 1.0 + 0.9 * abs(sin(vRot * 0.7)); // tumbling: the ellipse thins as it turns edge-on
+ float d = length(c * vec2(1.0, 1.8));
+ float a = smoothstep(0.5, 0.36, d);
+ vec3 col = mix(vec3(1.0, 0.66, 0.76), vec3(1.0, 0.86, 0.9), c.y + 0.5);
+ col = atmosphere(col, vW);
+ gl_FragColor = vec4(col, a * vA);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 4;
+ return pts;
+}
+
+function glowTexture() {
+ const c = document.createElement('canvas'); c.width = c.height = 128;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ grd.addColorStop(0, 'rgba(255,255,255,1)'); grd.addColorStop(0.18, 'rgba(255,236,200,.7)'); grd.addColorStop(0.5, 'rgba(255,200,140,.15)'); grd.addColorStop(1, 'rgba(255,200,140,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
+}
+
+/** The Lanternholm lamp: a glow and a slow sweeping beam (faint by day, it comes up at golden hour). */
+export function lighthouseLamp() {
+ const g = new THREE.Group();
+ const glow = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTexture(), color: new THREE.Color('#ffd89a').multiplyScalar(3), blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }));
+ glow.scale.setScalar(0.9);
+ g.add(glow);
+ const beamGeo = new THREE.CylinderGeometry(0.06, 1.5, 16, 24, 1, true);
+ beamGeo.translate(0, 8, 0);
+ beamGeo.rotateZ(-Math.PI / 2);
+ const beamMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ uniforms: { uPower: { value: 0.25 } },
+ vertexShader: 'varying vec3 vN; varying vec3 vV; varying float vX; void main(){ vX = position.x / 16.0; vec4 mv = modelViewMatrix * vec4(position,1.); vV = normalize(-mv.xyz); vN = normalize(normalMatrix * normal); gl_Position = projectionMatrix * mv; }',
+ fragmentShader: 'uniform float uPower; varying vec3 vN; varying vec3 vV; varying float vX; void main(){ float f = pow(abs(dot(vN, vV)), 1.6); float a = f * (1.0 - smoothstep(0.0, 1.0, vX)) * smoothstep(0.0, 0.04, vX); gl_FragColor = vec4(vec3(1.0, 0.86, 0.6) * a * uPower, 1.0); }',
+ });
+ const beam = new THREE.Group();
+ const b1 = new THREE.Mesh(beamGeo, beamMat), b2 = new THREE.Mesh(beamGeo, beamMat);
+ b2.rotation.y = Math.PI;
+ beam.add(b1, b2);
+ g.add(beam);
+ g.userData.update = (t, power) => { beam.rotation.y = t * 0.6; beamMat.uniforms.uPower.value = power; glow.material.opacity = 0.6 + power; };
+ return g;
+}
+
+/** Sunlit pollen and dust drifting around the camera: tiny warm motes that give the air some depth. */
+export function motes({ count = 700, box = 34 } = {}) {
+ const seed = new Float32Array(count * 4), pos = new Float32Array(count * 3);
+ for (let i = 0; i < count; i++) { seed.set([Math.random(), Math.random(), Math.random(), Math.random()], i * 4); pos.set([Math.random(), Math.random(), Math.random()], i * 3); }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 4));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { ...sky, ...pointU, uBox: { value: box }, uCam: { value: new THREE.Vector3() }, uAmt: { value: 1 } },
+ vertexShader: /* glsl */`
+ uniform float uTime, uResY, uBox, uAmt; uniform vec3 uCam;
+ attribute vec4 aSeed;
+ varying float vA;
+ void main(){
+ // a box of motes that wraps around the camera so it never runs out
+ vec3 p = position * uBox + vec3(uTime * 0.35, sin(uTime * 0.2 + aSeed.x * 6.0) * 0.6, uTime * 0.12) + aSeed.xyz * 3.0;
+ p = mod(p - uCam + uBox * 0.5, uBox) + uCam - uBox * 0.5;
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ float d = -mv.z;
+ gl_PointSize = (0.035 + aSeed.w * 0.05) * projectionMatrix[1][1] * uResY * 0.5 / d;
+ float tw = 0.55 + 0.45 * sin(uTime * (1.0 + aSeed.y * 2.0) + aSeed.z * 30.0);
+ vA = smoothstep(0.5, 3.0, d) * (1.0 - smoothstep(uBox * 0.3, uBox * 0.5, d)) * tw * uAmt;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uSunCol;
+ varying float vA;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ float a = smoothstep(0.5, 0.0, d);
+ gl_FragColor = vec4(mix(uSunCol, vec3(1.0), 0.5) * a * vA * 0.9, 1.0);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 6;
+ return pts;
+}
diff --git a/examples/ember/audio.js b/examples/ember/audio.js
new file mode 100644
index 0000000..b339d0d
--- /dev/null
+++ b/examples/ember/audio.js
@@ -0,0 +1,139 @@
+// Synthesised forge sounds. Nothing plays until the visitor clicks; everything routes through one master gain
+// so the nav toggle can silence it instantly.
+export class ForgeAudio {
+ constructor() {
+ this.enabled = true;
+ this.ctx = null;
+ }
+
+ ensure() {
+ if (this.ctx) { if (this.ctx.state === 'suspended') this.ctx.resume(); return this.ctx; }
+ try {
+ const ctx = this.ctx = new (window.AudioContext || window.webkitAudioContext)();
+ this.master = ctx.createGain();
+ this.master.gain.value = this.enabled ? 0.8 : 0;
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -14; comp.ratio.value = 4; comp.attack.value = 0.002; comp.release.value = 0.2;
+ this.master.connect(comp).connect(ctx.destination);
+ // Stone room: a short synthetic impulse response.
+ this.verb = ctx.createConvolver();
+ const len = ctx.sampleRate * 1.9, ir = ctx.createBuffer(2, len, ctx.sampleRate);
+ for (let c = 0; c < 2; c++) {
+ const d = ir.getChannelData(c);
+ for (let i = 0; i < len; i++) { const k = i / len; d[i] = (Math.random() * 2 - 1) * Math.pow(1 - k, 3.2) * (i < 900 ? i / 900 : 1); }
+ }
+ this.verb.buffer = ir;
+ this.verbGain = ctx.createGain(); this.verbGain.gain.value = 0.32;
+ this.verb.connect(this.verbGain).connect(this.master);
+ this.noise = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
+ const nd = this.noise.getChannelData(0);
+ for (let i = 0; i < nd.length; i++) nd[i] = Math.random() * 2 - 1;
+ this._ambient();
+ return ctx;
+ } catch { this.ctx = null; return null; }
+ }
+
+ setEnabled(on) {
+ this.enabled = on;
+ if (this.master) this.master.gain.setTargetAtTime(on ? 0.8 : 0, this.ctx.currentTime, 0.05);
+ }
+
+ _out(node, wet = 1) { node.connect(this.master); const s = this.ctx.createGain(); s.gain.value = wet; node.connect(s).connect(this.verb); }
+
+ /** Hammer on hot steel over an anvil: a dull thud, a bright inharmonic ring, a spit of noise. */
+ clang(power = 1, heat = 0.6) {
+ const ctx = this.ensure(); if (!ctx) return;
+ const t = ctx.currentTime + 0.005;
+ const pan = ctx.createStereoPanner(); pan.pan.value = (Math.random() - 0.5) * 0.3;
+ const bus = ctx.createGain(); bus.gain.value = 0.55 * (0.6 + power * 0.4);
+ bus.connect(pan); this._out(pan, 0.9);
+ // Anvil ring: inharmonic partials of a thick steel bar. Hot steel damps the ring a little.
+ const f0 = 540 + Math.random() * 60;
+ const partials = [[1, 1, 1.3], [2.76, 0.55, 0.9], [5.4, 0.32, 0.55], [8.93, 0.2, 0.32], [13.34, 0.12, 0.2], [1.51, 0.25, 0.7]];
+ const damp = 1 - heat * 0.35;
+ for (const [r, a, d] of partials) {
+ const o = ctx.createOscillator(); o.type = 'sine';
+ o.frequency.value = f0 * r * (1 + (Math.random() - 0.5) * 0.004);
+ const g = ctx.createGain();
+ g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a * 0.5, t + 0.002);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + d * damp * (0.8 + Math.random() * 0.3));
+ o.connect(g).connect(bus); o.start(t); o.stop(t + 1.6);
+ }
+ // Body thud.
+ const th = ctx.createOscillator(); th.type = 'sine';
+ th.frequency.setValueAtTime(140, t); th.frequency.exponentialRampToValueAtTime(48, t + 0.18);
+ const tg = ctx.createGain(); tg.gain.setValueAtTime(0.9, t); tg.gain.exponentialRampToValueAtTime(0.001, t + 0.24);
+ th.connect(tg).connect(bus); th.start(t); th.stop(t + 0.3);
+ // Impact transient + scale spit.
+ const n = ctx.createBufferSource(); n.buffer = this.noise; n.playbackRate.value = 1.3;
+ const hp = ctx.createBiquadFilter(); hp.type = 'bandpass'; hp.frequency.value = 3200; hp.Q.value = 0.7;
+ const ng = ctx.createGain(); ng.gain.setValueAtTime(0.7, t); ng.gain.exponentialRampToValueAtTime(0.001, t + 0.09);
+ n.connect(hp).connect(ng).connect(bus); n.start(t, Math.random()); n.stop(t + 0.12);
+ const s = ctx.createBufferSource(); s.buffer = this.noise;
+ const sf = ctx.createBiquadFilter(); sf.type = 'highpass'; sf.frequency.value = 5200;
+ const sg = ctx.createGain(); sg.gain.setValueAtTime(0.0, t); sg.gain.linearRampToValueAtTime(0.12 * heat, t + 0.03); sg.gain.exponentialRampToValueAtTime(0.001, t + 0.6);
+ s.connect(sf).connect(sg).connect(bus); s.start(t, Math.random()); s.stop(t + 0.7);
+ }
+
+ /** Continuous bellows breath while held. */
+ bellows(on) {
+ const ctx = this.ensure(); if (!ctx) return;
+ const t = ctx.currentTime;
+ if (on && !this._bel) {
+ const src = ctx.createBufferSource(); src.buffer = this.noise; src.loop = true;
+ const lp = ctx.createBiquadFilter(); lp.type = 'bandpass'; lp.frequency.value = 420; lp.Q.value = 0.6;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(0.5, t + 0.35);
+ src.connect(lp).connect(g); this._out(g, 0.4);
+ // Pumping: the breath swells and dips.
+ const lfo = ctx.createOscillator(); lfo.frequency.value = 1.1;
+ const lg = ctx.createGain(); lg.gain.value = 0.22; lfo.connect(lg).connect(g.gain);
+ const lf2 = ctx.createGain(); lf2.gain.value = 180; lfo.connect(lf2).connect(lp.frequency);
+ src.start(); lfo.start();
+ this._bel = { src, g, lfo };
+ } else if (!on && this._bel) {
+ const b = this._bel; this._bel = null;
+ b.g.gain.cancelScheduledValues(t); b.g.gain.setTargetAtTime(0, t, 0.12);
+ b.src.stop(t + 0.8); b.lfo.stop(t + 0.8);
+ }
+ }
+
+ /** A hiss for the quench, scaled by how much hot steel just met the water. */
+ hiss(amount) {
+ const ctx = this.ctx; if (!ctx || amount < 0.01) return;
+ if (!this._hiss) {
+ const src = ctx.createBufferSource(); src.buffer = this.noise; src.loop = true;
+ const hp = ctx.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 2400;
+ const bp = ctx.createBiquadFilter(); bp.type = 'peaking'; bp.frequency.value = 6000; bp.gain.value = 6;
+ const g = ctx.createGain(); g.gain.value = 0;
+ src.connect(hp).connect(bp).connect(g); this._out(g, 0.5); src.start();
+ this._hiss = g;
+ }
+ this._hiss.gain.setTargetAtTime(Math.min(amount, 1) * 0.45, ctx.currentTime, 0.08);
+ }
+
+ _ambient() {
+ // Low roar of the coals + irregular crackle. Very quiet.
+ const ctx = this.ctx;
+ const src = ctx.createBufferSource(); src.buffer = this.noise; src.loop = true; src.playbackRate.value = 0.5;
+ const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 180;
+ const g = ctx.createGain(); g.gain.value = 0.0; g.gain.setTargetAtTime(0.16, ctx.currentTime, 1.5);
+ src.connect(lp).connect(g).connect(this.master); src.start();
+ this.roar = { g, lp };
+ const crackle = () => {
+ if (!this.ctx) return;
+ const t = ctx.currentTime;
+ const s = ctx.createBufferSource(); s.buffer = this.noise;
+ const f = ctx.createBiquadFilter(); f.type = 'bandpass'; f.frequency.value = 1500 + Math.random() * 3500; f.Q.value = 2;
+ const cg = ctx.createGain(); cg.gain.setValueAtTime(0.05 + Math.random() * 0.1, t); cg.gain.exponentialRampToValueAtTime(0.001, t + 0.03 + Math.random() * 0.05);
+ s.connect(f).connect(cg).connect(this.master); s.start(t, Math.random() * 1.5); s.stop(t + 0.1);
+ setTimeout(crackle, 80 + Math.random() * (this._bel ? 180 : 700));
+ };
+ crackle();
+ }
+
+ fire(level) {
+ if (!this.roar) return;
+ this.roar.g.gain.setTargetAtTime(0.12 + level * 0.25, this.ctx.currentTime, 0.2);
+ this.roar.lp.frequency.setTargetAtTime(160 + level * 260, this.ctx.currentTime, 0.2);
+ }
+}
diff --git a/examples/ember/fx.js b/examples/ember/fx.js
new file mode 100644
index 0000000..ca6939d
--- /dev/null
+++ b/examples/ember/fx.js
@@ -0,0 +1,313 @@
+// Particles and screen effects: strike sparks (GPU, analytic ballistics with a floor bounce), forge embers,
+// quench steam, and a heat-haze / shockwave UV distortion effect for the post stack.
+import * as THREE from 'three';
+import { Effect } from 'postprocessing';
+import { NOISE, BLACKBODY } from './glsl.js';
+
+const rnd = (a, b) => a + Math.random() * (b - a);
+
+// ─── Sparks ─────────────────────────────────────────────────────────────────────
+export class Sparks {
+ constructor({ max = 2400, floor = 0 } = {}) {
+ this.max = max; this.head = 0;
+ const g = new THREE.InstancedBufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array([0, -1, 0, 1, -1, 0, 1, 1, 0, 0, 1, 0]), 3));
+ g.setIndex([0, 1, 2, 0, 2, 3]);
+ this.aO = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3).setUsage(THREE.DynamicDrawUsage);
+ this.aV = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3).setUsage(THREE.DynamicDrawUsage);
+ this.aT = new THREE.InstancedBufferAttribute(new Float32Array(max * 4).fill(-100), 4).setUsage(THREE.DynamicDrawUsage);
+ g.setAttribute('aO', this.aO); g.setAttribute('aV', this.aV); g.setAttribute('aT', this.aT);
+ g.instanceCount = max;
+ this.uniforms = { uTime: { value: 0 }, uFloor: { value: floor }, uRes: { value: new THREE.Vector2(1, 1) }, uDpr: { value: 1 }, uGain: { value: 1 } };
+ this.material = new THREE.ShaderMaterial({
+ uniforms: this.uniforms, transparent: true, depthWrite: false, depthTest: true, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ vertexShader: /* glsl */`
+ attribute vec3 aO; attribute vec3 aV; attribute vec4 aT;
+ uniform float uTime, uFloor, uDpr, uGain; uniform vec2 uRes;
+ varying vec3 vCol; varying vec2 vQ;
+ ${BLACKBODY}
+ vec3 motion(vec3 p0, vec3 v0, float k, float t, out vec3 v){
+ float e = exp(-k * t);
+ vec3 vt = vec3(0.0, -9.8 / k, 0.0);
+ v = (v0 - vt) * e + vt;
+ return p0 + (v0 - vt) * (1.0 - e) / k + vt * t;
+ }
+ void main(){
+ float age = uTime - aT.x, life = aT.y, seed = aT.z, kind = aT.w;
+ if (age < 0.0 || age > life){ gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
+ float k = kind > 0.5 ? mix(2.6, 4.0, fract(seed * 7.1)) : mix(0.5, 1.6, fract(seed * 13.7));
+ vec3 v; vec3 p = motion(aO, aV, k, age, v);
+ if (p.y < uFloor){
+ float a = 0.0, b = age; vec3 tv;
+ for (int i = 0; i < 12; i++){ float m = 0.5 * (a + b); if (motion(aO, aV, k, m, tv).y < uFloor) b = m; else a = m; }
+ vec3 vh; vec3 ph = motion(aO, aV, k, a, vh);
+ vec3 v1 = vec3(vh.x * 0.6, -vh.y * mix(0.18, 0.42, fract(seed * 3.3)), vh.z * 0.6);
+ p = motion(vec3(ph.x, uFloor + 0.001, ph.z), v1, k * 1.7, age - a, v);
+ if (p.y < uFloor){ p.y = uFloor + 0.002; v = vec3(v.x, 0.0, v.z) * 0.25; }
+ }
+ float f = age / life;
+ float K = kind > 0.5 ? mix(1450.0, 760.0, pow(f, 0.7)) : mix(2350.0, 820.0, pow(f, 0.55));
+ float fade = 1.0 - smoothstep(0.72, 1.0, f);
+ vCol = blackbody(K) * glowPower(K) * (kind > 0.5 ? 5.0 : 7.0) * fade * uGain;
+ float stretch = kind > 0.5 ? 0.006 : mix(0.008, 0.02, fract(seed * 5.3));
+ vec4 cH = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ vec4 cT = projectionMatrix * viewMatrix * vec4(p - v * stretch, 1.0);
+ vec2 sH = cH.xy / cH.w * uRes * 0.5, sT = cT.xy / cT.w * uRes * 0.5;
+ vec2 dir = sH - sT; float len = length(dir);
+ dir = len > 0.001 ? dir / len : vec2(1.0, 0.0);
+ vec2 perp = vec2(-dir.y, dir.x);
+ float w = (kind > 0.5 ? mix(1.1, 2.2, fract(seed * 17.0)) : mix(0.55, 1.1, fract(seed * 23.0))) * uDpr * clamp(1.6 / cH.w, 0.6, 3.0);
+ vec4 c = mix(cH, cT, position.x);
+ vec2 extra = dir * (1.0 - position.x * 2.0) * w * 0.7; // round the ends a little
+ c.xy += (perp * position.y * w + extra) / (uRes * 0.5) * c.w;
+ vQ = position.xy;
+ gl_Position = c;
+ }`,
+ fragmentShader: /* glsl */`
+ varying vec3 vCol; varying vec2 vQ;
+ void main(){
+ float across = 1.0 - vQ.y * vQ.y;
+ float along = mix(1.0, 0.15, vQ.x);
+ gl_FragColor = vec4(vCol * across * across * along, 1.0);
+ }`,
+ });
+ this.mesh = new THREE.Mesh(g, this.material);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 5;
+ }
+
+ /** Burst from a point. `dir` biases the spray; `power` 0..1 scales count and speed. */
+ burst(p, { count = 400, power = 1, time, spread = 1, up = 1, flakes = 40 } = {}) {
+ for (let i = 0; i < count + flakes; i++) {
+ const flake = i >= count;
+ const k = this.head++ % this.max;
+ const a = Math.random() * Math.PI * 2;
+ const sp = (flake ? rnd(0.5, 1.6) : Math.pow(Math.random(), 0.8) * rnd(1.4, 4.6)) * (0.55 + power * 0.55);
+ const el = flake ? rnd(0.3, 1.0) : rnd(0.05, 0.75) * up; // mostly squeezed out sideways by the hammer face
+ const h = Math.cos(Math.asin(Math.min(el, 0.99)));
+ this.aO.setXYZ(k, p.x + rnd(-0.02, 0.02), p.y + 0.01, p.z + rnd(-0.015, 0.015));
+ this.aV.setXYZ(k, Math.cos(a) * h * sp * spread, el * sp + (flake ? 0.5 : 0.4), Math.sin(a) * h * sp * spread * 0.8);
+ this.aT.setXYZW(k, time + rnd(0, 0.035), flake ? rnd(0.7, 1.6) : rnd(0.5, 1.9), Math.random(), flake ? 1 : 0);
+ }
+ this.aO.needsUpdate = this.aV.needsUpdate = this.aT.needsUpdate = true;
+ }
+
+ /** A few lazy pops off hot scale. */
+ pop(p, time, n = 2) {
+ for (let i = 0; i < n; i++) {
+ const k = this.head++ % this.max;
+ this.aO.setXYZ(k, p.x, p.y, p.z);
+ this.aV.setXYZ(k, rnd(-0.5, 0.5), rnd(0.6, 1.8), rnd(-0.4, 0.4));
+ this.aT.setXYZW(k, time, rnd(0.4, 1.0), Math.random(), Math.random() < 0.5 ? 1 : 0);
+ }
+ this.aO.needsUpdate = this.aV.needsUpdate = this.aT.needsUpdate = true;
+ }
+
+ resize(w, h, dpr) { this.uniforms.uRes.value.set(w * dpr, h * dpr); this.uniforms.uDpr.value = dpr; }
+}
+
+// ─── Embers ─────────────────────────────────────────────────────────────────────
+// Forge embers rise out of the fire pot and drift into the room; ambient motes hang in the air.
+export class Embers {
+ constructor({ count = 1400, forge, room, drift }) {
+ const seed = new Float32Array(count * 4);
+ for (let i = 0; i < count * 4; i++) seed[i] = Math.random();
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3));
+ g.setAttribute('aSeed', new THREE.BufferAttribute(seed, 4));
+ this.uniforms = {
+ uClock: { value: 0 }, uTime: { value: 0 }, uDpr: { value: 1 }, uBellows: { value: 0 }, uFire: { value: 1 },
+ uForge: { value: forge.clone() }, uRoomMin: { value: room.min.clone() }, uRoomMax: { value: room.max.clone() },
+ uDrift: { value: drift.clone() }, uGain: { value: 1 },
+ };
+ this.material = new THREE.ShaderMaterial({
+ uniforms: this.uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: /* glsl */`
+ attribute vec4 aSeed;
+ uniform float uClock, uTime, uDpr, uBellows, uFire, uGain; uniform vec3 uForge, uRoomMin, uRoomMax, uDrift;
+ varying vec3 vCol; varying float vA;
+ ${BLACKBODY}
+ void main(){
+ vec3 p; float a; float K; float size;
+ float kind = aSeed.w;
+ if (kind < 0.7){
+ // forge ember (0.55..0.7 only fly while the bellows blow)
+ float roar = step(0.4, kind);
+ float life = mix(2.2, 6.5, aSeed.x);
+ float spd = 0.8 + aSeed.y * 0.5;
+ float t = mod(uClock * spd + aSeed.z * life * 7.0, life);
+ float f = t / life;
+ float ang = aSeed.x * 6.2831 + aSeed.w * 51.0;
+ float r = sqrt(fract(aSeed.y * 7.7)) * (0.3 + roar * 0.05);
+ vec3 o = uForge + vec3(cos(ang) * r, 0.0, sin(ang) * r * 0.75);
+ float rise = t * mix(0.3, 0.75, aSeed.z) * (1.0 + roar * 1.6);
+ p = o + vec3(0.0, rise, 0.0);
+ float sw = 0.04 + rise * 0.22;
+ p.x += sin(t * 1.9 + aSeed.x * 21.0) * sw + sin(t * 4.3 + aSeed.z * 9.0) * 0.03;
+ p.z += cos(t * 1.4 + aSeed.y * 17.0) * sw;
+ p += uDrift * rise * rise * mix(0.25, 0.9, aSeed.w);
+ a = smoothstep(0.0, 0.05, f) * (1.0 - smoothstep(0.35, 1.0, f));
+ a *= 0.55 + 0.45 * sin(uTime * (9.0 + aSeed.x * 13.0) + aSeed.y * 40.0);
+ a *= mix(1.0, uBellows * 1.6, roar) * (0.6 + uFire * 0.4 + uBellows * 0.6);
+ K = mix(1500.0, 900.0, f) + uBellows * 150.0;
+ size = mix(1.2, 2.8, aSeed.z) * (1.0 + roar * 0.4);
+ } else {
+ // ambient mote drifting in the smoky air
+ vec3 span = uRoomMax - uRoomMin;
+ vec3 q = vec3(fract(aSeed.x * 3.1), fract(aSeed.y * 5.3), fract(aSeed.z * 7.7));
+ p = uRoomMin + q * span;
+ p.y = uRoomMin.y + mod(q.y * span.y + uTime * mix(0.02, 0.07, aSeed.x), span.y);
+ p.x += sin(uTime * 0.21 + aSeed.y * 30.0) * 0.25;
+ p.z += cos(uTime * 0.17 + aSeed.x * 20.0) * 0.25;
+ float edge = smoothstep(0.0, 0.15, (p.y - uRoomMin.y) / span.y) * (1.0 - smoothstep(0.8, 1.0, (p.y - uRoomMin.y) / span.y));
+ a = edge * (0.35 + 0.65 * pow(0.5 + 0.5 * sin(uTime * (0.8 + aSeed.w) + aSeed.z * 30.0), 3.0)) * 0.45;
+ K = mix(1050.0, 1350.0, aSeed.y);
+ size = mix(0.9, 2.2, aSeed.x);
+ }
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ float dist = -mv.z;
+ gl_PointSize = size * 1.35 * uDpr * clamp(3.2 / dist, 0.6, 9.0);
+ // big out-of-focus motes near the lens get dimmer per pixel
+ a /= 1.0 + max(0.0, 1.2 - dist) * 2.0;
+ vA = a * uGain;
+ vCol = blackbody(K) * (glowPower(K) * 22.0 + 0.4);
+ }`,
+ fragmentShader: /* glsl */`
+ varying vec3 vCol; varying float vA;
+ void main(){
+ float d = length(gl_PointCoord - 0.5);
+ float s = smoothstep(0.5, 0.0, d);
+ gl_FragColor = vec4(vCol * s * s * vA, 1.0);
+ }`,
+ });
+ this.points = new THREE.Points(g, this.material);
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 4;
+ }
+}
+
+// ─── Steam ──────────────────────────────────────────────────────────────────────
+export class Steam {
+ constructor({ max = 220, puff }) {
+ this.max = max; this.head = 0;
+ const g = new THREE.InstancedBufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0]), 3));
+ g.setIndex([0, 1, 2, 0, 2, 3]);
+ this.aP = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3).setUsage(THREE.DynamicDrawUsage);
+ this.aV = new THREE.InstancedBufferAttribute(new Float32Array(max * 3), 3).setUsage(THREE.DynamicDrawUsage);
+ this.aT = new THREE.InstancedBufferAttribute(new Float32Array(max * 4).fill(-100), 4).setUsage(THREE.DynamicDrawUsage);
+ g.setAttribute('aP', this.aP); g.setAttribute('aV', this.aV); g.setAttribute('aT', this.aT);
+ g.instanceCount = max;
+ this.uniforms = {
+ uTime: { value: 0 }, uPuff: { value: puff }, uGlow: { value: new THREE.Color(0, 0, 0) }, uWater: { value: 0.5 },
+ uAmb: { value: new THREE.Color(0.035, 0.037, 0.042) }, uFire: { value: new THREE.Color(0.12, 0.05, 0.02) }, uMoon: { value: new THREE.Color(0.12, 0.125, 0.14) }, uOpacity: { value: 1 },
+ };
+ this.material = new THREE.ShaderMaterial({
+ uniforms: this.uniforms, transparent: true, depthWrite: false,
+ blending: THREE.CustomBlending, blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor,
+ vertexShader: /* glsl */`
+ attribute vec3 aP; attribute vec3 aV; attribute vec4 aT;
+ uniform float uTime, uWater;
+ varying vec2 vUv; varying float vA; varying float vH; varying float vRot; varying float vSeed;
+ void main(){
+ float age = uTime - aT.x, life = aT.y;
+ if (age < 0.0 || age > life){ gl_Position = vec4(2.0, 2.0, 2.0, 1.0); return; }
+ float f = age / life;
+ vec3 p = aP + aV * (1.0 - exp(-age * 1.6)) / 1.6 + vec3(0.0, 0.16 * age * age, 0.0);
+ p.x += sin(age * 1.3 + aT.w * 30.0) * 0.06 * age;
+ p.z += cos(age * 1.1 + aT.w * 20.0) * 0.05 * age;
+ float size = aT.z * (0.3 + 1.6 * sqrt(f));
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ float rot = aT.w * 6.28 + age * (fract(aT.w * 9.1) - 0.5) * 0.8;
+ vec2 c = position.xy; float cs = cos(rot), sn = sin(rot);
+ mv.xy += vec2(c.x * cs - c.y * sn, c.x * sn + c.y * cs) * size;
+ gl_Position = projectionMatrix * mv;
+ vUv = position.xy * 0.5 + 0.5;
+ vA = smoothstep(0.0, 0.12, f) * (1.0 - smoothstep(0.35, 1.0, f)) * smoothstep(0.05, 0.4, -mv.z);
+ vH = p.y - uWater; vRot = rot; vSeed = aT.w;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform sampler2D uPuff; uniform vec3 uGlow, uAmb, uFire, uMoon; uniform float uOpacity, uTime;
+ varying vec2 vUv; varying float vA; varying float vH; varying float vSeed;
+ void main(){
+ vec2 q = vUv + vec2(vSeed * 0.37, vSeed * 0.71);
+ float n = texture2D(uPuff, q * 0.9 + vec2(0.0, -uTime * 0.03)).r;
+ float r = length(vUv - 0.5) * 2.0;
+ float n2 = texture2D(uPuff, q * 2.3 + vec2(uTime * 0.05, -uTime * 0.09)).r;
+ float m = smoothstep(0.35, 0.95, (n * 0.7 + n2 * 0.45) * (1.2 - r * r));
+ float a = m * vA * uOpacity * 0.2;
+ vec3 col = uAmb + uFire * 0.35 + uMoon * (0.5 + n * 1.1) + uGlow * exp(-max(vH, 0.0) * 2.4) * (0.35 + (1.0 - r) * 0.65);
+ gl_FragColor = vec4(col * a, a);
+ }`,
+ });
+ this.mesh = new THREE.Mesh(g, this.material);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 6;
+ }
+
+ emit(p, time, { spread = 0.05, vel = 0.5, size = 0.18, life = 3.2 } = {}) {
+ const k = this.head++ % this.max;
+ this.aP.setXYZ(k, p.x + rnd(-spread, spread), p.y, p.z + rnd(-spread, spread) * 0.6);
+ this.aV.setXYZ(k, rnd(-0.2, 0.2), vel * rnd(0.6, 1.3), rnd(-0.15, 0.15));
+ this.aT.setXYZW(k, time, life * rnd(0.7, 1.3), size * rnd(0.7, 1.35), Math.random());
+ this.aP.needsUpdate = this.aV.needsUpdate = this.aT.needsUpdate = true;
+ }
+}
+
+// ─── Heat haze ──────────────────────────────────────────────────────────────────
+const hazeFrag = /* glsl */`
+uniform vec3 uPts[8];
+uniform float uHazeTime, uStrength, uAsp;
+uniform vec4 uShock;
+${'' /* value noise for the refraction field */}
+float hz_h(vec2 p){ return fract(sin(dot(p, vec2(41.3, 289.1))) * 43758.5453); }
+float hz_n(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hz_h(i), hz_h(i + vec2(1, 0)), f.x), mix(hz_h(i + vec2(0, 1)), hz_h(i + vec2(1, 1)), f.x), f.y); }
+void mainUv(inout vec2 uv){
+ float m = 0.0;
+ for (int i = 0; i < 8; i++){
+ vec2 d = uv - uPts[i].xy; d.x *= uAsp;
+ float w = exp(-d.x * d.x / 0.0035) * smoothstep(-0.03, 0.04, d.y) * exp(-max(d.y, 0.0) / 0.2);
+ m += uPts[i].z * w;
+ }
+ m = min(m, 1.4) * uStrength;
+ if (m > 0.001){
+ vec2 q = vec2(uv.x * uAsp, uv.y) * 38.0 + vec2(0.0, -uHazeTime * 3.1);
+ vec2 off = vec2(hz_n(q) - 0.5, hz_n(q * 1.13 + 17.0 + vec2(0.0, uHazeTime * 0.7)) - 0.5);
+ off += 0.5 * vec2(hz_n(q * 2.1 + 5.0) - 0.5, hz_n(q * 2.3 + 9.0) - 0.5);
+ uv += off * m * 0.009;
+ }
+ if (uShock.w > 0.001){
+ vec2 d = (uv - uShock.xy) * vec2(uAsp, 1.0);
+ float r = length(d) + 1e-5;
+ float ring = uShock.z;
+ float w = exp(-pow((r - ring) / 0.03, 2.0));
+ uv -= (d / r) * w * uShock.w * 0.014 / vec2(uAsp, 1.0);
+ }
+}`;
+export class HeatHaze extends Effect {
+ constructor() {
+ super('HeatHaze', hazeFrag, {
+ uniforms: new Map([
+ ['uPts', new THREE.Uniform(Array.from({ length: 8 }, () => new THREE.Vector3()))],
+ ['uHazeTime', new THREE.Uniform(0)],
+ ['uStrength', new THREE.Uniform(1)],
+ ['uAsp', new THREE.Uniform(1.6)],
+ ['uShock', new THREE.Uniform(new THREE.Vector4())],
+ ]),
+ });
+ }
+}
+
+/** A soft cloud puff texture for steam. */
+export function puffTexture(bake, renderer) {
+ return bake(renderer, 256, `
+ void main(){
+ float n = fbm(vUv * 5.0, 5.0, 7, 0.58) * 0.5 + 0.5;
+ float b = 1.0 - abs(fbm(vUv * 3.0 + 1.7, 3.0, 5, 0.5));
+ gl_FragColor = vec4(vec3(clamp(n * 0.75 + b * b * 0.45 - 0.1, 0.0, 1.0)), 1.0);
+ }`);
+}
+
+export { NOISE };
diff --git a/examples/ember/glsl.js b/examples/ember/glsl.js
new file mode 100644
index 0000000..6de2d77
--- /dev/null
+++ b/examples/ember/glsl.js
@@ -0,0 +1,85 @@
+// Shared GLSL for the forge: noise, cellular scale, and a blackbody ramp used by steel, coals, sparks and embers.
+export const NOISE = /* glsl */`
+vec3 e_mod289(vec3 x){ return x - floor(x * (1.0 / 289.0)) * 289.0; }
+vec4 e_mod289(vec4 x){ return x - floor(x * (1.0 / 289.0)) * 289.0; }
+vec4 e_perm(vec4 x){ return e_mod289(((x * 34.0) + 10.0) * x); }
+vec4 e_tis(vec4 r){ return 1.79284291400159 - 0.85373472095314 * r; }
+float snoise(vec3 v){
+ const vec2 C = vec2(1.0/6.0, 1.0/3.0);
+ const vec4 D = vec4(0.0, 0.5, 1.0, 2.0);
+ vec3 i = floor(v + dot(v, C.yyy));
+ vec3 x0 = v - i + dot(i, C.xxx);
+ vec3 g = step(x0.yzx, x0.xyz);
+ vec3 l = 1.0 - g;
+ vec3 i1 = min(g.xyz, l.zxy);
+ vec3 i2 = max(g.xyz, l.zxy);
+ vec3 x1 = x0 - i1 + C.xxx;
+ vec3 x2 = x0 - i2 + C.yyy;
+ vec3 x3 = x0 - D.yyy;
+ i = e_mod289(i);
+ vec4 p = e_perm(e_perm(e_perm(i.z + vec4(0.0, i1.z, i2.z, 1.0)) + i.y + vec4(0.0, i1.y, i2.y, 1.0)) + i.x + vec4(0.0, i1.x, i2.x, 1.0));
+ float n_ = 0.142857142857;
+ vec3 ns = n_ * D.wyz - D.xzx;
+ vec4 j = p - 49.0 * floor(p * ns.z * ns.z);
+ vec4 x_ = floor(j * ns.z);
+ vec4 y_ = floor(j - 7.0 * x_);
+ vec4 x = x_ * ns.x + ns.yyyy;
+ vec4 y = y_ * ns.x + ns.yyyy;
+ vec4 h = 1.0 - abs(x) - abs(y);
+ vec4 b0 = vec4(x.xy, y.xy);
+ vec4 b1 = vec4(x.zw, y.zw);
+ vec4 s0 = floor(b0) * 2.0 + 1.0;
+ vec4 s1 = floor(b1) * 2.0 + 1.0;
+ vec4 sh = -step(h, vec4(0.0));
+ vec4 a0 = b0.xzyw + s0.xzyw * sh.xxyy;
+ vec4 a1 = b1.xzyw + s1.xzyw * sh.zzww;
+ vec3 p0 = vec3(a0.xy, h.x);
+ vec3 p1 = vec3(a0.zw, h.y);
+ vec3 p2 = vec3(a1.xy, h.z);
+ vec3 p3 = vec3(a1.zw, h.w);
+ vec4 norm = e_tis(vec4(dot(p0,p0), dot(p1,p1), dot(p2,p2), dot(p3,p3)));
+ p0 *= norm.x; p1 *= norm.y; p2 *= norm.z; p3 *= norm.w;
+ vec4 m = max(0.5 - vec4(dot(x0,x0), dot(x1,x1), dot(x2,x2), dot(x3,x3)), 0.0);
+ m = m * m;
+ return 105.0 * dot(m * m, vec4(dot(p0,x0), dot(p1,x1), dot(p2,x2), dot(p3,x3)));
+}
+float fbm3(vec3 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++){ s += a * snoise(p); p = p * 2.03 + 11.7; a *= 0.5; } return s; }
+float e_hash1(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+vec2 e_hash2(vec2 p){ return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); }
+// Cellular noise: x = distance to nearest feature, y = distance to border, z = cell id.
+vec3 cells(vec2 p){
+ vec2 n = floor(p), f = fract(p);
+ vec2 mg, mr; float md = 8.0; vec2 id;
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++){
+ vec2 g = vec2(float(i), float(j));
+ vec2 o = e_hash2(n + g);
+ vec2 r = g + o - f;
+ float d = dot(r, r);
+ if (d < md){ md = d; mr = r; mg = g; id = n + g; }
+ }
+ float bd = 8.0;
+ for (int j = -2; j <= 2; j++) for (int i = -2; i <= 2; i++){
+ vec2 g = mg + vec2(float(i), float(j));
+ vec2 o = e_hash2(n + g);
+ vec2 r = g + o - f;
+ if (dot(mr - r, mr - r) > 0.00001) bd = min(bd, dot(0.5 * (mr + r), normalize(r - mr)));
+ }
+ return vec3(sqrt(md), bd, e_hash1(id));
+}
+`;
+
+// Linear-sRGB chromaticity of a blackbody at K kelvin (Helland fit, linearised), plus a radiance curve
+// normalised so that ~1650 K reads as a searing yellow-white once tone mapped.
+export const BLACKBODY = /* glsl */`
+vec3 blackbody(float K){
+ float t = K / 100.0;
+ float g = clamp((99.4708025861 * log(max(t, 1.0)) - 161.1195681661) / 255.0, 0.0, 1.0);
+ float b = t <= 19.0 ? 0.0 : clamp((138.5177312231 * log(t - 10.0) - 305.0447927307) / 255.0, 0.0, 1.0);
+ vec3 c = pow(vec3(1.0, g, b), vec3(2.2));
+ // The eye reads the hottest steel as yellow-white; lift the green/blue a touch at the top of the range.
+ c.g += smoothstep(1250.0, 1750.0, K) * 0.16;
+ c.b += smoothstep(1450.0, 1850.0, K) * 0.07;
+ return c;
+}
+float glowPower(float K){ float x = max(K - 720.0, 0.0) / 930.0; return pow(x, 2.6); }
+`;
diff --git a/examples/ember/heat.js b/examples/ember/heat.js
new file mode 100644
index 0000000..61572a2
--- /dev/null
+++ b/examples/ember/heat.js
@@ -0,0 +1,207 @@
+// The blade: a per-vertex blade frame (u along the steel from tip to guard, v across edge to edge) and a
+// MeshStandardMaterial patch that adds blackbody emission, forge scale, glowing scale flakes and the etched
+// damascus pattern revealed after the quench.
+import * as THREE from 'three';
+import { NOISE, BLACKBODY } from './glsl.js';
+
+/**
+ * Analyse the sword geometry. Returns the matrix that maps geometry space -> sword space
+ * (metres, tip toward -X, flat of the blade facing +Y, guard start at the origin) and writes a
+ * `blade` attribute (u, v) on the geometry.
+ */
+export function analyseSword(geometry, length = 0.95) {
+ const pos = geometry.attributes.position;
+ const n = pos.count;
+ const P = new Float32Array(n * 3);
+ const mean = new THREE.Vector3();
+ for (let i = 0; i < n; i++) {
+ P[i * 3] = pos.getX(i); P[i * 3 + 1] = pos.getY(i); P[i * 3 + 2] = pos.getZ(i);
+ mean.x += P[i * 3]; mean.y += P[i * 3 + 1]; mean.z += P[i * 3 + 2];
+ }
+ mean.divideScalar(n);
+ const cov = (sel) => {
+ const C = [0, 0, 0, 0, 0, 0, 0, 0, 0]; let c = 0;
+ for (let i = 0; i < n; i++) {
+ if (sel && !sel(i)) continue;
+ const d = [P[i * 3] - mean.x, P[i * 3 + 1] - mean.y, P[i * 3 + 2] - mean.z];
+ for (let a = 0; a < 3; a++) for (let b = 0; b < 3; b++) C[a * 3 + b] += d[a] * d[b];
+ c++;
+ }
+ return C.map(v => v / Math.max(c, 1));
+ };
+ const power = (C, seed, ortho) => {
+ let e = new THREE.Vector3(...seed).normalize();
+ for (let it = 0; it < 80; it++) {
+ const r = new THREE.Vector3(C[0] * e.x + C[1] * e.y + C[2] * e.z, C[3] * e.x + C[4] * e.y + C[5] * e.z, C[6] * e.x + C[7] * e.y + C[8] * e.z);
+ if (ortho) r.addScaledVector(ortho, -r.dot(ortho));
+ e = r.normalize();
+ }
+ return e;
+ };
+ const axis = power(cov(), [1, 0.2, 0.1]);
+ const proj = new Float32Array(n);
+ let sMin = Infinity, sMax = -Infinity;
+ for (let i = 0; i < n; i++) {
+ const s = (P[i * 3] - mean.x) * axis.x + (P[i * 3 + 1] - mean.y) * axis.y + (P[i * 3 + 2] - mean.z) * axis.z;
+ proj[i] = s; sMin = Math.min(sMin, s); sMax = Math.max(sMax, s);
+ }
+ // Width axis: second principal direction of the whole sword (the guard spreads the same way as the edges).
+ const width = power(cov(), [0, 0, 1], axis);
+ // Find the guard: the slice with the largest spread along the width axis.
+ const BINS = 64;
+ const wMin = new Float32Array(BINS).fill(Infinity), wMax = new Float32Array(BINS).fill(-Infinity);
+ const binOf = s => Math.min(BINS - 1, Math.floor((s - sMin) / (sMax - sMin) * BINS));
+ const W = new Float32Array(n);
+ for (let i = 0; i < n; i++) {
+ const w = (P[i * 3] - mean.x) * width.x + (P[i * 3 + 1] - mean.y) * width.y + (P[i * 3 + 2] - mean.z) * width.z;
+ W[i] = w;
+ const b = binOf(proj[i]);
+ wMin[b] = Math.min(wMin[b], w); wMax[b] = Math.max(wMax[b], w);
+ }
+ let gb = 0, gw = 0;
+ for (let b = 0; b < BINS; b++) { const w = wMax[b] - wMin[b]; if (w > gw && isFinite(w)) { gw = w; gb = b; } }
+ // Tip is the end farther from the guard.
+ const flip = gb < BINS / 2;
+ if (flip) axis.negate();
+ const sTipAbs = flip ? -sMax : sMin; // in the (possibly flipped) axis
+ const S = i => (flip ? -proj[i] : proj[i]);
+ // Guard start: walk from the guard bin toward the tip until the width drops back to blade width.
+ const bladeW = [];
+ const B2 = i => Math.min(BINS - 1, Math.floor((S(i) - sTipAbs) / (sMax - sMin) * BINS));
+ const bMin = new Float32Array(BINS).fill(Infinity), bMax = new Float32Array(BINS).fill(-Infinity);
+ for (let i = 0; i < n; i++) { const b = B2(i); bMin[b] = Math.min(bMin[b], W[i]); bMax[b] = Math.max(bMax[b], W[i]); }
+ let guardBin = 0, gw2 = 0;
+ for (let b = 0; b < BINS; b++) { const w = bMax[b] - bMin[b]; if (w > gw2 && isFinite(w)) { gw2 = w; guardBin = b; } }
+ for (let b = 4; b < guardBin; b++) bladeW.push(bMax[b] - bMin[b]);
+ const typical = bladeW.sort((a, b) => a - b)[Math.floor(bladeW.length * 0.6)] ?? gw2 * 0.4;
+ let gStart = guardBin;
+ while (gStart > 0 && (bMax[gStart - 1] - bMin[gStart - 1]) > typical * 1.35) gStart--;
+ const sGuard = sTipAbs + gStart / BINS * (sMax - sMin);
+ const bladeLen = sGuard - sTipAbs;
+ // Blade centre line and half-width per bin, for v in -1..1 edge to edge.
+ const cen = new Float32Array(BINS), half = new Float32Array(BINS);
+ for (let b = 0; b < BINS; b++) {
+ if (isFinite(bMin[b])) { cen[b] = (bMin[b] + bMax[b]) / 2; half[b] = Math.max((bMax[b] - bMin[b]) / 2, 1e-4); }
+ else { cen[b] = cen[b - 1] ?? 0; half[b] = half[b - 1] ?? 0.01; }
+ }
+ const blade = new Float32Array(n * 2);
+ for (let i = 0; i < n; i++) {
+ const s = S(i);
+ const u = (s - sTipAbs) / bladeLen;
+ const bf = clampN((s - sTipAbs) / (sMax - sMin) * BINS - 0.5, 0, BINS - 1.001);
+ const b0 = Math.floor(bf), t = bf - b0;
+ const c = cen[b0] * (1 - t) + cen[Math.min(b0 + 1, BINS - 1)] * t;
+ const h = half[b0] * (1 - t) + half[Math.min(b0 + 1, BINS - 1)] * t;
+ blade[i * 2] = u;
+ blade[i * 2 + 1] = u <= 1 ? clampN((W[i] - c) / h, -1, 1) : 0;
+ }
+ geometry.setAttribute('blade', new THREE.BufferAttribute(blade, 2));
+
+ // Build geometry -> sword-space matrix.
+ const thick = new THREE.Vector3().crossVectors(width, axis).normalize(); // right-handed: axis x thick = width
+ const scale = length / (sMax - sMin);
+ const basis = new THREE.Matrix4().makeBasis(axis, thick, width); // columns: local X,Y,Z in geometry space
+ const rot = basis.clone().transpose(); // geometry -> local
+ // Origin at the guard start on the blade centre line.
+ const guardCentre = mean.clone().addScaledVector(axis, sGuard).addScaledVector(width, cen[Math.max(gStart - 2, 0)]);
+ // Centre thickness: average of thickness coordinate over blade vertices.
+ let tc = 0, tn = 0;
+ for (let i = 0; i < n; i += 7) { if (S(i) < sGuard - 0.05 && S(i) > sTipAbs + 0.1) { tc += (P[i * 3] - mean.x) * thick.x + (P[i * 3 + 1] - mean.y) * thick.y + (P[i * 3 + 2] - mean.z) * thick.z; tn++; } }
+ guardCentre.addScaledVector(thick, tn ? tc / tn : 0);
+ const m = new THREE.Matrix4().makeScale(scale, scale, scale).multiply(rot).multiply(new THREE.Matrix4().makeTranslation(-guardCentre.x, -guardCentre.y, -guardCentre.z));
+ // Blade thickness in metres (for resting on the anvil).
+ let tMin = Infinity, tMax = -Infinity;
+ for (let i = 0; i < n; i += 3) { if (S(i) < sGuard - 0.03) { const tt = (P[i * 3] - guardCentre.x) * thick.x + (P[i * 3 + 1] - guardCentre.y) * thick.y + (P[i * 3 + 2] - guardCentre.z) * thick.z; tMin = Math.min(tMin, tt); tMax = Math.max(tMax, tt); } }
+ return {
+ matrix: m,
+ bladeLength: bladeLen * scale,
+ total: length,
+ halfThickness: Math.max(Math.abs(tMin), Math.abs(tMax)) * scale,
+ thickMin: tMin * scale,
+ guardHalfWidth: gw2 / 2 * scale,
+ hiltLength: (sMax - sGuard) * scale,
+ };
+}
+function clampN(v, a, b) { return Math.min(b, Math.max(a, v)); }
+
+/** Patch the sword's glTF material. Returns the uniforms driven by the page. */
+export function heatMaterial(material, damascusTex) {
+ const u = {
+ uFront: { value: 0.3 }, // how far the heat has travelled from the tip (0..1.1 of blade length)
+ uPeak: { value: 0.5 }, // peak temperature, 0..1 -> 600..1700 K
+ uTime: { value: 0 },
+ uForged: { value: 1 }, // black forge scale over the steel
+ uDam: { value: 0 }, // etched damascus pattern
+ uCool: { value: 0 }, // quench front travelling from the tip
+ uStrike: { value: new THREE.Vector3(0.4, 0, 10) }, // u, amplitude, age
+ uGlow: { value: 10 },
+ uDamTex: { value: damascusTex },
+ };
+ material.userData.heat = u;
+ material.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute vec2 blade;\nvarying vec2 vBlade;\nvarying vec3 vLocal;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvBlade = blade;\nvLocal = position;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec2 vBlade; varying vec3 vLocal;
+ uniform float uFront, uPeak, uTime, uForged, uDam, uCool, uGlow;
+ uniform vec3 uStrike; uniform sampler2D uDamTex;
+ ${NOISE}
+ ${BLACKBODY}`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ float bladeM = 1.0 - smoothstep(0.975, 1.0, vBlade.x);
+ float hn = fbm3(vLocal * 9.0 + vec3(0.0, uTime * 0.04, 0.0));
+ // the scale falls away from tip to guard, revealing the etched layers
+ float damM = uDam >= 1.35 ? 1.0 : 1.0 - smoothstep(uDam - 0.16, uDam, vBlade.x + hn * 0.12 + 0.05);
+ float forgedM = uForged * (1.0 - damM);
+ float wipe = damM * (1.0 - damM) * 4.0 * step(0.01, uDam) * step(uDam, 1.34);
+ float d = vBlade.x + hn * 0.075;
+ float prof = 1.0 - smoothstep(uFront - 0.3, uFront + 0.035, d);
+ float grad = mix(1.0, 0.64, clamp(d / max(uFront, 0.05), 0.0, 1.0));
+ float edge = abs(vBlade.y);
+ float heat01 = clamp(uPeak * prof * grad * (1.0 + edge * 0.06) + smoothstep(0.06, 0.0, vBlade.x) * 0.05 * prof, 0.0, 1.2);
+ // quench: the cold front runs up from the tip
+ float cooled = 1.0 - smoothstep(uCool - 0.14, uCool + 0.01, vBlade.x + hn * 0.05);
+ heat01 *= 1.0 - cooled;
+ float strikeFlare = uStrike.y * exp(-pow((vBlade.x - uStrike.x) * 7.0, 2.0)) * exp(-uStrike.z * 2.6) * step(0.12, heat01);
+ heat01 = clamp(heat01 + strikeFlare * 0.28, 0.0, 1.25);
+ heat01 *= bladeM;
+ float K = 520.0 + heat01 * 1080.0;
+ // forge scale: mottled oxide with irregular glowing cracks; a few flakes flare as they lift
+ float scaleAmt = forgedM * bladeM * smoothstep(0.1, 0.45, heat01) * (1.0 - smoothstep(0.82, 1.08, heat01));
+ float mot = fbm3(vLocal * vec3(26.0, 26.0, 26.0) + 3.7);
+ float crack = 1.0 - smoothstep(0.0, 0.06, abs(snoise(vLocal * 21.0 + 1.3)));
+ vec3 cl = cells(vec2(vBlade.x * 70.0, vBlade.y * 2.6 + step(0.0, vLocal.x) * 7.0));
+ float pop = pow(max(sin(uTime * (0.6 + cl.z * 1.4) + cl.z * 91.0), 0.0), 40.0) * step(0.7, cl.z) * smoothstep(0.25, 0.0, cl.x);
+ float flakeMod = mix(1.0, 0.5 + 0.35 * smoothstep(-0.3, 0.4, -mot), scaleAmt) + crack * scaleAmt * 0.55 + pop * scaleAmt * 1.4;
+ vec3 heatEmit = blackbody(K) * glowPower(K) * uGlow * flakeMod;
+ // albedo: black scale over the forged blade, etched damascus after the polish
+ float mott = fbm3(vLocal * 34.0) * 0.5 + 0.5;
+ vec3 scaleCol = vec3(0.034, 0.032, 0.031) * (0.55 + mott * 0.9) * (0.85 + mot * 0.3);
+ diffuseColor.rgb = mix(diffuseColor.rgb, scaleCol, forgedM * bladeM);
+ vec3 dam = texture2D(uDamTex, vec2(vBlade.x * 1.1 + 0.13, vBlade.y * 0.11 + 0.5)).rgb;
+ float dl = smoothstep(0.1, 0.62, dot(dam, vec3(0.3333)));
+ float bevel = smoothstep(0.78, 0.97, edge);
+ vec3 damCol = mix(vec3(0.05, 0.05, 0.055), vec3(0.8, 0.8, 0.82), dl);
+ damCol = mix(damCol, vec3(0.62, 0.62, 0.64), bevel * 0.55);
+ diffuseColor.rgb = mix(diffuseColor.rgb, damCol, damM * bladeM);
+ heatEmit += blackbody(1100.0) * glowPower(1100.0) * 1.6 * pow(wipe, 6.0) * bladeM;
+ float e_rough = mix(0.62 + mott * 0.25, 0.85, scaleAmt);
+ float e_damRough = mix(0.55, 0.14, max(dl, bevel));
+ float e_damMetal = mix(0.3, 1.0, max(dl, bevel));
+ `)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(roughnessFactor, e_rough, forgedM * bladeM);
+ roughnessFactor = mix(roughnessFactor, e_damRough, damM * bladeM);`)
+ .replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment>
+ metalnessFactor = mix(metalnessFactor, 0.55 - scaleAmt * 0.3, forgedM * bladeM);
+ metalnessFactor = mix(metalnessFactor, e_damMetal, damM * bladeM);`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ totalEmissiveRadiance += heatEmit;`);
+ };
+ material.customProgramCacheKey = () => 'ember-heat';
+ material.needsUpdate = true;
+ return u;
+}
diff --git a/examples/ember/index.html b/examples/ember/index.html
new file mode 100644
index 0000000..e296bdc
--- /dev/null
+++ b/examples/ember/index.html
@@ -0,0 +1,220 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Hammer &amp; Ember — Pattern-welded swords, forged to commission</title>
+ <meta name="description" content="A two-person bladesmith atelier forging damascus swords to commission. Every blade is folded 512 times. None are made twice.">
+ <meta name="theme-color" content="#0a0806">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%226%22 fill=%22%230a0806%22/%3E%3Cpath d=%22M5 11h14l3-3h5v5h-3l-2 2H14l-1 4h-4l1-4H5z%22 fill=%22%23ff6a1f%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Oswald:wght@300;400;500;600;700&family=Crimson+Pro:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="flash" aria-hidden="true"></div>
+ <div class="grain" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-inner">
+ <p class="loader-mark">Hammer <em>&amp;</em> Ember</p>
+ <div class="loader-bar"><i></i></div>
+ <p class="loader-line"><span class="loader-state">Lighting the forge</span><span class="loader-pct">0</span></p>
+ </div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Hammer and Ember home">
+ <svg viewBox="0 0 32 32" aria-hidden="true">
+ <path d="M5 11h14l3-3h5v5h-3l-2 2H14l-1 4h-4l1-4H5z" fill="currentColor"/>
+ <path d="M9 22h14M11 25.5h10" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linecap="round"/>
+ <circle class="brand-spark" cx="25" cy="18" r="1.4"/>
+ </svg>
+ <span>Hammer <em>&amp;</em> Ember</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#process">Process</a>
+ <a href="#steel">The steel</a>
+ <a href="#commissions">Commissions</a>
+ <a href="#voices">Owners</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="true" data-cursor="link"><span class="sound-bars" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span class="sound-label">Sound on</span></button>
+ <a class="btn btn-hot" href="#commission" data-magnetic><span class="cta-long">Commission a blade</span><span class="cta-short">Commission</span></a>
+ </div>
+ </header>
+
+ <main id="top">
+ <section class="hero" data-station="hero">
+ <div class="hero-copy">
+ <p class="eyebrow"><span>Bladesmiths</span><span class="eb-sep"> &nbsp;·&nbsp; </span><span>Semois Valley, Belgium</span><span class="eb-3"> &nbsp;·&nbsp; Since 2009</span></p>
+ <h1 class="title">
+ <span class="t-line"><span>Every blade is</span></span>
+ <span class="t-line"><span>folded <b>512</b> times.</span></span>
+ <span class="t-accent"><span>None are made twice.</span></span>
+ </h1>
+ <p class="sub">Two smiths, one coal forge, and a waiting list. We forge pattern-welded swords to commission — one at a time, by hand, from raw billet to living edge.</p>
+ </div>
+ <div class="hint" aria-hidden="true">
+ <span><kbd>Scroll</kbd>heat the steel</span>
+ <span><kbd class="k-strike">Click</kbd>strike</span>
+ <span><kbd class="k-hold">Hold</kbd>work the bellows</span>
+ </div>
+ </section>
+
+ <section class="process" id="process">
+ <article class="step right" data-station="fold">
+ <p class="step-num"><b>01</b><span>Fold</span></p>
+ <h2>Two steels.<br><em>One billet.</em></h2>
+ <p>We stack bright 15N20 nickel steel between plates of 1095 high-carbon, forge-weld the stack at 1,260&nbsp;°C, then cut it, restack it and weld it again — nine times, until one bar holds 512 layers and a pattern no one could plan.</p>
+ <p class="meta">Welding heat · 1,260 °C &nbsp;/&nbsp; Flux · anhydrous borax</p>
+ </article>
+ <article class="step left" data-station="forge">
+ <p class="step-num"><b>02</b><span>Forge</span></p>
+ <h2>Strike at orange.<br><em>Never at red.</em></h2>
+ <p>Steel moves like cold clay at 1,100&nbsp;°C and cracks below cherry, so we hammer only while it glows. Roughly four hundred blows draw the bar into a blade, set the bevels and bring the point.</p>
+ <p class="meta">Try it: <span class="k-verb">click</span> to strike the hot spot</p>
+ </article>
+ <article class="step right" data-station="quenchstep">
+ <p class="step-num"><b>03</b><span>Quench</span></p>
+ <h2>One second<br><em>in warm brine.</em></h2>
+ <p>At 800&nbsp;°C the blade goes point-first into brine held at 50&nbsp;°C. The edge freezes into hard martensite; the spine stays springy. It is the most frightening second of the month — a hidden flaw shows itself here, or never.</p>
+ <p class="meta">The trough is waiting. Keep scrolling.</p>
+ </article>
+ <article class="step left" data-station="polish">
+ <p class="step-num"><b>04</b><span>Polish</span></p>
+ <h2>Nine stones.<br><em>Then acid.</em></h2>
+ <p>Three days on waterstones from 120 to 8,000 grit, by hand, along the length. Then a bath of ferric chloride eats the carbon layers dark and leaves the nickel bright — and the pattern the hammer made finally surfaces.</p>
+ <p class="meta">Finished blades hang on the north wall</p>
+ </article>
+ </section>
+
+ <section class="steel" id="steel" data-station="steel">
+ <div class="steel-head">
+ <p class="eyebrow">The steel</p>
+ <h2>It remembers<br><em>every blow.</em></h2>
+ </div>
+ <p class="lede steel-lede">Pattern-welded steel is not decoration. Hard layers carry the edge, soft layers take the shock, and the figure you see on the flat is a literal map of how the metal was moved.</p>
+ <dl class="stats">
+ <div><dt>Layers</dt><dd><span class="num" data-count="512">512</span></dd><p>1095 carbon steel and 15N20 nickel steel, forge-welded in nine folds.</p></div>
+ <div><dt>Carbon at the edge</dt><dd><span class="num" data-count="0.84" data-dec="2">0.84</span><small>%</small></dd><p>Measured after decarburisation losses in the fire.</p></div>
+ <div><dt>Hardness</dt><dd><span class="num">58–60</span><small>HRC</small></dd><p>Differentially tempered: a hard edge on a spring-soft spine of 48.</p></div>
+ <div><dt>Hours per blade</dt><dd><span class="num" data-count="310">310</span></dd><p>From the first weld to the last pass on the 8,000 stone.</p></div>
+ </dl>
+ </section>
+
+ <section class="commissions" id="commissions" data-station="wide">
+ <div class="com-head">
+ <p class="eyebrow">Commissions · 2027 list</p>
+ <h2>Eight swords a year.<br><em>Three places left.</em></h2>
+ <p class="lede">Every commission begins with a conversation at the forge, or on a call if you are far away. You choose the form; the steel chooses its pattern. Lead time is currently fourteen months.</p>
+ </div>
+ <div class="blades">
+ <article class="blade-card">
+ <p class="bc-type">Seax</p>
+ <h3>The Long Knife</h3>
+ <p>Broken-back single edge, 38–60&nbsp;cm. Bog-oak grip, bronze ferrule, riveted leather sheath.</p>
+ <p class="bc-price"><small>from</small> €4,800</p>
+ </article>
+ <article class="blade-card hot">
+ <p class="bc-type">Petersen Type X</p>
+ <h3>The Viking Sword</h3>
+ <p>Pattern-welded core with a fuller, 91&nbsp;cm. Cast-bronze guard and lobed pommel with knotwork carved by hand.</p>
+ <p class="bc-price"><small>from</small> €9,600</p>
+ </article>
+ <article class="blade-card">
+ <p class="bc-type">Oakeshott XVIIIa</p>
+ <h3>The Hand-and-a-Half</h3>
+ <p>Stiff, diamond-section longsword, 112&nbsp;cm. Wrought-iron guard, wire-bound grip, fitted scabbard.</p>
+ <p class="bc-price"><small>from</small> €14,500</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="voices" id="voices" data-station="voices">
+ <p class="eyebrow">Owners</p>
+ <div class="quotes">
+ <blockquote>
+ <p>“I asked for a sword my grandfather would have recognised. They sent me a photograph of the billet after every fold.”</p>
+ <cite>Ingrid Vestli · Bergen · Type X, 2024</cite>
+ </blockquote>
+ <blockquote>
+ <p>“Tap the flat and it rings for eleven seconds. I have timed it more often than I would like to admit.”</p>
+ <cite>Tomás Rivera · Seville · Seax, 2023</cite>
+ </blockquote>
+ <blockquote>
+ <p>“Fourteen months on the list. I would have waited three years.”</p>
+ <cite>K. Morimoto · Kyoto · Longsword, 2025</cite>
+ </blockquote>
+ </div>
+ </section>
+
+ <section class="finale" id="commission">
+ <div class="q-marker" data-station="qlift"></div>
+ <div class="q-marker" data-station="qplunge"></div>
+ <div class="q-marker" data-station="qrise"></div>
+ <div class="q-marker" data-station="display"></div>
+ <div class="finale-sticky">
+ <div class="finale-copy q-a">
+ <p class="eyebrow">The quench</p>
+ <h2>Into the brine.</h2>
+ </div>
+ <div class="finale-copy q-b">
+ <p class="eyebrow">Cooled · etched · yours</p>
+ <h2>Heat the blade.<br><em>Strike the steel.</em></h2>
+ <p class="lede">Tell us what it is for, who will carry it and how it should feel in the hand. We will tell you honestly whether we are the right smiths for it.</p>
+ <div class="cta-row">
+ <a class="btn btn-hot btn-lg" href="mailto:[email protected]" data-magnetic><span>Request a commission</span></a>
+ <a class="btn btn-ghost btn-lg" href="#process" data-magnetic><span>Visit the forge</span></a>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot">
+ <div class="foot-grid">
+ <div>
+ <p class="foot-brand">Hammer <em>&amp;</em> Ember</p>
+ <p>Forge de la Semois<br>Rue du Moulin 4, 6830 Bouillon<br>Belgium</p>
+ </div>
+ <div>
+ <p class="foot-h">The forge</p>
+ <p>Open to commissioners<br>Saturdays, by appointment<br>Fire lit at nine</p>
+ </div>
+ <div>
+ <p class="foot-h">Write</p>
+ <p><a href="mailto:[email protected]">[email protected]</a><br>+32 61 46 12 09</p>
+ </div>
+ <div>
+ <p class="foot-h">Letters from the forge</p>
+ <p>Four a year. Billets, failures, finished blades.</p>
+ <form class="news" onsubmit="event.preventDefault(); this.classList.add('sent');">
+ <input type="email" placeholder="your@email" aria-label="Email address" required>
+ <button type="submit" data-cursor="link">Subscribe</button>
+ </form>
+ </div>
+ </div>
+ <p class="foot-legal"><span>© 2026 Hammer &amp; Ember BV</span><span>Swords are sold as art objects and shipped to adults only.</span></p>
+ </footer>
+ </main>
+
+ <aside class="hud" aria-label="Forge readout">
+ <div class="hud-temp">
+ <p class="hud-label">Blade</p>
+ <p class="hud-val"><span class="hud-c">0</span><small>°C</small></p>
+ <p class="hud-name">Black heat</p>
+ </div>
+ <div class="hud-gauge" aria-hidden="true"><i class="hud-needle"></i></div>
+ <div class="hud-folds">
+ <p class="hud-label">Folds</p>
+ <p class="hud-val"><span class="hud-f">000</span><small>/512</small></p>
+ </div>
+ <div class="hud-bellows" aria-hidden="true"><span>Bellows</span><i></i></div>
+ </aside>
+ <div class="toast" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/ember/main.js b/examples/ember/main.js
new file mode 100644
index 0000000..e4bdfa7
--- /dev/null
+++ b/examples/ember/main.js
@@ -0,0 +1,814 @@
+import { ToneMappingMode } from 'postprocessing';
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal, ScrollTrigger } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { bakeTexture } from '../../src/core/textures.js';
+import { analyseSword, heatMaterial } from './heat.js';
+import { Sparks, Embers, Steam, HeatHaze, puffTexture } from './fx.js';
+import { ForgeAudio } from './audio.js';
+import { buildSmithy, ROOM, FIRE, TROUGH, WATER_Y, PRES_Y, PEGS, BLOCK, BLOCK_H } from './smithy.js';
+
+const DBG = new URLSearchParams(location.search);
+const coarse = matchMedia('(pointer: coarse)').matches;
+const V = (x, y, z) => new THREE.Vector3(x, y, z);
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let vol, haze;
+const engine = new Engine({
+ canvas, fov: 36, near: 0.03, far: 40, dpr: coarse ? 2 : 1.5, background: 0x040302,
+ post: {
+ ao: { aoRadius: 0.45, intensity: 2.6, distanceFalloff: 0.5 },
+ bloom: { intensity: 0.7, luminanceThreshold: 0.95, luminanceSmoothing: 0.4, radius: 0.78 },
+ pre: cam => [
+ (haze = new HeatHaze()),
+ (vol = new VolumetricSpotEffect(cam, { density: 0.028, noise: 0.92, noiseScale: 1.5, maxDist: 12, floorY: 0, wind: V(0.03, 0.09, 0.02) })),
+ ],
+ tone: 'aces',
+ vignette: { offset: 0.22, darkness: 0.82 },
+ noise: 0.055,
+ ca: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+scene.fog = new THREE.FogExp2(0x050302, 0.12);
+
+// Environment: dim soot dome, the forge as a hot orange softbox, the moonlit window as a cold one.
+scene.environment = studioEnvironment(renderer, {
+ top: 0x0e0b09, bottom: 0x030202, blur: 0.06,
+ panels: [
+ { pos: [4.6, 1.6, -7.0], size: [3.6, 2.4], intensity: 3.2, color: 0xff6a22 },
+ { pos: [4.0, -0.5, -6.0], size: [3.0, 1.2], intensity: 1.6, color: 0xff4a10 },
+ { pos: [7.0, 2.7, 1.1], size: [1.6, 2.0], intensity: 1.1, color: 0x8ea8d8 },
+ { pos: [0, 8, 0], size: [8, 8], intensity: 0.05, color: 0xffcfa0 },
+ ],
+});
+scene.environmentIntensity = 0.4;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+const audio = new ForgeAudio();
+const loaderEl = document.querySelector('.loader');
+const loaderState = loaderEl.querySelector('.loader-state');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = String(Math.round(v * 100)).padStart(2, '0');
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ loaderState.textContent = v < 0.45 ? 'Lighting the forge' : v < 0.9 ? 'Bringing the billet to heat' : 'At welding heat';
+ },
+ exit: async () => {
+ await gsap.timeline()
+ .to('.loader-bar i', { boxShadow: '0 0 40px rgba(255,220,170,1), 0 0 140px rgba(255,140,50,.9)', duration: 0.25 })
+ .to(loaderEl, { autoAlpha: 0, duration: 0.9, ease: 'power2.inOut' }, '+=0.1');
+ },
+});
+
+// ─── Lights ────────────────────────────────────────────────────────────────────
+scene.add(new THREE.HemisphereLight(0x1c2436, 0x0a0706, 0.09));
+const fireSpot = new THREE.SpotLight(0xff8a45, 0, 0, 0.78, 1.0, 2);
+fireSpot.position.set(FIRE.x - 0.12, FIRE.y + 0.34, FIRE.z + 0.5);
+fireSpot.target.position.set(-0.1, 0.7, 0.35);
+fireSpot.castShadow = true;
+fireSpot.shadow.mapSize.set(2048, 2048);
+fireSpot.shadow.camera.near = 0.15; fireSpot.shadow.camera.far = 9;
+fireSpot.shadow.bias = -0.00025; fireSpot.shadow.normalBias = 0.02;
+scene.add(fireSpot, fireSpot.target);
+const fireGlow = new THREE.PointLight(0xff7a38, 0, 6.5, 1.7);
+fireGlow.position.set(FIRE.x, FIRE.y + 0.28, FIRE.z + 0.12);
+scene.add(fireGlow);
+const moon = new THREE.SpotLight(0x7f9ccf, 48, 0, 0.3, 0.5, 1.2);
+moon.position.set(ROOM.x1 - 0.05, 2.4, 0.55);
+moon.target.position.set(0.9, 0, 2.3);
+scene.add(moon, moon.target);
+const lanternLight = new THREE.PointLight(0xffa458, 1.4, 5, 2);
+scene.add(lanternLight);
+const bladeLight = new THREE.PointLight(0xff7a2a, 0, 3.2, 2);
+const bladeLight2 = new THREE.PointLight(0xff7a2a, 0, 2.6, 2);
+scene.add(bladeLight, bladeLight2);
+// Finale lights: a cold bone-white key and a warm rim for the finished blade.
+const displayKey = new THREE.SpotLight(0xf1e4d0, 0, 0, 0.3, 0.9, 2);
+displayKey.position.set(1.25, 2.75, 0.95);
+const displayRim = new THREE.SpotLight(0xff9a50, 0, 0, 0.3, 0.9, 2);
+displayRim.position.set(3.35, 2.25, 2.75);
+const displayRim2 = new THREE.SpotLight(0xbcd0ff, 0, 0, 0.3, 0.9, 2);
+displayRim2.position.set(3.4, 1.9, 0.75);
+scene.add(displayRim2, displayRim2.target);
+scene.add(displayKey, displayKey.target, displayRim, displayRim.target);
+const flash = new THREE.PointLight(0xffd6a8, 0, 9, 1.4);
+scene.add(flash);
+vol.add(moon, { scale: 0.016, range: 0.02, softness: 0.45 });
+vol.add(fireSpot, { scale: 0.0016, range: 0.12, softness: 0.6 });
+
+// ─── Assets ────────────────────────────────────────────────────────────────────
+const T0 = performance.now();
+window.__emberDbg = {};
+const [anvilG, swordG, hammerG, brick, brickN, floorT, floorN, damT] = await Promise.all([
+ assets.gltf('models/ember/anvil.glb'),
+ assets.gltf('models/ember/sword.glb'),
+ assets.gltf('models/ember/hammer.glb'),
+ assets.texture('img/ember/brick.webp'),
+ assets.texture('img/ember/brick-n.webp', { srgb: false }),
+ assets.texture('img/ember/floor.webp'),
+ assets.texture('img/ember/floor-n.webp', { srgb: false }),
+ assets.texture('img/ember/damascus.webp'),
+]);
+window.__emberDbg.assets = Math.round(performance.now() - T0);
+damT.wrapS = THREE.MirroredRepeatWrapping; damT.wrapT = THREE.ClampToEdgeWrapping; damT.anisotropy = 16; damT.needsUpdate = true;
+
+const smithy = buildSmithy({ scene, renderer, tex: { brick, brickN, floor: floorT, floorN } });
+lanternLight.position.copy(smithy.lantern.position);
+
+// Anvil on its stump.
+const anvil = anvilG.scene;
+normalize(anvil, 0.9, { axis: 'y' });
+prepModel(anvil, renderer, { env: 0.9 });
+scene.add(anvil);
+anvil.updateMatrixWorld(true);
+const ray = new THREE.Raycaster();
+const hitY = (x, z, fallback) => {
+ ray.set(V(x, 3, z), V(0, -1, 0));
+ const h = ray.intersectObject(anvil, true)[0];
+ return h ? h.point.y : fallback;
+};
+const FACE_Y = Math.max(hitY(0.15, 0, 0.9), hitY(0.3, 0.02, 0.9));
+const STUMP_Y = hitY(0.0, 0.29, 0.45);
+
+// The sword.
+const swordMesh = firstMesh(swordG.scene);
+const SW = analyseSword(swordMesh.geometry, 0.95);
+swordMesh.removeFromParent();
+swordMesh.matrixAutoUpdate = false;
+swordMesh.matrix.copy(SW.matrix);
+swordMesh.castShadow = swordMesh.receiveShadow = true;
+prepModel(swordMesh, renderer, { env: 1.1 });
+const heat = heatMaterial(swordMesh.material, damT);
+const sword = new THREE.Group();
+sword.add(swordMesh);
+scene.add(sword);
+const bladeLocal = (u, out, top = true) => out.set(-(1 - u) * SW.bladeLength, top ? SW.halfThickness * 0.7 : 0, 0);
+
+// Finished blades hanging on the north wall.
+const wallEnv = studioEnvironment(renderer, {
+ top: 0x14100d, bottom: 0x040303, blur: 0.05,
+ panels: [
+ { pos: [3.5, 1.5, 6.0], size: [5, 3], intensity: 2.2, color: 0xff7a30 },
+ { pos: [-5.0, 2.5, 4.0], size: [2, 3], intensity: 1.4, color: 0x9fb4e0 },
+ { pos: [0, 6, 3], size: [4, 2], intensity: 0.8, color: 0xffe2c0 },
+ { pos: [0.5, 1.0, 8], size: [7, 4], intensity: 2.1, color: 0xeee2d2 },
+ { pos: [-2.5, 4.0, 5], size: [3, 2], intensity: 1.6, color: 0xf6ecdf },
+ ],
+});
+const wallSwords = [-1.58, -1.3, -1.02].map((x, i) => {
+ const m = swordMesh.clone();
+ m.material = swordMesh.material.clone();
+ m.material.envMap = wallEnv; m.material.envMapIntensity = 1.3;
+ const u = heatMaterial(m.material, damT);
+ u.uForged.value = 0; u.uDam.value = 1.4; u.uPeak.value = 0; u.uFront.value = 0;
+ const g = new THREE.Group();
+ g.add(m);
+ g.position.set(x, 1.68 - i * 0.02, ROOM.z0 + 0.1);
+ g.quaternion.setFromEuler(new THREE.Euler(0, Math.PI / 2 + (i - 1) * 0.12, Math.PI / 2 + (i - 1) * 0.02, 'YXZ'));
+ scene.add(g);
+ return g;
+});
+
+// The presentation blade: a finished sword on two pegs above the rack, lit for the macro in "The steel".
+const presEnv = studioEnvironment(renderer, {
+ top: 0x110d0b, bottom: 0x030202, blur: 0.04,
+ panels: [
+ { pos: [5.0, 1.2, 6.2], size: [1.6, 9], intensity: 4.2, color: 0xf3e7d6 },
+ { pos: [2.2, 1.0, 7.5], size: [1.0, 9], intensity: 1.6, color: 0xffd2a0 },
+ { pos: [7.5, 0.5, 2.0], size: [3, 3], intensity: 2.6, color: 0xff6a22 },
+ { pos: [-3, 5, 5], size: [4, 2], intensity: 0.6, color: 0xa8bce6 },
+ ],
+});
+const presSword = (() => {
+ const m = swordMesh.clone();
+ m.material = swordMesh.material.clone();
+ m.material.envMap = presEnv; m.material.envMapIntensity = 1.5;
+ const u = heatMaterial(m.material, damT);
+ u.uForged.value = 0; u.uDam.value = 1.4; u.uPeak.value = 0; u.uFront.value = 0;
+ // Lowest point of the mid-blade (sword-space +Z edge) so it rests exactly on the pegs.
+ const pos = swordMesh.geometry.attributes.position, bl = swordMesh.geometry.attributes.blade, v = V(0, 0, 0);
+ let edge = 0;
+ for (let i = 0; i < pos.count; i += 3) { const uu = bl.getX(i); if (uu > 0.2 && uu < 0.8) { v.fromBufferAttribute(pos, i).applyMatrix4(SW.matrix); edge = Math.max(edge, v.z); } }
+ const g = new THREE.Group();
+ g.add(m);
+ g.quaternion.setFromRotationMatrix(new THREE.Matrix4().makeBasis(V(1, 0, 0), V(0, 0, 1), V(0, -1, 0)));
+ g.position.set(PEGS[1] + 0.08, PRES_Y - 0.027 + edge, ROOM.z0 + 0.03);
+ scene.add(g);
+ return g;
+})();
+const presSpot = new THREE.SpotLight(0xffe0bc, 0, 0, 0.42, 0.85, 2);
+presSpot.position.set(-2.35, 2.62, -2.35);
+presSpot.target.position.set(-1.05, 2.25, -2.9);
+scene.add(presSpot, presSpot.target);
+// The finished blade in its block: a strip softbox behind the camera and the forge off to one side.
+const displayEnv = studioEnvironment(renderer, {
+ top: 0x0f0c0a, bottom: 0x030202, blur: 0.04,
+ panels: [
+ { pos: [-7.8, 0.6, 1.6], size: [1.5, 10], intensity: 4.0, color: 0xf3e8d8 },
+ { pos: [-6.5, 0.8, 4.6], size: [0.8, 10], intensity: 1.6, color: 0xc8d6f4 },
+ { pos: [-5.0, 0.2, -6.2], size: [3.5, 2.2], intensity: 4.5, color: 0xff6a22 },
+ { pos: [6.0, 3.0, -2.0], size: [2.0, 2.5], intensity: 1.2, color: 0x9fb4e0 },
+ ],
+});
+
+// The hammer.
+const hammerRoot = hammerG.scene;
+hammerRoot.updateMatrixWorld(true);
+const hBox = new THREE.Box3().setFromObject(hammerRoot);
+const hSize = hBox.getSize(V(0, 0, 0));
+const HS = 0.42 / hSize.x;
+prepModel(hammerRoot, renderer, { env: 0.9 });
+// Rig space: hand at the origin, handle along +X toward the hand, striking face pointing -Y.
+const hammerInner = new THREE.Group();
+hammerInner.add(hammerRoot);
+hammerRoot.rotation.x = Math.PI / 2;
+hammerRoot.scale.multiplyScalar(HS);
+const gripModel = V(hBox.max.x - hSize.x * 0.08, 0, (hBox.min.z + hBox.max.z) / 2 + 0.05);
+const faceModel = V(hBox.min.x + hSize.x * 0.08 + 0.02, 0, hBox.max.z);
+const headModel = V(hBox.min.x + hSize.x * 0.08 + 0.02, 0, 0);
+const toRig = p => V(p.x, -p.z, p.y).multiplyScalar(HS);
+hammerRoot.position.copy(toRig(gripModel)).negate();
+const FACE_L = toRig(faceModel).sub(toRig(gripModel));
+const HEAD_L = toRig(headModel).sub(toRig(gripModel));
+const hammer = new THREE.Group();
+hammer.add(hammerInner);
+scene.add(hammer);
+
+// ─── Brine reflection ─────────────────────────────────────────────────────────
+const brine = new PlanarReflection(renderer, { resolution: 0.5, point: V(0, WATER_Y, 0) });
+brine.hidden.push(smithy.waterMesh);
+{
+ const wm = smithy.waterMat, own = wm.onBeforeCompile;
+ brine.patch(wm, { strength: 1.8, distort: 0.035, lodScale: 3, lodBias: 0.4, f0: 0.035 });
+ const rp = wm.onBeforeCompile;
+ wm.onBeforeCompile = sh => { rp(sh); own(sh); };
+ wm.customProgramCacheKey = () => 'water-refl';
+}
+engine.onResize((w, h, dpr) => brine.setSize(w, h, dpr));
+const tubSphere = new THREE.Sphere(V(TROUGH.x, WATER_Y, TROUGH.z), 0.45), frustum = new THREE.Frustum(), projM = new THREE.Matrix4();
+
+// ─── Particles & haze ──────────────────────────────────────────────────────────
+const sparks = new Sparks({ max: 2600, floor: 0.004 });
+scene.add(sparks.mesh);
+const embers = new Embers({ count: coarse ? 900 : 1500, forge: V(FIRE.x, FIRE.y + 0.05, FIRE.z), room: new THREE.Box3(V(-3.0, 0.1, -2.7), V(3.4, 3.2, 3.0)), drift: V(-0.32, 0.04, 0.5) });
+scene.add(embers.points);
+const steam = new Steam({ max: 420, puff: puffTexture(bakeTexture, renderer) });
+scene.add(steam.mesh);
+engine.onResize((w, h, dpr) => {
+ sparks.resize(w, h, dpr);
+ embers.uniforms.uDpr.value = dpr;
+ haze.uniforms.get('uAsp').value = w / h;
+});
+
+// ─── Stations (camera + heat + sword pose per section) ────────────────────────
+const ST = {
+ hero: { pos: [-1.7, 1.55, 2.0], look: [-0.74, 0.8, -0.2], fov: 36, front: 0.42, peak: 0.7 },
+ fold: { pos: [-0.85, 1.2, 0.75], look: [0.25, 0.85, -0.35], fov: 34, front: 0.5, peak: 0.76 },
+ forge: { pos: [1.25, 1.1, 1.1], look: [-0.3, 0.85, -0.15], fov: 36, front: 0.6, peak: 0.82 },
+ quenchstep: { pos: [2.4, 1.45, 2.0], look: [1.35, 0.45, 0.3], fov: 36, front: 0.68, peak: 0.86 },
+ polish: { pos: [-2.55, 1.5, -1.2], look: [-1.7, 1.55, -2.9], fov: 38, front: 0.74, peak: 0.9 },
+ steel: { pos: [-1.8, 2.14, -2.26], look: [-1.22, 2.3, -2.88], fov: 32, front: 0.98, peak: 0.92 },
+ wide: { pos: [2.3, 2.0, 2.2], look: [0.1, 0.55, -0.7], fov: 42, front: 1.06, peak: 1.0 },
+ voices: { pos: [1.2, 0.6, -1.0], look: [-0.5, 0.95, 0.45], fov: 36, front: 1.06, peak: 1.0 },
+ qlift: { pos: [-0.36, 1.38, 2.17], look: [0.91, 1.15, 0.26], fov: 36, front: 1.06, peak: 1.0, sword: 'lift' },
+ qplunge: { pos: [0.5, 1.05, 1.65], look: [1.15, 0.62, 0.45], fov: 36, front: 1.06, peak: 1.0, sword: 'plunge' },
+ qrise: { pos: [0.3, 1.32, 2.0], look: [1.05, 1.24, 0.42], fov: 34, front: 1.06, peak: 1.0, sword: 'rise' },
+ display: { pos: [-0.3, 1.02, 2.1], look: [2.05, 1.16, 2.02], fov: 34, front: 1.06, peak: 1.0, sword: 'display' },
+};
+const FOCUS = {
+ hero: [0.05, 0.86, 0], fold: [-0.1, 0.9, -0.05], forge: [0.05, 0.9, 0], quenchstep: [1.2, 0.45, 0.45], polish: [-1.3, 1.5, -2.85],
+ steel: [-1.3, 2.3, -2.86], wide: [0.2, 0.6, -0.4], voices: [0, 0.9, 0], qlift: [1.2, 1.15, 0.45], qplunge: [1.2, 0.62, 0.45], qrise: [1.2, 1.25, 0.45], display: [2.05, 1.1, 1.75],
+};
+for (const k in ST) { ST[k].pos = V(...ST[k].pos); ST[k].look = V(...ST[k].look); ST[k].focus = V(...FOCUS[k]); ST[k].sword ??= 'anvil'; ST[k].key = k; }
+const stEls = [...document.querySelectorAll('[data-station]')];
+const stations = stEls.map(el => ST[el.dataset.station]);
+let anchors = [];
+function measure() {
+ const max = document.documentElement.scrollHeight - innerHeight;
+ anchors = stEls.map((el, i) => {
+ const r = el.getBoundingClientRect();
+ const top = r.top + scrollY;
+ if (i === 0) return 0;
+ const a = el.classList.contains('q-marker') ? top - innerHeight * 0.5 : top + r.height / 2 - innerHeight / 2;
+ return Math.min(a, max);
+ });
+}
+addEventListener('resize', () => requestAnimationFrame(measure));
+document.fonts?.ready.then(measure);
+
+// Sword poses.
+const qAnvil = new THREE.Quaternion().setFromEuler(new THREE.Euler(0, -0.06, 0));
+// Vertical, hilt up, the flat turned toward the display camera.
+const vertFacing = f => new THREE.Quaternion().setFromRotationMatrix(new THREE.Matrix4().makeBasis(V(0, 1, 0), f, new THREE.Vector3().crossVectors(V(0, 1, 0), f)));
+const faceQ = V(ST.qplunge.pos.x - TROUGH.x, 0, ST.qplunge.pos.z - TROUGH.z).normalize();
+const faceD = V(ST.display.pos.x - BLOCK.x, 0, ST.display.pos.z - BLOCK.z).normalize().applyAxisAngle(V(0, 1, 0), 0.22);
+const qVert = vertFacing(faceQ), qShow = vertFacing(faceD);
+const qPlunge = new THREE.Quaternion().setFromAxisAngle(faceQ, 0.3).multiply(qVert);
+const L = SW.bladeLength;
+const tipAt = (tip, q) => tip.clone().sub(V(-L, 0, 0).applyQuaternion(q));
+const POSES = {
+ anvil: { p: V(0.47, 0, 0.0), q: qAnvil },
+ lift: { p: tipAt(V(TROUGH.x, WATER_Y + 0.26, TROUGH.z), qVert), q: qVert },
+ plunge: { p: tipAt(V(TROUGH.x - 0.04, WATER_Y - 0.34, TROUGH.z + 0.02), qPlunge), q: qPlunge },
+ rise: { p: tipAt(V(TROUGH.x, WATER_Y + 0.2, TROUGH.z), qVert), q: qVert },
+ display: { p: tipAt(V(BLOCK.x, BLOCK_H - 0.05, BLOCK.z), qShow), q: qShow },
+};
+POSES.anvil.p.y = FACE_Y - SW.thickMin + 0.0015;
+
+// ─── Hammer rig ────────────────────────────────────────────────────────────────
+const hm = {
+ state: 'rest', t: 0,
+ from: { p: V(0, 0, 0), q: new THREE.Quaternion() },
+ cur: { p: V(0, 0, 0), q: new THREE.Quaternion() },
+ rest: { p: V(0, 0, 0), q: new THREE.Quaternion() },
+ impact: { p: V(0, 0, 0), q: new THREE.Quaternion() },
+ raised: { p: V(0, 0, 0), q: new THREE.Quaternion() },
+ axis: V(0, 0, 1), target: V(0, 0, 0), u: 0.4,
+};
+{
+ // Lying on the stump, head near the anvil foot, handle out toward the smith.
+ const handle = V(0.75, 0, -0.66).normalize();
+ const up = V(0, 1, 0);
+ const y = new THREE.Vector3().crossVectors(up, handle);
+ const m = new THREE.Matrix4().makeBasis(handle, y, up);
+ hm.rest.q.setFromRotationMatrix(m);
+ const headRest = V(-0.05, STUMP_Y + 0.03, -0.25);
+ hm.rest.p.copy(headRest).sub(HEAD_L.clone().applyQuaternion(hm.rest.q));
+ hm.cur.p.copy(hm.rest.p); hm.cur.q.copy(hm.rest.q);
+}
+const tmpV = V(0, 0, 0), tmpV2 = V(0, 0, 0), tmpQ = new THREE.Quaternion();
+function strikeTarget(out) {
+ hm.u = clamp(heat.uFront.value * 0.52, 0.3, 0.52);
+ sword.updateMatrixWorld(true);
+ return out.copy(bladeLocal(hm.u, tmpV)).applyMatrix4(sword.matrixWorld);
+}
+function computeSwing() {
+ strikeTarget(hm.target);
+ const D = V(0.5, 0.34, -1).normalize(); // handle direction at impact: toward the smith across the anvil, rising slightly
+ const Y = V(0, 1, 0).addScaledVector(D, -D.y).normalize();
+ const Z = new THREE.Vector3().crossVectors(D, Y);
+ hm.impact.q.setFromRotationMatrix(new THREE.Matrix4().makeBasis(D, Y, Z));
+ hm.impact.p.copy(hm.target).sub(FACE_L.clone().applyQuaternion(hm.impact.q));
+ hm.axis.copy(Z);
+ // Raised: rotate about the wrist so the head lifts up and back, and lift the arm.
+ const th = 1.35;
+ tmpQ.setFromAxisAngle(hm.axis, th);
+ const headA = HEAD_L.clone().applyQuaternion(tmpQ.clone().multiply(hm.impact.q));
+ const sgn = headA.y > HEAD_L.clone().applyQuaternion(hm.impact.q).y ? 1 : -1;
+ hm.sign = sgn;
+ hm.raised.q.setFromAxisAngle(hm.axis, th * sgn).multiply(hm.impact.q);
+ hm.raised.p.copy(hm.impact.p).add(V(0, 0.2, 0)).addScaledVector(D, 0.1);
+}
+const ease = {
+ 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), in: t => t * t * t,
+};
+function setPose(p, q, arc = 0) { hammer.position.copy(p); hammer.position.y += arc; hammer.quaternion.copy(q); hm.cur.p.copy(hammer.position); hm.cur.q.copy(q); }
+function blendPose(a, b, t, arc = 0) {
+ tmpV.lerpVectors(a.p, b.p, t);
+ tmpQ.slerpQuaternions(a.q, b.q, t);
+ setPose(tmpV, tmpQ, Math.sin(t * Math.PI) * arc);
+}
+const hammerApi = {
+ canStrike: () => swordOnAnvil > 0.95,
+ grab() {
+ if (!this.canStrike() || hm.state === 'swing') return false;
+ computeSwing();
+ hm.from.p.copy(hm.cur.p); hm.from.q.copy(hm.cur.q);
+ hm.state = 'grab'; hm.t = 0; hm.release = false;
+ return true;
+ },
+ release() { if (hm.state === 'grab' || hm.state === 'raised') hm.release = true; },
+ cancel() {
+ if (hm.state === 'grab' || hm.state === 'raised') { hm.from.p.copy(hm.cur.p); hm.from.q.copy(hm.cur.q); hm.state = 'return'; hm.t = 0; }
+ },
+};
+function updateHammer(dt) {
+ hm.t += dt;
+ if (hm.state === 'rest') { setPose(hm.rest.p, hm.rest.q); return; }
+ if (hm.state === 'grab') {
+ const k = clamp(hm.t / 0.2);
+ blendPose(hm.from, hm.raised, ease.out(k), 0.08);
+ if (k >= 1) { hm.state = 'raised'; hm.t = 0; }
+ }
+ if (hm.state === 'raised') {
+ // Tiny tremble at the top of the swing.
+ tmpQ.setFromAxisAngle(hm.axis, Math.sin(hm.t * 30) * 0.01).multiply(hm.raised.q);
+ setPose(hm.raised.p, tmpQ);
+ if (hm.release && hm.t > 0.04) { hm.state = 'swing'; hm.t = 0; computeSwing(); }
+ }
+ if (hm.state === 'swing') {
+ const k = clamp(hm.t / 0.11);
+ const e = ease.in(k);
+ tmpQ.setFromAxisAngle(hm.axis, 1.35 * hm.sign * (1 - e)).multiply(hm.impact.q);
+ tmpV.lerpVectors(hm.raised.p, hm.impact.p, e);
+ setPose(tmpV, tmpQ);
+ if (k >= 1) { hm.state = 'recoil'; hm.t = 0; impact(hm.target); }
+ }
+ if (hm.state === 'recoil') {
+ const k = clamp(hm.t / 0.18);
+ tmpQ.setFromAxisAngle(hm.axis, 0.34 * hm.sign * Math.sin(k * Math.PI * 0.9)).multiply(hm.impact.q);
+ tmpV.copy(hm.impact.p).add(V(0, Math.sin(k * Math.PI * 0.9) * 0.03, 0));
+ setPose(tmpV, tmpQ);
+ if (k >= 1) { hm.state = 'hover'; hm.t = 0; hm.from.p.copy(hm.cur.p); hm.from.q.copy(hm.cur.q); }
+ }
+ if (hm.state === 'hover') {
+ // Held just above the steel for a beat, ready for another blow.
+ const k = clamp(hm.t / 0.25);
+ tmpQ.setFromAxisAngle(hm.axis, 0.45 * hm.sign).multiply(hm.impact.q);
+ tmpV.copy(hm.impact.p).add(V(0, 0.07, 0));
+ blendPose(hm.from, { p: tmpV.clone(), q: tmpQ.clone() }, ease.out(k));
+ if (hm.t > 0.32) { hm.state = 'return'; hm.t = 0; hm.from.p.copy(hm.cur.p); hm.from.q.copy(hm.cur.q); }
+ }
+ if (hm.state === 'return') {
+ const k = clamp(hm.t / 0.7);
+ blendPose(hm.from, hm.rest, ease.inOut(k), 0.12);
+ if (k >= 1) hm.state = 'rest';
+ }
+}
+
+// ─── Strike ────────────────────────────────────────────────────────────────────
+const flashEl = document.querySelector('.flash');
+const foldsEl = document.querySelector('.hud-f');
+let folds = 0, shake = 0, lastStrike = -10, strikeScreen = new THREE.Vector2();
+let heatBoost = 0;
+function impact(p) {
+ const t = engine.time;
+ const h = heat.uPeak.value * smooth(0.0, 0.3, heat.uFront.value - hm.u + 0.25);
+ sparks.burst(p, { count: Math.round(50 + h * 190), flakes: Math.round(14 + h * 46), power: 0.4 + h * 0.7, time: t });
+ heat.uStrike.value.set(hm.u, 1, 0);
+ shake = 1;
+ lastStrike = t;
+ heatBoost = Math.min(heatBoost + 0.02, 0.35);
+ gsap.fromTo(flash, { intensity: 6 + h * 10 }, { intensity: 0, duration: 0.5, ease: 'expo.out', overwrite: true });
+ flash.position.copy(p).add(V(0, 0.4, 0.35));
+ tmpV.copy(p).project(camera);
+ strikeScreen.set((tmpV.x + 1) / 2, (tmpV.y + 1) / 2);
+ flashEl.style.setProperty('--fx', (strikeScreen.x * 100).toFixed(1) + '%');
+ flashEl.style.setProperty('--fy', ((1 - strikeScreen.y) * 100).toFixed(1) + '%');
+ gsap.fromTo(flashEl, { opacity: 0.1 + h * 0.18 }, { opacity: 0, duration: 0.5, ease: 'expo.out', overwrite: true });
+ if (audioReady) audio.clang(0.6 + h * 0.4, h);
+ folds = Math.min(512, folds + 1);
+ foldsEl.textContent = String(folds).padStart(3, '0');
+ gsap.fromTo(foldsEl, { scale: 1.35, color: '#ffb35a' }, { scale: 1, color: '#e2d6c2', duration: 0.6, ease: 'expo.out' });
+ if (folds === 512) toast('512 folds. Now quench it.');
+}
+
+// ─── Input: click to strike, hold for the bellows ─────────────────────────────
+let press = null, holdTimer = 0, bellowsHeld = false, audioReady = false;
+const cur = cursor({ color: '#ffd9b8', blend: 'normal', size: 34 });
+const blocked = e => e.target.closest?.('a,button,input,form,.blade-card,.cta-row,.foot,.tw-nav,.nav');
+addEventListener('pointerdown', e => {
+ if (e.button !== 0 || blocked(e) || !started) return;
+ audio.ensure(); audioReady = true; audio.setEnabled(soundOn);
+ press = { t: performance.now() };
+ if (!coarse) hammerApi.grab(); // touch waits for a clean tap so scrolling never lifts the hammer
+ clearTimeout(holdTimer);
+ holdTimer = setTimeout(() => {
+ if (!press) return;
+ press.hold = true;
+ hammerApi.cancel();
+ bellowsHeld = true;
+ document.body.classList.add('is-bellows');
+ cur?.set('hold', 'Bellows');
+ audio.bellows(true);
+ }, 280);
+});
+const endPress = cancel => {
+ if (!press) return;
+ clearTimeout(holdTimer);
+ if (press.hold) { bellowsHeld = false; document.body.classList.remove('is-bellows'); audio.bellows(false); cur?.set(''); }
+ else if (cancel) hammerApi.cancel();
+ else if (coarse) { if (hammerApi.grab()) setTimeout(() => hammerApi.release(), 40); }
+ else hammerApi.release();
+ press = null;
+};
+addEventListener('pointerup', () => endPress(false));
+addEventListener('pointercancel', () => endPress(true));
+addEventListener('keydown', e => { if (e.code === 'Space' && !e.repeat && document.activeElement === document.body) { e.preventDefault(); if (hammerApi.grab()) setTimeout(() => hammerApi.release(), 60); } });
+
+// Sound toggle.
+const soundBtn = document.querySelector('.sound');
+let soundOn = true;
+soundBtn.addEventListener('click', () => {
+ soundOn = !soundOn;
+ soundBtn.setAttribute('aria-pressed', String(soundOn));
+ soundBtn.querySelector('.sound-label').textContent = soundOn ? 'Sound on' : 'Sound off';
+ if (audioReady) audio.setEnabled(soundOn);
+});
+
+const toastEl = document.querySelector('.toast');
+let toastTimer;
+function toast(msg, ms = 2600) { toastEl.textContent = msg; toastEl.classList.add('on'); clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms); }
+
+// ─── HUD ───────────────────────────────────────────────────────────────────────
+const hudBel = document.querySelector('.hud-bellows');
+const hintEl = document.querySelector('.hint');
+const hudC = document.querySelector('.hud-c'), hudName = document.querySelector('.hud-name'), hudEl = document.querySelector('.hud');
+const HEATS = [[480, 'Black heat'], [580, 'Faint red'], [680, 'Blood red'], [780, 'Dark cherry'], [880, 'Cherry red'], [980, 'Bright cherry'], [1080, 'Orange'], [1180, 'Yellow'], [1280, 'Light yellow'], [9999, 'Welding white']];
+let hudShown = -1, hudTick = 0;
+const hudAvoid = [...document.querySelectorAll('.stats, .blades, .foot-grid, .quotes blockquote, .steel-head, .steel-lede, .com-head, .step > *')];
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const camPos = V(0, 0, 0), camLook = V(0, 0, 0), camTmp = V(0, 0, 0);
+let camT = 0, swordOnAnvil = 1, started = false, intro = { fire: 0, heat: 0 };
+let coolFront = 0, damFront = 0, lastSteamT = 0, submergedPrev = 0;
+const qaEl = document.querySelector('.q-a'), qbEl = document.querySelector('.q-b');
+const shakeN = t => Math.sin(t * 91.3) * 0.5 + Math.sin(t * 57.1 + 1.3) * 0.35 + Math.sin(t * 131.7 + 2.1) * 0.15;
+const hazePts = haze.uniforms.get('uPts').value;
+const debugCam = DBG.get('cam')?.split(',').map(Number);
+
+function stationBlend(y) {
+ // Returns [i, f] with f eased so the camera settles at each station.
+ if (!anchors.length) return [0, 0, 0];
+ let i = 0;
+ while (i < anchors.length - 2 && y >= anchors[i + 1]) i++;
+ const a = anchors[i], b = anchors[i + 1] ?? a + 1;
+ const raw = clamp((y - a) / Math.max(b - a, 1));
+ return [i, smooth(0.08, 0.92, raw), raw];
+}
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ const y = window.__lenis?.animatedScroll ?? scrollY;
+ const [si, sf, raw] = stationBlend(y);
+ camT = damp(camT, si + sf, 6, dt);
+ const i0 = Math.min(Math.floor(camT), stations.length - 1), i1 = Math.min(i0 + 1, stations.length - 1), f = camT - i0;
+ const A = stations[i0], B = stations[i1];
+ const heatT = si + raw; // unsmoothed for heat, so the steel keeps warming as you read
+ const hA = stations[Math.min(Math.floor(heatT), stations.length - 1)], hB = stations[Math.min(Math.floor(heatT) + 1, stations.length - 1)], hf = heatT - Math.floor(heatT);
+ document.body.classList.toggle('is-scrolled', y > 40);
+
+ // Camera.
+ camPos.lerpVectors(A.pos, B.pos, f);
+ camLook.lerpVectors(A.look, B.look, f);
+ // Keep long moves from cutting through the anvil: lift the path a little mid-transition.
+ camPos.y += Math.sin(f * Math.PI) * A.pos.distanceTo(B.pos) * 0.08;
+ camera.fov = lerp(A.fov, B.fov, f);
+ const asp = camera.aspect;
+ if (asp < 1) {
+ // Portrait: aim at the subject itself, pull back, and lift it into the upper half above the copy.
+ const dir = camTmp.copy(camPos).sub(camLook);
+ camLook.lerpVectors(A.focus, B.focus, f);
+ const k = 1 + (1 - asp) * 1.05;
+ camPos.copy(camLook).addScaledVector(dir, k);
+ camLook.y -= dir.length() * k * 0.2 * (1 - asp);
+ }
+ const dc = window.__cam ?? debugCam;
+ if (dc) { camPos.set(dc[0], dc[1], dc[2]); camLook.set(dc[3], dc[4], dc[5]); if (dc[6]) camera.fov = dc[6]; }
+ shake = Math.max(0, shake - dt * 3.2);
+ const sh = shake * shake * 0.018;
+ camera.position.copy(camPos).add(camTmp.set(pointer.sx * 0.06 + Math.sin(t * 0.3) * 0.012 + shakeN(t) * sh, pointer.sy * 0.035 + Math.sin(t * 0.47) * 0.008 + shakeN(t + 7) * sh, 0));
+ camera.lookAt(camLook.x + shakeN(t + 3) * sh * 0.6, camLook.y + shakeN(t + 5) * sh * 0.6, camLook.z);
+ camera.updateProjectionMatrix();
+
+ // Bellows.
+ const bel = embers.uniforms.uBellows;
+ bel.value = damp(bel.value, bellowsHeld ? 1 : 0, bellowsHeld ? 2.2 : 1.1, dt);
+ if (bellowsHeld) heatBoost = Math.min(heatBoost + dt * 0.1, 0.4);
+ else heatBoost = Math.max(0, heatBoost - dt * 0.012);
+ hudBel.style.setProperty('--b', bel.value.toFixed(3));
+
+ // Heat along the page.
+ const frontT = lerp(hA.front, hB.front, hf) * intro.heat + heatBoost;
+ const peakT = Math.min(1, lerp(hA.peak, hB.peak, hf) * intro.heat + heatBoost * 0.5 + bel.value * 0.06);
+ const rate = 1.1 + bel.value * 2.2;
+ heat.uFront.value = damp(heat.uFront.value, Math.min(frontT, 1.12), rate, dt);
+ heat.uPeak.value = damp(heat.uPeak.value, peakT, rate, dt);
+ heat.uTime.value = t;
+ heat.uStrike.value.z = t - lastStrike;
+
+ // Fire.
+ const flick = 0.82 + 0.1 * Math.sin(t * 13.1) * Math.sin(t * 7.3 + 1.2) + 0.08 * Math.sin(t * 23.7);
+ const pump = bel.value * (0.8 + 0.2 * Math.sin(t * 5.5));
+ const fireLevel = intro.fire * (1 + pump * 1.1);
+ if (bel.value > 0.3 && Math.random() < dt * 14 * bel.value) sparks.pop(tmpV.set(FIRE.x + (Math.random() - 0.5) * 0.4, FIRE.y + 0.1, FIRE.z + (Math.random() - 0.5) * 0.3), t, 1);
+ smithy.fire.uTime.value = t;
+ smithy.fire.uFire.value = fireLevel;
+ fireSpot.intensity = 36 * fireLevel * flick;
+ fireGlow.intensity = 18 * fireLevel * (flick * 0.8 + 0.2);
+ lanternLight.intensity = 5.5 * (0.94 + Math.sin(t * 17) * 0.03 + Math.sin(t * 5.3) * 0.03) * intro.fire;
+ embers.uniforms.uClock.value += dt * (1 + bel.value * 2.4);
+ embers.uniforms.uTime.value = t;
+ embers.uniforms.uFire.value = intro.fire;
+ if (audioReady) audio.fire(bel.value);
+
+ // Sword pose: blend between the station poses.
+ const pA = POSES[A.sword], pB = POSES[B.sword];
+ const sf2 = A.sword === B.sword ? 0 : f;
+ sword.position.lerpVectors(pA.p, pB.p, sf2);
+ sword.quaternion.slerpQuaternions(pA.q, pB.q, sf2);
+ if (A.sword === 'anvil' && B.sword !== 'anvil') sword.position.y += Math.sin(sf2 * Math.PI) * 0.25;
+ if (A.sword !== 'anvil' && B.sword !== 'display') sword.position.y += Math.sin(t * 1.3) * 0.004; // held, not fixed
+ if (B.sword === 'display' && A.sword !== 'display') sword.position.y += Math.sin(sf2 * Math.PI) * 0.12; // lifted over, set down
+ swordOnAnvil = A.sword === 'anvil' ? (B.sword === 'anvil' ? 1 : 1 - sf2) : 0;
+ sword.updateMatrixWorld(true);
+
+ // Quench: which part of the blade is under the brine?
+ const tipW = bladeLocal(0, tmpV, false).applyMatrix4(sword.matrixWorld);
+ const guardW = bladeLocal(1, tmpV2, false).applyMatrix4(sword.matrixWorld);
+ const inTrough = Math.hypot(tipW.x - TROUGH.x, tipW.z - TROUGH.z) < 0.33;
+ const uSub = inTrough && tipW.y < WATER_Y ? clamp((WATER_Y - tipW.y) / Math.max(guardW.y - tipW.y, 0.01)) : 0;
+ // The quench is tied to scroll position (so jumps via the nav still land on a finished blade),
+ // but the cold front travels up the steel over time.
+ const qpi = anchorIndex('qplunge');
+ const coolTarget = Math.max(uSub > 0 ? uSub + 0.06 : 0, camT > qpi + 0.12 ? 1.25 : 0);
+ coolFront = coolTarget > coolFront ? damp(coolFront, coolTarget, uSub > 0 ? 2.6 : 1.6, dt) : damp(coolFront, coolTarget, 1.0, dt);
+ heat.uCool.value = coolFront;
+ // Scale falls away as it rises from the brine.
+ const damTarget = camT > anchorIndex('qrise') - 0.5 ? clamp((camT - (anchorIndex('qrise') - 0.5)) / 1.2) * 1.4 : 0;
+ damFront = damp(damFront, damTarget * smooth(0.6, 1.0, coolFront), 3, dt);
+ heat.uDam.value = damFront;
+ heat.uForged.value = 1;
+ const reveal = clamp(damFront / 1.2);
+ swordMesh.material.envMap = reveal > 0.02 ? displayEnv : null;
+ swordMesh.material.envMapIntensity = lerp(1.1, 1.6, reveal);
+ const onDisplay = smooth(anchorIndex('display') - 1, anchorIndex('display') - 0.2, camT);
+ displayKey.intensity = reveal * 14 + onDisplay * 10; displayRim.intensity = reveal * 16 + onDisplay * 14; displayRim2.intensity = onDisplay * 12;
+ displayKey.target.position.set(sword.position.x, sword.position.y - L * 0.55, sword.position.z);
+ displayRim.target.position.copy(displayKey.target.position); displayRim2.target.position.copy(displayKey.target.position);
+ const nearSteel = clamp(1 - Math.abs(camT - anchorIndex('steel')) / 1.1);
+ presSpot.intensity = 3 + nearSteel * 9;
+
+ // Steam: hot steel entering water.
+ const hotSub = Math.max(0, uSub - coolFront * 0.6) * heat.uPeak.value;
+ const entering = Math.max(0, uSub - submergedPrev);
+ submergedPrev = uSub;
+ let steamRate = hotSub * 170 + entering * 1400 + (uSub > 0 ? 6 : 0) + (coolFront > 0.3 && coolFront < 1.19 && uSub === 0 ? 8 : 0);
+ steam.uniforms.uTime.value = t;
+ if (steamRate > 0) {
+ lastSteamT += dt * steamRate;
+ while (lastSteamT > 1) {
+ lastSteamT -= 1;
+ if (uSub > 0) {
+ // Emit at the waterline where the blade pierces it.
+ const k = clamp((WATER_Y - tipW.y) / Math.max(guardW.y - tipW.y, 0.01));
+ tmpV.lerpVectors(tipW, guardW, k);
+ tmpV.y = WATER_Y + 0.01;
+ steam.emit(tmpV, t, { spread: 0.1, vel: 0.6 + hotSub * 0.9, size: 0.09 + hotSub * 0.08, life: 3.0 });
+ } else {
+ tmpV.lerpVectors(tipW, guardW, Math.random() * 0.9);
+ steam.emit(tmpV, t, { spread: 0.02, vel: 0.25, size: 0.08, life: 2.4 });
+ }
+ }
+ }
+ const glowK = 520 + heat.uPeak.value * 1080;
+ const glowCol = blackbodyJS(glowK);
+ const glowI = Math.pow(Math.max(glowK - 720, 0) / 930, 2.6);
+ steam.uniforms.uGlow.value.copy(glowCol).multiplyScalar(glowI * 9 * clamp(Math.max(0, uSub - coolFront * 0.8 + 0.15)) * (uSub > 0 ? 1 : 0));
+ steam.uniforms.uFire.value.setRGB(0.1, 0.045, 0.02).multiplyScalar(fireLevel);
+ smithy.water.uTime.value = t;
+ smithy.water.uBlade.value.set(tipW.x + (guardW.x - tipW.x) * uSub, tipW.z + (guardW.z - tipW.z) * uSub);
+ smithy.water.uBoil.value = damp(smithy.water.uBoil.value, uSub > 0 ? clamp(hotSub * 3 + 0.2) : 0, 3, dt);
+ smithy.water.uGlow.value.copy(glowCol).multiplyScalar(glowI * 4 * Math.max(0, uSub - coolFront * 0.9 + 0.05));
+ if (audioReady) audio.hiss(uSub > 0 ? hotSub * 2 + entering * 20 : 0);
+
+ // Light from the hot steel itself.
+ const fr = heat.uFront.value;
+ const hotLen = Math.max(0, Math.min(fr, 1) - coolFront);
+ const peakK = 520 + heat.uPeak.value * 1080 * (coolFront > 1 ? 0 : 1);
+ const bI = Math.pow(Math.max(peakK - 720, 0) / 930, 2.6);
+ bladeLight.color.copy(blackbodyJS(peakK));
+ bladeLight2.color.copy(bladeLight.color);
+ bladeLocal(clamp(coolFront + hotLen * 0.3, 0, 1), bladeLight.position).applyMatrix4(sword.matrixWorld);
+ bladeLocal(clamp(coolFront + hotLen * 0.75, 0, 1), bladeLight2.position).applyMatrix4(sword.matrixWorld);
+ bladeLight.position.y += 0.16; bladeLight2.position.y += 0.16;
+ bladeLight.intensity = bI * 7 * Math.min(1, hotLen * 2.5);
+ bladeLight2.intensity = bI * 4.5 * Math.min(1, hotLen * 1.6);
+
+ // Glowing flakes popping off the hottest steel.
+ if (swordOnAnvil > 0.9 && Math.random() < dt * heat.uPeak.value * fr * 5) {
+ bladeLocal(Math.random() * Math.min(fr, 1) * 0.9, tmpV).applyMatrix4(sword.matrixWorld);
+ sparks.pop(tmpV, t, 1 + (Math.random() < 0.3 ? 1 : 0));
+ }
+ sparks.uniforms.uTime.value = t;
+
+ // Heat haze above the hot part of the blade (screen space).
+ for (let k = 0; k < 8; k++) {
+ const u = clamp(coolFront + (k + 0.5) / 8 * hotLen, 0, 1);
+ bladeLocal(u, tmpV).applyMatrix4(sword.matrixWorld).project(camera);
+ const vis = tmpV.z < 1 && Math.abs(tmpV.x) < 1.3 && Math.abs(tmpV.y) < 1.3 ? 1 : 0;
+ hazePts[k].set((tmpV.x + 1) / 2, (tmpV.y + 1) / 2, vis * Math.min(1, hotLen * 2) * heat.uPeak.value * 0.5);
+ }
+ const shockAge = t - lastStrike;
+ haze.uniforms.get('uShock').value.set(strikeScreen.x, strikeScreen.y, shockAge * 0.75, shockAge < 0.6 ? (1 - shockAge / 0.6) : 0);
+ haze.uniforms.get('uHazeTime').value = t;
+
+ // Brine reflection, only while the tub is in view.
+ camera.updateMatrixWorld();
+ frustum.setFromProjectionMatrix(projM.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse));
+ brine.enabled = frustum.intersectsSphere(tubSphere);
+ smithy.water.uForgeCol.value.setRGB(1.0, 0.36, 0.09).multiplyScalar(fireLevel * flick * 1.2);
+ brine.update(scene, camera);
+
+ // Hammer.
+ updateHammer(dt);
+ if (swordOnAnvil < 0.95 && hm.state !== 'rest' && hm.state !== 'return') hammerApi.cancel();
+
+ // Finale copy.
+ const qi = anchorIndex('qplunge'), ri = anchorIndex('qrise'), di = anchorIndex('display');
+ qaEl.style.opacity = (smooth(qi - 1.1, qi - 0.5, camT) * (1 - smooth(qi + 0.35, qi + 0.85, camT))).toFixed(3);
+ qbEl.style.opacity = smooth(di - 0.5, di - 0.05, camT).toFixed(3);
+ qbEl.style.transform = `translateY(${((1 - smooth(di - 0.5, di, camT)) * 30).toFixed(1)}px)`;
+ document.body.classList.toggle('is-finale', camT > anchorIndex('qlift') - 0.4);
+
+ // HUD: step aside when content panels pass underneath it.
+ if ((hudTick = (hudTick + 1) % 8) === 0) {
+ const hr = hudEl.getBoundingClientRect();
+ let over = false;
+ for (const el of hudAvoid) { const r = el.getBoundingClientRect(); if (r.top < hr.bottom && r.bottom > hr.top && r.left < hr.right && r.right > hr.left) { over = true; break; } }
+ hudEl.classList.toggle('hud-away', over);
+ hintEl.classList.toggle('away', over || y > innerHeight * 5.5);
+ }
+ // HUD.
+ const hottest = Math.max(0, heat.uPeak.value * (hotLen > 0.02 ? 1 : 0) * (1 + (t - lastStrike < 0.4 ? 0.04 : 0)));
+ const C = Math.round((520 + hottest * 1080 - 273) / 5) * 5;
+ if (C !== hudShown) {
+ hudShown = C;
+ hudC.textContent = Math.max(C, 20).toLocaleString('en-US');
+ hudName.textContent = HEATS.find(h => C < h[0])[1];
+ hudEl.style.setProperty('--t', clamp((C - 250) / 1100).toFixed(3));
+ }
+});
+function anchorIndex(key) { const i = stations.findIndex(s => s.key === key); return i < 0 ? 99 : i; }
+function blackbodyJS(K) {
+ const t = K / 100;
+ let g = clamp((99.4708025861 * Math.log(Math.max(t, 1)) - 161.1195681661) / 255);
+ let b = t <= 19 ? 0 : clamp((138.5177312231 * Math.log(t - 10) - 305.0447927307) / 255);
+ const c = new THREE.Color(1, Math.pow(g, 2.2), Math.pow(b, 2.2));
+ c.g += smooth(1250, 1750, K) * 0.16;
+ return c;
+}
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('ember', { theme: 'dark', corner: 'bl' });
+if (coarse) { document.querySelector('.k-strike').textContent = 'Tap'; document.querySelector('.k-verb').textContent = 'tap'; }
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+// In-page links glide through the scene instead of jumping; the commission CTA lands on the finished blade.
+document.addEventListener('click', e => {
+ const a = e.target.closest?.('a[href^="#"]');
+ if (!a) return;
+ const id = a.getAttribute('href').slice(1);
+ e.preventDefault();
+ let y = 0;
+ if (id === 'commission') y = anchors[anchorIndex('display')] ?? 0;
+ else if (id && id !== 'top') { const el = document.getElementById(id); if (el) y = el.getBoundingClientRect().top + scrollY; }
+ const dist = Math.abs(y - scrollY) / innerHeight;
+ lenis.scrollTo(y, { duration: Math.min(1.2 + dist * 0.35, 4.5), easing: t => 1 - Math.pow(1 - t, 3) });
+});
+measure();
+// Cursor label over the forge.
+document.addEventListener('pointermove', e => {
+ if (!cur || bellowsHeld) return;
+ const over3D = !blocked(e) && swordOnAnvil > 0.95;
+ if (over3D && cur.root.dataset.state !== 'link') cur.set('strike', '');
+ else if (!over3D && cur.root.dataset.state === 'strike') cur.set('');
+}, { passive: true });
+
+// Warm up every program with the fire and the steel at full heat.
+intro.fire = 1; intro.heat = 1;
+heat.uPeak.value = 1; heat.uFront.value = 0.6;
+camera.position.copy(ST.hero.pos); camera.lookAt(ST.hero.look);
+const TC = performance.now();
+renderer.compile(scene, camera);
+window.__emberDbg.compile = Math.round(performance.now() - TC);
+sparks.burst(V(0, 1, 0), { count: 1, flakes: 1, time: -10 });
+steam.emit(V(0, -5, 0), -100);
+intro.fire = 0; intro.heat = 0;
+heat.uPeak.value = 0; heat.uFront.value = 0;
+gsap.set('.title .t-line > span, .title .t-accent > span', { yPercent: 110 });
+gsap.set('.eyebrow, .sub, .hint, .hud, .nav', { opacity: 0 });
+engine.start();
+window.__ember = { setTone: m => { engine.post.tone.mode = ToneMappingMode[m]; }, post: engine.post, sparks, steam, embers, smithy, heat, hm, hammerApi, stations, anchors: () => anchors, impact, POSES, sword, SW, FACE_Y, STUMP_Y, camera };
+if (DBG.has('now')) { intro.fire = 1; intro.heat = 1; }
+await loader.finish();
+started = true;
+measure();
+window.__emberReady = true;
+window.__emberDbg.ready = Math.round(performance.now() - T0);
+
+// Intro: the fire wakes, the steel comes up to heat, the first blow lands with the title.
+reveal('.step h2, .steel-head h2, .com-head h2, .q-b h2', { type: 'lines', stagger: 0.09 });
+reveal('.quotes blockquote p, .lede', { type: 'lines', stagger: 0.05, y: '100%' });
+gsap.to(intro, { fire: 1, duration: 2.2, ease: 'power2.out' });
+gsap.to(intro, { heat: 1, duration: 2.6, ease: 'power2.inOut', delay: 0.2 });
+setTimeout(() => { if (hammerApi.grab()) setTimeout(() => hammerApi.release(), 120); }, 1300);
+gsap.to('.title .t-line > span', { yPercent: 0, duration: 1.1, ease: 'expo.out', stagger: 0.07, delay: 1.72 });
+gsap.to('.title .t-accent > span', { yPercent: 0, duration: 1.4, ease: 'expo.out', delay: 2.05 });
+gsap.to('.eyebrow, .sub, .hint, .hud, .nav', { opacity: 1, duration: 1.2, ease: 'power2.out', stagger: 0.06, delay: 2.2 });
+
+// Count-up stats.
+document.querySelectorAll('.stats .num[data-count]').forEach(el => {
+ const to = +el.dataset.count, dec = +(el.dataset.dec ?? 0);
+ const o = { v: 0 };
+ gsap.to(o, { v: to, duration: 2, ease: 'power3.out', scrollTrigger: { trigger: el, start: 'top 90%', once: true },
+ onUpdate: () => { el.textContent = o.v.toFixed(dec); } });
+});
diff --git a/examples/ember/smithy.js b/examples/ember/smithy.js
new file mode 100644
index 0000000..9e2d2c4
--- /dev/null
+++ b/examples/ember/smithy.js
@@ -0,0 +1,443 @@
+// The smithy: soot-black brick room, a coal forge with a hood, a brine trough, tools on the wall, a moonlit window.
+import * as THREE from 'three';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { NOISE, BLACKBODY } from './glsl.js';
+
+export const ROOM = { x0: -3.3, x1: 3.9, z0: -2.9, z1: 4.6, h: 3.6 };
+export const FORGE = new THREE.Vector3(1.45, 0, -2.3); // hearth centre on the floor
+export const FIRE = new THREE.Vector3(1.45, 0.86, -2.22); // top of the coal bed
+export const TROUGH = new THREE.Vector3(1.2, 0, 0.45);
+export const WATER_Y = 0.55;
+export const PRES_Y = 2.32; // presentation blade above the tool rack
+export const PEGS = [-1.58, -1.02];
+export const BLOCK = new THREE.Vector3(2.05, 0, 1.75); // oak sword block, in front of the moonlit window
+export const BLOCK_H = 0.68;
+
+const rnd = (a, b) => a + Math.random() * (b - a);
+
+export function buildSmithy({ scene, renderer, tex }) {
+ const out = { uniforms: [] };
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+ const T = (t, rx, ry) => { const c = t.clone(); c.wrapS = c.wrapT = THREE.RepeatWrapping; c.repeat.set(rx, ry); c.anisotropy = aniso; c.needsUpdate = true; return c; };
+
+ // ─── Soot gradient patch for walls (darker toward the ceiling, warmer near the hearth) ───
+ const soot = (mat, { top = 3.2, amount = 0.72 } = {}) => {
+ mat.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vSootW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvSootW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nvarying vec3 vSootW;')
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ diffuseColor.rgb *= mix(1.0, 1.0 - ${amount.toFixed(2)}, smoothstep(0.6, ${top.toFixed(2)}, vSootW.y));
+ diffuseColor.rgb *= 1.0 - 0.45 * exp(-length(vSootW.xz - vec2(${FORGE.x.toFixed(2)}, ${FORGE.z.toFixed(2)})) * 1.1) * smoothstep(1.2, 2.4, vSootW.y);`);
+ };
+ mat.customProgramCacheKey = () => 'soot' + top + amount;
+ return mat;
+ };
+
+ // ─── Room ───
+ const W = ROOM.x1 - ROOM.x0, D = ROOM.z1 - ROOM.z0;
+ const floorMat = new THREE.MeshStandardMaterial({
+ map: T(tex.floor, W / 2.2, D / 2.2), normalMap: T(tex.floorN, W / 2.2, D / 2.2), normalScale: new THREE.Vector2(0.9, 0.9),
+ color: 0x464341, roughness: 0.72, metalness: 0, envMapIntensity: 0.35,
+ });
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(W, D), floorMat);
+ floor.rotation.x = -Math.PI / 2; floor.position.set((ROOM.x0 + ROOM.x1) / 2, 0, (ROOM.z0 + ROOM.z1) / 2);
+ floor.receiveShadow = true;
+ scene.add(floor);
+ out.floor = floor;
+
+ const brick = (w, h) => soot(new THREE.MeshStandardMaterial({
+ map: T(tex.brick, w / 1.05, h / 1.05), normalMap: T(tex.brickN, w / 1.05, h / 1.05), normalScale: new THREE.Vector2(0.95, 0.95),
+ color: 0x5a5856, roughness: 0.88, metalness: 0, envMapIntensity: 0.2,
+ }));
+ const wall = (w, h, pos, ry) => {
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(w, h), brick(w, h));
+ m.position.copy(pos); m.rotation.y = ry; m.receiveShadow = true; scene.add(m); return m;
+ };
+ wall(W, ROOM.h, new THREE.Vector3((ROOM.x0 + ROOM.x1) / 2, ROOM.h / 2, ROOM.z0), 0);
+ wall(D, ROOM.h, new THREE.Vector3(ROOM.x0, ROOM.h / 2, (ROOM.z0 + ROOM.z1) / 2), Math.PI / 2);
+ wall(D, ROOM.h, new THREE.Vector3(ROOM.x1, ROOM.h / 2, (ROOM.z0 + ROOM.z1) / 2), -Math.PI / 2);
+ wall(W, ROOM.h, new THREE.Vector3((ROOM.x0 + ROOM.x1) / 2, ROOM.h / 2, ROOM.z1), Math.PI);
+
+ // Ceiling and heavy oak beams.
+ const woodAlb = bakeTexture(renderer, 1024, `
+ void main(){
+ vec2 p = vUv * vec2(1.0, 8.0);
+ float g = fbm(vec2(vUv.x * 3.0, vUv.y * 40.0), 3.0, 5, 0.55);
+ float rings = sin((vUv.x * 60.0 + g * 9.0)) * 0.5 + 0.5;
+ float n = fbm(vUv * 12.0, 12.0, 5, 0.5) * 0.5 + 0.5;
+ vec3 c = mix(vec3(0.075, 0.05, 0.034), vec3(0.16, 0.105, 0.066), rings * 0.55 + n * 0.45);
+ c *= 0.75 + 0.5 * fbm(vUv * 5.0 + 3.1, 5.0, 4, 0.5);
+ gl_FragColor = vec4(c, 1.0);
+ }`);
+ const woodN = fbmNormal(renderer, { size: 512, scale: 6, octaves: 5, strength: 1.4 });
+ const woodMat = new THREE.MeshStandardMaterial({ map: woodAlb, normalMap: woodN, roughness: 0.82, color: 0xffffff });
+ out.woodMat = woodMat;
+ const ceil = new THREE.Mesh(new THREE.PlaneGeometry(W, D), new THREE.MeshStandardMaterial({ color: 0x0c0a09, roughness: 1 }));
+ ceil.rotation.x = Math.PI / 2; ceil.position.set(floor.position.x, ROOM.h, floor.position.z);
+ scene.add(ceil);
+ for (const x of [-2.3, -0.7, 0.9, 2.5]) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.22, 0.28, D), woodMat);
+ b.position.set(x, ROOM.h - 0.14, floor.position.z); b.receiveShadow = true; scene.add(b);
+ }
+ const tie = new THREE.Mesh(new THREE.BoxGeometry(W, 0.24, 0.2), woodMat);
+ tie.position.set(floor.position.x, ROOM.h - 0.4, -0.6); tie.receiveShadow = true; scene.add(tie);
+
+ // ─── Forge hearth ───
+ const hw = 1.45, hd = 1.15, hh = 0.8;
+ const hearth = new THREE.Mesh(new RoundedBoxGeometry(hw, hh, hd, 2, 0.02), brick(hw * 1.2, hh * 1.2));
+ hearth.material = new THREE.MeshStandardMaterial({ map: T(tex.brick, 1.4, 0.8), normalMap: T(tex.brickN, 1.4, 0.8), normalScale: new THREE.Vector2(1.3, 1.3), color: 0x9a8a7e, roughness: 0.9 });
+ hearth.position.set(FORGE.x, hh / 2, ROOM.z0 + hd / 2);
+ hearth.castShadow = hearth.receiveShadow = true;
+ scene.add(hearth);
+ const slabMat = new THREE.MeshStandardMaterial({ color: 0x1a1512, roughness: 0.75, metalness: 0.25, normalMap: fbmNormal(renderer, { size: 512, scale: 7, octaves: 6, strength: 2.2 }) });
+ const slab = new THREE.Mesh(new RoundedBoxGeometry(hw + 0.08, 0.07, hd + 0.06, 2, 0.015), slabMat);
+ slab.position.set(FORGE.x, hh + 0.03, ROOM.z0 + hd / 2 + 0.02);
+ slab.castShadow = slab.receiveShadow = true;
+ scene.add(slab);
+ // Iron fire-pot rim.
+ const ironMat = new THREE.MeshStandardMaterial({ color: 0x2a2522, roughness: 0.55, metalness: 0.85, normalMap: slabMat.normalMap });
+ out.ironMat = ironMat;
+ const rim = new THREE.Mesh(new THREE.TorusGeometry(0.36, 0.028, 10, 48), ironMat);
+ rim.rotation.x = Math.PI / 2; rim.position.set(FIRE.x, hh + 0.075, FIRE.z);
+ rim.castShadow = true; scene.add(rim);
+
+ // Coal bed glow + lumps.
+ const fireU = { uTime: { value: 0 }, uFire: { value: 1 } };
+ out.fire = fireU;
+ const bed = new THREE.Mesh(new THREE.CircleGeometry(0.34, 48), new THREE.ShaderMaterial({
+ uniforms: fireU,
+ vertexShader: 'varying vec3 vW; void main(){ vW = (modelMatrix * vec4(position,1.)).xyz; gl_Position = projectionMatrix * viewMatrix * vec4(vW, 1.); }',
+ fragmentShader: `uniform float uTime, uFire; varying vec3 vW; ${NOISE} ${BLACKBODY}
+ void main(){
+ vec2 d = vW.xz - vec2(${FIRE.x.toFixed(3)}, ${FIRE.z.toFixed(3)});
+ float r = length(d) / 0.34;
+ float n = fbm3(vec3(vW.xz * 14.0, uTime * 0.4));
+ float h = clamp((1.0 - r * r) * 0.85 + n * 0.45, 0.0, 1.0) * (0.75 + uFire * 0.35);
+ float K = 900.0 + h * 700.0;
+ gl_FragColor = vec4(blackbody(K) * glowPower(K) * 14.0 * smoothstep(1.0, 0.8, r), 1.0);
+ }`,
+ }));
+ bed.rotation.x = -Math.PI / 2; bed.position.set(FIRE.x, hh + 0.072, FIRE.z);
+ scene.add(bed);
+
+ const coalMat = new THREE.MeshStandardMaterial({ color: 0x0c0b0a, roughness: 0.92, metalness: 0.0, flatShading: true });
+ coalMat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, fireU);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vCW; varying vec3 vCN;')
+ .replace('#include <project_vertex>', `#include <project_vertex>
+ #ifdef USE_INSTANCING
+ vCW = (modelMatrix * instanceMatrix * vec4(transformed, 1.0)).xyz;
+ vCN = normalize(mat3(modelMatrix * instanceMatrix) * objectNormal);
+ #else
+ vCW = (modelMatrix * vec4(transformed, 1.0)).xyz; vCN = normalize(mat3(modelMatrix) * objectNormal);
+ #endif`);
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', `#include <common>
+ varying vec3 vCW; varying vec3 vCN; uniform float uTime, uFire; ${NOISE} ${BLACKBODY}`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ vec2 d = vCW.xz - vec2(${FIRE.x.toFixed(3)}, ${FIRE.z.toFixed(3)});
+ float r = length(d) / 0.36;
+ float n = fbm3(vCW * 16.0 + vec3(0.0, -uTime * 0.45, uTime * 0.1));
+ float depth = clamp(1.0 - (vCW.y - ${(0.8 + 0.07).toFixed(3)}) / 0.13, 0.0, 1.0);
+ float down = 1.0 - clamp(vCN.y, 0.0, 1.0) * 0.55;
+ float h = clamp(n * 0.7 + depth * 0.55 + (1.0 - r) * 0.35 - 0.35, 0.0, 1.0) * down;
+ h *= 0.55 + uFire * 0.55;
+ float K = 700.0 + h * 1000.0;
+ totalEmissiveRadiance += blackbody(K) * glowPower(K) * 18.0;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.12, 0.115, 0.11), smoothstep(0.55, 0.95, vCN.y) * (1.0 - h) * 0.6);
+ }`);
+ };
+ coalMat.customProgramCacheKey = () => 'coal';
+ {
+ const variants = [0, 1, 2].map(k => {
+ const g = new THREE.IcosahedronGeometry(1, 1);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const v = new THREE.Vector3().fromBufferAttribute(p, i);
+ v.multiplyScalar(0.72 + Math.random() * 0.5).multiply(new THREE.Vector3(1, 0.7 + k * 0.1, 1));
+ p.setXYZ(i, v.x, v.y, v.z);
+ }
+ g.computeVertexNormals();
+ return g;
+ });
+ const N = 110, m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), s = new THREE.Vector3(), pp = new THREE.Vector3();
+ for (const g of variants) {
+ const im = new THREE.InstancedMesh(g, coalMat, N);
+ for (let i = 0; i < N; i++) {
+ const a = Math.random() * Math.PI * 2, r = Math.sqrt(Math.random()) * 0.36;
+ const dome = Math.max(0, 1 - (r / 0.4) ** 2);
+ pp.set(FIRE.x + Math.cos(a) * r, hh + 0.08 + dome * 0.1 * Math.random() + dome * 0.03, FIRE.z + Math.sin(a) * r);
+ e.set(Math.random() * 6, Math.random() * 6, Math.random() * 6); q.setFromEuler(e);
+ const sz = rnd(0.028, 0.06); s.set(sz, sz, sz);
+ im.setMatrixAt(i, m4.compose(pp, q, s));
+ }
+ im.castShadow = false; im.receiveShadow = true;
+ scene.add(im);
+ }
+ }
+ // Flames: a few crossed sheets of licking fire.
+ const flameU = { uTime: fireU.uTime, uFire: fireU.uFire };
+ const flameMat = new THREE.ShaderMaterial({
+ uniforms: flameU, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ vertexShader: 'varying vec2 vUv; varying float vS; attribute float seed; void main(){ vUv = uv; vS = seed; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }',
+ fragmentShader: `uniform float uTime, uFire; varying vec2 vUv; varying float vS; ${NOISE} ${BLACKBODY}
+ void main(){
+ vec2 p = vUv;
+ float n = fbm3(vec3(p.x * 3.2 + vS * 7.0, p.y * 2.2 - uTime * (1.3 + uFire * 0.6), uTime * 0.3 + vS));
+ float shape = smoothstep(0.5, 0.05, abs(p.x - 0.5 + n * 0.12)) * smoothstep(1.0, 0.0, p.y * (1.25 - uFire * 0.3) + n * 0.35);
+ float h = clamp(shape * (1.1 - p.y) * 1.3, 0.0, 1.0);
+ float K = 900.0 + h * 700.0;
+ gl_FragColor = vec4(blackbody(K) * glowPower(K) * 7.0 * h * (0.4 + uFire * 0.5), 1.0);
+ }`,
+ });
+ for (let i = 0; i < 4; i++) {
+ const g = new THREE.PlaneGeometry(0.62, 0.55);
+ g.translate(0, 0.27, 0);
+ g.setAttribute('seed', new THREE.BufferAttribute(new Float32Array(4).fill(i * 0.37), 1));
+ const f = new THREE.Mesh(g, flameMat);
+ f.position.set(FIRE.x + rnd(-0.05, 0.05), hh + 0.1, FIRE.z + rnd(-0.05, 0.05));
+ f.rotation.y = i * Math.PI / 4;
+ f.renderOrder = 3;
+ scene.add(f);
+ }
+
+ // Hood + chimney (sheet iron).
+ const hoodMat = new THREE.MeshStandardMaterial({ color: 0x1b1816, roughness: 0.6, metalness: 0.7, normalMap: slabMat.normalMap, side: THREE.DoubleSide });
+ {
+ const g = new THREE.CylinderGeometry(0.36, 0.95, 0.85, 4, 1, true);
+ g.rotateY(Math.PI / 4);
+ g.scale(1, 1, 0.78);
+ const hood = new THREE.Mesh(g, hoodMat);
+ hood.position.set(FORGE.x, 1.62 + 0.42, ROOM.z0 + 0.6);
+ hood.castShadow = hood.receiveShadow = true;
+ scene.add(hood);
+ const lip = new THREE.Mesh(new THREE.BoxGeometry(1.36, 0.05, 1.06), hoodMat);
+ lip.position.set(FORGE.x, 1.6, ROOM.z0 + 0.6); lip.receiveShadow = true;
+ // Only the front and side lips, as a frame.
+ const frame = new THREE.Group();
+ for (const [w, d, x, z] of [[1.36, 0.05, 0, 0.5], [0.05, 1.06, -0.66, 0], [0.05, 1.06, 0.66, 0]]) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(w, 0.06, d), ironMat); b.position.set(x, 0, z); b.castShadow = true; frame.add(b);
+ }
+ frame.position.set(FORGE.x, 1.6, ROOM.z0 + 0.6); scene.add(frame);
+ const chim = new THREE.Mesh(new THREE.BoxGeometry(0.52, ROOM.h - 2.45, 0.52), hoodMat);
+ chim.position.set(FORGE.x, 2.45 + (ROOM.h - 2.45) / 2, ROOM.z0 + 0.46); chim.receiveShadow = true;
+ scene.add(chim);
+ }
+
+ // ─── Slack tub: half a wine barrel of brine ───
+ {
+ const g = new THREE.Group();
+ const R = 0.34, H = 0.6, staves = 20;
+ const staveAlb = bakeTexture(renderer, 1024, `
+ void main(){
+ float sx = vUv.x * ${staves}.0;
+ float id = floor(sx), f = fract(sx);
+ float seam = smoothstep(0.0, 0.035, f) * smoothstep(1.0, 0.965, f);
+ float tone = fract(sin(id * 91.7) * 43758.5);
+ float grain = fbm(vec2(vUv.x * 60.0 + id * 3.1, vUv.y * 4.0), 4.0, 5, 0.55) * 0.5 + 0.5;
+ float streak = fbm(vec2(vUv.x * 240.0, vUv.y * 2.0), 2.0, 4, 0.6) * 0.5 + 0.5;
+ vec3 c = mix(vec3(0.08, 0.045, 0.024), vec3(0.24, 0.14, 0.075), tone * 0.55 + grain * 0.45) * (0.7 + streak * 0.5);
+ c *= mix(0.45, 1.0, smoothstep(0.0, 0.3, vUv.y)); // water-darkened foot
+ c *= mix(1.0, 0.55, smoothstep(0.8, 1.0, vUv.y)); // wet rim
+ float drip = smoothstep(0.55, 0.9, fbm(vec2(vUv.x * 90.0, vUv.y * 1.5), 1.5, 4, 0.5) + vUv.y * 0.3);
+ c *= 1.0 - drip * 0.35;
+ gl_FragColor = vec4(c * mix(0.2, 1.0, seam), 1.0);
+ }`);
+ staveAlb.repeat.set(1, 1);
+ const staveN = bakeTexture(renderer, 1024, `
+ void main(){
+ float sx = vUv.x * ${staves}.0; float f = fract(sx);
+ float seam = smoothstep(0.0, 0.05, f) - smoothstep(0.95, 1.0, f);
+ float gr = fbm(vec2(vUv.x * 80.0, vUv.y * 6.0), 6.0, 4, 0.5);
+ gl_FragColor = vec4(0.5 + seam * 0.35 + gr * 0.05, 0.5 + gr * 0.12, 1.0, 1.0);
+ }`);
+ const staveRough = bakeTexture(renderer, 512, `
+ void main(){
+ float wet = smoothstep(0.75, 1.0, vUv.y) + (1.0 - smoothstep(0.0, 0.2, vUv.y));
+ float n = fbm(vec2(vUv.x * 50.0, vUv.y * 5.0), 5.0, 4, 0.5) * 0.5 + 0.5;
+ gl_FragColor = vec4(1.0, clamp(0.5 + n * 0.25 - wet * 0.3, 0.12, 1.0), 0.0, 1.0);
+ }`);
+ const staveMat = new THREE.MeshPhysicalMaterial({ map: staveAlb, normalMap: staveN, normalScale: new THREE.Vector2(2.0, 2.0), roughnessMap: staveRough, roughness: 1, metalness: 0,
+ clearcoat: 0.7, clearcoatRoughness: 0.3, side: THREE.DoubleSide, envMapIntensity: 1.0 });
+ // Blackened, hammered hoop iron.
+ const hoopMat = new THREE.MeshStandardMaterial({ color: 0x100e0d, roughness: 0.48, metalness: 0.7, normalMap: ironMat.normalMap, normalScale: new THREE.Vector2(1.4, 1.4), envMapIntensity: 1.1 });
+ out.hoopMat = hoopMat;
+ // Bulged barrel profile, cut at the waist.
+ const prof = [];
+ for (let i = 0; i <= 12; i++) { const t = i / 12; prof.push(new THREE.Vector2(R * (0.9 + 0.1 * Math.sin(t * Math.PI * 0.95 + 0.2)), t * H)); }
+ const shell = new THREE.Mesh(new THREE.LatheGeometry(prof, 64), staveMat);
+ shell.castShadow = shell.receiveShadow = true; g.add(shell);
+ const inner = new THREE.Mesh(new THREE.CylinderGeometry(R * 0.93, R * 0.86, H - 0.02, 48, 1, true), new THREE.MeshPhysicalMaterial({ color: 0x0a0605, roughness: 0.55, clearcoat: 1, clearcoatRoughness: 0.2, side: THREE.BackSide }));
+ inner.position.y = H / 2; g.add(inner);
+ const rimTop = new THREE.Mesh(new THREE.TorusGeometry(R * 0.965, 0.018, 8, 64), staveMat);
+ rimTop.rotation.x = Math.PI / 2; rimTop.position.y = H; g.add(rimTop);
+ for (const [y, r] of [[0.08, 0.93], [0.44, 0.995], [0.57, 0.97]]) {
+ const hoop = new THREE.Mesh(new THREE.CylinderGeometry(R * r + 0.007, R * r + 0.007, 0.045, 64, 1, true), hoopMat);
+ hoop.position.y = y; hoop.castShadow = true; g.add(hoop);
+ for (let k = 0; k < 6; k++) { // rivets
+ const a = k / 6 * Math.PI * 2 + y * 9;
+ const rv = new THREE.Mesh(new THREE.SphereGeometry(0.007, 8, 6), hoopMat);
+ rv.position.set(Math.cos(a) * (R * r + 0.008), y, Math.sin(a) * (R * r + 0.008)); g.add(rv);
+ }
+ }
+ const waterU = { uTime: { value: 0 }, uGlow: { value: new THREE.Color(0, 0, 0) }, uBlade: { value: new THREE.Vector2(0, 0) }, uBoil: { value: 0 } };
+ out.water = waterU;
+ const waterN = fbmNormal(renderer, { size: 512, scale: 5, octaves: 4, strength: 0.8 });
+ waterN.wrapS = waterN.wrapT = THREE.RepeatWrapping;
+ const wmat = new THREE.MeshStandardMaterial({ color: 0x010101, roughness: 0.04, metalness: 0.0, normalMap: waterN, normalScale: new THREE.Vector2(0.12, 0.12), envMapIntensity: 1.2 });
+ waterU.uForgeCol = { value: new THREE.Color(1.0, 0.36, 0.09) };
+ wmat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, waterU);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vWW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvWW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', `#include <common>
+ varying vec3 vWW; uniform float uTime, uBoil; uniform vec3 uGlow, uForgeCol; uniform vec2 uBlade; ${NOISE}`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ float dd = length(vWW.xz - uBlade);
+ float ripple = sin(dd * 70.0 - uTime * 11.0) * exp(-dd * 14.0) * uBoil * 0.5;
+ float boil = snoise(vec3(vWW.xz * 70.0, uTime * 4.0)) * exp(-dd * 16.0) * uBoil;
+ vec2 idle = vec2(snoise(vec3(vWW.xz * 18.0, uTime * 0.35)), snoise(vec3(vWW.xz * 18.0 + 7.0, uTime * 0.35))) * 0.05;
+ normal = normalize(normal + vec3(ripple * 0.3 + boil * 0.35 + idle.x, 0.0, ripple * 0.2 + boil * 0.3 + idle.y));
+ }`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ float dd = length(vWW.xz - uBlade);
+ float fz = snoise(vec3(vWW.xz * 90.0, uTime * 5.0));
+ totalEmissiveRadiance += uGlow * exp(-dd * 26.0) * (0.6 + 0.4 * fz);
+ totalEmissiveRadiance += vec3(0.5, 0.52, 0.55) * smoothstep(0.35, 0.8, fz) * exp(-dd * 18.0) * uBoil * 0.25;
+ // The forge, smeared across the dark brine by the ripples.
+ vec3 Nw = inverseTransformDirection(normal, viewMatrix);
+ vec3 Vw = normalize(vWW - cameraPosition);
+ vec3 Rw = reflect(Vw, Nw);
+ vec2 Fd = normalize(vec2(${FIRE.x.toFixed(3)}, ${FIRE.z.toFixed(3)}) - vWW.xz);
+ float az = max(dot(normalize(Rw.xz), Fd), 0.0);
+ float fr = 0.04 + 0.96 * pow(1.0 - clamp(dot(-Vw, Nw), 0.0, 1.0), 5.0);
+ float glint = pow(az, 14.0) * smoothstep(-0.05, 0.45, Rw.y);
+ totalEmissiveRadiance += uForgeCol * glint * (0.25 + fr * 2.5);
+ }`);
+ };
+ wmat.customProgramCacheKey = () => 'water';
+ const water = new THREE.Mesh(new THREE.CircleGeometry(R * 0.93, 64), wmat);
+ water.rotation.x = -Math.PI / 2; water.position.y = WATER_Y; water.receiveShadow = true;
+ g.add(water);
+ out.waterMat = wmat;
+ g.position.copy(TROUGH);
+ scene.add(g);
+ out.trough = g;
+ out.waterMesh = water;
+ }
+
+ // ─── Wall tools ───
+ {
+ const rack = new THREE.Mesh(new RoundedBoxGeometry(2.4, 0.12, 0.07, 2, 0.01), woodMat);
+ rack.position.set(-1.35, 1.72, ROOM.z0 + 0.04); rack.castShadow = rack.receiveShadow = true; scene.add(rack);
+ // Tongs: two long reins with jaws.
+ const tongs = (x, jaw, rot) => {
+ const grp = new THREE.Group();
+ for (const s of [-1, 1]) {
+ const pts = [new THREE.Vector3(0, 0, 0), new THREE.Vector3(s * 0.012, -0.35, 0.01), new THREE.Vector3(s * 0.02, -0.62, 0.012), new THREE.Vector3(s * 0.03, -0.7, 0.012),
+ new THREE.Vector3(s * (0.02 + jaw), -0.78, 0.015), new THREE.Vector3(s * 0.012, -0.86, 0.02)];
+ const tube = new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(pts), 40, 0.009, 6), ironMat);
+ tube.castShadow = true; grp.add(tube);
+ }
+ const rivet = new THREE.Mesh(new THREE.SphereGeometry(0.016, 10, 8), ironMat); rivet.position.set(0, -0.68, 0.02); grp.add(rivet);
+ grp.position.set(x, 1.66, ROOM.z0 + 0.08); grp.rotation.z = rot; scene.add(grp);
+ };
+ tongs(-2.3, 0.03, 0.03); tongs(-2.12, 0.05, -0.02); tongs(-1.95, 0.02, 0.04);
+ // Poker and shovel.
+ const rod = (x, len, rot, head) => {
+ const grp = new THREE.Group();
+ const r = new THREE.Mesh(new THREE.CylinderGeometry(0.009, 0.009, len, 8), ironMat); r.position.y = -len / 2; r.castShadow = true; grp.add(r);
+ const ring = new THREE.Mesh(new THREE.TorusGeometry(0.028, 0.006, 6, 20), ironMat); ring.position.y = 0.02; grp.add(ring);
+ if (head) { const h = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.16, 0.012), ironMat); h.position.y = -len - 0.06; h.castShadow = true; grp.add(h); }
+ grp.position.set(x, 1.66, ROOM.z0 + 0.07); grp.rotation.z = rot; scene.add(grp);
+ };
+ rod(-0.25, 1.05, 0.02, true); rod(-0.08, 1.1, -0.03, false);
+ // Steel bar stock leaning in the corner.
+ for (let i = 0; i < 7; i++) {
+ const b = new THREE.Mesh(new THREE.BoxGeometry(0.03, 1.3 + Math.random() * 0.3, 0.012), ironMat);
+ b.position.set(2.62 + i * 0.045, 0.66, ROOM.z0 + 0.14 + Math.random() * 0.05); b.rotation.z = 0.08 + Math.random() * 0.05; b.rotation.x = -0.1;
+ b.castShadow = true; scene.add(b);
+ }
+ }
+
+ // ─── Window with moonlight on the left wall ───
+ {
+ const grp = new THREE.Group();
+ const glass = new THREE.Mesh(new THREE.PlaneGeometry(0.8, 1.0), new THREE.ShaderMaterial({
+ fog: false,
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }',
+ fragmentShader: `varying vec2 vUv; ${NOISE}
+ void main(){
+ // Night over the valley: deep blue sky, a smear of cloud, the moon's halo in the upper pane, old uneven glass.
+ vec2 p = vUv;
+ float wob = snoise(vec3(p * 9.0, 1.0)) * 0.01;
+ vec3 sky = mix(vec3(0.004, 0.006, 0.012), vec3(0.02, 0.032, 0.065), smoothstep(0.0, 1.0, p.y + wob));
+ float cloud = smoothstep(0.1, 0.7, fbm3(vec3(p.x * 2.2, p.y * 4.0, 3.0)) * 0.5 + 0.5);
+ sky = mix(sky, vec3(0.03, 0.036, 0.05), cloud * 0.5);
+ vec2 m = p - vec2(0.72, 0.8);
+ float halo = exp(-dot(m, m) * 30.0);
+ sky += vec3(0.25, 0.3, 0.42) * halo * 0.35 + vec3(0.9, 0.95, 1.0) * smoothstep(0.035, 0.025, length(m)) * 0.8;
+ float ridge = step(p.y, 0.12 + 0.05 * sin(p.x * 7.0) + 0.03 * snoise(vec3(p.x * 6.0, 0.0, 2.0)));
+ sky = mix(sky, vec3(0.002, 0.003, 0.005), ridge);
+ gl_FragColor = vec4(sky, 1.0);
+ }`,
+ }));
+ grp.add(glass);
+ const bar = (w, h, x, y) => { const b = new THREE.Mesh(new THREE.BoxGeometry(w, h, 0.05), woodMat); b.position.set(x, y, 0.02); grp.add(b); };
+ bar(0.9, 0.07, 0, 0.52); bar(0.9, 0.07, 0, -0.52); bar(0.07, 1.1, -0.43, 0); bar(0.07, 1.1, 0.43, 0); bar(0.8, 0.035, 0, 0); bar(0.035, 1.0, 0, 0);
+ const sill = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.06, 0.18), woodMat); sill.position.set(0, -0.58, 0.07); grp.add(sill);
+ grp.position.set(ROOM.x1 - 0.01, 2.35, 0.55); grp.rotation.y = -Math.PI / 2;
+ scene.add(grp);
+ out.window = grp;
+ }
+
+ // ─── Pegs for the presentation blade above the rack ───
+ for (const x of PEGS) {
+ const peg = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.009, 0.075, 10), ironMat);
+ peg.rotation.x = Math.PI / 2; peg.position.set(x, PRES_Y - 0.036, ROOM.z0 + 0.037); peg.castShadow = true; scene.add(peg);
+ const tip = new THREE.Mesh(new THREE.CylinderGeometry(0.007, 0.008, 0.03, 10), ironMat);
+ tip.position.set(x, PRES_Y - 0.024, ROOM.z0 + 0.072); scene.add(tip);
+ const plate = new THREE.Mesh(new THREE.CylinderGeometry(0.022, 0.022, 0.006, 16), ironMat);
+ plate.rotation.x = Math.PI / 2; plate.position.set(x, PRES_Y - 0.036, ROOM.z0 + 0.003); scene.add(plate);
+ }
+
+ // ─── The sword block: where the finished blade stands ───
+ {
+ const blockMat = new THREE.MeshPhysicalMaterial({ map: woodAlb, normalMap: woodN, color: 0x6a5a50, roughness: 0.5, clearcoat: 0.5, clearcoatRoughness: 0.4, envMapIntensity: 0.8 });
+ const g = new THREE.Group();
+ const b = new THREE.Mesh(new RoundedBoxGeometry(0.3, BLOCK_H, 0.3, 3, 0.02), blockMat);
+ b.position.y = BLOCK_H / 2; b.castShadow = b.receiveShadow = true; g.add(b);
+ const bandMat = new THREE.MeshStandardMaterial({ color: 0x100e0d, roughness: 0.45, metalness: 0.75, normalMap: ironMat.normalMap, envMapIntensity: 1.1 });
+ for (const y of [0.09, BLOCK_H - 0.09]) {
+ const band = new THREE.Mesh(new RoundedBoxGeometry(0.312, 0.04, 0.312, 2, 0.006), bandMat);
+ band.position.y = y; band.castShadow = true; g.add(band);
+ }
+ const cap = new THREE.Mesh(new RoundedBoxGeometry(0.16, 0.014, 0.1, 2, 0.004), bandMat);
+ cap.position.y = BLOCK_H + 0.006; g.add(cap);
+ const slot = new THREE.Mesh(new THREE.BoxGeometry(0.07, 0.004, 0.024), new THREE.MeshBasicMaterial({ color: 0x000000 }));
+ slot.position.y = BLOCK_H + 0.014; g.add(slot);
+ g.position.copy(BLOCK);
+ scene.add(g);
+ out.block = g;
+ }
+
+ // ─── Hanging lantern by the tool wall ───
+ {
+ const grp = new THREE.Group();
+ const cage = new THREE.Mesh(new THREE.CylinderGeometry(0.07, 0.08, 0.2, 6, 1, true), new THREE.MeshStandardMaterial({ color: 0x222, metalness: 0.8, roughness: 0.5, wireframe: true }));
+ grp.add(cage);
+ const glow = new THREE.Mesh(new THREE.SphereGeometry(0.035, 12, 10), new THREE.MeshBasicMaterial({ color: new THREE.Color(8, 4.2, 1.6) }));
+ grp.add(glow);
+ const cap = new THREE.Mesh(new THREE.ConeGeometry(0.1, 0.07, 6), ironMat); cap.position.y = 0.13; grp.add(cap);
+ const chain = new THREE.Mesh(new THREE.CylinderGeometry(0.004, 0.004, 1.4, 4), ironMat); chain.position.y = 0.86; grp.add(chain);
+ grp.position.set(-2.45, 2.2, -2.45);
+ scene.add(grp);
+ out.lantern = grp;
+ }
+
+ return out;
+}
diff --git a/examples/ember/style.css b/examples/ember/style.css
new file mode 100644
index 0000000..c2b48cd
--- /dev/null
+++ b/examples/ember/style.css
@@ -0,0 +1,249 @@
+:root {
+ --bg: #0a0806;
+ --ink: #ece4d6;
+ --bone: #e2d6c2;
+ --muted: #968878;
+ --faint: rgba(236, 228, 214, .12);
+ --hot: #ff6a1f;
+ --hot2: #ffb35a;
+ --display: 'Oswald', 'Arial Narrow', sans-serif;
+ --serif: 'Crimson Pro', Georgia, serif;
+ --pad: clamp(18px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 19px/1.55 var(--serif); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+::selection { background: var(--hot); color: #140a04; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+.flash { position: fixed; inset: 0; z-index: 40; pointer-events: none; opacity: 0; mix-blend-mode: screen;
+ background: radial-gradient(60% 60% at var(--fx, 50%) var(--fy, 55%), rgba(255, 214, 160, .55), rgba(255, 106, 31, .12) 45%, transparent 75%); }
+.grain { position: fixed; inset: -50%; z-index: 41; pointer-events: none; opacity: .07; mix-blend-mode: overlay;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
+ animation: grain 1.2s steps(6) infinite; }
+@keyframes grain { 0% { transform: translate(0, 0); } 20% { transform: translate(-3%, 2%); } 40% { transform: translate(2%, -4%); } 60% { transform: translate(-4%, -1%); } 80% { transform: translate(3%, 3%); } 100% { transform: translate(0, 0); } }
+
+/* ─── Loader ─── */
+.loader { position: fixed; inset: 0; z-index: 100; background: #070504; display: grid; place-items: center; }
+.loader-inner { width: min(440px, 80vw); display: grid; gap: 22px; position: relative; }
+.loader::before { content: ''; position: absolute; left: 50%; top: 50%; width: 90vmin; height: 90vmin; transform: translate(-50%, -50%); border-radius: 50%;
+ background: radial-gradient(closest-side, rgba(255, 106, 31, .16), rgba(255, 60, 10, .05) 45%, transparent 70%); opacity: var(--p, 0); filter: blur(10px); animation: breathe 2.8s ease-in-out infinite; }
+@keyframes breathe { 0%, 100% { scale: 1; } 50% { scale: 1.06; } }
+.loader-mark { font: 500 clamp(30px, 4vw, 44px)/1 var(--display); letter-spacing: .06em; text-transform: uppercase; color: var(--bone); }
+.loader-mark em { font: italic 400 1.05em/1 var(--serif); color: var(--hot); text-transform: none; letter-spacing: 0; }
+.loader-bar { position: relative; height: 3px; background: #1a1411; overflow: visible; }
+.loader-bar i { position: absolute; left: 0; top: 0; bottom: 0; width: calc(var(--p, 0) * 100%);
+ background: linear-gradient(90deg, #3a0b02, #9a1d04 25%, #ff4a0c 55%, #ffa23a 80%, #fff1d2);
+ background-size: calc(100% / max(var(--p, 0.01), 0.01)) 100%;
+ box-shadow: 0 0 18px rgba(255, 106, 31, calc(var(--p, 0) * .9)), 0 0 60px rgba(255, 140, 50, calc(var(--p, 0) * .5)); }
+.loader-line { display: flex; justify-content: space-between; font: 400 12px/1 var(--display); letter-spacing: .28em; text-transform: uppercase; color: var(--muted); }
+.loader-pct { font-variant-numeric: tabular-nums; color: var(--bone); }
+
+/* ─── Nav ─── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 24px;
+ padding: 22px var(--pad); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 500 15px/1 var(--display); letter-spacing: .2em; text-transform: uppercase; color: var(--bone); }
+.brand em { font: italic 400 19px/1 var(--serif); letter-spacing: 0; color: var(--hot); text-transform: none; }
+.brand svg { width: 30px; height: 30px; color: var(--bone); }
+.brand-spark { fill: var(--hot); filter: drop-shadow(0 0 4px var(--hot)); animation: spark 2.4s ease-in-out infinite; }
+@keyframes spark { 0%, 100% { opacity: .35; } 50% { opacity: 1; } }
+.links { display: flex; gap: 38px; }
+.links a { text-decoration: none; font: 400 13px/1 var(--display); letter-spacing: .2em; text-transform: uppercase; color: rgba(236, 228, 214, .62); transition: color .3s; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: -7px; height: 1px; background: var(--hot); transform: scaleX(0); transform-origin: left; transition: transform .45s cubic-bezier(.2, .8, .2, 1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after { transform: scaleX(1); }
+.nav-right { display: flex; align-items: center; gap: 18px; }
+.sound { display: flex; align-items: center; gap: 10px; background: none; border: 0; color: var(--muted); font: 400 11px/1 var(--display); letter-spacing: .22em; text-transform: uppercase; cursor: pointer; }
+.sound-bars { display: flex; align-items: end; gap: 2px; height: 12px; }
+.sound-bars i { width: 2px; background: var(--hot); height: 100%; animation: bars 1s ease-in-out infinite; }
+.sound-bars i:nth-child(2) { animation-delay: -.3s; } .sound-bars i:nth-child(3) { animation-delay: -.6s; } .sound-bars i:nth-child(4) { animation-delay: -.8s; }
+@keyframes bars { 0%, 100% { transform: scaleY(.3); } 50% { transform: scaleY(1); } }
+.sound-bars i { transform-origin: bottom; }
+.sound[aria-pressed="false"] .sound-bars i { animation: none; transform: scaleY(.2); background: var(--muted); }
+.btn { display: inline-flex; align-items: center; justify-content: center; height: 46px; padding: 0 24px; text-decoration: none;
+ font: 500 12.5px/1 var(--display); letter-spacing: .2em; text-transform: uppercase; white-space: nowrap; position: relative; overflow: hidden;
+ clip-path: polygon(10px 0, 100% 0, calc(100% - 10px) 100%, 0 100%); transition: color .35s, background .35s, box-shadow .35s; }
+.btn span { position: relative; z-index: 1; }
+.cta-short { display: none; }
+@media (max-width: 900px) { .cta-long { display: none; } .cta-short { display: inline; } }
+.btn-hot { background: var(--hot); color: #160a03; }
+.btn-hot::before { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, #ffb35a, #fff1d6); transform: translateX(-101%); transition: transform .55s cubic-bezier(.2, .8, .2, 1); }
+.btn-hot:hover::before { transform: translateX(0); }
+.btn-ghost { color: var(--ink); background: rgba(12, 9, 7, .45); box-shadow: inset 0 0 0 1px rgba(236, 228, 214, .3); backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--hot); color: #fff; }
+.btn-lg { height: 58px; padding: 0 34px; font-size: 13.5px; }
+
+/* ─── Shared type ─── */
+.eyebrow { font: 400 12px/1.4 var(--display); letter-spacing: .32em; text-transform: uppercase; color: var(--hot); margin-bottom: 22px; }
+h2 { font: 500 clamp(46px, 6.2vw, 108px)/.9 var(--display); text-transform: uppercase; letter-spacing: -.005em; color: var(--bone); }
+h2 em { display: inline-block; font: italic 400 1.02em/.95 var(--serif); text-transform: none; letter-spacing: -.02em; color: var(--hot); margin-top: .08em; }
+.lede { font: 400 clamp(19px, 1.5vw, 23px)/1.5 var(--serif); color: #cfc3b3; max-width: 32em; margin-top: 30px; }
+main { position: relative; z-index: 2; }
+section, footer { position: relative; }
+.shade { text-shadow: 0 2px 30px rgba(0, 0, 0, .9); }
+
+/* ─── Hero ─── */
+.hero { height: 100vh; min-height: 640px; display: grid; align-content: end; padding: 0 var(--pad) 12vh; pointer-events: none; }
+.hero-copy { max-width: 58rem; }
+.title { font: 600 clamp(54px, 7.3vw, 132px)/.86 var(--display); text-transform: uppercase; letter-spacing: -.012em; color: #f1e8da;
+ text-shadow: 0 0 80px rgba(0, 0, 0, .8); }
+.title .t-line { display: block; overflow: hidden; padding-bottom: .02em; }
+.title .t-line > span { display: inline-block; }
+.title b { font-weight: 600; color: var(--hot); text-shadow: 0 0 40px rgba(255, 106, 31, .55); }
+.title .t-accent { display: block; overflow: hidden; margin-top: .12em; }
+.title .t-accent > span { display: inline-block; font: italic 400 .6em/1.05 var(--serif); text-transform: none; letter-spacing: -.015em; color: var(--hot2); }
+.sub { max-width: 30em; margin-top: 30px; font: 400 clamp(18px, 1.35vw, 21px)/1.5 var(--serif); color: #cbbfae; text-shadow: 0 2px 20px #000; }
+.hint { position: fixed; left: 50%; bottom: 26px; transform: translateX(-50%); z-index: 12; display: flex; gap: 28px; color: var(--muted);
+ font: 400 11px/1 var(--display); letter-spacing: .22em; text-transform: uppercase; transition: opacity .6s; white-space: nowrap; pointer-events: none; }
+.hint kbd { font: inherit; color: var(--ink); padding: 5px 8px 4px; margin-right: 10px; box-shadow: inset 0 0 0 1px rgba(255, 106, 31, .45); border-radius: 2px; }
+.is-finale .hint, .hint.away { opacity: 0 !important; }
+
+/* ─── Process ─── */
+.process { padding: 10vh 0 0; pointer-events: none; }
+.steel { margin-top: 20vh; }
+.step { min-height: 128vh; display: grid; align-content: center; padding: 0 var(--pad); }
+.step > * { max-width: 30rem; }
+.step.right { justify-items: end; text-align: left; }
+.step.right > * { width: min(30rem, 100%); }
+.step-num { display: flex; align-items: baseline; gap: 16px; margin-bottom: 26px; font: 400 13px/1 var(--display); letter-spacing: .3em; text-transform: uppercase; color: var(--hot); }
+.step-num b { font: 300 64px/.8 var(--display); letter-spacing: -.02em; color: var(--bone); }
+.step h2 { font-size: clamp(42px, 4.8vw, 82px); }
+.step p { margin-top: 26px; color: #d3c7b6; font-size: clamp(18px, 1.3vw, 21px); text-shadow: 0 2px 24px #000, 0 0 2px #000; }
+.step .meta { font: 400 11.5px/1.5 var(--display); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); border-top: 1px solid var(--faint); padding-top: 16px; }
+.step, .steel, .voices { background: none; }
+.step::before { content: ''; position: absolute; }
+
+/* ─── The steel ─── */
+.steel { min-height: 100vh; padding: 16vh var(--pad) 8vh; display: grid; align-content: space-between; gap: 8vh; pointer-events: none; }
+.steel-head { max-width: 36rem; margin-left: auto; text-shadow: 0 2px 30px #000; }
+.steel-lede { max-width: 25rem; margin-top: 0; text-shadow: 0 2px 24px #000, 0 0 3px #000; }
+.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0; border-top: 1px solid rgba(236, 228, 214, .18); text-shadow: 0 2px 30px #000, 0 0 3px rgba(0,0,0,.8); }
+.stats > div { padding: 30px 28px 34px 0; border-right: 1px solid var(--faint); margin-right: 28px; }
+.stats > div:last-child { border-right: 0; margin-right: 0; }
+.stats dt { font: 400 12px/1 var(--display); letter-spacing: .28em; text-transform: uppercase; color: var(--hot); }
+.stats dd { white-space: nowrap; font: 300 clamp(52px, 6.2vw, 112px)/1 var(--display); letter-spacing: -.03em; color: var(--bone); margin-top: 16px; font-variant-numeric: tabular-nums; }
+.stats dd small { font: italic 400 .32em/1 var(--serif); color: var(--hot2); margin-left: .2em; letter-spacing: 0; }
+.stats p { font-size: 16px; color: #b8ab9a; margin-top: 12px; max-width: 16em; }
+
+/* ─── Commissions ─── */
+.commissions { min-height: 100vh; padding: 16vh var(--pad) 8vh; display: grid; align-content: space-between; gap: 8vh; margin-top: 30vh; }
+.com-head { max-width: 40rem; margin-left: auto; text-shadow: 0 2px 30px #000; pointer-events: none; }
+.blades { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
+.blade-card { position: relative; padding: 30px 30px 32px; background: linear-gradient(180deg, rgba(20, 15, 11, .72), rgba(10, 8, 6, .82)); backdrop-filter: blur(14px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(236, 228, 214, .1), 0 40px 80px -30px rgba(0, 0, 0, .9); transition: box-shadow .5s, transform .6s cubic-bezier(.2, .8, .2, 1); }
+.blade-card:hover { transform: translateY(-6px); box-shadow: inset 0 0 0 1px rgba(255, 106, 31, .55), 0 40px 80px -30px rgba(0, 0, 0, .9), 0 0 60px -20px rgba(255, 106, 31, .5); }
+.blade-card.hot { box-shadow: inset 0 0 0 1px rgba(255, 106, 31, .5), 0 40px 80px -30px rgba(0, 0, 0, .9); }
+.blade-card.hot::after { content: 'Most commissioned'; position: absolute; top: 30px; right: 30px; font: 400 10px/1 var(--display); letter-spacing: .24em; text-transform: uppercase; color: var(--hot); }
+.bc-type { font: 400 11.5px/1 var(--display); letter-spacing: .28em; text-transform: uppercase; color: var(--muted); }
+.blade-card h3 { font: 500 34px/1 var(--display); text-transform: uppercase; color: var(--bone); margin: 16px 0 14px; letter-spacing: .01em; }
+.blade-card p { font-size: 17px; color: #bdb09f; }
+.bc-price { margin-top: 26px; padding-top: 18px; border-top: 1px solid var(--faint); font: 300 42px/1 var(--display) !important; color: var(--hot2) !important; letter-spacing: -.01em; }
+.bc-price small { font: italic 400 17px/1 var(--serif); color: var(--muted); margin-right: 6px; }
+
+/* ─── Voices ─── */
+.voices { min-height: 160vh; padding: 24vh var(--pad) 20vh; pointer-events: none; }
+.quotes { display: grid; gap: 22vh; }
+.quotes blockquote { max-width: 29rem; }
+.quotes blockquote:nth-child(2) { margin-left: auto; }
+.quotes blockquote p { font: italic 300 clamp(30px, 2.8vw, 44px)/1.14 var(--serif); letter-spacing: -.012em; color: #efe6d8; text-shadow: 0 2px 30px #000, 0 0 3px #000; }
+.quotes cite { display: block; margin-top: 22px; font: 400 11.5px/1 var(--display); font-style: normal; letter-spacing: .26em; text-transform: uppercase; color: var(--hot); }
+
+/* ─── Finale ─── */
+.finale { height: 420vh; }
+.q-marker { position: absolute; left: 0; width: 1px; height: 1px; }
+.q-marker:nth-child(1) { top: 60vh; }
+.q-marker:nth-child(2) { top: 170vh; }
+.q-marker:nth-child(3) { top: 250vh; }
+.q-marker:nth-child(4) { top: 340vh; }
+.finale-sticky { position: sticky; top: 0; height: 100vh; pointer-events: none; }
+.finale-copy { position: absolute; left: var(--pad); right: var(--pad); opacity: 0; }
+.q-a { top: 16vh; }
+.q-a h2 { font-size: clamp(64px, 11vw, 200px); line-height: .84; color: #f3ebdf; text-shadow: 0 0 60px rgba(0, 0, 0, .7); }
+.q-b { bottom: 14vh; left: auto; max-width: 36rem; }
+.q-b .lede { text-shadow: 0 2px 20px #000; }
+.cta-row { display: flex; gap: 16px; margin-top: 36px; flex-wrap: wrap; pointer-events: auto; }
+
+/* ─── Footer ─── */
+.foot { min-height: 100vh; display: grid; align-content: end; padding: 30vh var(--pad) 40px; background: linear-gradient(180deg, transparent 0%, rgba(8, 6, 5, .7) 55%, #080605 100%); }
+.foot-grid > * { min-width: 0; }
+.foot a { overflow-wrap: anywhere; }
+.foot-grid { display: grid; grid-template-columns: 1.3fr 1fr 1fr 1.4fr; gap: 40px; padding-top: 40px; border-top: 1px solid var(--faint); color: #b3a696; font-size: 17px; }
+.foot-brand { font: 500 26px/1 var(--display); text-transform: uppercase; letter-spacing: .08em; color: var(--bone); margin-bottom: 14px; }
+.foot-brand em { font: italic 400 1.1em/1 var(--serif); color: var(--hot); text-transform: none; letter-spacing: 0; }
+.foot-h { font: 400 11.5px/1 var(--display) !important; letter-spacing: .28em; text-transform: uppercase; color: var(--hot) !important; margin-bottom: 14px; }
+.foot a { text-decoration: none; border-bottom: 1px solid rgba(255, 106, 31, .4); }
+.news { display: flex; margin-top: 14px; box-shadow: inset 0 0 0 1px rgba(236, 228, 214, .2); }
+.news input { flex: 1; min-width: 0; background: transparent; border: 0; padding: 12px 14px; color: var(--ink); font: 400 16px var(--serif); outline: none; }
+.news button { background: var(--hot); color: #160a03; border: 0; padding: 0 16px; font: 500 11px/1 var(--display); letter-spacing: .2em; text-transform: uppercase; cursor: pointer; }
+.news.sent { box-shadow: inset 0 0 0 1px var(--hot); }
+.news.sent input { color: var(--hot2); }
+.news.sent button { background: transparent; color: var(--hot); }
+.foot-legal { display: flex; justify-content: space-between; gap: 20px; margin-top: 60px; font: 400 11px/1.4 var(--display); letter-spacing: .2em; text-transform: uppercase; color: #6f6357; padding-left: 170px; }
+
+/* ─── HUD ─── */
+.hud { position: fixed; right: var(--pad); bottom: 26px; z-index: 12; display: grid; grid-template-columns: auto auto; gap: 8px 30px; align-items: end;
+ font-family: var(--display); pointer-events: none; transition: opacity .6s; }
+.hud-label { font: 400 10px/1 var(--display); letter-spacing: .3em; text-transform: uppercase; color: var(--muted); margin-bottom: 8px; }
+.hud-val { font: 300 30px/1 var(--display); color: var(--bone); font-variant-numeric: tabular-nums; letter-spacing: -.01em; }
+.hud-val small { font: 400 11px/1 var(--display); color: var(--muted); letter-spacing: .1em; margin-left: 4px; }
+.hud-name { font: italic 400 15px/1 var(--serif); color: var(--hot2); margin-top: 6px; }
+.hud-folds { text-align: right; }
+.hud-f { display: inline-block; }
+.hud-gauge { grid-column: 1 / -1; order: 3; position: relative; height: 3px; width: 250px;
+ background: linear-gradient(90deg, #1a1210 0%, #4a0e04 26%, #b3240a 42%, #ff5a12 58%, #ffa53c 76%, #fff0cf 100%); opacity: .9; }
+.hud-needle { position: absolute; top: -5px; bottom: -5px; width: 2px; left: calc(var(--t, 0) * 100%); background: var(--ink); box-shadow: 0 0 10px #fff; transition: left .2s; }
+.hud-bellows { grid-column: 1 / -1; order: 4; display: flex; align-items: center; gap: 10px; font: 400 10px/1 var(--display); letter-spacing: .3em; text-transform: uppercase; color: var(--hot);
+ opacity: 0; transition: opacity .3s; }
+.hud-bellows i { flex: 1; height: 2px; background: rgba(255, 106, 31, .2); position: relative; overflow: hidden; }
+.hud-bellows i::after { content: ''; position: absolute; inset: 0; background: var(--hot); transform-origin: left; transform: scaleX(var(--b, 0)); }
+.is-bellows .hud-bellows { opacity: 1; }
+.is-finale .hud, .hud.hud-away { opacity: 0 !important; }
+.toast { position: fixed; left: 50%; top: 92px; transform: translate(-50%, -12px); z-index: 30; padding: 13px 22px 12px; background: rgba(14, 10, 8, .8); backdrop-filter: blur(10px);
+ box-shadow: inset 0 0 0 1px rgba(255, 106, 31, .35); color: var(--ink); font: 400 11.5px/1 var(--display); letter-spacing: .22em; text-transform: uppercase;
+ opacity: 0; transition: opacity .45s, transform .45s; pointer-events: none; white-space: nowrap; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+/* hover cursor over the 3D */
+.tw-cursor[data-state="strike"] .tw-cursor-ring::before { transform: scale(1.35); border-color: var(--hot); opacity: 1; }
+.tw-cursor[data-state="hold"] .tw-cursor-ring::before { transform: scale(2.2); border-color: var(--hot); background: rgba(255, 106, 31, .12); opacity: 1; }
+
+@media (max-width: 900px) {
+ body { font-size: 17px; }
+ .links, .sound-label { display: none; }
+ .nav { padding: 16px 18px; }
+ .nav .btn { height: 36px; padding: 0 14px; font-size: 10.5px; letter-spacing: .14em; }
+ .nav-right { gap: 12px; }
+ .brand span { display: none; }
+ .hero { padding-bottom: 20vh; }
+ .eyebrow .eb-3 { display: none; }
+ .title { font-size: clamp(44px, 12.4vw, 80px); }
+ .sub { font-size: 17px; margin-top: 20px; }
+ .hint { bottom: auto; top: 74px; gap: 12px; font-size: 9px; letter-spacing: .12em; }
+ .hint kbd { margin-right: 5px; padding: 4px 5px 3px; }
+ .hint span:first-child { display: none; }
+ .step::after, .steel::after, .commissions::before, .voices::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 75vh; z-index: -1; pointer-events: none;
+ background: linear-gradient(180deg, transparent, rgba(8, 6, 5, .78) 45%, rgba(8, 6, 5, .9)); }
+ .steel::after { top: 0; bottom: auto; height: 60vh; background: linear-gradient(0deg, transparent, rgba(8, 6, 5, .82) 50%); }
+ .commissions::before { top: 0; bottom: auto; height: 70vh; background: linear-gradient(0deg, transparent, rgba(8, 6, 5, .85) 45%); }
+ .voices::after { top: 0; height: auto; background: rgba(8, 6, 5, .35); }
+ .step { min-height: 110vh; align-content: end; padding-bottom: 19vh; }
+ .step.right { justify-items: start; }
+ .step h2 { font-size: 44px; }
+ .step p { font-size: 17px; }
+ .steel { gap: 30vh; }
+ .stats { grid-template-columns: 1fr 1fr; }
+ .stats > div { margin-right: 0; padding: 22px 12px 22px 0; border-right: 0; }
+ .stats dd { font-size: 44px; }
+ .blades { grid-template-columns: 1fr; }
+ .blade-card.hot::after { top: 12px; right: 16px; }
+ .com-head, .steel-head { margin-left: 0; }
+ .foot-grid { grid-template-columns: 1fr; gap: 28px; }
+ .foot-legal { flex-direction: column; padding-left: 0; margin-bottom: 50px; }
+ .hud { right: 16px; bottom: 16px; gap: 6px 18px; }
+ .hud-val { font-size: 22px; }
+ .hud-gauge { width: 170px; }
+ .hud-name { font-size: 13px; }
+ .q-b { bottom: 10vh; left: var(--pad); }
+ .quotes blockquote p { font-size: 28px; }
+}
diff --git a/examples/florae/index.html b/examples/florae/index.html
new file mode 100644
index 0000000..9e99366
--- /dev/null
+++ b/examples/florae/index.html
@@ -0,0 +1,241 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Florae — A flower a month, from the edge of the map</title>
+ <meta name="description" content="Florae is a botanical archive and flower atelier. One extraordinary specimen each month, cut at dawn by the person who grew it, with its botanical plate.">
+ <meta name="theme-color" content="#f4efe6">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%2215%22 fill=%22%23f4efe6%22/%3E%3Cg fill=%22none%22 stroke=%22%23d6456b%22 stroke-width=%221.6%22%3E%3Cpath d=%22M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z%22/%3E%3Cpath d=%22M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z%22 transform=%22rotate(72 16 16)%22/%3E%3Cpath d=%22M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z%22 transform=%22rotate(144 16 16)%22/%3E%3Cpath d=%22M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z%22 transform=%22rotate(216 16 16)%22/%3E%3Cpath d=%22M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z%22 transform=%22rotate(288 16 16)%22/%3E%3C/g%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Cormorant:ital,wght@0,300;0,400;0,500;1,300;1,400;1,500&family=EB+Garamond:ital,wght@0,400;0,500;1,400;1,500&family=Inter+Tight:wght@400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <canvas class="loader-seed" aria-hidden="true"></canvas>
+ <p class="loader-line"><em>Pressing the specimen</em> <span class="loader-pct">0</span></p>
+ <p class="loader-sub caps">Florae &nbsp;·&nbsp; Plates I — IV &nbsp;·&nbsp; Autumn 2026</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Florae home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><g fill="none" stroke="currentColor" stroke-width="1.1"><path d="M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z"/><path d="M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z" transform="rotate(72 16 16)"/><path d="M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z" transform="rotate(144 16 16)"/><path d="M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z" transform="rotate(216 16 16)"/><path d="M16 16c-2.6-3.4-2.6-8.2 0-11.4 2.6 3.2 2.6 8 0 11.4Z" transform="rotate(288 16 16)"/></g><circle cx="16" cy="16" r="1.6" fill="currentColor"/></svg>
+ <span>Florae</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#specimens">Specimens</a>
+ <a href="#archive">The archive</a>
+ <a href="#subscribe">Membership</a>
+ </nav>
+ <a class="btn btn-line" href="#subscribe" data-magnetic>Begin <span class="btn-sep">—</span> €48<small>/mo</small></a>
+ </header>
+
+ <svg class="leaders" aria-hidden="true"></svg>
+ <div class="callouts" aria-hidden="true"></div>
+ <p class="fig caps" aria-hidden="true">Fig. 1 &nbsp;— &nbsp;<em>Rosa</em> ‘Explorer’, drawn in <span class="fig-n">200,704</span> points</p>
+
+ <aside class="rail" aria-label="This season's plates">
+ <a href="#spec-0" data-k="0"><b>I</b><span>Rosa</span></a>
+ <a href="#spec-1" data-k="1"><b>II</b><span>Protea</span></a>
+ <a href="#spec-2" data-k="2"><b>III</b><span>Phalaenopsis</span></a>
+ <a href="#spec-3" data-k="3"><b>IV</b><span>Morpho</span></a>
+ </aside>
+
+ <main id="top">
+ <!-- ── Hero ─────────────────────────────────────────── -->
+ <section class="hero">
+ <p class="hero-kicker caps"><span>No. 037</span><span>October 2026</span><span>Cayambe, Ecuador &nbsp;0°02′ N</span></p>
+ <h1 class="hero-title" aria-label="Florae">Florae</h1>
+ <p class="hero-line"><em>A flower a month,</em><br><em>from the edge of the map.</em></p>
+ <p class="hero-body">One extraordinary specimen, cut at dawn by the person who grew it — somewhere most maps leave blank — and at your door within forty-eight hours, with its botanical plate.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#subscribe" data-magnetic>Subscribe — €48 / month</a>
+ <a class="link" href="#specimens">This season’s plates <span aria-hidden="true">↓</span></a>
+ </div>
+ </section>
+
+ <!-- ── Atelier ──────────────────────────────────────── -->
+ <section class="atelier" id="atelier">
+ <div class="atelier-inner">
+ <p class="eyebrow caps">The atelier &nbsp;·&nbsp; Lisbon, since 2019</p>
+ <h2>We don’t send bouquets. We send <em>one flower</em>, and everything we know about it.</h2>
+ <div class="atelier-cols">
+ <p>Florae began as a herbarium in a Lisbon attic: six hundred pressed sheets, a brass microscope, and a list of places the flower trade has never reached.</p>
+ <p>Today twenty-three growers on five continents cut a single stem for each member on the same morning. It travels in a cedar box with its plate, its coordinates, and a letter from the hands that grew it.</p>
+ </div>
+ <dl class="stats">
+ <div><dt>23</dt><dd class="caps">growers on five continents</dd></div>
+ <div><dt>48<small>h</small></dt><dd class="caps">from the stem to your door</dd></div>
+ <div><dt>37</dt><dd class="caps">months sent, not one repeated</dd></div>
+ </dl>
+ </div>
+ </section>
+
+ <!-- ── Specimens ────────────────────────────────────── -->
+ <section class="spec" id="specimens" data-k="0">
+ <span id="spec-0" class="anchor"></span>
+ <div class="pin">
+ <article class="plate plate-left">
+ <p class="plate-top caps"><span>Plate I</span><span class="plate-status">Settled</span><span>Month 37 · October</span></p>
+ <h2 class="latin"><em>Rosa</em> ‘Explorer’</h2>
+ <p class="common">The equator rose</p>
+ <dl class="facts">
+ <div><dt class="caps">Origin</dt><dd>Cayambe volcano, Ecuador<span>0°02′ N &nbsp;·&nbsp; 2,850 m</span></dd></div>
+ <div><dt class="caps">Bloom season</dt><dd>All year<span>the equator has no seasons, only altitude</span></dd></div>
+ <div><dt class="caps">Grown by</dt><dd>Rosa Quishpe<span>Finca Yanahurco, third generation</span></dd></div>
+ <div><dt class="caps">Vase life</dt><dd>Fourteen days<span>recut the stem every second morning</span></dd></div>
+ </dl>
+ <p class="notes">Twelve hours of vertical sun and cold Andean nights grow a head the size of a fist on a stem as straight as a rule. Forty-two petals, velvet to the touch, darkest where they are still furled.</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="spec" data-k="1">
+ <span id="spec-1" class="anchor"></span>
+ <div class="pin">
+ <article class="plate plate-right">
+ <p class="plate-top caps"><span>Plate II</span><span class="plate-status">Settled</span><span>Month 38 · November</span></p>
+ <h2 class="latin"><em>Protea cynaroides</em></h2>
+ <p class="common">The king that waits for fire</p>
+ <dl class="facts">
+ <div><dt class="caps">Origin</dt><dd>Kogelberg, Western Cape<span>34°19′ S &nbsp;·&nbsp; 400 m, in the fynbos</span></dd></div>
+ <div><dt class="caps">Bloom season</dt><dd>May — October<span>the Cape winter, when the rain comes</span></dd></div>
+ <div><dt class="caps">Grown by</dt><dd>Thandi Mokoena<span>on land her grandmother burned and replanted</span></dd></div>
+ <div><dt class="caps">Keeps</dt><dd>For years<span>dried on its own stem, out of water</span></dd></div>
+ </dl>
+ <p class="notes">What looks like one flower is two hundred, packed into a cone and guarded by pink, silver-haired bracts. In the wild it waits for fire to open its seed. It arrives fresh and dries without losing its shape.</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="spec" data-k="2">
+ <span id="spec-2" class="anchor"></span>
+ <div class="pin">
+ <article class="plate plate-left">
+ <p class="plate-top caps"><span>Plate III</span><span class="plate-status">Settled</span><span>Month 39 · December</span></p>
+ <h2 class="latin"><em>Phalaenopsis amabilis</em></h2>
+ <p class="common">The moon orchid</p>
+ <dl class="facts">
+ <div><dt class="caps">Origin</dt><dd>Crocker Range, Sabah, Borneo<span>5°25′ N &nbsp;·&nbsp; 900 m, in the canopy</span></dd></div>
+ <div><dt class="caps">Bloom season</dt><dd>Spikes in spring<span>each flower stays open up to a hundred days</span></dd></div>
+ <div><dt class="caps">Grown by</dt><dd>The Kinabalu Orchid Trust<span>from nursery seed-stock, never the wild</span></dd></div>
+ <div><dt class="caps">Arrives</dt><dd>Rooted, in bark<span>from the same forest it came from</span></dd></div>
+ </dl>
+ <p class="notes">An epiphyte: it lives in the treetops and never touches soil. Its lip is a landing strip painted for a single carpenter bee. Keep its roots in the light and it will flower for you again next spring.</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="spec" data-k="3">
+ <span id="spec-3" class="anchor"></span>
+ <div class="pin">
+ <article class="plate plate-right">
+ <p class="plate-top caps"><span>Plate IV</span><span class="plate-status">Settled</span><span>Month 40 · January</span></p>
+ <h2 class="latin"><em>Morpho peleides</em></h2>
+ <p class="common">The one that isn’t a flower</p>
+ <dl class="facts">
+ <div><dt class="caps">Origin</dt><dd>Osa Peninsula, Costa Rica<span>8°32′ N &nbsp;·&nbsp; lowland rainforest</span></dd></div>
+ <div><dt class="caps">On the wing</dt><dd>All year<span>most in the green season, May — November</span></dd></div>
+ <div><dt class="caps">Reared by</dt><dd>Co-operative of Rancho Quemado<span>twelve families, farm-bred stock</span></dd></div>
+ <div><dt class="caps">Arrives</dt><dd>Under museum glass<span>after a natural life of three weeks</span></dd></div>
+ </dl>
+ <p class="notes">Every twelfth month we send the visitor instead of the visited. There is no blue pigment in these wings: the scales are ridged like tiny shelves that fold light into colour. Watch the blue change as it breathes.</p>
+ </article>
+ </div>
+ </section>
+
+ <!-- ── Archive ──────────────────────────────────────── -->
+ <section class="archive" id="archive">
+ <div class="archive-inner">
+ <header class="archive-head">
+ <p class="eyebrow caps">The archive &nbsp;·&nbsp; 137.5°</p>
+ <h2>Next month is <em>already in bud.</em></h2>
+ <p class="lede">Our archive grows like a sunflower head. Every specimen we have sent is a floret in this spiral, set at the golden angle — the oldest at the rim, the months to come still green at the centre.</p>
+ </header>
+ <ol class="months">
+ <li><span class="mo caps">Nov 2026</span><span class="la"><em>Paphiopedilum rothschildianum</em><small>Gold of Kinabalu</small></span><span class="or caps">Sabah, Borneo</span><span class="st caps"><i></i>In bud</span></li>
+ <li><span class="mo caps">Dec 2026</span><span class="la"><em>Helleborus niger</em><small>The Christmas rose</small></span><span class="or caps">Julian Alps, Slovenia</span><span class="st caps"><i></i>In bud</span></li>
+ <li><span class="mo caps">Jan 2027</span><span class="la"><em>Camellia japonica</em> ‘Kuro-tsubaki’<small>The black camellia</small></span><span class="or caps">Izu Ōshima, Japan</span><span class="st caps"><i></i>Setting buds</span></li>
+ <li><span class="mo caps">Feb 2027</span><span class="la"><em>Swainsona formosa</em><small>Sturt’s desert pea</small></span><span class="or caps">Pilbara, Australia</span><span class="st caps"><i></i>Seed sown</span></li>
+ <li><span class="mo caps">Mar 2027</span><span class="la"><em>Tulipa sprengeri</em><small>The last wild tulip of Amasya</small></span><span class="or caps">Anatolia, Türkiye</span><span class="st caps"><i></i>Bulbs resting</span></li>
+ <li><span class="mo caps">Apr 2027</span><span class="la"><em>Meconopsis betonicifolia</em><small>The Himalayan blue poppy</small></span><span class="or caps">Bumthang, Bhutan</span><span class="st caps"><i></i>Under snow</span></li>
+ </ol>
+ <p class="archive-foot caps">36 florets sent &nbsp;·&nbsp; none repeated &nbsp;·&nbsp; one added on the 3rd of every month</p>
+ </div>
+ </section>
+
+ <!-- ── Membership ───────────────────────────────────── -->
+ <section class="subscribe" id="subscribe">
+ <div class="subscribe-inner">
+ <p class="eyebrow caps">Membership</p>
+ <h2>Three ways to <em>receive the month.</em></h2>
+ <div class="tiers">
+ <article class="tier">
+ <p class="tier-no caps">I</p>
+ <h3>The Stem</h3>
+ <p class="price">€48<span>/ month</span></p>
+ <ul>
+ <li>One specimen, cut to order and couriered cold in a cedar box</li>
+ <li>Its botanical plate, printed on cotton rag</li>
+ <li>The grower’s letter, translated</li>
+ </ul>
+ <a class="btn btn-line" href="#begin" data-magnetic>Begin with the Stem</a>
+ </article>
+ <article class="tier tier-feature">
+ <p class="tier-no caps">II &nbsp;·&nbsp; Most kept</p>
+ <h3>The Herbarium</h3>
+ <p class="price">€76<span>/ month</span></p>
+ <ul>
+ <li>Everything in the Stem</li>
+ <li>A pressed duplicate, mounted on archival card</li>
+ <li>At month twelve, the year’s plates bound in linen</li>
+ </ul>
+ <a class="btn btn-solid" href="#begin" data-magnetic>Keep a herbarium</a>
+ </article>
+ <article class="tier">
+ <p class="tier-no caps">III</p>
+ <h3>The Expedition</h3>
+ <p class="price">€140<span>/ month</span></p>
+ <ul>
+ <li>Two stems: one to keep, one to give away</li>
+ <li>A hand-coloured plate, signed by the illustrator</li>
+ <li>A place in the ballot for our spring collecting journey</li>
+ </ul>
+ <a class="btn btn-line" href="#begin" data-magnetic>Join the expedition</a>
+ </article>
+ </div>
+ <p class="fine caps">Free cold-chain delivery to 31 countries &nbsp;·&nbsp; Pause, skip or gift any month &nbsp;·&nbsp; Cancel with a postcard</p>
+ </div>
+ </section>
+
+ <!-- ── Footer ───────────────────────────────────────── -->
+ <footer class="foot" id="begin">
+ <div class="foot-inner">
+ <p class="eyebrow caps">October’s rose is cut on the 3rd, at dawn</p>
+ <h2 class="foot-title">Your first flower <em>is already growing.</em></h2>
+ <a class="btn btn-solid btn-big" href="#subscribe" data-magnetic>Subscribe — €48 / month</a>
+ <div class="foot-grid">
+ <div><h4 class="caps">Atelier</h4><p>Rua das Flores 28<br>1200-195 Lisboa, Portugal</p></div>
+ <div><h4 class="caps">Growers</h4><p>Twenty-three, on five continents.<br><a href="#archive">Meet them in the archive</a></p></div>
+ <div><h4 class="caps">Letters</h4><p>One note a month, on the morning the flower is cut. Nothing else.</p></div>
+ <div><h4 class="caps">Elsewhere</h4><p><a href="#top">Instagram</a> · <a href="#top">Are.na</a> · <a href="#top">Press</a></p></div>
+ </div>
+ <p class="colophon caps"><span>© 2026 Florae Atelier</span><span>Plates drawn from living specimens</span><span>Set in Cormorant, EB Garamond &amp; Inter Tight</span></p>
+ </div>
+ </footer>
+ </main>
+
+ <div class="hint" aria-hidden="true">
+ <span><i>Move</i>a breeze</span>
+ <span><i>Click</i>a gust</span>
+ <span><i>Hold</i>a storm</span>
+ </div>
+ <div class="charge" aria-hidden="true"><svg viewBox="0 0 64 64"><circle class="charge-bg" cx="32" cy="32" r="26"/><circle class="charge-fg" cx="32" cy="32" r="26"/></svg><span>storm</span></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/florae/main.js b/examples/florae/main.js
new file mode 100644
index 0000000..625fa5f
--- /dev/null
+++ b/examples/florae/main.js
@@ -0,0 +1,619 @@
+import { Engine, THREE, normalize, damp, clamp, smooth, lerp } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal, SplitText } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { bakeTexture } from '../../src/core/textures.js';
+import { GPUComputationRenderer } from 'three/examples/jsm/misc/GPUComputationRenderer.js';
+import { sampleMesh, packShape, spiralShape, anchorOf } from './shapes.js';
+import { VELOCITY, POSITION, CORE_VERT, CORE_FRAG, GLOW_VERT, GLOW_FRAG, MOTE_VERT, MOTE_FRAG, PAPER_VERT, PAPER_FRAG } from './shaders.js';
+
+const Q = new URLSearchParams(location.search);
+const MOBILE = matchMedia('(max-width: 760px)').matches;
+const COARSE = matchMedia('(pointer: coarse)').matches;
+const SIZE = +(Q.get('size') ?? (MOBILE || COARSE ? 320 : 448));
+const N = SIZE * SIZE;
+const FOV = 30;
+
+// paper, toned edge, light pool — one set per plate (display colours; the paper shader inverts the tone mapper)
+const PALETTES = [
+ ['#f4efe6', '#e6dac8', '#f8f3ea'], // rose: cream
+ ['#f5ebe3', '#e7d4c7', '#f9f2ec'], // protea: blush
+ ['#e9e7df', '#d4d1c4', '#f1efe8'], // orchid: pearl — a little darker so white petals can shine
+ ['#ebedea', '#d6dad3', '#f3f4f0'], // morpho: river mist
+ ['#f2ebdf', '#e2d4bf', '#f7f1e7'], // archive: old stock
+].map(p => p.map(h => new THREE.Color(h)));
+
+// ─── Engine ─────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: FOV, near: 0.05, far: 80, dpr: MOBILE ? 2 : 1.75, background: 0xf4efe6, shadows: false,
+ post: {
+ ao: false,
+ bloom: { intensity: 0.8, luminanceThreshold: 2.3, luminanceSmoothing: 0.5, radius: 0.65 }, // above the paper (≈1.1–1.5 pre-tone): only glints bloom
+ tone: 'neutral', vignette: false, noise: 0.042, ca: false, smaa: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+
+// ─── Loader: a sunflower head that fills floret by floret ───────────────────
+const assets = new Assets();
+const loaderEl = document.querySelector('.loader');
+const seedCv = loaderEl.querySelector('.loader-seed');
+const seedCx = seedCv.getContext('2d');
+{
+ const s = 200 * Math.min(2, devicePixelRatio || 1);
+ seedCv.width = seedCv.height = s; seedCx.scale(s / 200, s / 200);
+}
+const GA = Math.PI * (3 - Math.sqrt(5));
+const FLORETS = 460;
+let florets = 0;
+function drawFlorets(n) {
+ while (florets < n) {
+ const i = florets++, f = i / FLORETS;
+ const r = 4.3 * Math.sqrt(i + 0.5), a = i * GA;
+ const x = 100 + Math.cos(a) * r, y = 100 + Math.sin(a) * r;
+ seedCx.fillStyle = f < 0.2 ? `rgba(150,140,62,${0.9 - f})` : `rgba(${Math.round(lerp(168, 214, f))},${Math.round(lerp(40, 69, f))},${Math.round(lerp(75, 107, f))},${0.55 + f * 0.4})`;
+ seedCx.beginPath(); seedCx.arc(x, y, 1.1 + f * 1.9, 0, Math.PI * 2); seedCx.fill();
+ }
+}
+let procP = 0;
+const progress = { get progress() { return assets.progress * 0.8 + procP * 0.2; } };
+const pctEl = loaderEl.querySelector('.loader-pct');
+const loader = preloader({
+ assets: progress, el: loaderEl, minTime: 1400,
+ onValue: v => { drawFlorets(Math.floor(v * FLORETS)); pctEl.textContent = String(Math.round(v * 100)).padStart(2, '0'); },
+ exit: () => gsap.timeline()
+ .to(seedCv, { scale: 1.6, rotation: 40, opacity: 0, duration: 1.1, ease: 'power3.in' })
+ .to(loaderEl.querySelectorAll('p'), { opacity: 0, y: -8, duration: 0.5, stagger: 0.05 }, 0)
+ .to(loaderEl, { autoAlpha: 0, duration: 0.9, ease: 'power2.inOut' }, 0.55),
+});
+
+// ─── Paper ──────────────────────────────────────────────────────────────────
+const grain = bakeTexture(renderer, 512, `
+ void main(){
+ float a = fbm(vUv * 6.0, 6.0, 6, 0.55) * 0.5 + 0.5;
+ float b = fbm(vUv * 48.0, 48.0, 3, 0.5) * 0.5 + 0.5;
+ gl_FragColor = vec4(a, b, 0.0, 1.0);
+ }`);
+const paperU = {
+ uPaper: { value: PALETTES[0][0].clone() }, uEdge: { value: PALETTES[0][1].clone() }, uGlowC: { value: PALETTES[0][2].clone() },
+ uGlowP: { value: new THREE.Vector2(0.65, 0.5) }, uAspect: { value: 1.6 }, uGlow: { value: 1 }, tGrain: { value: grain },
+};
+const paper = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({
+ uniforms: paperU, vertexShader: PAPER_VERT, fragmentShader: PAPER_FRAG, depthTest: false, depthWrite: false,
+}));
+paper.frustumCulled = false; paper.renderOrder = -10;
+scene.add(paper);
+
+// ─── Specimens ──────────────────────────────────────────────────────────────
+const SPECS = [
+ { key: 'rose', file: 'models/florae/rose.glb', size: 2.4, axis: 'y', heart: 'top' },
+ { key: 'protea', file: 'models/florae/protea.glb', size: 2.55, axis: 'y', heart: 'top' },
+ { key: 'orchid', file: 'models/florae/orchid.glb', size: 2.6, axis: 'max', heart: 'bottom' },
+ { key: 'morpho', file: 'models/florae/morpho.glb', size: 2.6, axis: 'max', heart: 'center' },
+];
+const yieldFrame = () => new Promise(r => setTimeout(r, 0));
+async function buildShapes() {
+ const tl = performance.now();
+ const glbs = await Promise.all(SPECS.map(s => assets.gltf(s.file)));
+ const raws = [], packs = [];
+ const t0 = performance.now();
+ console.info(`[florae] models loaded in ${Math.round(t0 - tl)} ms`);
+ for (let i = 0; i < SPECS.length; i++) {
+ const s = SPECS[i], root = glbs[i].scene;
+ normalize(root, s.size, { ground: false, axis: s.axis });
+ root.updateMatrixWorld(true);
+ const ta = performance.now();
+ const raw = sampleMesh(firstMesh(root), N);
+ raws.push(raw);
+ procP = (i + 0.5) / 5; await yieldFrame();
+ const tb = performance.now();
+ packs.push(packShape(raw, SIZE, { heart: s.heart }));
+ console.info(`[florae] ${s.key}: sample ${Math.round(tb - ta)} ms, pack+AO ${Math.round(performance.now() - tb)} ms`);
+ procP = (i + 1) / 5; await yieldFrame();
+ }
+ packs.push(packShape(spiralShape(SIZE, raws), SIZE, { heart: 'center' }));
+ procP = 1;
+ console.info(`[florae] ${N} particles × 5 shapes in ${Math.round(performance.now() - t0)} ms`);
+ return packs;
+}
+
+// ─── Simulation ─────────────────────────────────────────────────────────────
+const U = {
+ tA: { value: null }, tB: { value: null }, tNA: { value: null }, tNB: { value: null },
+ uF: { value: 0 }, uFlapA: { value: 0 }, uFlapB: { value: 0 }, uBloom: { value: 0 }, uTime: { value: 0 }, uStagger: { value: 0.55 },
+ uDisc: { value: new THREE.Matrix3() },
+};
+const SIMU = {
+ ...U, uDt: { value: 1 / 60 }, uStiff: { value: 50 }, uBreeze: { value: 0 }, uBreezeR: { value: 0.4 }, uCharge: { value: 0 }, uScrollV: { value: 0 },
+ uRayO: { value: new THREE.Vector3(0, 0, 50) }, uRayD: { value: new THREE.Vector3(0, 0, -1) }, uRayV: { value: new THREE.Vector3() },
+ uGustD: { value: new THREE.Vector3(0, 0, -1) }, uGust: { value: new THREE.Vector4() },
+};
+const gpu = new GPUComputationRenderer(SIZE, SIZE, renderer);
+const pos0 = gpu.createTexture(), vel0 = gpu.createTexture();
+{
+ const d = pos0.image.data;
+ for (let i = 0; i < N; i++) {
+ const u = Math.random() * 2 - 1, a = Math.random() * Math.PI * 2, r = 2.2 + Math.pow(Math.random(), 0.6) * 5;
+ const s = Math.sqrt(1 - u * u);
+ d[i * 4] = Math.cos(a) * s * r; d[i * 4 + 1] = u * r * 0.7 - 0.6; d[i * 4 + 2] = Math.sin(a) * s * r; d[i * 4 + 3] = 1;
+ }
+}
+const posVar = gpu.addVariable('texturePosition', POSITION, pos0);
+const velVar = gpu.addVariable('textureVelocity', VELOCITY, vel0);
+gpu.setVariableDependencies(posVar, [posVar, velVar]);
+gpu.setVariableDependencies(velVar, [posVar, velVar]);
+Object.assign(velVar.material.uniforms, SIMU);
+posVar.material.uniforms.uDt = SIMU.uDt;
+{ const err = gpu.init(); if (err) console.error(err); }
+
+// ─── Particles: opaque pointillist cores + a soft glow / bokeh pass ─────────
+const R = {
+ ...U,
+ tPos: { value: null }, tCA: { value: null }, tCB: { value: null },
+ uDot: { value: MOBILE ? 0.0085 : 0.0068 }, uScale: { value: 1000 }, uFocus: { value: 5 }, uAperture: { value: 0.05 }, uCoreCut: { value: 3.2 },
+ uCharge: SIMU.uCharge, uGlowFrac: { value: MOBILE || COARSE ? 0.7 : 1.0 }, uGlowA: { value: 0.3 }, uIrid: { value: 2.6 }, uPetal: { value: 0.02 }, uLift: { value: 0.1 },
+ uSize: { value: SIZE },
+ uL: { value: new THREE.Vector3(-0.5, 0.62, 0.6).normalize() },
+ uKey: { value: new THREE.Color(1.22, 1.12, 1.02) }, uAmb: { value: new THREE.Color(0.28, 0.27, 0.31) },
+};
+const geo = new THREE.BufferGeometry();
+{
+ const ref = new Float32Array(N * 2), perm = new Uint32Array(N);
+ for (let i = 0; i < N; i++) perm[i] = i;
+ for (let i = N - 1; i > 0; i--) { const j = (Math.random() * (i + 1)) | 0; const t = perm[i]; perm[i] = perm[j]; perm[j] = t; }
+ for (let j = 0; j < N; j++) { const i = perm[j]; ref[j * 2] = ((i % SIZE) + 0.5) / SIZE; ref[j * 2 + 1] = (Math.floor(i / SIZE) + 0.5) / SIZE; }
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(N * 3), 3));
+ geo.setAttribute('ref', new THREE.BufferAttribute(ref, 2));
+}
+const flower = new THREE.Group();
+scene.add(flower);
+const cores = new THREE.Points(geo, new THREE.ShaderMaterial({ uniforms: R, vertexShader: CORE_VERT, fragmentShader: CORE_FRAG }));
+const glows = new THREE.Points(geo, new THREE.ShaderMaterial({ uniforms: R, vertexShader: GLOW_VERT, fragmentShader: GLOW_FRAG, transparent: true, depthWrite: false }));
+cores.frustumCulled = glows.frustumCulled = false;
+glows.renderOrder = 2;
+flower.add(cores, glows);
+if (Q.has('noflower')) flower.visible = false;
+
+// The specimen's shadow on the paper: its silhouette at low resolution, disc-blurred by the paper shader.
+const SHADOW = !MOBILE && !Q.has('noshadow');
+const SH_DIV = 5;
+const shadowRT = new THREE.WebGLRenderTarget(4, 4, { type: THREE.UnsignedByteType, depthBuffer: false });
+const shadowScene = new THREE.Scene();
+const shadowU = { ...R, uScale: { value: 100 }, uCoreCut: { value: 1e6 }, uPetal: { value: 0 } };
+const shadowPts = new THREE.Points(geo, new THREE.ShaderMaterial({
+ uniforms: shadowU, vertexShader: CORE_VERT, depthTest: false, depthWrite: false,
+ fragmentShader: 'void main(){ vec2 c = gl_PointCoord * 2.0 - 1.0; if (dot(c, c) > 1.0) discard; gl_FragColor = vec4(1.0); }',
+}));
+shadowPts.frustumCulled = false; shadowPts.matrixAutoUpdate = false;
+shadowScene.add(shadowPts);
+paperU.tShadow = { value: shadowRT.texture };
+paperU.uShadow = { value: SHADOW ? 1 : 0 };
+paperU.uShadowOff = { value: new THREE.Vector2(0.012, -0.022) };
+paperU.uTexel = { value: new THREE.Vector2(1 / 288, 1 / 180) };
+
+// Pollen, seed fluff: pure depth of field
+const moteU = { uTime: U.uTime, uScale: R.uScale, uFocus: R.uFocus, uAperture: R.uAperture, uGustE: { value: 0 }, uGustC: { value: new THREE.Vector3() } };
+{
+ const M = MOBILE ? 700 : 1800;
+ const p = new Float32Array(M * 3), s = new Float32Array(M * 4);
+ for (let i = 0; i < M; i++) {
+ const u = Math.random() * 2 - 1, a = Math.random() * Math.PI * 2, r = 1.6 + Math.random() * 8.5, q = Math.sqrt(1 - u * u);
+ p[i * 3] = Math.cos(a) * q * r * 1.3; p[i * 3 + 1] = u * r * 0.8; p[i * 3 + 2] = Math.sin(a) * q * r;
+ for (let k = 0; k < 4; k++) s[i * 4 + k] = Math.random();
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(p, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(s, 4));
+ const motes = new THREE.Points(g, new THREE.ShaderMaterial({ uniforms: moteU, vertexShader: MOTE_VERT, fragmentShader: MOTE_FRAG, transparent: true, depthWrite: false }));
+ motes.frustumCulled = false; motes.renderOrder = 3;
+ if (!Q.has('nomotes')) scene.add(motes);
+}
+
+engine.onResize((w, h, dpr) => {
+ R.uScale.value = h * dpr / (2 * Math.tan(FOV * Math.PI / 360));
+ const sw = Math.max(4, Math.round(w / SH_DIV)), sh = Math.max(4, Math.round(h / SH_DIV));
+ shadowRT.setSize(sw, sh);
+ shadowU.uScale.value = sh / (2 * Math.tan(FOV * Math.PI / 360)) * 1.5;
+ paperU.uTexel.value.set(1 / sw, 1 / sh);
+ paperU.uAspect.value = w / h;
+});
+
+// ─── Scroll choreography ────────────────────────────────────────────────────
+// Each keyframe is a full scene state; the page's sections pin them to scroll positions.
+const D = Math.PI / 180;
+const S = o => ({ m: 0, dist: 5.6, elev: 0.1, azim: 0, ty: 0.2, sx: 0.3, sy: 0, yaw: 0, pal: 0, ap: 0.05, spin: 1, rot: 0, glow: 1, ...o });
+const ST = {
+ hero: S({ m: 0, dist: 5.7, elev: 7 * D, ty: 0.06, sx: 0.3, sy: 0.02, yaw: -20 * D, ap: 0.05 }),
+ atelier: S({ m: 0, dist: 4.4, elev: 24 * D, ty: 0.45, sx: -0.36, sy: 0.02, yaw: 40 * D, ap: 0.06 }),
+ rose: S({ m: 0, dist: 4.8, elev: 32 * D, ty: 0.45, sx: 0.26, sy: -0.04, yaw: 95 * D, ap: 0.07 }),
+ protea: S({ m: 1, dist: 5.5, elev: -2 * D, ty: 0.28, sx: -0.36, sy: -0.02, yaw: 150 * D, pal: 1, ap: 0.055 }),
+ orchid: S({ m: 2, dist: 6.3, elev: 8 * D, ty: 0.12, sx: 0.28, sy: -0.03, yaw: 0, pal: 2, ap: 0.055 }),
+ morpho: S({ m: 3, dist: 6.1, elev: 16 * D, ty: 0, sx: -0.34, sy: 0.02, yaw: -24 * D, pal: 3, ap: 0.06, spin: 0.5 }),
+ archive: S({ m: 4, dist: 10.2, elev: 68 * D, ty: -0.2, sx: 0.52, sy: 0.0, yaw: 0, pal: 4, ap: 0.07, spin: 0, rot: 0.06 }),
+ subscribe: S({ m: 5, dist: 6.6, elev: 12 * D, ty: 0.1, sx: 0.54, sy: 0.0, yaw: 200 * D, pal: 0, ap: 0.05 }),
+ foot: S({ m: 5, dist: 5.9, elev: 14 * D, ty: 0.2, sx: 0.46, sy: -0.04, yaw: 250 * D, pal: 0, ap: 0.05 }),
+};
+// Phones: the specimen takes the top of the screen, type sits below it.
+const MOB = { hero: [1.75, 0.36], atelier: [1.6, 0.38], rose: [1.8, 0.32], protea: [1.6, 0.3], orchid: [1.65, 0.3], morpho: [2.1, 0.33], archive: [1.45, 0.4], subscribe: [1.9, 0.42], foot: [2.9, 0.68] };
+if (MOBILE) for (const k in ST) Object.assign(ST[k], { sx: 0, sy: MOB[k][1], dist: ST[k].dist * MOB[k][0] });
+const KEYS_NUM = Object.keys(ST.hero);
+let KEYS = [];
+function layoutKeys() {
+ const vh = innerHeight, top = el => el.getBoundingClientRect().top + scrollY;
+ const specs = [...document.querySelectorAll('.spec')];
+ const at = document.querySelector('.atelier'), ar = document.querySelector('.archive'), su = document.querySelector('.subscribe'), fo = document.querySelector('.foot');
+ const order = [ST.rose, ST.protea, ST.orchid, ST.morpho];
+ const K = [[0, ST.hero], [top(at) + vh * 0.05, ST.atelier], [top(specs[0]), ST.rose]];
+ for (let k = 1; k < 4; k++) {
+ const t = top(specs[k]), span = specs[k].offsetHeight - vh;
+ K.push([t - vh * 0.6, order[k - 1]], [t + span * 0.38, order[k]]);
+ }
+ K.push([top(ar) - vh * 0.85, ST.morpho], [top(ar) + vh * 0.15, ST.archive]);
+ K.push([top(su) - vh * 0.55, ST.archive], [top(su) + vh * 0.25, ST.subscribe]);
+ K.push([top(fo) - vh * 0.3, ST.subscribe], [document.documentElement.scrollHeight - vh, ST.foot]);
+ KEYS = K.sort((a, b) => a[0] - b[0]);
+ specY = specs.map(s => [top(s), s.offsetHeight]);
+ subY = top(su);
+}
+let specY = [], subY = 1e9, hintReady = false;
+const target = S({}), cur = S({});
+function sampleKeys(y, out) {
+ let i = 0;
+ while (i < KEYS.length - 2 && y > KEYS[i + 1][0]) i++;
+ const [y0, a] = KEYS[i], [y1, b] = KEYS[i + 1];
+ const f = clamp((y - y0) / Math.max(1, y1 - y0));
+ const e = f * f * (3 - 2 * f);
+ // during a morph the specimen changes sides early, so the swirl never passes under the pinned plate
+ const es = a.m !== b.m ? smooth(0.0, 0.34, f) : e;
+ for (const k of KEYS_NUM) out[k] = lerp(a[k], b[k], k === 'm' ? f : (k === 'sx' || k === 'sy') ? es : e);
+ return out;
+}
+
+// ─── Interaction: breeze, gust, storm ───────────────────────────────────────
+const pointer = new Pointer({ lambda: 9 });
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const invM = new THREE.Matrix4();
+const rayO = new THREE.Vector3(), rayD = new THREE.Vector3(), rayP = new THREE.Vector3(), rayPrev = new THREE.Vector3(), rayV = new THREE.Vector3();
+let lastMove = -10, breeze = 0, rayInit = false;
+const hintEl = document.querySelector('.hint');
+if (COARSE) { hintEl.children[0].remove(); hintEl.querySelector('i').textContent = 'Tap'; }
+const hintSpans = hintEl.querySelectorAll('span');
+const litIdx = COARSE ? [-1, 0, 1] : [0, 1, 2];
+const litHint = j => { const i = litIdx[j]; if (i < 0) return; hintSpans[i].classList.add('lit'); clearTimeout(hintSpans[i]._t); hintSpans[i]._t = setTimeout(() => hintSpans[i].classList.remove('lit'), 1400); };
+pointer.on('move', () => { lastMove = engine.time; });
+
+const bloom = { v: 0 };
+const gustS = { w: 0 };
+const shake = { v: 0 };
+let charge = 0, pressing = false, pressT = 0, started = false;
+const chargeEl = document.querySelector('.charge'), chargeFg = chargeEl.querySelector('.charge-fg');
+const isUI = t => t.closest?.('a, button, input, select, textarea, label, .tier, .rail, .nav, .months li');
+
+function gust(power) {
+ if (!started) return;
+ // centre: the point on the pointer ray nearest the specimen's axis, nudged toward the viewer
+ const t = Math.max(0.5, -rayO.dot(rayD));
+ const c = rayP.copy(rayO).addScaledVector(rayD, t - 0.35);
+ SIMU.uGust.value.set(c.x, c.y, c.z, 0);
+ SIMU.uGustD.value.copy(rayD);
+ gsap.killTweensOf(gustS);
+ gsap.fromTo(gustS, { w: 9 + 13 * power }, { w: 0, duration: 0.35 + 0.12 * power, ease: 'power2.out' });
+ gsap.killTweensOf(bloom);
+ bloom.v = 0;
+ gsap.to(bloom, { v: 1, duration: 2.4 + power * 0.6, delay: 0.5 + power * 0.4, ease: 'power1.inOut' });
+ moteU.uGustC.value.copy(c).applyMatrix4(flower.matrixWorld);
+ gsap.fromTo(moteU.uGustE, { value: 0.4 + power * 0.5 }, { value: 0, duration: 3.5, ease: 'power2.out' });
+ gsap.fromTo(shake, { v: 0.02 + power * 0.03 }, { v: 0, duration: 0.9, ease: 'power2.out' });
+ gsap.fromTo(paperU.uGlow, { value: 1.25 + power * 0.25 }, { value: 1, duration: 2.4, ease: 'power2.out' });
+}
+addEventListener('pointerdown', e => {
+ if (e.button !== 0 || isUI(e.target)) return;
+ pressing = true; pressT = engine.time;
+});
+addEventListener('pointerup', () => {
+ if (!pressing) return;
+ pressing = false;
+ const p = charge;
+ litHint(p > 0.25 ? 2 : 1);
+ gust(1 + p * 2.2);
+ gsap.to({ c: charge }, { c: 0, duration: 0.25, onUpdate() { charge = this.targets()[0].c; } });
+});
+addEventListener('pointercancel', () => { pressing = false; charge = 0; });
+addEventListener('contextmenu', e => { if (!isUI(e.target)) e.preventDefault(); });
+
+// ─── Botanical callouts, projected from the specimen ────────────────────────
+// `at`: a fixed point (bbox fractions); `band` + `pick`: the extreme particle within a height band on the
+// given screen side (r / l / t), chosen when the callouts appear, so labels always sit outside the silhouette.
+const NOTES = [
+ [ // rose — plate on the left, labels to the right
+ { at: [0.5, 0.96, 0.5], n: 'i.', h: 'The heart', d: 'forty-two petals, still furled', dx: 250, dy: -120 },
+ { band: [0.6, 0.86], pick: 'r', n: 'ii.', h: 'Guard petals', d: 'reflexed, velvet to the touch', dx: 110, dy: 16 },
+ { band: [0.12, 0.45], pick: 'r', n: 'iii.', h: 'Compound leaf', d: 'five leaflets, finely serrate', dx: 100, dy: 24 },
+ ],
+ [ // protea — plate on the right, labels to the left
+ { band: [0.86, 1.0], pick: 't', n: 'i.', h: 'The florets', d: 'two hundred, packed in one cone', dx: -150, dy: -46 },
+ { band: [0.62, 0.84], pick: 'l', n: 'ii.', h: 'Involucral bracts', d: 'pink, with silver hairs', dx: -150, dy: -20 },
+ { band: [0.3, 0.58], pick: 'l', n: 'iii.', h: 'Leathery leaves', d: 'fire-hardened, red at the rim', dx: -80, dy: 40 },
+ ],
+ [ // orchid — plate on the left, labels to the right
+ { at: [0.7, 0.8, 1.0], n: 'i.', h: 'Dorsal sepal', d: 'white as a moth, 9 cm across', dx: 190, dy: -70 },
+ { at: [0.85, 0.55, 1.0], n: 'ii.', h: 'Labellum', d: 'a landing strip for one bee', dx: 150, dy: 40 },
+ { at: [0.0, 0.85, 0.5], n: 'iii.', h: 'The buds', d: 'opening in order, tip last', dx: 90, dy: -150 },
+ ],
+ [ // morpho — plate on the right, labels to the left
+ { at: [0.15, 0.95, 1.0], n: 'i.', h: 'Forewing', d: 'structural blue — no pigment', dx: -120, dy: -60 },
+ { at: [0.1, 0.12, 1.0], n: 'ii.', h: 'The margin', d: 'a border of white eyespots', dx: -110, dy: 70 },
+ { at: [0.5, 0.64, 1.0], n: 'iii.', h: 'Thorax', d: 'all flight muscle', dx: -60, dy: -230 },
+ ],
+];
+const leadersEl = document.querySelector('.leaders');
+const calloutsEl = document.querySelector('.callouts');
+const SVGNS = 'http://www.w3.org/2000/svg';
+const callouts = NOTES.map(list => {
+ const g = document.createElementNS(SVGNS, 'g');
+ leadersEl.appendChild(g);
+ return list.map(n => {
+ const path = document.createElementNS(SVGNS, 'path'), dot = document.createElementNS(SVGNS, 'circle');
+ dot.setAttribute('r', '3.2');
+ g.append(path, dot);
+ const el = document.createElement('div');
+ el.className = 'callout' + (n.dx < 0 ? ' left' : '');
+ el.innerHTML = `<b>${n.n}</b><span>${n.h}</span><small>${n.d}</small>`;
+ calloutsEl.appendChild(el);
+ return { ...n, g, path, dot, el, p: null };
+ });
+});
+function candidates(shape, n = 1600) {
+ const P = shape.P, NN = P.length / 4;
+ let y0 = Infinity, y1 = -Infinity;
+ for (let j = 0; j < NN; j += 5) { y0 = Math.min(y0, P[j * 4 + 1]); y1 = Math.max(y1, P[j * 4 + 1]); }
+ const out = [];
+ for (let i = 0; i < n; i++) { const j = (Math.random() * NN) | 0; out.push({ p: new THREE.Vector3(P[j * 4], P[j * 4 + 1], P[j * 4 + 2]), v: (P[j * 4 + 1] - y0) / (y1 - y0) }); }
+ return out;
+}
+function pickAnchors(k, flap, only = null) {
+ for (const c of callouts[k]) {
+ if (!c.band || (only && c !== only)) continue;
+ let best = null, bs = -Infinity;
+ for (const q of cands[k]) {
+ if (q.v < c.band[0] || q.v > c.band[1]) continue;
+ flapJS(q.p, k === 3 ? flap : 0, tmp).applyMatrix4(flower.matrixWorld).project(camera);
+ const sc = c.pick === 'r' ? tmp.x : c.pick === 'l' ? -tmp.x : tmp.y;
+ if (sc > bs) { bs = sc; best = q.p; }
+ }
+ if (best) c.p = best;
+ }
+}
+let cands = [];
+const flapJS = (p, ang, out) => {
+ if (ang <= 0) return out.copy(p);
+ const hx = Math.abs(p.x) / 1.3, ht = clamp((hx - 0.02) / 0.12), a = ang * ht * ht * (3 - 2 * ht) * (0.7 + 0.3 * hx), sd = p.x < 0 ? -1 : 1, ax = Math.abs(p.x), c = Math.cos(a), s = Math.sin(a);
+ return out.set(sd * (ax * c - p.z * s), p.y - (ang - 0.45) * 0.07, ax * s + p.z * c);
+};
+
+// ─── UI elements driven by the scene ────────────────────────────────────────
+const plates = [...document.querySelectorAll('.plate')];
+const statusEls = plates.map(p => p.querySelector('.plate-status'));
+const railEl = document.querySelector('.rail'), railLinks = [...railEl.querySelectorAll('a')];
+const figEl = document.querySelector('.fig');
+const heroEl = document.querySelector('.hero');
+const navEl = document.querySelector('.nav');
+document.querySelector('.fig-n').textContent = N.toLocaleString('en-US');
+
+// ─── Frame loop ─────────────────────────────────────────────────────────────
+let SHAPES = null;
+let yawOsc = 0, rotPhase = 0, scrollV = 0;
+const tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), camTarget = new THREE.Vector3();
+const discN = new THREE.Vector3(), discT = new THREE.Vector3(), discB = new THREE.Vector3();
+let activePlate = -1, calloutOn = -1;
+
+engine.onTick((dt, t) => {
+ if (!SHAPES) return;
+ pointer.update(dt);
+ U.uTime.value = t;
+ SIMU.uDt.value = Math.min(dt, 1 / 30);
+
+ // scroll → state
+ sampleKeys(scrollY, target);
+ for (const k of KEYS_NUM) cur[k] = damp(cur[k], target[k], k === 'm' ? 7 : 4.2, dt);
+
+ // camera orbit, lens-shifted so the specimen sits beside the type
+ camTarget.set(0, cur.ty, 0);
+ const ce = Math.cos(cur.elev), fm = cur.m - Math.floor(cur.m);
+ const dist = cur.dist + Math.sin(Math.PI * fm) * 1.3; // step back to watch the swirl
+ camera.position.set(Math.sin(cur.azim) * ce, Math.sin(cur.elev), Math.cos(cur.azim) * ce).multiplyScalar(dist).add(camTarget);
+ camera.lookAt(camTarget);
+ tmp.set(pointer.sx * 0.16 + (Math.random() - 0.5) * shake.v, pointer.sy * 0.1 + (Math.random() - 0.5) * shake.v, 0).applyQuaternion(camera.quaternion);
+ camera.position.add(tmp);
+ camera.lookAt(camTarget);
+ camera.updateProjectionMatrix();
+ camera.projectionMatrix.elements[8] = -cur.sx;
+ camera.projectionMatrix.elements[9] = -cur.sy;
+ camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
+ camera.updateMatrixWorld();
+
+ rotPhase += cur.rot * dt;
+ yawOsc = Math.sin(t * 0.16) * 0.32 * cur.spin;
+ flower.rotation.y = cur.yaw + yawOsc + rotPhase;
+ flower.updateMatrixWorld();
+
+ // the whirl's plane tilts toward the viewer
+ discN.copy(camera.position).applyMatrix4(invM.copy(flower.matrixWorld).invert()).normalize().multiplyScalar(0.75).add(tmp.set(0, 0.7, 0)).normalize();
+ discT.set(1, 0, 0).addScaledVector(discN, -discN.x).normalize();
+ discB.crossVectors(discT, discN);
+ U.uDisc.value.set(discT.x, discN.x, discB.x, discT.y, discN.y, discB.y, discT.z, discN.z, discB.z);
+
+ // morph: shape k → k+1
+ const m = clamp(cur.m, 0, SHAPES.length - 1);
+ const k = Math.min(SHAPES.length - 2, Math.floor(m)), f = m - k;
+ const A = SHAPES[k], B = SHAPES[k + 1];
+ U.tA.value = A.pos; U.tB.value = B.pos; U.tNA.value = A.nrm; U.tNB.value = B.nrm;
+ R.tCA.value = A.col; R.tCB.value = B.col;
+ U.uF.value = f;
+ const flap = 0.2 + 0.62 * Math.pow(0.5 + 0.5 * Math.sin(t * 2.3), 1.4);
+ U.uFlapA.value = k === 3 ? flap : 0;
+ U.uFlapB.value = k + 1 === 3 ? flap : 0;
+ U.uBloom.value = bloom.v;
+
+ // lens
+ R.uFocus.value = dist;
+ R.uAperture.value = cur.ap;
+ const pi = clamp(cur.pal, 0, PALETTES.length - 1), p0 = Math.floor(pi), p1 = Math.min(PALETTES.length - 1, p0 + 1), pf = pi - p0;
+ paperU.uPaper.value.copy(PALETTES[p0][0]).lerp(PALETTES[p1][0], pf);
+ paperU.uEdge.value.copy(PALETTES[p0][1]).lerp(PALETTES[p1][1], pf);
+ paperU.uGlowC.value.copy(PALETTES[p0][2]).lerp(PALETTES[p1][2], pf);
+ tmp.set(0, 0.35, 0).applyMatrix4(flower.matrixWorld).project(camera);
+ paperU.uGlowP.value.set(tmp.x * 0.5 + 0.5, tmp.y * 0.5 + 0.5);
+
+ // pointer ray, in the specimen's space
+ ndc.set(pointer.x, pointer.y);
+ ray.setFromCamera(ndc, camera);
+ invM.copy(flower.matrixWorld).invert();
+ rayO.copy(ray.ray.origin).applyMatrix4(invM);
+ rayD.copy(ray.ray.direction).transformDirection(invM);
+ tmp2.copy(rayO).addScaledVector(rayD, cur.dist);
+ if (!rayInit) { rayPrev.copy(tmp2); rayInit = true; }
+ rayV.subVectors(tmp2, rayPrev).divideScalar(Math.max(dt, 1e-3));
+ if (rayV.length() > 10) rayV.setLength(10);
+ rayPrev.copy(tmp2);
+ SIMU.uRayV.value.lerp(rayV, 1 - Math.exp(-12 * dt));
+ const speed = SIMU.uRayV.value.length();
+ const idle = clamp(1 - (t - lastMove - 0.6) / 0.8);
+ breeze = damp(breeze, pointer.active && started ? clamp(0.18 + speed * 0.32, 0, 1.5) * idle : 0, 10, dt);
+ if (speed > 1.2 && started) litHint(0);
+ SIMU.uBreeze.value = breeze;
+ SIMU.uRayO.value.copy(rayO); SIMU.uRayD.value.copy(rayD);
+ SIMU.uGust.value.w = gustS.w;
+
+ // holding charges a storm
+ if (pressing && t - pressT > 0.16) charge = Math.min(1, charge + dt / 1.5);
+ SIMU.uCharge.value = charge;
+ chargeEl.classList.toggle('on', pressing && t - pressT > 0.2);
+ chargeEl.style.transform = `translate3d(${pointer.px}px, ${pointer.py}px, 0)`;
+ chargeFg.style.strokeDashoffset = (163.4 * (1 - charge)).toFixed(1);
+
+ // scrolling drags the petals
+ scrollV = damp(scrollV, clamp((window.__lenis?.velocity ?? 0) / 50, -1, 1), 6, dt);
+ SIMU.uScrollV.value = scrollV;
+
+ gpu.compute();
+ R.tPos.value = gpu.getCurrentRenderTarget(posVar).texture;
+ if (SHADOW) {
+ shadowPts.matrix.copy(flower.matrixWorld); shadowPts.matrixWorld.copy(flower.matrixWorld);
+ const prev = renderer.getRenderTarget();
+ renderer.setRenderTarget(shadowRT);
+ renderer.setClearColor(0x000000, 0); renderer.clear();
+ renderer.render(shadowScene, camera);
+ renderer.setRenderTarget(prev);
+ renderer.setClearColor(0xf4efe6, 1);
+ }
+
+ // ── page chrome tied to the scene ──
+ const vh = innerHeight;
+ let ap = -1;
+ specY.forEach(([y, h], i) => { if (scrollY >= y - vh * (i ? 0.02 : 0.2) && scrollY < y + h - vh * 1.12) ap = i; });
+ if (ap !== activePlate) {
+ plates.forEach((p, i) => p.classList.toggle('on', i === ap));
+ railLinks.forEach((a, i) => a.classList.toggle('on', i === ap));
+ railEl.classList.toggle('on', ap >= 0);
+ activePlate = ap;
+ }
+ if (ap >= 0) {
+ const formed = ap === 0 ? 1 : clamp(cur.m - (ap - 1));
+ const b = bloom.v;
+ const st = formed < 0.995 ? `Assembling ${Math.round(formed * 100)}%` : b < 0.995 ? `Re-blooming ${Math.round(b * 100)}%` : 'Settled';
+ if (statusEls[ap]._s !== st) { statusEls[ap].textContent = st; statusEls[ap]._s = st; plates[ap].classList.toggle('forming', st !== 'Settled'); }
+ }
+ const calm = Math.abs(cur.dist - target.dist) + Math.abs(cur.sx - target.sx) * 3 + Math.abs(cur.yaw - target.yaw) + Math.abs(cur.elev - target.elev) < 0.06;
+ const settled = ap >= 0 && Math.abs(cur.m - ap) < 0.02 && bloom.v > 0.97 && calm && !MOBILE;
+ const cOn = settled ? ap : -1;
+ if (cOn !== calloutOn) {
+ if (cOn >= 0) callouts[cOn].forEach(c => { c.fresh = true; });
+ callouts.forEach((list, i) => { list[0].g.classList.toggle('on', i === cOn); list.forEach(c => c.el.classList.toggle('on', i === cOn)); });
+ calloutOn = cOn;
+ }
+ if (cOn >= 0) {
+ pickAnchors(cOn, flap);
+ for (const c of callouts[cOn]) {
+ flapJS(c.p, cOn === 3 ? flap : 0, tmp).applyMatrix4(flower.matrixWorld).project(camera);
+ const tx = (tmp.x * 0.5 + 0.5) * innerWidth, ty = (0.5 - tmp.y * 0.5) * innerHeight;
+ if (c.fresh) { c.sx = tx; c.sy = ty; c.fresh = false; }
+ c.sx = damp(c.sx, tx, 5, dt); c.sy = damp(c.sy, ty, 5, dt);
+ const x = c.sx, y = c.sy;
+ const ex = clamp(x + c.dx, 210, innerWidth - 210), ey = clamp(y + c.dy, 110, innerHeight - 110);
+ c.path.setAttribute('d', `M${x.toFixed(1)} ${y.toFixed(1)} L${lerp(x, ex, 0.4).toFixed(1)} ${ey.toFixed(1)} L${ex.toFixed(1)} ${ey.toFixed(1)}`);
+ c.dot.setAttribute('cx', x.toFixed(1)); c.dot.setAttribute('cy', y.toFixed(1));
+ c.el.style.transform = `translate3d(${(c.dx < 0 ? ex - 198 : ex + 8).toFixed(1)}px, ${(ey - 11).toFixed(1)}px, 0)`;
+ }
+ }
+
+ // hero figure caption hangs under the rose
+ const heroOn = scrollY < vh * 0.3 && started;
+ figEl.style.opacity = heroOn ? 1 - smooth(0, vh * 0.3, scrollY) : 0;
+ if (heroOn) {
+ tmp.set(0, -1.05, 0).applyMatrix4(flower.matrixWorld).project(camera);
+ figEl.style.transform = `translate3d(${((tmp.x * 0.5 + 0.5) * innerWidth + 64).toFixed(1)}px, ${((0.5 - tmp.y * 0.5) * innerHeight).toFixed(1)}px, 0)`;
+ }
+ heroEl.style.setProperty('--fade', 1 - smooth(0, vh * 0.6, scrollY));
+ navEl.classList.toggle('scrolled', scrollY > vh * 0.5);
+ if (hintReady) hintEl.classList.toggle('on', MOBILE ? scrollY < vh * 0.5 : scrollY < subY - vh * 0.6);
+});
+
+// ─── Boot ───────────────────────────────────────────────────────────────────
+worldNav('florae', { theme: 'light', corner: 'bl' });
+cursor({ color: '#a8284b', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? 0 : document.querySelector(id);
+ if (el === null) return;
+ e.preventDefault();
+ lenis.scrollTo(el, { duration: 2.2 });
+}));
+
+SHAPES = await buildShapes();
+SHAPES.push(SHAPES[0]); // the rose returns at the end: rose, protea, orchid, morpho, archive, rose
+callouts.forEach((list, i) => list.forEach(c => { c.p = anchorOf(SHAPES[i], SIZE, c.at ?? [0.5, (c.band[0] + c.band[1]) / 2, 0.5]); }));
+cands = SHAPES.slice(0, 4).map(sh => candidates(sh));
+layoutKeys();
+addEventListener('resize', layoutKeys);
+new ResizeObserver(layoutKeys).observe(document.body);
+sampleKeys(scrollY, target); Object.assign(cur, target);
+
+// Every particle starts packed in the rose's heart, a bud about to open.
+{
+ const [hx, hy, hz] = SHAPES[0].heart, d = pos0.image.data;
+ for (let i = 0; i < N; i++) {
+ const u = Math.random() * 2 - 1, a = Math.random() * Math.PI * 2, r = 0.16 * Math.cbrt(Math.random()), q = Math.sqrt(1 - u * u);
+ d[i * 4] = hx + Math.cos(a) * q * r; d[i * 4 + 1] = hy + u * r * 1.2; d[i * 4 + 2] = hz + Math.sin(a) * q * r;
+ }
+ pos0.needsUpdate = true;
+ gpu.renderTexture(pos0, posVar.renderTargets[0]);
+ gpu.renderTexture(pos0, posVar.renderTargets[1]);
+}
+// Warm every program before the reveal.
+U.tA.value = U.tB.value = SHAPES[0].pos; U.tNA.value = U.tNB.value = SHAPES[0].nrm; R.tCA.value = R.tCB.value = SHAPES[0].col;
+gpu.compute();
+R.tPos.value = gpu.getCurrentRenderTarget(posVar).texture;
+renderer.compile(scene, camera);
+engine.start();
+await loader.finish();
+started = true;
+
+// Intro: the rose assembles from its heart outward.
+gsap.to(bloom, { v: 1, duration: 3.6, ease: 'power1.inOut', delay: 0.25 });
+const titleSplit = SplitText.create('.hero-title', { type: 'chars', charsClass: 'char' });
+gsap.from(titleSplit.chars, { yPercent: 70, opacity: 0, rotate: 6, duration: 2.2, ease: 'expo.out', stagger: 0.07, delay: 0.25 });
+gsap.from('.hero-kicker, .hero-line, .hero-body, .hero-cta, .nav', { opacity: 0, y: 16, duration: 1.4, ease: 'power3.out', stagger: 0.09, delay: 0.7 });
+setTimeout(() => { hintReady = true; }, 1500);
+reveal('.atelier h2, .archive h2, .subscribe h2, .foot-title', { type: 'lines', stagger: 0.09 });
+reveal('.atelier-cols p, .lede', { type: 'lines', stagger: 0.05, y: '100%' });
+gsap.from('.months li', { opacity: 0, x: -18, duration: 1, ease: 'power3.out', stagger: 0.08, scrollTrigger: { trigger: '.months', start: 'top 80%', once: true } });
+gsap.from('.tier', { opacity: 0, y: 40, duration: 1.2, ease: 'power3.out', stagger: 0.12, scrollTrigger: { trigger: '.tiers', start: 'top 85%', once: true } });
+gsap.from('.stats > div', { opacity: 0, y: 20, duration: 1, ease: 'power3.out', stagger: 0.1, scrollTrigger: { trigger: '.stats', start: 'top 88%', once: true } });
+
+window.__florae = { gust, bloom, cur, SHAPES, R, SIMU, ready: true };
diff --git a/examples/florae/shaders.js b/examples/florae/shaders.js
new file mode 100644
index 0000000..32c919d
--- /dev/null
+++ b/examples/florae/shaders.js
@@ -0,0 +1,333 @@
+// GLSL for the petal simulation and its rendering.
+// HOME = where a particle wants to be: its place on specimen A → B, carried through a vortex while in transit,
+// wings flapping if the specimen is the morpho. The simulation springs particles toward HOME and lets
+// wind (curl flow), the cursor's breeze and gusts push them around it.
+
+export const COMMON = /* glsl */`
+ uniform sampler2D tA, tB, tNA, tNB;
+ uniform float uF, uFlapA, uFlapB, uBloom, uTime, uStagger;
+
+ vec3 hash32(vec2 p){
+ vec3 p3 = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973));
+ p3 += dot(p3, p3.yxz + 33.33);
+ return fract((p3.xxy + p3.yzz) * p3.zyx);
+ }
+ float hash12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+
+ // per-particle progress through the current morph: staggered by seed so the flower leaves in waves
+ float stageQ(float s){ return clamp((uF - s * uStagger) / (1.0 - uStagger), 0.0, 1.0); }
+
+ // morpho wings hinge about the body axis (y): 0 at the body, 1 at the tips (wingspan ±1.3)
+ float hingeOf(float x){ float ax = abs(x) / 1.3; return smoothstep(0.02, 0.14, ax) * (0.7 + 0.3 * ax); }
+ vec3 flapP(vec3 p, float ang){
+ if (ang <= 0.0) return p;
+ float a = ang * hingeOf(p.x);
+ float sd = p.x < 0.0 ? -1.0 : 1.0;
+ float ax = abs(p.x), c = cos(a), s = sin(a);
+ return vec3(sd * (ax * c - p.z * s), p.y - (ang - 0.45) * 0.07, ax * s + p.z * c);
+ }
+ vec3 flapN(vec3 n, float px, float ang){
+ if (ang <= 0.0) return n;
+ float a = ang * hingeOf(px); float sd = px < 0.0 ? -1.0 : 1.0; float nx = sd * n.x; float c = cos(a), s = sin(a);
+ return vec3(sd * (nx * c - n.z * s), n.y, nx * s + n.z * c);
+ }
+
+ // the wind between specimens: particles lift out of the old form into a whirl of petals — a thin,
+ // three-armed spiral turning about the specimen, tilted toward the viewer (uDisc) so its arms read in
+ // any still frame — then fall out of it into the new form. Rotation lives on the whirl target, weighted
+ // by w, so scrubbing the scroll back and forth never makes particles jump.
+ uniform mat3 uDisc;
+ vec3 vortex(vec3 m, float w, vec3 s){
+ if (w < 1e-4) return m;
+ float arm = floor(fract(s.y * 91.7 + s.z * 47.3) * 3.0);
+ float u = s.y;
+ float rad = 0.26 + 0.8 * u + (s.z - 0.5) * 0.1;
+ float ang = arm * 2.0944 + log(rad) * 3.0 + (s.z - 0.5) * (0.16 + 0.3 * u) + uTime * (0.75 - 0.35 * u) + w * 1.3;
+ float y = (fract(s.z * 13.7) - 0.5) * (0.05 + 0.12 * u) + 0.05 * sin(ang * 3.0 + uTime);
+ vec3 g = uDisc * vec3(cos(ang) * rad, y, sin(ang) * rad) + vec3(0.0, 0.12, 0.0);
+ return mix(m, g, smoothstep(0.0, 1.0, w));
+ }
+ vec3 sway(vec3 p){
+ float h = p.y + 1.25;
+ return vec3(sin(uTime * 0.77 + p.y * 1.3) * 0.009, sin(uTime * 1.3 + p.x * 3.0) * 0.003, cos(uTime * 0.61 + p.y * 1.1) * 0.007) * h;
+ }
+`;
+
+const CURL = /* glsl */`
+ // analytic curl of a trigonometric vector potential, three rotated octaves
+ vec3 curlTrig(vec3 p, vec3 ph){
+ float s1 = sin(1.1 * p.y + ph.x), c1 = cos(1.1 * p.y + ph.x);
+ float s2 = sin(0.9 * p.z + ph.y), c2 = cos(0.9 * p.z + ph.y);
+ float s3 = sin(1.4 * p.x + ph.z), c3 = cos(1.4 * p.x + ph.z);
+ float cbz = cos(1.3 * p.z), sbz = sin(1.3 * p.z);
+ float cdx = cos(1.2 * p.x), sdx = sin(1.2 * p.x);
+ float cfy = cos(0.8 * p.y), sfy = sin(0.8 * p.y);
+ return vec3(-0.8 * s3 * sfy - 0.9 * c2 * cdx, -1.3 * s1 * sbz - 1.4 * c3 * cfy, -1.2 * s2 * sdx - 1.1 * c1 * cbz);
+ }
+ const mat3 ROT = mat3(0.8, 0.6, 0.0, -0.48, 0.64, 0.6, 0.36, -0.48, 0.8);
+ vec3 curl(vec3 p, float t){
+ vec3 v = curlTrig(p, vec3(t * 0.31, t * 0.23, t * 0.27));
+ p = ROT * p * 2.03 + 1.7;
+ v += 0.55 * curlTrig(p, vec3(t * 0.41, t * 0.37, t * 0.29));
+ p = ROT * p * 2.01 + 3.1;
+ v += 0.3 * curlTrig(p, vec3(t * 0.53, t * 0.47, t * 0.43));
+ return v * 0.5;
+ }
+`;
+
+export const VELOCITY = /* glsl */`
+ ${COMMON}
+ ${CURL}
+ uniform float uDt, uStiff, uBreeze, uBreezeR, uCharge, uScrollV;
+ uniform vec3 uRayO, uRayD, uRayV, uGustD;
+ uniform vec4 uGust;
+ void main(){
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
+ vec3 P = texture2D(texturePosition, uv).xyz;
+ vec3 V = texture2D(textureVelocity, uv).xyz;
+ vec3 s = hash32(gl_FragCoord.xy);
+ float q = stageQ(s.x), e = q * q * (3.0 - 2.0 * q), w = sin(3.14159265 * q);
+ vec4 a = texture2D(tA, uv), b = texture2D(tB, uv);
+ vec3 H = vortex(mix(flapP(a.xyz, uFlapA), flapP(b.xyz, uFlapB), e), w, s);
+ H += sway(H) * (1.0 - w);
+ float ord = mix(texture2D(tNA, uv).a, texture2D(tNB, uv).a, e);
+ float att = smoothstep(ord * 0.7, ord * 0.7 + 0.3, uBloom);
+
+ float k = uStiff * mix(1.0, 0.4, w) * (0.03 + 0.97 * att * att);
+ vec3 acc = (H - P) * k;
+ acc -= V * (2.0 * sqrt(k) * 0.62 + (1.0 - att) * 1.1);
+
+ // wind: always a whisper, a gale in transit or after a gust
+ float windy = w * 0.5 + (1.0 - att) * 1.2 + 0.02 + uCharge * 0.25;
+ acc += curl(P * 0.75 + vec3(0.0, -uTime * 0.16, uTime * 0.07), uTime) * windy * 2.6;
+ acc.y += (1.0 - att) * 0.1;
+
+ // the cursor is a breeze: push away from the pointer ray, and along the way it moves
+ vec3 rp = P - uRayO;
+ vec3 d = rp - uRayD * dot(rp, uRayD);
+ float dl = length(d) + 1e-4;
+ float fall = exp(-dl * dl / (uBreezeR * uBreezeR));
+ acc += (d / dl * 24.0 + uRayV * 13.0 + curl(P * 2.0, uTime) * 8.0) * fall * uBreeze * (0.55 + 0.9 * s.z);
+
+ // a gust: radial blast from the click, carried away from the viewer and upward
+ vec3 g = P - uGust.xyz; float gl = length(g) + 1e-4;
+ vec3 gd = normalize(g / gl * 1.2 + uGustD * 0.7 + vec3(0.0, 0.12, 0.0) + (s - 0.5) * 1.1);
+ acc += gd * uGust.w * exp(-gl * 0.55) * (0.35 + 1.2 * s.y);
+
+ // holding: the flower draws in its breath and trembles
+ acc += vec3(-P.x, (0.25 - P.y) * 0.45, -P.z) * uCharge * 9.0 * (0.4 + s.z);
+ acc += (hash32(gl_FragCoord.xy + fract(uTime * 7.31) * 413.0) - 0.5) * uCharge * uCharge * 90.0;
+
+ // scrolling drags the petals a little
+ acc.y += uScrollV * (1.0 + w * 2.0 + (1.0 - att) * 2.0) * (0.6 + s.y) * 3.0;
+
+ V += acc * uDt;
+ float sp = length(V);
+ if (sp > 14.0) V *= 14.0 / sp;
+ gl_FragColor = vec4(V, 1.0);
+ }
+`;
+
+export const POSITION = /* glsl */`
+ uniform float uDt;
+ void main(){
+ vec2 uv = gl_FragCoord.xy / resolution.xy;
+ vec4 P = texture2D(texturePosition, uv);
+ P.xyz += texture2D(textureVelocity, uv).xyz * uDt;
+ gl_FragColor = P;
+ }
+`;
+
+// ─── Rendering ──────────────────────────────────────────────────────────────
+const PART_VERT = (glow) => /* glsl */`
+ ${COMMON}
+ attribute vec2 ref;
+ uniform sampler2D tPos, tCA, tCB;
+ uniform float uDot, uScale, uFocus, uAperture, uCoreCut, uCharge, uGlowFrac, uGlowA, uIrid, uPetal, uLift, uSize;
+ uniform vec3 uL, uKey, uAmb;
+ varying vec4 vCol;
+ varying vec4 vPet;
+ void main(){
+ vec3 P = texture2D(tPos, ref).xyz;
+ vec2 id = ref * uSize;
+ vec3 s = hash32(id);
+ float s4 = hash12(id + 17.0);
+ float q = stageQ(s.x), e = q * q * (3.0 - 2.0 * q), w = sin(3.14159265 * q);
+ vec4 a = texture2D(tA, ref), b = texture2D(tB, ref);
+ vec4 na = texture2D(tNA, ref), nb = texture2D(tNB, ref);
+ vec3 n = normalize(mix(flapN(na.xyz * 2.0 - 1.0, a.x, uFlapA), flapN(nb.xyz * 2.0 - 1.0, b.x, uFlapB), e) + 1e-4);
+ float ord = mix(na.a, nb.a, e);
+ float att = smoothstep(ord * 0.7, ord * 0.7 + 0.3, uBloom);
+ float windS = max(w, 1.0 - att);
+
+ vec4 ca = texture2D(tCA, ref), cb = texture2D(tCB, ref);
+ vec3 base = pow(mix(ca.rgb, cb.rgb, smoothstep(0.3, 0.7, q)), vec3(2.2));
+ float ao = mix(mix(ca.a, cb.a, e), 0.9, windS * 0.75);
+
+ vec4 mv = modelViewMatrix * vec4(P, 1.0);
+ vec3 nv = normalize(normalMatrix * n);
+ vec3 vd = normalize(-mv.xyz);
+ float fc = dot(nv, vd);
+ if (fc < 0.0) { nv = -nv; fc = -fc; }
+ float ndl = dot(nv, uL);
+ float wrap = clamp((ndl + 0.45) / 1.45, 0.0, 1.0);
+ float trans = clamp(-ndl, 0.0, 1.0);
+ float aoF = mix(0.2, 1.0, ao);
+ vec3 lit = base * (uAmb * aoF + uKey * (wrap * mix(0.45, 1.0, aoF) + trans * 0.45 * aoF));
+ lit += (base * 0.8 + 0.03) * pow(1.0 - fc, 3.0) * 0.22 * aoF;
+ // structural colour: morpho scales flash as the wing turns through the light
+ float blue = clamp((base.b - max(base.r, base.g)) * 5.0, 0.0, 1.0);
+ vec3 hv = normalize(uL + vd);
+ lit += vec3(0.25, 0.6, 1.0) * pow(max(dot(nv, hv), 0.0), 12.0) * blue * uIrid;
+ lit = lit * (1.0 + uLift) + base * uLift * 0.25;
+ lit *= 1.0 + uCharge * 0.4 * s.y;
+
+ float depth = -mv.z;
+ float dotPx = uDot * uScale / depth * (0.7 + 0.6 * s.z) * mix(a.w, b.w, e);
+ float coc = uAperture * abs(depth - uFocus) / (depth * uFocus) * uScale;
+ float cut = uCoreCut * (0.55 + 0.9 * s.y);
+ float petal = step(1.0 - uPetal, s4) * smoothstep(0.25, 0.7, windS);
+ gl_Position = projectionMatrix * mv;
+ ${glow ? `
+ bool defoc = coc > cut;
+ if (!defoc && s.z > uGlowFrac) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); gl_PointSize = 0.0; return; }
+ float g = dotPx * 2.3;
+ float size = sqrt(g * g + 4.0 * coc * coc);
+ gl_PointSize = size;
+ float alpha = defoc ? clamp(3.2 * dotPx * dotPx / (size * size), 0.03, 0.8) : uGlowA;
+ vCol = vec4(lit, alpha);
+ vPet = vec4(defoc ? 1.0 : 0.0, 0.0, 0.0, 0.0);
+ ` : `
+ if (coc > cut && petal < 0.01) { gl_Position = vec4(2.0, 2.0, 2.0, 1.0); gl_PointSize = 0.0; return; }
+ gl_PointSize = min(dotPx * (1.0 + petal * 3.4), max(dotPx, uScale * 0.012)) + coc * 0.3;
+ vCol = vec4(lit, 1.0);
+ vPet = vec4(petal, s.x * 6.2831 + uTime * (0.6 + s.y * 1.4) * petal, cos(uTime * (1.3 + s.z * 2.0) + s.y * 9.0), 0.0);
+ `}
+ }
+`;
+
+export const CORE_VERT = PART_VERT(false);
+export const GLOW_VERT = PART_VERT(true);
+
+export const CORE_FRAG = /* glsl */`
+ varying vec4 vCol;
+ varying vec4 vPet;
+ void main(){
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
+ float d = length(c);
+ float shade = 1.0;
+ if (vPet.x > 0.01) {
+ float ca = cos(vPet.y), sa = sin(vPet.y);
+ vec2 p = mat2(ca, -sa, sa, ca) * c;
+ p.x /= max(abs(vPet.z), 0.22);
+ float wdt = 0.5 + 0.34 * p.y;
+ float dp = length(vec2(p.x / max(wdt, 0.05), p.y * 1.02));
+ d = mix(d * (1.0 + 5.0 * vPet.x), dp, vPet.x);
+ shade = mix(1.0, 0.78 + 0.34 * (p.y * 0.5 + 0.5) - abs(p.x) * 0.2, vPet.x);
+ }
+ if (d > 1.0) discard;
+ gl_FragColor = vec4(vCol.rgb * shade, 1.0);
+ }
+`;
+
+export const GLOW_FRAG = /* glsl */`
+ varying vec4 vCol;
+ varying vec4 vPet;
+ void main(){
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
+ float d = dot(c, c);
+ if (d > 1.0) discard;
+ float a = vPet.x > 0.5 ? smoothstep(1.0, 0.7, d) * (0.78 + 0.3 * d) : exp(-d * 4.0) * (1.0 - d);
+ gl_FragColor = vec4(vCol.rgb, vCol.a * a);
+ }
+`;
+
+// Pollen and seed-fluff drifting through the plate: depth of field only, no simulation.
+export const MOTE_VERT = /* glsl */`
+ attribute vec4 seed;
+ uniform float uTime, uScale, uFocus, uAperture, uGustE;
+ uniform vec3 uGustC;
+ varying vec4 vCol;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.05 + seed.x * 0.08);
+ p += vec3(sin(t * 3.1 + seed.y * 40.0), sin(t * 2.3 + seed.z * 13.0) * 0.7 + t * 0.6, cos(t * 2.7 + seed.w * 27.0)) * 0.6;
+ p.y = mod(p.y + 6.0, 12.0) - 6.0;
+ vec3 gd = p - uGustC;
+ p += normalize(gd + 1e-3) * uGustE * (1.6 + seed.y * 2.0) * exp(-length(gd) * 0.25);
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ float depth = -mv.z;
+ gl_Position = projectionMatrix * mv;
+ float dotPx = (0.006 + seed.x * 0.012) * uScale / depth;
+ float coc = uAperture * 1.6 * abs(depth - uFocus) / (depth * uFocus) * uScale;
+ float size = sqrt(dotPx * dotPx + 4.0 * coc * coc);
+ gl_PointSize = clamp(size, 1.0, 90.0);
+ vec3 col = mix(vec3(1.0, 0.88, 0.66), vec3(1.0, 0.8, 0.74), seed.z);
+ col = mix(col, vec3(1.0, 0.97, 0.92), seed.w * 0.6);
+ vCol = vec4(col, clamp(2.4 * dotPx * dotPx / (size * size), 0.015, 0.6) * smoothstep(1.2, 4.0, depth) * (0.3 + 0.45 * seed.y));
+ }
+`;
+
+export const MOTE_FRAG = /* glsl */`
+ varying vec4 vCol;
+ void main(){
+ vec2 c = gl_PointCoord * 2.0 - 1.0;
+ float d = dot(c, c);
+ if (d > 1.0) discard;
+ gl_FragColor = vec4(vCol.rgb, vCol.a * smoothstep(1.0, 0.55, d));
+ }
+`;
+
+// The paper: warm stock, a pool of light behind the specimen, fibre grain, a toned edge.
+export const PAPER_VERT = /* glsl */`
+ varying vec2 vUv;
+ void main(){ vUv = position.xy * 0.5 + 0.5; gl_Position = vec4(position.xy, 0.9999, 1.0); }
+`;
+export const PAPER_FRAG = /* glsl */`
+ uniform vec3 uPaper, uEdge, uGlowC;
+ uniform vec2 uGlowP;
+ uniform float uAspect, uGlow;
+ uniform sampler2D tGrain, tShadow;
+ uniform float uShadow;
+ uniform vec2 uShadowOff, uTexel;
+ varying vec2 vUv;
+ // soft drop shadow: 16-tap golden-angle disc over the low-res silhouette
+ float shadowAt(vec2 p){
+ float s = 0.0;
+ for (int i = 0; i < 16; i++) {
+ float fi = float(i) + 0.5;
+ float r = sqrt(fi / 16.0) * 4.2;
+ float a = fi * 2.39996;
+ s += texture2D(tShadow, p + vec2(cos(a), sin(a)) * r * uTexel).a;
+ }
+ return s / 16.0;
+ }
+ // exact inverse of the Khronos PBR Neutral tone mapper, so the paper lands on the brand cream
+ vec3 invNeutral(vec3 o){
+ const float sc = 0.76, ds = 0.15, d = 0.24;
+ float np = min(max(o.r, max(o.g, o.b)), 0.995);
+ vec3 c = o;
+ if (np >= sc) {
+ float peak = d * d / (1.0 - np) - d + sc;
+ float g = 1.0 - 1.0 / (ds * (peak - np) + 1.0);
+ c = (o - g * np) / (1.0 - g) * (peak / np);
+ }
+ return c + 0.04;
+ }
+ void main(){
+ vec2 p = vUv;
+ vec2 q = (p - uGlowP) * vec2(uAspect, 1.0);
+ float g = exp(-dot(q, q) * 2.4);
+ vec2 e = (p - 0.5) * vec2(uAspect, 1.0);
+ vec3 c = mix(uPaper, uEdge, smoothstep(0.35, 1.25, length(e)));
+ c = mix(c, uGlowC, g * uGlow);
+ float fib = texture2D(tGrain, p * vec2(uAspect, 1.0) * 1.3).r;
+ float fib2 = texture2D(tGrain, p * vec2(uAspect, 1.0) * 5.1 + 0.37).g;
+ c *= 0.982 + fib * 0.026 + fib2 * 0.012;
+ if (uShadow > 0.0) {
+ float sh = shadowAt(p - uShadowOff);
+ c *= 1.0 - sh * 0.13 * uShadow * vec3(0.9, 1.0, 1.08);
+ }
+ gl_FragColor = vec4(invNeutral(c), 1.0);
+ }
+`;
diff --git a/examples/florae/shapes.js b/examples/florae/shapes.js
new file mode 100644
index 0000000..41bd393
--- /dev/null
+++ b/examples/florae/shapes.js
@@ -0,0 +1,208 @@
+// Specimen point clouds: surface samples of each Meshy model packed into GPU data textures.
+// Every shape shares the same particle count; texel j of every shape is "the same petal", so a morph
+// is one particle travelling from its place on one specimen to its place on the next.
+import * as THREE from 'three';
+import { MeshSurfaceSampler } from 'three/examples/jsm/math/MeshSurfaceSampler.js';
+
+/** Surface samples with sRGB texture colour (bytes) — a leaner variant of core sampleSurface. */
+export function sampleMesh(mesh, count) {
+ mesh.updateMatrixWorld(true);
+ const sampler = new MeshSurfaceSampler(mesh).build();
+ const pos = new Float32Array(count * 3), nor = new Float32Array(count * 3), col = new Uint8Array(count * 3);
+ const p = new THREE.Vector3(), n = new THREE.Vector3(), uv = new THREE.Vector2();
+ const nm = new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld);
+ const map = mesh.material?.map;
+ let px = null, tw = 0, th = 0;
+ if (map?.image) {
+ const img = map.image;
+ tw = Math.min(img.width, 2048); th = Math.min(img.height, 2048);
+ const cv = document.createElement('canvas'); cv.width = tw; cv.height = th;
+ const cx = cv.getContext('2d', { willReadFrequently: true });
+ cx.drawImage(img, 0, 0, tw, th);
+ px = cx.getImageData(0, 0, tw, th).data;
+ }
+ const e = mesh.matrixWorld.elements;
+ for (let i = 0; i < count; i++) {
+ sampler.sample(p, n, undefined, uv);
+ const x = p.x, y = p.y, z = p.z;
+ pos[i * 3] = e[0] * x + e[4] * y + e[8] * z + e[12];
+ pos[i * 3 + 1] = e[1] * x + e[5] * y + e[9] * z + e[13];
+ pos[i * 3 + 2] = e[2] * x + e[6] * y + e[10] * z + e[14];
+ n.applyMatrix3(nm).normalize();
+ nor[i * 3] = n.x; nor[i * 3 + 1] = n.y; nor[i * 3 + 2] = n.z;
+ if (px) {
+ const u = ((uv.x % 1) + 1) % 1, v = ((uv.y % 1) + 1) % 1;
+ const tx = Math.floor(u * (tw - 1)), ty = Math.floor((map.flipY ? 1 - v : v) * (th - 1));
+ const k = (ty * tw + tx) * 4;
+ col[i * 3] = px[k]; col[i * 3 + 1] = px[k + 1]; col[i * 3 + 2] = px[k + 2];
+ } else { col[i * 3] = col[i * 3 + 1] = col[i * 3 + 2] = 220; }
+ }
+ return { pos, nor, col, count };
+}
+
+/**
+ * Ambient occlusion from point density: voxelise the cloud, then march a few short rays through the
+ * hemisphere on each side of the (double-sided) surface. The heart of a rose is enclosed on both sides,
+ * an outer petal is open on one — so we keep the more open side.
+ */
+function densityAO(pos, nor, count) {
+ let mnx = Infinity, mny = Infinity, mnz = Infinity, mxx = -Infinity, mxy = -Infinity, mxz = -Infinity;
+ for (let i = 0; i < count; i++) {
+ const x = pos[i * 3], y = pos[i * 3 + 1], z = pos[i * 3 + 2];
+ if (x < mnx) mnx = x; if (x > mxx) mxx = x; if (y < mny) mny = y; if (y > mxy) mxy = y; if (z < mnz) mnz = z; if (z > mxz) mxz = z;
+ }
+ const ext = Math.max(mxx - mnx, mxy - mny, mxz - mnz);
+ const cell = ext / 70, pad = 10;
+ const gx = Math.ceil((mxx - mnx) / cell) + pad * 2, gy = Math.ceil((mxy - mny) / cell) + pad * 2, gz = Math.ceil((mxz - mnz) / cell) + pad * 2;
+ const ox = mnx - pad * cell, oy = mny - pad * cell, oz = mnz - pad * cell;
+ const grid = new Uint16Array(gx * gy * gz);
+ for (let i = 0; i < count; i++) {
+ const ix = ((pos[i * 3] - ox) / cell) | 0, iy = ((pos[i * 3 + 1] - oy) / cell) | 0, iz = ((pos[i * 3 + 2] - oz) / cell) | 0;
+ const k = (iz * gy + iy) * gx + ix;
+ if (grid[k] < 65535) grid[k]++;
+ }
+ let occ = 0, sum = 0;
+ for (let k = 0; k < grid.length; k++) if (grid[k]) { occ++; sum += grid[k]; }
+ const inv = 1 / Math.max(1, (sum / occ) * 0.45);
+ const steps = [2.2, 3.6, 5.6, 8.5], wts = [1, 0.85, 0.65, 0.45];
+ let wsum = 0; for (const w of wts) wsum += w;
+ const ao = new Float32Array(count), cov = new Float32Array(count);
+ // coverage: single-layer surfaces (leaves, wings) get bigger dots than the many-layered heart
+ const hist = new Uint32Array(256);
+ for (let k = 0; k < grid.length; k++) if (grid[k]) hist[Math.min(255, grid[k])]++;
+ let acc = 0, ref = 1;
+ for (let c = 1; c < 256; c++) { acc += hist[c]; if (acc >= occ * 0.8) { ref = c; break; } }
+ const D = [[0, 0, 1], [0.62, 0, 0.78], [-0.62, 0, 0.78], [0, 0.62, 0.78], [0, -0.62, 0.78], [0.44, 0.44, 0.78], [-0.44, -0.44, 0.78]];
+ const look = (x, y, z) => {
+ const ix = ((x - ox) / cell) | 0, iy = ((y - oy) / cell) | 0, iz = ((z - oz) / cell) | 0;
+ if (ix < 0 || iy < 0 || iz < 0 || ix >= gx || iy >= gy || iz >= gz) return 0;
+ return Math.min(1, grid[(iz * gy + iy) * gx + ix] * inv);
+ };
+ for (let i = 0; i < count; i++) {
+ const px = pos[i * 3], py = pos[i * 3 + 1], pz = pos[i * 3 + 2];
+ const nx = nor[i * 3], ny = nor[i * 3 + 1], nz = nor[i * 3 + 2];
+ // tangent frame
+ let tx, ty, tz;
+ if (Math.abs(ny) < 0.9) { tx = nz; ty = 0; tz = -nx; } else { tx = 0; ty = -nz; tz = ny; }
+ const tl = Math.hypot(tx, ty, tz) || 1; tx /= tl; ty /= tl; tz /= tl;
+ const bx = ny * tz - nz * ty, by = nz * tx - nx * tz, bz = nx * ty - ny * tx;
+ let best = 1;
+ for (let side = 1; side >= -1; side -= 2) {
+ let o = 0;
+ for (const d of D) {
+ const dx = (tx * d[0] + bx * d[1] + nx * d[2] * side), dy = (ty * d[0] + by * d[1] + ny * d[2] * side), dz = (tz * d[0] + bz * d[1] + nz * d[2] * side);
+ for (let s = 0; s < steps.length; s++) {
+ const r = steps[s] * cell;
+ o += look(px + dx * r, py + dy * r, pz + dz * r) * wts[s];
+ }
+ }
+ o /= D.length * wsum;
+ if (o < best) best = o;
+ }
+ ao[i] = 1 - Math.min(1, best * 1.9);
+ const ix = ((px - ox) / cell) | 0, iy = ((py - oy) / cell) | 0, iz = ((pz - oz) / cell) | 0;
+ cov[i] = Math.min(2.6, Math.max(0.85, Math.sqrt(ref / Math.max(1, grid[(iz * gy + iy) * gx + ix]))));
+ }
+ return { ao, cov };
+}
+
+/**
+ * Pack a sampled cloud into textures. Particles are ranked by height so texel j sits at the same
+ * relative height in every specimen (stems become stems) — the swirl does the rest.
+ * pos (float): xyz, w = dot coverage factor (sparse surfaces draw bigger dots)
+ * col (rgba8): sRGB colour, a = ambient occlusion
+ * nrm (rgba8): normal, a = bloom order (0 = heart of the flower, 1 = farthest tip)
+ */
+export function packShape(s, size, { heart = 'top', rand = Math.random } = {}) {
+ const N = size * size, { pos, nor, col } = s;
+ const { ao, cov } = s.ao ? { ao: s.ao, cov: null } : densityAO(pos, nor, N);
+ // heart of the specimen, where re-blooming starts
+ const idx = new Uint32Array(N);
+ for (let i = 0; i < N; i++) idx[i] = i;
+ const key = new Float32Array(N);
+ for (let i = 0; i < N; i++) key[i] = pos[i * 3 + 1] + rand() * 1e-4;
+ idx.sort((a, b) => key[a] - key[b]);
+ let hx = 0, hy = 0, hz = 0;
+ if (heart === 'center') { hx = hy = hz = 0; }
+ else {
+ const from = heart === 'top' ? Math.floor(N * 0.82) : 0, to = heart === 'top' ? N : Math.floor(N * 0.04);
+ for (let j = from; j < to; j++) { const i = idx[j]; hx += pos[i * 3]; hy += pos[i * 3 + 1]; hz += pos[i * 3 + 2]; }
+ const c = to - from; hx /= c; hy /= c; hz /= c;
+ if (heart === 'top') hy = Math.max(hy - 0.1, -1e9);
+ }
+ if (s.heart) [hx, hy, hz] = s.heart;
+ let maxD = 0;
+ const dist = new Float32Array(N);
+ for (let i = 0; i < N; i++) { const d = Math.hypot(pos[i * 3] - hx, pos[i * 3 + 1] - hy, pos[i * 3 + 2] - hz); dist[i] = d; if (d > maxD) maxD = d; }
+ const P = new Float32Array(N * 4), C = new Uint8Array(N * 4), Q = new Uint8Array(N * 4);
+ for (let j = 0; j < N; j++) {
+ const i = idx[j];
+ P[j * 4] = pos[i * 3]; P[j * 4 + 1] = pos[i * 3 + 1]; P[j * 4 + 2] = pos[i * 3 + 2];
+ P[j * 4 + 3] = cov ? cov[i] : 1;
+ C[j * 4] = col[i * 3]; C[j * 4 + 1] = col[i * 3 + 1]; C[j * 4 + 2] = col[i * 3 + 2];
+ C[j * 4 + 3] = Math.round(Math.max(0, Math.min(1, ao[i])) * 255);
+ Q[j * 4] = Math.round(nor[i * 3] * 127.5 + 127.5); Q[j * 4 + 1] = Math.round(nor[i * 3 + 1] * 127.5 + 127.5); Q[j * 4 + 2] = Math.round(nor[i * 3 + 2] * 127.5 + 127.5);
+ Q[j * 4 + 3] = Math.round(Math.pow(dist[i] / maxD, 0.85) * 255);
+ }
+ const tex = (data, type) => {
+ const t = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, type);
+ t.minFilter = t.magFilter = THREE.NearestFilter; t.generateMipmaps = false; t.needsUpdate = true;
+ return t;
+ };
+ return { pos: tex(P, THREE.FloatType), col: tex(C, THREE.UnsignedByteType), nrm: tex(Q, THREE.UnsignedByteType), P, C, Q, heart: [hx, hy, hz] };
+}
+
+/**
+ * The archive: a sunflower head. Florets at the golden angle, oldest (outermost) rings coloured by the
+ * specimens already sent, the centre still in bud — the months to come.
+ */
+export function spiralShape(size, sources, { R = 1.95, per = 40 } = {}) {
+ const N = size * size, NF = Math.floor(N / per);
+ const pos = new Float32Array(N * 3), nor = new Float32Array(N * 3), col = new Uint8Array(N * 3), ao = new Float32Array(N);
+ const GA = Math.PI * (3 - Math.sqrt(5));
+ const bud = [[196, 160, 72], [150, 150, 64], [120, 132, 58], [214, 186, 110]];
+ const spacing = R * Math.sqrt(Math.PI / NF);
+ // one colour per floret: rings of past specimens, oldest (rose) at the rim, buds at the centre
+ const fc = new Uint8Array(NF * 3);
+ for (let i = 0; i < NF; i++) {
+ const rr = Math.sqrt((i + 0.5) / NF) + (Math.random() - 0.5) * 0.1;
+ let c;
+ if (rr < 0.2) c = bud[(Math.random() * 4) | 0];
+ else {
+ const src = sources[3 - Math.min(3, Math.floor((rr - 0.2) / 0.2))];
+ const k = (Math.random() * src.count) | 0;
+ c = [src.col[k * 3], src.col[k * 3 + 1], src.col[k * 3 + 2]];
+ }
+ const arm = (i % 34) < 17 ? 1 : 0.86;
+ fc[i * 3] = c[0] * arm; fc[i * 3 + 1] = c[1] * arm; fc[i * 3 + 2] = c[2] * arm;
+ }
+ for (let j = 0; j < N; j++) {
+ const i = Math.min(NF - 1, Math.floor(j / per)), f = (i + 0.5) / NF;
+ const r = R * Math.sqrt(f), a = i * GA;
+ // each floret is a small domed seed of `per` particles
+ const sr = spacing * 0.36 * (0.75 + 0.5 * f) * Math.sqrt(Math.random()), sa = Math.random() * Math.PI * 2;
+ const x = Math.cos(a) * r + Math.cos(sa) * sr, z = Math.sin(a) * r + Math.sin(sa) * sr;
+ const rn = Math.hypot(x, z) / R;
+ pos[j * 3] = x; pos[j * 3 + 2] = z;
+ pos[j * 3 + 1] = -0.2 * rn * rn + 0.012 * (1 - (sr / (spacing * 0.5)) ** 2);
+ const nx = 0.4 * x / R, nz = 0.4 * z / R, nl = Math.hypot(nx, 1, nz);
+ nor[j * 3] = nx / nl; nor[j * 3 + 1] = 1 / nl; nor[j * 3 + 2] = nz / nl;
+ col[j * 3] = fc[i * 3]; col[j * 3 + 1] = fc[i * 3 + 1]; col[j * 3 + 2] = fc[i * 3 + 2];
+ ao[j] = (0.6 + 0.4 * Math.min(1, f * 3)) * (1 - 0.35 * sr / (spacing * 0.5));
+ }
+ return { pos, nor, col, ao, count: N, heart: [0, 0, 0] };
+}
+
+/** Screen-space anchor on a shape: the particle nearest a point given in the shape's bbox (0..1). */
+export function anchorOf(packed, size, [u, v, w]) {
+ const N = size * size, P = packed.P;
+ let mn = [Infinity, Infinity, Infinity], mx = [-Infinity, -Infinity, -Infinity];
+ for (let j = 0; j < N; j += 7) for (let k = 0; k < 3; k++) { mn[k] = Math.min(mn[k], P[j * 4 + k]); mx[k] = Math.max(mx[k], P[j * 4 + k]); }
+ const t = [mn[0] + (mx[0] - mn[0]) * u, mn[1] + (mx[1] - mn[1]) * v, mn[2] + (mx[2] - mn[2]) * w];
+ let best = 0, bd = Infinity;
+ for (let j = 0; j < N; j += 3) {
+ const d = (P[j * 4] - t[0]) ** 2 + (P[j * 4 + 1] - t[1]) ** 2 + (P[j * 4 + 2] - t[2]) ** 2;
+ if (d < bd) { bd = d; best = j; }
+ }
+ return new THREE.Vector3(P[best * 4], P[best * 4 + 1], P[best * 4 + 2]);
+}
diff --git a/examples/florae/style.css b/examples/florae/style.css
new file mode 100644
index 0000000..1cf54ef
--- /dev/null
+++ b/examples/florae/style.css
@@ -0,0 +1,270 @@
+:root {
+ --paper: #f4efe6;
+ --ink: #1f1a17;
+ --ink-2: #5f554c;
+ --ink-3: #8c8177;
+ --hair: rgba(31, 26, 23, .16);
+ --crimson: #d6456b;
+ --crimson-deep: #a8284b;
+ --display: 'Cormorant', 'Cormorant Garamond', Georgia, serif;
+ --serif: 'EB Garamond', Georgia, serif;
+ --sans: 'Inter Tight', system-ui, sans-serif;
+ --gut: clamp(20px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--paper); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 17px/1.55 var(--serif); background: var(--paper); overflow-x: hidden; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
+a { color: inherit; }
+em { font-style: italic; }
+.caps { font-family: var(--sans); font-size: 10.5px; font-weight: 500; letter-spacing: .17em; text-transform: uppercase; line-height: 1.4; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+
+/* ── loader ─────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--paper); display: grid; place-content: center; justify-items: center; gap: 18px; }
+.loader-seed { width: 200px; height: 200px; }
+.loader-line { font: 400 23px/1 var(--display); color: var(--ink); letter-spacing: .01em; display: flex; gap: 12px; align-items: baseline; }
+.loader-pct { font: 500 11px/1 var(--sans); letter-spacing: .14em; color: var(--crimson); font-variant-numeric: tabular-nums; min-width: 2.4em; }
+.loader-sub { color: var(--ink-3); }
+
+/* ── nav ────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 20px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: inline-flex; align-items: center; gap: 10px; text-decoration: none; justify-self: start; color: var(--ink); }
+.brand svg { width: 26px; height: 26px; color: var(--crimson); transition: transform 1.4s cubic-bezier(.2,.8,.2,1); }
+.brand:hover svg { transform: rotate(144deg); }
+.brand span { font: 400 italic 27px/1 var(--display); letter-spacing: -.01em; }
+.links { display: flex; gap: 36px; }
+.links a { text-decoration: none; font: 500 11px/1 var(--sans); letter-spacing: .17em; text-transform: uppercase; color: var(--ink-2); position: relative; padding: 6px 0; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: var(--crimson); transform: scaleX(0); transform-origin: right; transition: transform .5s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after { transform: scaleX(1); transform-origin: left; }
+.nav .btn { justify-self: end; }
+.brand, .links { transition: background .5s, box-shadow .5s, padding .5s; border-radius: 999px; }
+.nav.scrolled .brand { background: rgba(244,239,230,.72); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--hair); padding: 8px 16px 8px 10px; margin-left: -10px; }
+.nav.scrolled .links { background: rgba(244,239,230,.72); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--hair); padding: 8px 26px; }
+
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 8px; height: 44px; padding: 0 22px; border-radius: 999px; text-decoration: none; white-space: nowrap;
+ font: 500 12px/1 var(--sans); letter-spacing: .06em; transition: background .4s, color .4s, box-shadow .4s; }
+.btn small { font-size: 10px; opacity: .7; margin-left: 1px; }
+.btn-sep { opacity: .45; }
+.btn-line { color: var(--ink); box-shadow: inset 0 0 0 1px rgba(31,26,23,.32); background: rgba(244,239,230,.55); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }
+.btn-line:hover { box-shadow: inset 0 0 0 1px var(--crimson); color: var(--crimson-deep); }
+.btn-solid { background: var(--crimson); color: #fff8f4; box-shadow: 0 10px 30px -12px rgba(214,69,107,.7); }
+.btn-solid:hover { background: var(--crimson-deep); box-shadow: 0 16px 40px -14px rgba(168,40,75,.8); }
+.btn-big { height: 56px; padding: 0 32px; font-size: 13px; }
+.link { font: 500 11px/1 var(--sans); letter-spacing: .17em; text-transform: uppercase; text-decoration: none; color: var(--ink-2); display: inline-flex; gap: 8px; }
+.link:hover { color: var(--crimson-deep); }
+
+/* ── content base ───────────────────────────────────── */
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, .tier { pointer-events: auto; }
+.eyebrow { color: var(--crimson-deep); margin-bottom: 26px; }
+h2 { font: 300 clamp(44px, 5.6vw, 92px)/.98 var(--display); letter-spacing: -.02em; color: var(--ink); }
+h2 em { font-style: italic; color: var(--crimson-deep); font-weight: 400; }
+
+/* ── hero ───────────────────────────────────────────── */
+.hero { position: relative; height: 100vh; min-height: 640px; padding: 0 var(--gut); display: grid; align-content: center; }
+.hero-kicker { display: flex; gap: 22px; color: var(--ink-2); margin-bottom: 8px; padding-left: .5vw; }
+.hero-kicker span + span::before { content: ''; display: inline-block; width: 18px; height: 1px; background: var(--hair); vertical-align: middle; margin-right: 22px; }
+.hero-title { font: 300 italic clamp(112px, 19vw, 330px)/.78 var(--display); letter-spacing: -.045em; color: var(--crimson); margin-left: -.06em; padding-bottom: .06em; }
+.hero-title .char { display: inline-block; }
+.hero-line { font: 400 clamp(26px, 2.6vw, 42px)/1.08 var(--display); color: var(--ink); margin-top: 18px; max-width: 14em; }
+.hero-body { max-width: 25em; margin-top: 22px; font-size: clamp(16px, 1.15vw, 18px); color: var(--ink-2); }
+.hero-cta { display: flex; align-items: center; gap: 30px; margin-top: 34px; }
+
+.fig { position: fixed; left: 0; top: 0; z-index: 3; color: var(--ink-3); white-space: nowrap; pointer-events: none; transform: translate3d(-9999px,0,0); transition: opacity .6s; }
+.fig em { font: italic 13px/1 var(--serif); letter-spacing: 0; text-transform: none; color: var(--ink-2); }
+
+/* ── atelier ────────────────────────────────────────── */
+.atelier { min-height: 125vh; padding: 22vh var(--gut) 16vh; display: grid; align-items: center; }
+.atelier-inner { margin-left: auto; width: min(640px, 46vw); margin-right: 3vw; }
+.atelier h2 { font-size: clamp(40px, 4.4vw, 74px); }
+.atelier-cols { display: grid; grid-template-columns: 1fr 1fr; gap: 28px; margin-top: 38px; color: var(--ink-2); font-size: 16.5px; }
+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-top: 56px; padding-top: 26px; border-top: 1px solid var(--hair); }
+.stats dt { font: 300 clamp(48px, 4.6vw, 76px)/1 var(--display); color: var(--crimson); letter-spacing: -.02em; }
+.stats dt small { font-size: .45em; margin-left: 2px; }
+.stats dd { color: var(--ink-2); margin-top: 10px; max-width: 13em; }
+
+/* ── specimen plates ────────────────────────────────── */
+.spec { position: relative; height: 260vh; }
+.spec .anchor { position: absolute; top: 60vh; }
+.pin { position: sticky; top: 0; height: 100vh; display: grid; align-items: center; padding: 0 var(--gut); }
+.plate { width: min(470px, 35vw); position: relative; }
+.plate-left { margin-left: 4vw; }
+.plate-right { margin-left: auto; margin-right: 3vw; }
+.plate > * { opacity: 0; transform: translate3d(0, 18px, 0); transition: opacity .9s cubic-bezier(.2,.8,.2,1), transform 1.1s cubic-bezier(.2,.8,.2,1); }
+.plate.on > * { opacity: 1; transform: none; }
+.plate.on > :nth-child(2) { transition-delay: .08s; } .plate.on > :nth-child(3) { transition-delay: .16s; }
+.plate.on > :nth-child(4) { transition-delay: .24s; } .plate.on > :nth-child(5) { transition-delay: .32s; }
+.plate-top { display: grid; grid-template-columns: auto 1fr auto; gap: 14px; align-items: center; color: var(--ink-2); padding-bottom: 14px; border-bottom: 1px solid var(--hair); margin-bottom: 30px; }
+.plate-top span:first-child { color: var(--crimson-deep); }
+.plate-status { justify-self: center; color: var(--ink-3); position: relative; padding-left: 14px; font-variant-numeric: tabular-nums; }
+.plate-status::before { content: ''; position: absolute; left: 0; top: 50%; width: 6px; height: 6px; margin-top: -3px; border-radius: 50%; background: var(--crimson); opacity: .35; }
+.plate.forming .plate-status::before { opacity: 1; animation: pulse 1s ease-in-out infinite; }
+@keyframes pulse { 50% { transform: scale(.5); } }
+.latin { font: 400 clamp(42px, 4.3vw, 72px)/.98 var(--display); letter-spacing: -.02em; }
+.latin em { color: var(--ink); font-weight: 400; }
+.common { font: italic 400 clamp(19px, 1.5vw, 23px)/1.2 var(--serif); color: var(--crimson-deep); margin-top: 12px; }
+.facts { display: grid; grid-template-columns: 1fr 1fr; gap: 20px 26px; margin-top: 30px; padding: 22px 0; border-top: 1px solid var(--hair); border-bottom: 1px solid var(--hair); }
+.facts dt { color: var(--ink-3); margin-bottom: 6px; font-size: 9.5px; }
+.facts dd { font-size: 16px; line-height: 1.3; color: var(--ink); }
+.facts dd span { display: block; font-style: italic; color: var(--ink-2); font-size: 14px; margin-top: 3px; }
+.notes { margin-top: 22px; color: var(--ink-2); font-size: 16.5px; line-height: 1.55; }
+
+/* callouts: botanical plate leader lines projected from the specimen */
+.leaders { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 3; pointer-events: none; overflow: visible; }
+.leaders path { fill: none; stroke: rgba(31,26,23,.5); stroke-width: .8; }
+.leaders circle { fill: var(--paper); stroke: var(--crimson-deep); stroke-width: 1.1; }
+.leaders g { opacity: 0; transition: opacity .7s; }
+.leaders g.on { opacity: 1; }
+.callouts { position: fixed; inset: 0; z-index: 3; pointer-events: none; }
+.callout { position: absolute; left: 0; top: 0; width: 220px; opacity: 0; transition: opacity .7s; }
+.callout.on { opacity: 1; }
+.callout.left { text-align: right; }
+.callout b { font: italic 400 14px/1 var(--serif); color: var(--crimson-deep); margin-right: 6px; }
+.callout span { font: italic 400 16px/1.1 var(--serif); color: var(--ink); }
+.callout small { display: block; margin-top: 4px; font: 500 9.5px/1.35 var(--sans); letter-spacing: .15em; text-transform: uppercase; color: var(--ink-3); }
+
+/* plate rail */
+.rail { position: fixed; right: var(--gut); bottom: 26px; z-index: 12; display: flex; gap: 18px; align-items: center;
+ opacity: 0; transition: opacity .6s; pointer-events: none; }
+.rail.on { opacity: 1; pointer-events: auto; }
+.rail a { display: flex; align-items: center; gap: 8px; text-decoration: none; color: var(--ink-3); }
+.rail b { font: italic 400 16px/1 var(--display); }
+.rail span { font: 500 9.5px/1 var(--sans); letter-spacing: .17em; text-transform: uppercase; max-width: 0; overflow: hidden; opacity: 0; transition: max-width .6s, opacity .4s; white-space: nowrap; }
+.rail a::before { content: ''; width: 5px; height: 5px; border-radius: 50%; box-shadow: inset 0 0 0 1px currentColor; transition: background .4s; }
+.rail a.on { color: var(--crimson-deep); }
+.rail a.on::before { background: currentColor; }
+.rail a.on span, .rail a:hover span { max-width: 120px; opacity: 1; }
+
+/* ── archive ────────────────────────────────────────── */
+.archive { padding: 30vh var(--gut) 22vh; min-height: 190vh; }
+.archive-inner { width: min(620px, 46vw); margin-left: 3vw; }
+.archive h2 { font-size: clamp(44px, 5vw, 84px); }
+.lede { margin-top: 26px; font-size: clamp(17px, 1.25vw, 20px); color: var(--ink-2); max-width: 30em; }
+.months { list-style: none; margin-top: 64px; border-top: 1px solid var(--hair); }
+.months li { display: grid; grid-template-columns: 78px 1fr auto; grid-template-areas: 'mo la st' 'mo or st'; gap: 2px 18px; align-items: baseline;
+ padding: 18px 0 17px; border-bottom: 1px solid var(--hair); background: linear-gradient(90deg, rgba(244,239,230,.72), rgba(244,239,230,.35)); pointer-events: auto; transition: background .5s; }
+.months li:hover { background: linear-gradient(90deg, rgba(244,239,230,.95), rgba(244,239,230,.55)); }
+.months .mo { grid-area: mo; color: var(--crimson-deep); padding-top: 4px; }
+.months .la { grid-area: la; font: 400 21px/1.15 var(--display); }
+.months .la em { font-size: 23px; }
+.months .la small { font: italic 400 14px/1 var(--serif); color: var(--ink-2); margin-left: 10px; }
+.months .or { grid-area: or; color: var(--ink-3); font-size: 9.5px; }
+.months .st { grid-area: st; color: var(--ink-2); display: inline-flex; align-items: center; gap: 8px; align-self: center; }
+.months .st i { width: 7px; height: 7px; border-radius: 50%; background: #9bab5c; box-shadow: 0 0 0 3px rgba(155,171,92,.18); }
+.months li:nth-child(n+3) .st i { background: #c8b16a; box-shadow: 0 0 0 3px rgba(200,177,106,.18); }
+.months li:nth-child(n+5) .st i { background: transparent; box-shadow: inset 0 0 0 1px var(--ink-3); }
+.archive-foot { margin-top: 26px; color: var(--ink-3); }
+
+/* ── membership ─────────────────────────────────────── */
+.subscribe { padding: 40vh var(--gut) 18vh; }
+.subscribe-inner { width: min(800px, 58vw); margin-left: 3vw; }
+.subscribe .eyebrow { margin-bottom: 20px; }
+.subscribe h2 { max-width: 9em; }
+.tiers { display: grid; gap: 14px; margin-top: 52px; }
+.tier { display: grid; grid-template-columns: 180px 1fr auto; grid-template-areas: 'no ul btn' 'h3 ul btn' 'pr ul btn'; gap: 6px 32px; align-items: center;
+ padding: 24px 28px; border-radius: 3px;
+ background: rgba(247,243,236,.68); backdrop-filter: blur(16px) saturate(1.1); -webkit-backdrop-filter: blur(16px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px var(--hair), 0 30px 60px -44px rgba(80,40,30,.35); transition: transform .6s cubic-bezier(.2,.8,.2,1), box-shadow .6s; }
+.tier:hover { transform: translateX(6px); box-shadow: inset 0 0 0 1px rgba(214,69,107,.4), 0 40px 70px -44px rgba(120,40,60,.45); }
+.tier-feature { background: rgba(250,245,240,.86); box-shadow: inset 0 0 0 1px rgba(214,69,107,.5), 0 40px 80px -44px rgba(168,40,75,.5); }
+.tier-no { grid-area: no; color: var(--crimson-deep); align-self: end; }
+.tier h3 { grid-area: h3; font: 400 italic 32px/1 var(--display); letter-spacing: -.01em; }
+.price { grid-area: pr; font: 300 44px/1 var(--display); color: var(--ink); letter-spacing: -.02em; align-self: start; margin-top: 4px; }
+.price span { font: 500 10px/1 var(--sans); letter-spacing: .17em; text-transform: uppercase; color: var(--ink-3); margin-left: 6px; }
+.tier ul { grid-area: ul; list-style: none; display: grid; gap: 7px; color: var(--ink-2); font-size: 15.5px; line-height: 1.35; padding-left: 28px; border-left: 1px solid var(--hair); }
+.tier li { padding-left: 18px; position: relative; }
+.tier li::before { content: ''; position: absolute; left: 1px; top: .55em; width: 6px; height: 6px; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--crimson); }
+.tier .btn { grid-area: btn; }
+.fine { margin-top: 30px; color: var(--ink-3); }
+
+/* ── footer ─────────────────────────────────────────── */
+.foot { min-height: 100vh; padding: 24vh var(--gut) 40px; display: grid; }
+.foot-inner { display: grid; align-content: space-between; min-height: calc(76vh - 40px); }
+.foot-title { font-size: clamp(56px, 7vw, 124px); line-height: .92; max-width: 7.4em; }
+.foot-title em { display: block; }
+.foot .btn-big { justify-self: start; margin-top: 38px; }
+.foot-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 30px; margin-top: 14vh; width: 58%; padding-top: 28px; border-top: 1px solid var(--hair); }
+.foot-grid h4 { color: var(--crimson-deep); margin-bottom: 10px; font-weight: 500; }
+.foot-grid p { color: var(--ink-2); font-size: 15.5px; line-height: 1.5; }
+.foot-grid a { pointer-events: auto; text-decoration-color: rgba(214,69,107,.5); text-underline-offset: 3px; }
+.colophon { display: flex; justify-content: flex-start; gap: 36px; margin-top: 44px; color: var(--ink-3); padding-left: 150px; }
+
+/* ── interaction chrome ─────────────────────────────── */
+.hint { position: fixed; left: 50%; bottom: 22px; transform: translate(-50%, 16px); z-index: 20; display: flex; gap: 4px; padding: 5px; border-radius: 999px;
+ background: rgba(244,239,230,.7); backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--hair);
+ opacity: 0; transition: opacity .8s, transform .8s cubic-bezier(.2,.8,.2,1); pointer-events: none; }
+.hint.on { opacity: 1; transform: translate(-50%, 0); }
+.hint span { display: inline-flex; align-items: center; gap: 8px; padding: 8px 14px 8px 8px; border-radius: 999px; font: italic 400 15px/1 var(--serif); color: var(--ink-2); transition: background .5s, color .5s; }
+.hint i { font: 500 9.5px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; font-style: normal; color: var(--crimson-deep); padding: 6px 8px; border-radius: 999px; box-shadow: inset 0 0 0 1px rgba(214,69,107,.35); }
+.hint span.lit { background: rgba(214,69,107,.1); color: var(--ink); }
+.charge { position: fixed; left: 0; top: 0; width: 80px; height: 80px; margin: -40px 0 0 -40px; filter: drop-shadow(0 0 1px rgba(31,26,23,.55)) drop-shadow(0 2px 8px rgba(31,26,23,.25)); z-index: 9998; pointer-events: none; opacity: 0; transition: opacity .25s; }
+.charge.on { opacity: 1; }
+.charge svg { width: 100%; height: 100%; transform: rotate(-90deg); overflow: visible; }
+.charge circle { fill: none; stroke-width: 1.6; }
+.charge-bg { stroke: rgba(255,250,244,.35); }
+.charge-fg { stroke: #fffaf4; stroke-dasharray: 163.4; stroke-dashoffset: 163.4; stroke-linecap: round; }
+.charge span { position: absolute; left: 50%; top: 100%; transform: translate(-50%, 6px); font: 500 9px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: #fffaf4; }
+
+/* ── mobile ─────────────────────────────────────────── */
+@media (max-width: 760px) {
+ body { font-size: 16px; }
+ .nav { grid-template-columns: 1fr auto; padding: 14px 16px; }
+ .links { display: none; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 11px; }
+ .brand span { font-size: 24px; }
+ .hero { align-content: end; padding: 0 16px 15vh; min-height: 0; height: 100svh; }
+ .hero-kicker { gap: 12px; font-size: 9px; flex-wrap: wrap; margin-bottom: 4px; }
+ .hero-kicker span + span::before { width: 10px; margin-right: 12px; }
+ .hero-kicker span:last-child { display: none; }
+ .hero-title { font-size: 31vw; }
+ .hero-line { font-size: 27px; margin-top: 10px; }
+ .hero-body { display: none; }
+ .hero-cta { gap: 18px; margin-top: 22px; flex-wrap: wrap; }
+ .fig { display: none; }
+ .atelier { padding: 60vh 16px 10vh; min-height: 0; }
+ .atelier-inner { width: 100%; margin: 0; padding: 24px 0 0; background: linear-gradient(180deg, rgba(244,239,230,0), rgba(244,239,230,.9) 12%, rgba(244,239,230,.9)); }
+ .atelier-cols { grid-template-columns: 1fr; gap: 14px; }
+ .stats { grid-template-columns: 1fr 1fr 1fr; gap: 12px; }
+ .stats dt { font-size: 40px; }
+ .stats dd { font-size: 8.5px; }
+ .spec { height: 230vh; }
+ .pin { align-items: end; padding: 0 16px 84px; }
+ .plate, .plate-left, .plate-right { width: 100%; margin: 0; padding: 18px 16px 16px; background: rgba(244,239,230,.84); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); border-radius: 3px; box-shadow: inset 0 0 0 1px var(--hair); }
+ .plate-top { margin-bottom: 14px; padding-bottom: 10px; font-size: 9px; }
+ .latin { font-size: 36px; }
+ .common { font-size: 18px; margin-top: 6px; }
+ .facts { gap: 12px 14px; margin-top: 14px; padding: 14px 0 0; border-bottom: 0; }
+ .facts dd { font-size: 14px; }
+ .facts dd span { font-size: 12.5px; }
+ .facts > div:nth-child(n+3) { display: none; }
+ .notes { display: none; }
+ .callouts, .leaders, .rail { display: none; }
+ .archive { padding: 70vh 16px 12vh; }
+ .archive-head { padding-top: 22px; background: linear-gradient(180deg, rgba(242,235,223,0), rgba(242,235,223,.92) 18%, rgba(242,235,223,.92)); }
+ .archive-inner { width: 100%; margin: 0; }
+ .months li { grid-template-columns: 62px 1fr; grid-template-areas: 'mo la' 'mo or' 'mo st'; }
+ .months .st { align-self: start; margin-top: 6px; }
+ .months .la small { display: block; margin: 4px 0 0; }
+ .subscribe { padding: 60vh 16px 10vh; }
+ .subscribe-inner { width: 100%; margin: 0; }
+ .tier { grid-template-columns: 1fr auto; grid-template-areas: 'no no' 'h3 pr' 'ul ul' 'btn btn'; gap: 10px 16px; padding: 20px; }
+ .tier ul { padding-left: 0; border-left: 0; padding-top: 12px; border-top: 1px solid var(--hair); }
+ .tier .btn { justify-self: start; }
+ .foot-grid { width: 100%; }
+ .foot { padding: 46vh 16px 84px; }
+ .foot-inner { min-height: 0; }
+ .foot-title { font-size: 13vw; }
+ .foot .btn-big { margin-top: 24px; height: 50px; }
+ .foot-grid { margin-top: 36px; gap: 18px; }
+ .foot-grid p { font-size: 14px; }
+ .colophon { margin-top: 22px; }
+ .foot-grid { grid-template-columns: 1fr 1fr; }
+ .colophon { flex-direction: column; padding-left: 0; gap: 6px; }
+ .hint { bottom: 74px; }
+ .hint span { font-size: 13px; padding: 6px 10px 6px 6px; white-space: nowrap; }
+ .facts dd span { display: none; }
+ .pin { padding-bottom: 70px; }
+}
diff --git a/examples/gambit/extras.js b/examples/gambit/extras.js
new file mode 100644
index 0000000..0439992
--- /dev/null
+++ b/examples/gambit/extras.js
@@ -0,0 +1,98 @@
+// Loader knight's tour and the (optional, off by default) sound of marble on walnut.
+
+/** Draw a knight's tour (Warnsdorff) across an 8x8 grid; set(v) reveals it as loading progresses. */
+export function buildTour(svg) {
+ const NS = 'http://www.w3.org/2000/svg';
+ const grid = svg.querySelector('.tour-grid');
+ for (let r = 0; r < 8; r++) for (let f = 0; f < 8; f++) {
+ const s = document.createElementNS(NS, 'rect');
+ s.setAttribute('x', f * 10); s.setAttribute('y', r * 10); s.setAttribute('width', 10); s.setAttribute('height', 10);
+ if ((r + f) % 2) s.classList.add('d');
+ grid.appendChild(s);
+ }
+ const J = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]];
+ const seen = new Set();
+ const key = (f, r) => f * 8 + r;
+ const ok = (f, r) => f >= 0 && f < 8 && r >= 0 && r < 8 && !seen.has(key(f, r));
+ const deg = (f, r) => J.filter(([a, b]) => ok(f + a, r + b)).length;
+ let f = 1, r = 7; // g1-ish from White's view: start on b1 (knight's home)
+ const path = [[f, r]];
+ seen.add(key(f, r));
+ for (let i = 1; i < 64; i++) {
+ let best = null, bd = 9;
+ for (const [a, b] of J) {
+ const nf = f + a, nr = r + b;
+ if (!ok(nf, nr)) continue;
+ seen.add(key(nf, nr)); const d = deg(nf, nr); seen.delete(key(nf, nr));
+ if (d < bd) { bd = d; best = [nf, nr]; }
+ }
+ if (!best) break;
+ [f, r] = best; seen.add(key(f, r)); path.push([f, r]);
+ }
+ const pts = path.map(([a, b]) => [a * 10 + 5, b * 10 + 5]);
+ const line = svg.querySelector('.tour-line');
+ line.setAttribute('points', pts.map(p => p.join(',')).join(' '));
+ const segs = pts.slice(1).map((p, i) => Math.hypot(p[0] - pts[i][0], p[1] - pts[i][1]));
+ const total = segs.reduce((a, b) => a + b, 0);
+ line.style.strokeDasharray = total;
+ line.style.strokeDashoffset = total;
+ const dot = svg.querySelector('.tour-knight');
+ return {
+ set(v) {
+ line.style.strokeDashoffset = total * (1 - v);
+ let d = total * v, i = 0;
+ while (i < segs.length - 1 && d > segs[i]) { d -= segs[i]; i++; }
+ const k = Math.min(1, d / segs[i]);
+ dot.setAttribute('cx', pts[i][0] + (pts[i + 1][0] - pts[i][0]) * k);
+ dot.setAttribute('cy', pts[i][1] + (pts[i + 1][1] - pts[i][1]) * k);
+ },
+ };
+}
+
+/** Synthesised sounds: a stone-on-wood "clack", a softer lift, and a toppling knock. */
+export const sound = (() => {
+ let ctx = null, on = false, master = null;
+ const ensure = () => {
+ if (!ctx) {
+ ctx = new AudioContext();
+ master = ctx.createGain(); master.gain.value = 0.55;
+ const comp = ctx.createDynamicsCompressor();
+ master.connect(comp).connect(ctx.destination);
+ }
+ if (ctx.state === 'suspended') ctx.resume();
+ return ctx;
+ };
+ function noiseBurst(t, len, freq, q, gain) {
+ const c = ctx, buf = c.createBuffer(1, Math.ceil(c.sampleRate * len), c.sampleRate);
+ const d = buf.getChannelData(0);
+ for (let i = 0; i < d.length; i++) { const k = i / d.length; d[i] = (Math.random() * 2 - 1) * Math.exp(-k * 30); }
+ const src = c.createBufferSource(); src.buffer = buf;
+ const bp = c.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = freq; bp.Q.value = q;
+ const g = c.createGain(); g.gain.value = gain;
+ src.connect(bp).connect(g).connect(master); src.start(t);
+ }
+ function tone(t, f0, f1, len, gain, type = 'sine') {
+ const c = ctx, o = c.createOscillator(), g = c.createGain();
+ o.type = type; o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(f1, t + len);
+ g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(gain, t + 0.004); g.gain.exponentialRampToValueAtTime(0.0001, t + len);
+ o.connect(g).connect(master); o.start(t); o.stop(t + len + 0.02);
+ }
+ return {
+ toggle() { on = !on; if (on) ensure(); return on; },
+ get on() { return on; },
+ clack(s = 1) {
+ if (!on) return; ensure();
+ const t = ctx.currentTime + 0.005, v = 0.5 + Math.random() * 0.3;
+ noiseBurst(t, 0.05, 2600 + Math.random() * 900, 2.2, 0.9 * s * v);
+ tone(t, 1150 + Math.random() * 200, 780, 0.07, 0.18 * s * v, 'triangle');
+ tone(t, 190, 120, 0.12, 0.32 * s * v);
+ },
+ lift() { if (!on) return; ensure(); noiseBurst(ctx.currentTime, 0.035, 4200, 1.2, 0.16); },
+ topple(s = 1) {
+ if (!on) return; ensure();
+ const t = ctx.currentTime + 0.02;
+ noiseBurst(t, 0.06, 1700, 2, 0.6 * s); tone(t, 160, 90, 0.16, 0.35 * s);
+ noiseBurst(t + 0.11, 0.05, 2100, 2, 0.28 * s); tone(t + 0.11, 150, 95, 0.1, 0.15 * s);
+ },
+ };
+})();
diff --git a/examples/gambit/game.js b/examples/gambit/game.js
new file mode 100644
index 0000000..2a2c43b
--- /dev/null
+++ b/examples/gambit/game.js
@@ -0,0 +1,145 @@
+// The Immortal Game — Adolf Anderssen vs Lionel Kieseritzky, London, 21 June 1851.
+// 23 moves, 45 plies, hardcoded as from/to squares. States are derived by replaying them.
+
+export const PLIES = [
+ // [from, to, SAN, annotation]
+ ['e2', 'e4', 'e4', 'Anderssen opens with the king’s pawn. Nothing yet hints at immortality.'],
+ ['e7', 'e5', 'e5', 'Kieseritzky answers in kind. The classical centre is set.'],
+ ['f2', 'f4', 'f4', 'The King’s Gambit — a pawn offered on move two, in the romantic manner of the age.'],
+ ['e5', 'f4', 'exf4', 'Accepted. Black takes the gambit pawn.'],
+ ['f1', 'c4', 'Bc4', 'The Bishop’s Gambit. White aims at f7 and invites his king to be chased.'],
+ ['d8', 'h4', 'Qh4+', 'Check. The black queen strikes, and White loses the right to castle.'],
+ ['e1', 'f1', 'Kf1', 'The king steps aside. Anderssen will never castle in this game.'],
+ ['b7', 'b5', 'b5', 'The Bryan Counter-Gambit: a pawn returned to lure the bishop away.'],
+ ['c4', 'b5', 'Bxb5', 'Anderssen takes it. Material is level; time is not.'],
+ ['g8', 'f6', 'Nf6', 'Black develops with a threat against e4.'],
+ ['g1', 'f3', 'Nf3', 'The knight comes out and chases the queen from h4.'],
+ ['h4', 'h6', 'Qh6', 'The queen retreats to h6, still watching the kingside.'],
+ ['d2', 'd3', 'd3', 'Quiet and solid. e4 is defended; the dark-squared bishop can breathe.'],
+ ['f6', 'h5', 'Nh5', 'The knight heads for g3, where it would fork the rook on h1.'],
+ ['f3', 'h4', 'Nh4', 'Anderssen covers g2 and eyes the f5 square.'],
+ ['h6', 'g5', 'Qg5', 'The queen attacks the knight on h4.'],
+ ['h4', 'f5', 'Nf5', 'The knight lands on f5 — an outpost it will keep until the end.'],
+ ['c7', 'c6', 'c6', 'Black strikes at the bishop on b5.'],
+ ['g2', 'g4', 'g4', 'A pawn lunge at the knight on h5. The bishop is left hanging.'],
+ ['h5', 'f6', 'Nf6', 'The knight falls back to f6.'],
+ ['h1', 'g1', 'Rg1', 'Anderssen abandons the bishop. The sacrifices begin.'],
+ ['c6', 'b5', 'cxb5', 'Kieseritzky takes it. White is a whole piece down.'],
+ ['h2', 'h4', 'h4', 'The h-pawn drives at the black queen.'],
+ ['g5', 'g6', 'Qg6', 'The queen retreats to g6.'],
+ ['h4', 'h5', 'h5', 'Again. The queen is running out of squares.'],
+ ['g6', 'g5', 'Qg5', 'Back to g5, where the net is waiting.'],
+ ['d1', 'f3', 'Qf3', 'Quiet and deadly: Bxf4 would now trap the queen.'],
+ ['f6', 'g8', 'Ng8', 'The knight retreats to g8 to give the queen a way out.'],
+ ['c1', 'f4', 'Bxf4', 'The bishop wins back the gambit pawn, with tempo on the queen.'],
+ ['g5', 'f6', 'Qf6', 'The queen escapes to f6.'],
+ ['b1', 'c3', 'Nc3', 'Development. Every white piece now points at the black king.'],
+ ['f8', 'c5', 'Bc5', 'Black develops with a threat of his own: Bxg1.'],
+ ['c3', 'd5', 'Nd5', 'The knight leaps to d5, hitting the queen and the c7 square.'],
+ ['f6', 'b2', 'Qxb2', 'The queen takes b2 and attacks both white rooks.'],
+ ['f4', 'd6', 'Bd6!!', 'The immortal move. Anderssen offers both rooks and plays for mate.'],
+ ['c5', 'g1', 'Bxg1', 'Kieseritzky takes the first rook.'],
+ ['e4', 'e5', 'e5!', 'The pawn cuts the long diagonal: the queen can no longer guard g7.'],
+ ['b2', 'a1', 'Qxa1+', 'The second rook falls, with check.'],
+ ['f1', 'e2', 'Ke2', 'The king steps up. White is two rooks and a bishop down.'],
+ ['b8', 'a6', 'Na6', 'Black covers c7. It is already too late.'],
+ ['f5', 'g7', 'Nxg7+', 'The knight tears into g7 with check.'],
+ ['e8', 'd8', 'Kd8', 'The king runs to d8.'],
+ ['f3', 'f6', 'Qf6+!!', 'And now the queen is given away too.'],
+ ['g8', 'f6', 'Nxf6', 'Forced. Black takes the queen.'],
+ ['d6', 'e7', 'Be7#', 'Checkmate with three minor pieces — after giving up a queen, two rooks and a bishop.'],
+];
+export const PLY_COUNT = PLIES.length; // 45
+
+export const EPILOGUE = 'The black king lies down. 1–0. Ernst Falkbeer named it the Immortal Game in 1855.';
+
+// Squares that tell the story after the mate: the king, the three attackers, and the sealed escape squares.
+export const MATE_NET = ['d8', 'e7', 'd5', 'g7', 'c7', 'e8', 'c8', 'd7', 'e7'];
+
+export const FILES = 'abcdefgh';
+export const TYPE_OF = { K: 'king', Q: 'queen', R: 'rook', B: 'bishop', N: 'knight', P: 'pawn' };
+const BACK = 'RNBQKBNR';
+
+/** 32 pieces keyed by colour + starting square, e.g. 'wg1' is White's king knight. */
+export function initialPieces() {
+ const out = [];
+ for (let f = 0; f < 8; f++) {
+ const file = FILES[f];
+ out.push({ id: 'w' + file + '1', color: 'w', type: TYPE_OF[BACK[f]], start: file + '1' });
+ out.push({ id: 'w' + file + '2', color: 'w', type: 'pawn', start: file + '2' });
+ out.push({ id: 'b' + file + '7', color: 'b', type: 'pawn', start: file + '7' });
+ out.push({ id: 'b' + file + '8', color: 'b', type: TYPE_OF[BACK[f]], start: file + '8' });
+ }
+ return out;
+}
+
+/**
+ * Replays the game. states[k] = board before ply k (states[45] = final).
+ * Each state: { sq: {pieceId: square}, grave: {pieceId: slotIndex} }. Each ply gets { mover, victim, check }.
+ */
+export function replay(pieces) {
+ const board = {};
+ for (const p of pieces) board[p.start] = p.id;
+ const colorOf = Object.fromEntries(pieces.map(p => [p.id, p.color]));
+ const typeOf = Object.fromEntries(pieces.map(p => [p.id, p.type]));
+ const grave = {};
+ const graveCount = { w: 0, b: 0 };
+ const snapshot = () => {
+ const sq = {};
+ for (const [s, id] of Object.entries(board)) sq[id] = s;
+ return { sq, grave: { ...grave } };
+ };
+ const states = [snapshot()];
+ const plies = PLIES.map(([from, to, san, note], k) => {
+ const mover = board[from];
+ if (!mover) throw new Error(`ply ${k}: no piece on ${from}`);
+ const side = k % 2 === 0 ? 'w' : 'b';
+ if (colorOf[mover] !== side) throw new Error(`ply ${k}: ${from} holds the wrong colour`);
+ if (!legalShape(typeOf[mover], side, from, to, !!board[to], board)) throw new Error(`ply ${k}: ${san} is not a legal ${typeOf[mover]} move`);
+ const victim = board[to] ?? null;
+ if (victim && colorOf[victim] === side) throw new Error(`ply ${k}: captures own piece`);
+ if (san.includes('x') !== !!victim) throw new Error(`ply ${k}: capture mismatch in ${san}`);
+ if (victim) { grave[victim] = graveCount[colorOf[victim]]++; }
+ delete board[from];
+ board[to] = mover;
+ states.push(snapshot());
+ return { k, from, to, san, note, mover, victim, check: /[+#]/.test(san), mate: san.includes('#'), knight: typeOf[mover] === 'knight', side };
+ });
+ return { states, plies };
+}
+
+// Geometric legality (enough to catch transcription errors): piece movement shape and clear paths.
+function legalShape(type, side, from, to, capture, board) {
+ const fx = FILES.indexOf(from[0]), fy = +from[1], tx = FILES.indexOf(to[0]), ty = +to[1];
+ const dx = tx - fx, dy = ty - fy, ax = Math.abs(dx), ay = Math.abs(dy);
+ const clear = () => {
+ const sx = Math.sign(dx), sy = Math.sign(dy);
+ for (let x = fx + sx, y = fy + sy; x !== tx || y !== ty; x += sx, y += sy) if (board[FILES[x] + y]) return false;
+ return true;
+ };
+ switch (type) {
+ case 'knight': return (ax === 1 && ay === 2) || (ax === 2 && ay === 1);
+ case 'bishop': return ax === ay && ax > 0 && clear();
+ case 'rook': return (ax === 0) !== (ay === 0) && clear();
+ case 'queen': return (ax === ay || ax === 0 || ay === 0) && (ax + ay > 0) && clear();
+ case 'king': return Math.max(ax, ay) === 1;
+ case 'pawn': {
+ const dir = side === 'w' ? 1 : -1, home = side === 'w' ? 2 : 7;
+ if (capture) return ax === 1 && dy === dir;
+ if (dx !== 0) return false;
+ if (dy === dir) return true;
+ return dy === 2 * dir && fy === home && !board[FILES[fx] + (fy + dir)];
+ }
+ }
+ return false;
+}
+
+/** Square name -> board-space centre (square = 1 unit, a1 at (-3.5, +3.5), White at +z). */
+export function squareXZ(sq) {
+ return [FILES.indexOf(sq[0]) - 3.5, 4.5 - +sq[1]];
+}
+export function xzSquare(x, z) {
+ const f = Math.round(x + 3.5), r = Math.round(4.5 - z);
+ if (f < 0 || f > 7 || r < 1 || r > 8) return null;
+ return FILES[f] + r;
+}
diff --git a/examples/gambit/index.html b/examples/gambit/index.html
new file mode 100644
index 0000000..39b8178
--- /dev/null
+++ b/examples/gambit/index.html
@@ -0,0 +1,164 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Gambit — Hand-carved marble chess &amp; a members’ salon</title>
+ <meta name="description" content="Chess sets carved from Carrara and Nero Marquina marble, and a salon in Paris where the old games are still played. Replay the Immortal Game, move by move.">
+ <meta name="theme-color" content="#080706">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Bodoni+Moda:ital,opsz,wght@0,6..96,400;0,6..96,500;1,6..96,400;1,6..96,500&family=Inter:wght@300;400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="grade" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <svg class="tour" viewBox="0 0 80 80" aria-hidden="true"><g class="tour-grid"></g><polyline class="tour-line" fill="none"/><circle class="tour-knight" r="1.6"/></svg>
+ <p class="loader-brand">Gambit</p>
+ <p class="loader-line">Setting the board <span class="loader-pct">0</span></p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Gambit home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><path d="M10 27h13M11.5 27c.4-3 1.6-5.2 3.4-7.1-2.3-.2-4.3.6-5.6 1.8-.9-.9-1.2-2.1-.7-3.3 1.4-3.6 4-6.3 5.3-9.6l1.2-2.9 1.3 2.4c3.9 1 6.4 4.5 6.3 9.4-.1 3.4-1.2 6.4-1.5 9.3" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linejoin="round"/><circle cx="16.8" cy="12.2" r=".8" fill="currentColor"/></svg>
+ <span>Gambit</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#game">The Immortal Game</a>
+ <a href="#set">The Set</a>
+ <a href="#salon">The Salon</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" aria-label="Toggle sound"><i></i><i></i><i></i><i></i><span>Sound</span></button>
+ <a class="btn btn-ghost" href="#set" data-magnetic>Reserve a set</a>
+ </div>
+ </header>
+
+ <main id="top">
+ <!-- Hero ─────────────────────────────────────────────────────────────── -->
+ <section class="hero" aria-labelledby="hero-title">
+ <div class="hero-inner">
+ <div class="hero-top">
+ <p class="eyebrow">Hand-carved marble chess · Carrara — Paris</p>
+ <h1 id="hero-title" class="hero-title"><span class="ln"><span>Some games</span></span><span class="ln"><span>are never <em>finished.</em></span></span></h1>
+ </div>
+ <div class="hero-bottom">
+ <p class="hero-sub">We carve chess sets from Carrara and Nero Marquina marble, one piece at a time, and keep a salon where the old games are still played. Begin with the most famous of them.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#game" data-magnetic>Replay the Immortal Game</a>
+ <a class="link-arrow" href="#set">The set, €3,900</a>
+ </div>
+ </div>
+ </div>
+ <div class="scroll-cue" aria-hidden="true"><span class="cue-line"><i></i></span><span>Scroll to play the first move</span></div>
+ </section>
+
+ <!-- The replay (pinned) ──────────────────────────────────────────────── -->
+ <section class="replay" id="game" aria-label="The Immortal Game, replayed">
+ <div class="replay-pin">
+ <div class="replay-intro">
+ <p class="eyebrow">London · 21 June 1851</p>
+ <h2>The Immortal Game</h2>
+ <p>An informal game at Simpson’s Divan, played in a break of the first international tournament. Anderssen gives away a bishop, both rooks and his queen — and mates with what is left.</p>
+ </div>
+
+ <aside class="score" aria-label="Game score">
+ <header class="score-head">
+ <p class="eyebrow">The score</p>
+ <p class="players"><span><i class="dot w"></i>Adolf Anderssen</span><span class="vs">—</span><span><i class="dot b"></i>Lionel Kieseritzky</span></p>
+ <p class="opening">King’s Gambit Accepted · Bryan Counter-Gambit</p>
+ </header>
+ <div class="score-window"><ol class="score-list"></ol></div>
+ <footer class="score-foot">
+ <div class="score-bar"><i></i></div>
+ <p><span class="score-move">Before the first move</span><span class="score-count">0 / 23</span></p>
+ </footer>
+ </aside>
+
+ <div class="caption" aria-live="polite">
+ <p class="caption-san"><span class="caption-num"></span><span class="caption-text"></span></p>
+ <p class="caption-note"></p>
+ </div>
+ <div class="tag" aria-hidden="true"><span class="tag-san"></span><i class="tag-line"></i></div>
+ </div>
+ </section>
+
+ <!-- Free play ────────────────────────────────────────────────────────── -->
+ <section class="free" id="play" aria-labelledby="free-title">
+ <div class="free-pin">
+ <div class="free-copy">
+ <p class="eyebrow">1–0 · Your move</p>
+ <h2 id="free-title">The game is over.<br><em>The board is yours.</em></h2>
+ <p>Pick up any piece and put it down wherever you like. Drop it on an opponent and it falls. Each piece is turned, carved and polished by hand; each one weighs what a chess piece should.</p>
+ <div class="free-actions">
+ <button class="btn btn-ghost" type="button" data-arrange="final" data-magnetic>Restore the final position</button>
+ <button class="btn btn-ghost" type="button" data-arrange="start" data-magnetic>Set up a new game</button>
+ </div>
+ </div>
+ <p class="free-hint" aria-hidden="true"><span class="hand"></span>Drag any piece · drop it on a square</p>
+ </div>
+ </section>
+
+ <!-- The set ──────────────────────────────────────────────────────────── -->
+ <section class="set panel" id="set" aria-labelledby="set-title">
+ <div class="set-copy">
+ <p class="eyebrow">No. 1851 · The Immortal Set</p>
+ <h2 id="set-title">Carrara &amp;<br><em>Nero Marquina.</em></h2>
+ <p class="lede">Thirty-two pieces from two quarries a thousand kilometres apart: white statuary from the Apuan Alps above Carrara, and black Nero Marquina from Markina in the Basque hills, its veins running bone and gold.</p>
+ <dl class="specs">
+ <div><dt>King</dt><dd>98 mm, Staunton proportions, weighted and felted in green baize</dd></div>
+ <div><dt>Board</dt><dd>Botticino and Emperador squares, 57 mm, inlaid in American black walnut with a brass fillet</dd></div>
+ <div><dt>Hands</dt><dd>One carver per set, from the first cut to the last polish — eleven weeks</dd></div>
+ <div><dt>Edition</dt><dd>Numbered, signed under the white king. Forty sets a year</dd></div>
+ </dl>
+ <div class="price-row" id="reserve">
+ <p class="price">€3,900 <span>board, set and fitted case · delivered by hand in Europe</span></p>
+ <a class="btn btn-solid" href="mailto:[email protected]?subject=Reserving%20set%20No.%201851" data-magnetic>Reserve set No. 1851</a>
+ </div>
+ </div>
+ <div class="set-notes" aria-hidden="true">
+ <div class="note-card"><span class="nc-k">White</span><b>Statuario Carrara</b><span>Apuan Alps, Tuscany</span></div>
+ <div class="note-card"><span class="nc-k">Black</span><b>Nero Marquina</b><span>Markina-Xemein, Biscay</span></div>
+ </div>
+ </section>
+
+ <!-- The salon ────────────────────────────────────────────────────────── -->
+ <section class="salon panel" id="salon" aria-labelledby="salon-title">
+ <div class="salon-copy">
+ <p class="eyebrow">The Salon · rue Saint-Honoré, Paris</p>
+ <h2 id="salon-title">Members’<br><em>evenings.</em></h2>
+ <p class="lede">A few doors from where the Café de la Régence once stood, twelve tables under twelve lamps. Kieseritzky telegraphed this game to his club in Paris the night he lost it. We have been replaying it ever since.</p>
+ <ol class="evenings">
+ <li><span class="ev-day">Tuesday</span><div><h3>Replay night</h3><p>A grandmaster walks the room through one historic game, move by move. This month: the Evergreen, Berlin 1852.</p></div><span class="ev-time">20:00</span></li>
+ <li><span class="ev-day">Thursday</span><div><h3>Slow chess</h3><p>Ninety minutes a side. Clocks are pressed, never slammed. Wine by the glass, phones in the drawer.</p></div><span class="ev-time">19:30</span></li>
+ <li><span class="ev-day">First Sunday</span><div><h3>The simultaneous</h3><p>Our house master plays twenty members at once. Win, and your name is cut into the wall.</p></div><span class="ev-time">16:00</span></li>
+ </ol>
+ <div class="price-row">
+ <p class="price">€480 <span>a year · two guest evenings · your own locker for your own set</span></p>
+ <a class="btn btn-ghost" href="mailto:[email protected]?subject=Membership" data-magnetic>Apply for membership</a>
+ </div>
+ </div>
+ </section>
+
+ <!-- CTA + footer ─────────────────────────────────────────────────────── -->
+ <footer class="foot panel" id="visit">
+ <h2 class="foot-title">Your <em>move.</em></h2>
+ <div class="foot-cta">
+ <a class="btn btn-solid" href="#set" data-magnetic>Reserve a set</a>
+ <a class="btn btn-ghost" href="#salon" data-magnetic>Visit the salon</a>
+ </div>
+ <div class="foot-cols">
+ <p><span class="k">Salon</span>Rue Saint-Honoré, Paris 1<sup>er</sup><br>Tuesday to Sunday, 18:00 — late</p>
+ <p><span class="k">Atelier</span>Via Carriona, Carrara<br>Visits by appointment</p>
+ <p><span class="k">Write</span>[email protected]<br>+33 1 40 00 18 51</p>
+ </div>
+ <p class="fine">© 2026 Gambit. Carved in Carrara, played in Paris. The Immortal Game: Anderssen – Kieseritzky, London 1851, 1–0.</p>
+ </footer>
+ </main>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/gambit/main.js b/examples/gambit/main.js
new file mode 100644
index 0000000..b497061
--- /dev/null
+++ b/examples/gambit/main.js
@@ -0,0 +1,1206 @@
+import { Engine, THREE, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal, elementProgress } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { DepthOfFieldEffect } from 'postprocessing';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { PLIES, PLY_COUNT, EPILOGUE, initialPieces, replay, squareXZ, xzSquare, FILES } from './game.js';
+import { boardTextures, walnutTextures, leatherTextures, coordinateTexture, marbleMaterial, BRASS } from './materials.js';
+import { buildTour, sound } from './extras.js';
+import { buildSalon, TABLES } from './salon.js';
+
+const D = Math.PI / 180;
+const DBG = new URLSearchParams(location.search);
+const MOBILE = matchMedia('(max-width: 760px)').matches;
+const UP = new THREE.Vector3(0, 1, 0);
+const TH = 0.34; // board thickness; the table sits at -TH
+const TABLE_Y = -TH;
+const INLAY = 0.05; // brass fillet
+const FRAME = 0.74; // walnut border
+const EDGE = 4 + INLAY + FRAME;
+const HEIGHTS = { king: 1.62, queen: 1.44, bishop: 1.2, knight: 1.1, rook: 0.98, pawn: 0.84 };
+const MAX_BASE = { king: 0.8, queen: 0.78, bishop: 0.72, knight: 0.74, rook: 0.74, pawn: 0.64 };
+const FILES_GLB = { king: 'king', queen: 'queen', bishop: 'bishop', knight: 'knight', rook: 'rook', pawn: 'pawn-lo' };
+const END_P = PLY_COUNT + 1; // 46: the epilogue (the king lies down) is the last step
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let vol, dof;
+const engine = new Engine({
+ canvas, fov: 30, near: 0.3, far: 420, dpr: 1.6, background: 0x050404,
+ post: {
+ ao: DBG.has('noao') ? false : { aoRadius: 0.55, intensity: 2.2, distanceFalloff: 0.55 },
+ bloom: { intensity: 0.6, luminanceThreshold: 0.95, luminanceSmoothing: 0.25, radius: 0.7 },
+ pre: cam => {
+ const fx = [];
+ vol = new VolumetricSpotEffect(cam, { density: 0.011, noise: 0.9, noiseScale: 0.55, maxDist: 34, floorY: TABLE_Y });
+ fx.push(vol);
+ if (!DBG.has('nodof')) { dof = new DepthOfFieldEffect(cam, { focusDistance: 10, focusRange: 5, bokehScale: 2.4, resolutionScale: 0.5 }); fx.push(dof); }
+ return fx;
+ },
+ tone: DBG.get('tone') ?? 'agx',
+ vignette: { offset: 0.2, darkness: 0.74 },
+ noise: 0.055,
+ ca: 0.0007,
+ },
+});
+const { scene, camera, renderer } = engine;
+scene.fog = new THREE.FogExp2(0x040303, 0.012);
+scene.environment = studioEnvironment(renderer, {
+ top: 0x14110d, bottom: 0x030302, blur: 0.03,
+ panels: [
+ { pos: [-2, 10, 3], size: [6, 3], intensity: 5.5, color: 0xfff0dc }, // the lamp's diffuser, overhead
+ { pos: [-9, 3.2, 3], size: [1.3, 6.5], intensity: 5, color: 0xffe6c6 }, // tall warm strip, left
+ { pos: [9, 3.5, -2.5], size: [1.1, 6.5], intensity: 3.6, color: 0xdfe6ff }, // cool strip, right
+ { pos: [0, 1.6, -10], size: [9, 1.1], intensity: 1.6, color: 0xffffff }, // low kicker behind Black
+ { pos: [2, 1.2, 10], size: [6, 0.8], intensity: 0.9, color: 0xffe0c0 }, // low kicker behind White
+ ],
+});
+scene.environmentIntensity = 0.4;
+scene.add(new THREE.HemisphereLight(0x303848, 0x0c0906, 0.03));
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+
+// ─── Loader ────────────────────────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+const tour = buildTour(loaderEl.querySelector('.tour'));
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => { loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100) + '%'; tour.set(v); },
+ exit: async () => {
+ await gsap.to(loaderEl.querySelector('.tour'), { scale: 0.92, opacity: 0, duration: 0.7, ease: 'power2.in' });
+ startIntro();
+ await gsap.to(loaderEl, { autoAlpha: 0, duration: 1.1, ease: 'power2.inOut' });
+ },
+});
+
+// ─── Lights ────────────────────────────────────────────────────────────────────
+// Key: one lamp above and to White's left, as over a salon table.
+const key = new THREE.SpotLight(0xffe0ba, 0, 0, 0.5, 0.62, 2);
+key.position.set(-3.0, 15, 8.0);
+key.target.position.set(0.4, 0, -0.2);
+key.castShadow = true;
+key.shadow.mapSize.set(4096, 4096);
+key.shadow.camera.near = 8; key.shadow.camera.far = 30;
+key.shadow.bias = -0.00008; key.shadow.normalBias = 0.018; key.shadow.radius = 2.5;
+scene.add(key, key.target);
+const KEY_ON = 1500;
+vol.add(key, { scale: 0.0016, range: 0.004, softness: 0.4 });
+// Rims ride with the camera so every silhouette keeps an edge, including black marble against black.
+const rimA = new THREE.SpotLight(0xcfdcff, 0, 0, 0.55, 0.85, 2);
+const rimB = new THREE.SpotLight(0xffd3a0, 0, 0, 0.55, 0.85, 2);
+scene.add(rimA, rimA.target, rimB, rimB.target);
+const RIM_A = 230, RIM_B = 150;
+const lights = { k: 0 };
+
+// ─── Board ─────────────────────────────────────────────────────────────────────
+const reflection = new PlanarReflection(renderer, { resolution: MOBILE ? 0.4 : 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+function onTopOnly(mat) {
+ // Reflection only on the horizontal top face (world y ~ 0), not on the board's sides.
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (sh, r) => {
+ prev(sh, r);
+ sh.fragmentShader = sh.fragmentShader.replace('outgoingLight += refl * uReflTint', 'outgoingLight += step(-0.004, vReflW.y) * refl * uReflTint');
+ };
+}
+const bt = boardTextures(renderer);
+// Physical so the analytic highlight can be tamed (specularIntensity) while the planar mirror stays crisp.
+const boardMat = new THREE.MeshPhysicalMaterial({ map: bt.albedo, roughnessMap: bt.rough, roughness: 1, metalness: 0, envMapIntensity: 0.4, specularIntensity: 0.08 });
+if (!DBG.has('norefl')) reflection.patch(boardMat, { strength: 1.05, distort: 0.002, lodScale: 5, lodBias: 0.0, f0: 0.05 });
+{
+ const prev = boardMat.onBeforeCompile;
+ boardMat.onBeforeCompile = (sh, r) => {
+ prev?.(sh, r);
+ if (!sh.fragmentShader.includes('vReflW')) {
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vReflW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvReflW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nvarying vec3 vReflW;');
+ }
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <map_fragment>', `
+ vec4 sampledDiffuseColor = texture2D(map, vMapUv);
+ sampledDiffuseColor.rgb *= sampledDiffuseColor.rgb;
+ diffuseColor *= sampledDiffuseColor;
+ vec2 gq = abs(fract(vReflW.xz + 4.0) - 0.5);
+ float gE = 0.5 - max(gq.x, gq.y);
+ float gSeam = 1.0 - smoothstep(0.0, 0.0065, gE);
+ diffuseColor.rgb *= 1.0 - gSeam * 0.6;`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(max(roughnessFactor, 0.1), 0.55, gSeam);`);
+ };
+ boardMat.customProgramCacheKey = () => 'gambit-board';
+}
+const board = new THREE.Group();
+scene.add(board);
+const field = new THREE.Mesh(new THREE.PlaneGeometry(8, 8), boardMat);
+field.rotation.x = -Math.PI / 2;
+field.receiveShadow = true;
+board.add(field);
+
+const brassMat = new THREE.MeshStandardMaterial({ color: BRASS.clone().convertSRGBToLinear().multiplyScalar(1.15), metalness: 1, roughness: 0.26, envMapIntensity: 1.6 });
+// The brass fillet is a ring of four strips (a full plane under the field z-fights from far away).
+const fillet = new THREE.Group();
+for (const [w, d, x, z] of [[8 + INLAY * 2, INLAY, 0, 4 + INLAY / 2], [8 + INLAY * 2, INLAY, 0, -4 - INLAY / 2], [INLAY, 8, 4 + INLAY / 2, 0], [INLAY, 8, -4 - INLAY / 2, 0]]) {
+ const s = new THREE.Mesh(new THREE.PlaneGeometry(w, d), brassMat);
+ s.rotation.x = -Math.PI / 2; s.position.set(x, 0, z); s.receiveShadow = true;
+ fillet.add(s);
+}
+board.add(fillet);
+
+const wt = walnutTextures(renderer);
+const walnutMat = new THREE.MeshPhysicalMaterial({ map: wt.albedo, normalMap: wt.normal, normalScale: new THREE.Vector2(0.4, 0.4), roughness: 0.42, metalness: 0,
+ clearcoat: 0.8, clearcoatRoughness: 0.14, envMapIntensity: 0.7 });
+{
+ walnutMat.onBeforeCompile = sh => {
+ sh.fragmentShader = sh.fragmentShader.replace('#include <map_fragment>', `
+ vec4 sampledDiffuseColor = texture2D(map, vMapUv);
+ sampledDiffuseColor.rgb *= sampledDiffuseColor.rgb;
+ diffuseColor *= sampledDiffuseColor;`);
+ };
+ if (!DBG.has('norefl')) {
+ const own = walnutMat.onBeforeCompile;
+ reflection.patch(walnutMat, { strength: 0.55, distort: 0.01, lodScale: 6, lodBias: 0.6, f0: 0.04 });
+ const refl = walnutMat.onBeforeCompile;
+ walnutMat.onBeforeCompile = (sh, r) => { own(sh, r); refl(sh, r); };
+ onTopOnly(walnutMat);
+ }
+ walnutMat.customProgramCacheKey = () => 'gambit-walnut';
+}
+{
+ const L = 8 + INLAY * 2 + FRAME * 2;
+ for (const s of [-1, 1]) {
+ const a = new THREE.Mesh(new RoundedBoxGeometry(L, TH, FRAME, 2, 0.028), walnutMat);
+ a.position.set(0, -TH / 2, s * (4 + INLAY + FRAME / 2));
+ const b = new THREE.Mesh(new RoundedBoxGeometry(8 + INLAY * 2, TH, FRAME, 2, 0.028), walnutMat);
+ b.rotation.y = Math.PI / 2;
+ b.position.set(s * (4 + INLAY + FRAME / 2), -TH / 2, 0);
+ for (const m of [a, b]) { m.castShadow = m.receiveShadow = true; board.add(m); reflection.hidden.push(m); }
+ }
+ const core = new THREE.Mesh(new THREE.BoxGeometry(8 + INLAY * 2, TH - 0.01, 8 + INLAY * 2), walnutMat);
+ core.position.y = -TH / 2 - 0.006; core.castShadow = true; reflection.hidden.push(core);
+ board.add(core);
+}
+let coordMesh;
+function buildCoordinates() {
+ const tex = coordinateTexture(INLAY + FRAME);
+ const mat = new THREE.MeshStandardMaterial({ color: BRASS.clone().convertSRGBToLinear().multiplyScalar(1.1), metalness: 1, roughness: 0.3, alphaMap: tex,
+ transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, envMapIntensity: 1.5 });
+ coordMesh = new THREE.Mesh(new THREE.PlaneGeometry(EDGE * 2, EDGE * 2), mat);
+ coordMesh.rotation.x = -Math.PI / 2; coordMesh.position.y = 0.0004;
+ coordMesh.receiveShadow = true;
+ board.add(coordMesh);
+ reflection.hidden.push(coordMesh);
+}
+
+// Highlights: last move, check, the mating net, the square under a lifted piece, and landing ripples.
+const HN = 12;
+const hlMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false,
+ uniforms: { uH: { value: Array.from({ length: HN }, () => new THREE.Vector4(0, 0, 0, 0)) }, uRip: { value: new THREE.Vector4(0, 0, 99, 0) }, uTime: { value: 0 } },
+ vertexShader: 'varying vec2 vUv; varying vec3 vW; void main(){ vUv = uv; vW = (modelMatrix * vec4(position, 1.)).xyz; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }',
+ fragmentShader: `
+ uniform vec4 uH[${HN}]; uniform vec4 uRip; uniform float uTime; varying vec2 vUv; varying vec3 vW;
+ void main(){
+ vec2 g = vUv * 8.0; vec2 id = floor(g); vec2 f = fract(g);
+ float edge = min(min(f.x, 1.0 - f.x), min(f.y, 1.0 - f.y));
+ vec3 col = vec3(0.0);
+ for (int i = 0; i < ${HN}; i++) {
+ vec4 h = uH[i];
+ if (h.z < 0.002) continue;
+ if (abs(id.x - h.x) > 0.5 || abs(id.y - h.y) > 0.5) continue;
+ float line = smoothstep(0.052, 0.042, edge) * smoothstep(0.026, 0.034, edge);
+ float glow = exp(-edge * 9.0);
+ float fill = 1.0;
+ vec3 c; float a;
+ if (h.w < 1.5) { c = vec3(0.62, 0.47, 0.25); a = fill * 0.045 + line * 0.35; } // from
+ else if (h.w < 2.5) { c = vec3(0.80, 0.62, 0.33); a = fill * 0.08 + line * 0.9 + glow * 0.12; } // to
+ else if (h.w < 3.5) { c = vec3(0.85, 0.22, 0.14); float r = length(f - 0.5); a = exp(-r * r * 7.0) * 0.55 + line * 0.5; } // check
+ else if (h.w < 4.5) { c = vec3(0.85, 0.66, 0.36); a = line * 1.1 + glow * 0.2; } // attacker
+ else if (h.w < 5.5) { c = vec3(0.7, 0.55, 0.32); a = line * 0.45 + fill * 0.03; } // covered
+ else if (h.w < 6.5) { c = vec3(0.86, 0.70, 0.42); a = line * 1.0 + fill * 0.07 + glow * 0.15; } // hover
+ else { c = vec3(0.9, 0.3, 0.2); a = line * 1.0 + fill * 0.08; } // capture target
+ col += c * a * h.z;
+ }
+ float age = uRip.z;
+ if (age < 2.0) {
+ float r = length(vW.xz - uRip.xy);
+ float rx = (r - 0.18 - age * 1.9) / 0.035; // (no pow() on a negative base: NaN on D3D)
+ float ring = exp(-rx * rx) * exp(-age * 2.6) * uRip.w;
+ col += vec3(0.85, 0.66, 0.38) * ring * 0.55;
+ }
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+});
+const hl = new THREE.Mesh(new THREE.PlaneGeometry(8, 8), hlMat);
+hl.rotation.x = -Math.PI / 2; hl.position.y = 0.0012; hl.renderOrder = 2;
+board.add(hl);
+reflection.hidden.push(hl, field, ...fillet.children);
+
+// Our table: a round leather top with a walnut rim, one of twelve in the salon.
+const lt = leatherTextures(renderer);
+lt.normal.repeat.set(14, 14); lt.rough.repeat.set(2, 2);
+const TABLE_R = 8.85;
+const table = new THREE.Mesh(new THREE.CircleGeometry(TABLE_R, 128), new THREE.MeshStandardMaterial({ color: 0x0d0b0a, roughness: 1, roughnessMap: lt.rough, normalMap: lt.normal, normalScale: new THREE.Vector2(0.14, 0.14), envMapIntensity: 0.2 }));
+table.rotation.x = -Math.PI / 2; table.position.y = TABLE_Y; table.receiveShadow = true;
+scene.add(table);
+{
+ const ring = new THREE.Mesh(new THREE.RingGeometry(TABLE_R, 9.4, 128, 1), walnutMat);
+ ring.rotation.x = -Math.PI / 2; ring.position.y = TABLE_Y; ring.receiveShadow = true;
+ const side = new THREE.Mesh(new THREE.CylinderGeometry(9.4, 9.2, 0.36, 128, 1, true), walnutMat);
+ side.position.y = TABLE_Y - 0.18; side.receiveShadow = true;
+ scene.add(ring, side);
+ reflection.hidden.push(ring, side);
+}
+
+// The salon beyond: warm lamps far away that turn into bokeh in the low shots and sparkle in the board.
+const orbs = [];
+{
+ const g = new THREE.SphereGeometry(0.11, 12, 8);
+ const rnd = mulberry(7);
+ for (let i = 0; i < 26; i++) {
+ const a = rnd() * Math.PI * 2, r = 40 + rnd() * 38;
+ const k = 5 + rnd() * 9;
+ const m = new THREE.Mesh(g, new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 0.66, 0.36).multiplyScalar(k), fog: false }));
+ m.userData.k = k;
+ m.position.set(Math.cos(a) * r, 2.2 + rnd() * 9, Math.sin(a) * r);
+ m.scale.setScalar((0.7 + rnd() * 0.9) * r / 24);
+ scene.add(m);
+ orbs.push(m);
+ }
+}
+
+// Dust that only exists inside the lamp's cone.
+const dust = (() => {
+ const N = MOBILE ? 900 : 2200;
+ const pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ const rnd = mulberry(99);
+ for (let i = 0; i < N; i++) {
+ const a = rnd() * Math.PI * 2, r = Math.sqrt(rnd()) * 8;
+ pos[i * 3] = Math.cos(a) * r; pos[i * 3 + 1] = rnd() * 7; pos[i * 3 + 2] = Math.sin(a) * r;
+ seed[i] = rnd();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false,
+ uniforms: { uTime: { value: 0 }, uLPos: { value: key.position }, uLDir: { value: new THREE.Vector3() }, uPower: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: `
+ attribute float seed; uniform float uTime, uPower, uDpr; uniform vec3 uLPos, uLDir; varying float vA;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.03 + seed * 0.05);
+ p += vec3(sin(t * 3.1 + seed * 40.0), sin(t * 2.3 + seed * 13.0) * 0.5 + t * 0.2, cos(t * 2.7 + seed * 27.0)) * 0.6;
+ p.y = mod(p.y, 7.0) + 0.05;
+ vec3 d = p - uLPos; float dist = length(d);
+ float cone = smoothstep(0.93, 0.985, dot(d / dist, uLDir));
+ vA = cone * uPower * (0.35 + 0.65 * fract(seed * 91.7)) * smoothstep(0.0, 0.6, p.y);
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (1.0 + seed * 2.2) * uDpr * (6.0 / -mv.z);
+ }`,
+ fragmentShader: `varying float vA; void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.0, d); gl_FragColor = vec4(vec3(1.0, 0.85, 0.62) * a * vA * 0.45, 1.0); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ scene.add(pts);
+ reflection.hidden.push(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ return mat;
+})();
+
+// ─── Pieces ────────────────────────────────────────────────────────────────────
+const PIECES = initialPieces();
+const { states, plies } = replay(PIECES);
+const byId = {};
+const TYPES = {};
+const typeLoads = Object.entries(FILES_GLB).map(([type, file]) => assets.gltf(`models/gambit/${file}.glb`).then(g => { TYPES[type] = prepType(type, g.scene); }));
+const FAR = {};
+const farLoads = Object.keys(FILES_GLB).map(type => assets.gltf(`models/gambit/far-${type}.glb`).then(g => { FAR[type] = g.scene; }));
+
+function toFloatGeometry(src, matrix) {
+ const geo = new THREE.BufferGeometry();
+ for (const name of ['position', 'normal', 'uv']) {
+ const a = src.getAttribute(name);
+ if (!a) continue;
+ const arr = new Float32Array(a.count * a.itemSize);
+ for (let i = 0; i < a.count; i++) for (let j = 0; j < a.itemSize; j++) arr[i * a.itemSize + j] = a.getComponent(i, j);
+ geo.setAttribute(name, new THREE.BufferAttribute(arr, a.itemSize));
+ }
+ geo.setIndex(src.index ? new THREE.BufferAttribute(src.index.array.slice(), 1) : null);
+ geo.applyMatrix4(matrix);
+ return geo;
+}
+
+function prepType(type, root) {
+ root.updateMatrixWorld(true);
+ const mesh = firstMesh(root);
+ const geo = toFloatGeometry(mesh.geometry, mesh.matrixWorld);
+ geo.computeBoundingBox();
+ const bb = geo.boundingBox, h0 = bb.max.y - bb.min.y;
+ const pos = geo.attributes.position;
+ // Base centre from the bottom ring of vertices (the knight's head would skew a bounding-box centre).
+ let cx = 0, cz = 0, n = 0;
+ for (let i = 0; i < pos.count; i++) if (pos.getY(i) < bb.min.y + h0 * 0.03) { cx += pos.getX(i); cz += pos.getZ(i); n++; }
+ cx /= n; cz /= n;
+ let rB = 0;
+ for (let i = 0; i < pos.count; i++) if (pos.getY(i) < bb.min.y + h0 * 0.03) rB = Math.max(rB, Math.hypot(pos.getX(i) - cx, pos.getZ(i) - cz));
+ let s = HEIGHTS[type] / h0;
+ s = Math.min(s, MAX_BASE[type] / (rB * 2));
+ geo.translate(-cx, -bb.min.y, -cz);
+ geo.scale(s, s, s);
+ geo.computeBoundingSphere();
+ const h = h0 * s;
+ rB *= s;
+ // Resting angle when it lies down: rotate about the base rim until another point touches the floor.
+ const rest = restAngle(geo, rB);
+ const src = mesh.material;
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+ for (const k of ['map', 'normalMap', 'roughnessMap']) if (src[k]) src[k].anisotropy = aniso;
+ const mats = { w: marbleMaterial(src, { envIntensity: 0.9 }), b: marbleMaterial(src, { black: true, envIntensity: 1.25, veins: type === 'king' || type === 'queen' ? [0.26, 0.6] : [0.1, 0.42] }) };
+ return { type, geo, h, rB, rest, mats, xf: { cx, cz, y0: bb.min.y, s } };
+}
+
+function restAngle(geo, rB) {
+ const p = geo.attributes.position;
+ const step = Math.max(1, Math.floor(p.count / 5000));
+ const xs = [], ys = [];
+ for (let i = 0; i < p.count; i += step) {
+ const rx = p.getX(i) - rB, ry = p.getY(i);
+ if (rx * rx + ry * ry < 0.0025) continue;
+ xs.push(rx); ys.push(ry);
+ }
+ let prev = 0;
+ for (let a = 0.5 * D; a < 140 * D; a += 0.25 * D) {
+ const c = Math.cos(a), sn = Math.sin(a);
+ let lo = Infinity;
+ for (let i = 0; i < xs.length; i++) { const y = -sn * xs[i] + c * ys[i]; if (y < lo) lo = y; }
+ if (lo < -0.002) return prev;
+ prev = a;
+ }
+ return Math.PI / 2;
+}
+
+function makePieces() {
+ const rnd = mulberry(1851);
+ for (const p of PIECES) {
+ const T = TYPES[p.type];
+ const mesh = new THREE.Mesh(T.geo, T.mats[p.color]);
+ mesh.castShadow = true; mesh.receiveShadow = true;
+ scene.add(mesh);
+ // Everything faces the opponent (models face +Z). Round pieces get a random turn so the veining differs.
+ const face = p.color === 'w' ? Math.PI : 0;
+ const round = p.type === 'pawn' || p.type === 'rook';
+ const yaw = round ? rnd() * Math.PI * 2 : face + (rnd() - 0.5) * (p.type === 'knight' ? 0.12 : 0.3);
+ Object.assign(p, { T, mesh, yaw, jit: rnd() - 0.5, pos: new THREE.Vector3(), quat: new THREE.Quaternion(),
+ fp: new THREE.Vector3(), fq: new THREE.Quaternion(), drop: 0 });
+ byId[p.id] = p;
+ }
+}
+
+// ─── Poses ─────────────────────────────────────────────────────────────────────
+const _q1 = new THREE.Quaternion(), _q2 = new THREE.Quaternion(), _q3 = new THREE.Quaternion();
+const _v1 = new THREE.Vector3(), _v2 = new THREE.Vector3(), _v3 = new THREE.Vector3(), _v4 = new THREE.Vector3();
+const _axis = new THREE.Vector3();
+const sqPos = (sq, out) => { const [x, z] = squareXZ(sq); return out.set(x, 0, z); };
+const ease = {
+ io3: t => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2),
+ io2: t => (t < 0.5 ? 2 * t * t : 1 - Math.pow(-2 * t + 2, 2) / 2),
+ sine: t => -(Math.cos(Math.PI * t) - 1) / 2,
+ fall: t => { if (t < 0.8) { const a = t / 0.8; return a * a; } const b = (t - 0.8) / 0.2; return 1 - Math.sin(b * Math.PI) * 0.04 * (1 - b); },
+};
+function upright(p, pos, oP, oQ) { oP.copy(pos); oQ.setFromAxisAngle(UP, p.yaw); }
+/** Tip a piece whose base centre sits at `anchor` toward horizontal `dir` by `angle`, around its base rim. */
+function tipPose(p, anchor, dir, angle, yaw, oP, oQ) {
+ _axis.set(dir.z, 0, -dir.x).normalize();
+ _q1.setFromAxisAngle(_axis, angle);
+ oQ.copy(_q1).multiply(_q2.setFromAxisAngle(UP, yaw));
+ _v1.copy(dir).multiplyScalar(p.T.rB);
+ oP.copy(anchor).add(_v1).sub(_v1.applyQuaternion(_q1));
+}
+/** Where captured pieces settle: lying on the table beside the board, White's losses on the kingside. */
+function gravePose(p, i, oP, oQ) {
+ const side = p.color === 'w' ? 1 : -1;
+ const row = Math.floor(i / 8), col = i % 8;
+ const dir = _v3.set(side, 0, p.jit * 0.5).normalize();
+ const z = side * (3.15 - col * 0.9) + p.jit * 0.1;
+ _v4.set(side * (EDGE + 0.42 + row * 2.05), TABLE_Y, z);
+ const yaw = Math.atan2(-dir.z, dir.x) + (p.type === 'knight' ? 0 : p.jit * 2);
+ tipPose(p, _v4, dir, p.T.rest, yaw, oP, oQ);
+}
+function restPose(p, st, oP, oQ) {
+ const sq = st.sq[p.id];
+ if (sq) upright(p, sqPos(sq, _v2), oP, oQ);
+ else gravePose(p, st.grave[p.id], oP, oQ);
+}
+/** Rotate a pose about a point at height `ph` above its base by quaternion q (lean, pitch). */
+function lean(oP, oQ, axis, angle, ph) {
+ _q3.setFromAxisAngle(axis, angle);
+ oQ.premultiply(_q3);
+ _v1.set(0, ph, 0);
+ oP.add(_v1).sub(_v1.applyQuaternion(_q3));
+}
+// Tempo per ply; the great moments play slower (the leap into g7 is nearly slow motion).
+const SLOW = { 34: 1.35, 40: 2.2, 42: 1.6, 44: 1.7 };
+const DUR = plies.map((p, k) => SLOW[k] ?? (p.victim ? 1.45 : p.knight ? 1.2 : 1));
+const EPI_DIR = new THREE.Vector3(1, 0, 0.14).normalize();
+const toppleTmp = { p: new THREE.Vector3(), q: new THREE.Quaternion() };
+
+function moverPose(p, ply, u, oP, oQ) {
+ const from = sqPos(ply.from, _v2), to = sqPos(ply.to, _v3);
+ const dist = from.distanceTo(to);
+ const dir = _v4.subVectors(to, from).normalize();
+ _axis.set(dir.z, 0, -dir.x);
+ const axis = _axis.clone();
+ if (ply.knight) {
+ const e = ease.io2(u);
+ oP.lerpVectors(from, to, e);
+ oP.y = (1.05 + dist * 0.14) * Math.pow(Math.sin(Math.PI * e), 0.92);
+ oQ.setFromAxisAngle(UP, p.yaw);
+ lean(oP, oQ, axis, -0.46 * Math.sin(2 * Math.PI * e), p.T.h * 0.45);
+ } else {
+ const e = ease.io3(u);
+ oP.lerpVectors(from, to, e);
+ oP.y = 0.03 * Math.sin(Math.PI * e);
+ oQ.setFromAxisAngle(UP, p.yaw);
+ lean(oP, oQ, axis, -0.075 * Math.sin(2 * Math.PI * e) * Math.min(1, dist / 1.6), 0);
+ }
+}
+
+function victimPose(p, ply, u, oP, oQ, slot) {
+ const at = sqPos(ply.to, _v2).clone();
+ const dir = _v3.subVectors(at, sqPos(ply.from, _v4)).setY(0).normalize().clone();
+ const tU = clamp((u - 0.46) / 0.2), gU = clamp((u - 0.64) / 0.36);
+ tipPose(p, at, dir, p.T.rest * ease.fall(tU), p.yaw, oP, oQ);
+ if (gU <= 0) return;
+ toppleTmp.p.copy(oP); toppleTmp.q.copy(oQ);
+ gravePose(p, slot, oP, oQ);
+ const g = ease.io3(gU);
+ const d = toppleTmp.p.distanceTo(oP);
+ oP.lerpVectors(toppleTmp.p, oP, g);
+ oP.y += Math.sin(Math.PI * g) * (0.85 + d * 0.07);
+ oQ.slerpQuaternions(toppleTmp.q, oQ.clone(), g);
+}
+
+function replayPose(p, P, oP, oQ) {
+ const Pc = clamp(P, 0, END_P);
+ const k = Math.min(Math.floor(Pc), PLY_COUNT);
+ if (k === PLY_COUNT) {
+ restPose(p, states[PLY_COUNT], oP, oQ);
+ if (p.id === 'be8') tipPose(p, sqPos('d8', _v2).clone(), EPI_DIR, p.T.rest * ease.fall(clamp((Pc - k) / 0.9)), p.yaw, oP, oQ);
+ return;
+ }
+ const u = Pc - k, ply = plies[k];
+ if (p.id === ply.mover) moverPose(p, ply, ply.victim ? clamp(u / 0.62) : u, oP, oQ);
+ else if (p.id === ply.victim) victimPose(p, ply, u, oP, oQ, states[k + 1].grave[p.id]);
+ else restPose(p, states[k], oP, oQ);
+}
+
+// ─── Knight trail ─────────────────────────────────────────────────────────────
+class Arc extends THREE.Curve {
+ constructor(a, b, h) { super(); this.a = a; this.b = b; this.h = h; }
+ getPoint(t, out = new THREE.Vector3()) {
+ out.lerpVectors(this.a, this.b, t);
+ out.y = this.h * Math.pow(Math.sin(Math.PI * t), 0.92) + 0.02;
+ return out;
+ }
+}
+const trailMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false,
+ uniforms: { uHead: { value: 0 }, uAlpha: { value: 0 } },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }',
+ fragmentShader: `uniform float uHead, uAlpha; varying vec2 vUv;
+ void main(){
+ float s = vUv.x;
+ float a = smoothstep(uHead - 0.7, uHead, s) * (1.0 - smoothstep(uHead, uHead + 0.01, s));
+ a = max(a * 1.0, (1.0 - smoothstep(0.0, 1.0, abs(s - uHead) * 60.0)) * 1.5 * step(0.001, uHead) * step(uHead, 0.999));
+ a *= smoothstep(0.0, 0.05, s) * smoothstep(1.0, 0.95, s);
+ gl_FragColor = vec4(vec3(1.0, 0.76, 0.42) * a * uAlpha * 2.2, 1.0);
+ }`,
+});
+const trail = new THREE.Mesh(new THREE.BufferGeometry(), trailMat);
+trail.frustumCulled = false;
+scene.add(trail);
+reflection.hidden.push(trail);
+let trailPly = -1;
+function updateTrail(P) {
+ const k = Math.floor(P), u = P - k;
+ const ply = plies[k];
+ if (!ply?.knight || u <= 0) { trailMat.uniforms.uAlpha.value = damp(trailMat.uniforms.uAlpha.value, 0, 5, 1 / 60); return; }
+ if (trailPly !== k) {
+ trailPly = k;
+ const a = sqPos(ply.from, new THREE.Vector3()), b = sqPos(ply.to, new THREE.Vector3());
+ trail.geometry.dispose();
+ trail.geometry = new THREE.TubeGeometry(new Arc(a, b, (1.05 + a.distanceTo(b) * 0.14) + byId[ply.mover].T.h * 0.02), 90, 0.007, 6, false);
+ }
+ const mu = ply.victim ? clamp(u / 0.62) : u;
+ trailMat.uniforms.uHead.value = ease.io2(mu);
+ trailMat.uniforms.uAlpha.value = smooth(0, 0.08, mu) * (1 - smooth(0.9, 1, mu) * 0.6);
+}
+
+// ─── Camera ────────────────────────────────────────────────────────────────────
+// Shots for the replay, keyed by the ply they frame (0 = 1.e4). [az, el, dist, tx, tz]
+const SHOTS = [
+ [0, [20, 17, 11, 0.4, 0.5]],
+ [2, [30, 19, 9.4, 1.0, 0.8]],
+ [4, [36, 22, 8.8, 0.8, 1.5]],
+ [5, [66, 10, 7.6, 2.2, 1.4]], // Qh4+ — down the diagonal at the king
+ [6, [42, 17, 7.0, 1.3, 2.6]],
+ [7, [-40, 16, 7.4, -2.0, -0.4]], // the queenside skirmish
+ [9, [-12, 24, 8.6, 0.4, -1.0]],
+ [10, [40, 22, 8.8, 1.9, 1.2]],
+ [12, [72, 18, 8.2, 2.0, 0.6]], // knights on the rim
+ [16, [56, 14, 7.4, 1.4, -0.4]],
+ [18, [78, 13, 7.0, 2.4, 0.2]],
+ [20, [18, 30, 10.8, 0.0, 0.8]], // Rg1 — the bishop is left to die
+ [21, [-52, 14, 6.4, -2.4, -0.6]],
+ [22, [86, 12, 7.6, 2.6, 0.0]], // the h-pawn hunts the queen
+ [26, [30, 21, 8.2, 1.2, 1.2]],
+ [28, [50, 15, 7.0, 1.4, 0.4]],
+ [30, [-26, 26, 9.4, -1.0, 0.6]],
+ [32, [-14, 30, 9.2, -1.0, 0.0]],
+ [33, [-30, 44, 10.8, -1.2, 0.8]],
+ [34, [0, 57, 12.6, 0.0, 1.1]], // Bd6!! — from above White's back rank: both rooks en prise
+ [35, [16, 54, 12.2, 0.6, 1.3]],
+ [36, [-8, 52, 12.2, -0.3, 1.0]],
+ [37, [-30, 50, 11.4, -1.2, 1.8]],
+ [38, [30, 26, 8.4, 1.0, 1.8]],
+ [39, [-36, 22, 8.4, -1.6, -1.4]],
+ [40, [72, 7, 7.3, 2.0, -1.5]], // Nxg7+ — the leap, low across the board
+ [41, [160, 18, 7.0, 0.2, -2.8]],
+ [42, [66, 21, 7.4, 1.2, -1.1]], // Qf6+!! — the queen goes
+ [43, [76, 13, 6.6, 1.3, -1.8]],
+ [44, [198, 40, 7.8, 0.3, -2.3]], // Be7# — the net, from behind the black king
+ [45, [214, 36, 8.4, 0.4, -2.5]], // the king lies down
+];
+const shotAt = [];
+for (let k = 0, j = 0; k <= END_P; k++) { while (j + 1 < SHOTS.length && SHOTS[j + 1][0] <= k) j++; shotAt[k] = SHOTS[j][1]; }
+const rig = () => ({ az: 0, el: 20, d: 10, tx: 0, ty: 0, tz: 0, shift: 0, fov: 30, bokeh: 2, range: 0.5 });
+function lerpRig(a, b, f, o = rig()) {
+ let daz = b.az - a.az; daz = ((daz + 540) % 360) - 180;
+ o.az = a.az + daz * f;
+ for (const k of ['el', 'd', 'tx', 'ty', 'tz', 'shift', 'fov', 'bokeh', 'range']) o[k] = lerp(a[k], b[k], f);
+ return o;
+}
+function fromShot(s, o) { Object.assign(o, { az: s[0], el: s[1], d: s[2], tx: s[3], tz: s[4], ty: 0.25 }); return o; }
+const shiftReplay = () => (MOBILE ? 0 : 0.09);
+// Pieces low and to the right; the copy owns the dark room above-left. On phones the board sits in the lower third.
+const heroRig = MOBILE
+ ? Object.assign(rig(), { az: 28, el: -1, d: 5.2, tx: 0.8, ty: 2.0, tz: 3.1, shift: 0, bokeh: 3.6, range: 0.32 })
+ : Object.assign(rig(), { az: 56, el: 5, d: 8.4, tx: 2.4, ty: 1.6, tz: 1.3, shift: -0.37, bokeh: 4, range: 0.3 });
+const introRig = Object.assign(rig(), { az: -28, el: 46, d: 19, tx: 0, ty: 0, tz: 0.2, shift: 0, bokeh: 1, range: 0.6 });
+const freeRig = Object.assign(rig(), { az: 0, el: MOBILE ? 66 : 54, d: MOBILE ? 29 : 16.4, tx: MOBILE ? 0 : 0.2, ty: 0, tz: MOBILE ? -1.4 : 0.7, shift: MOBILE ? 0 : -0.15, bokeh: 1.2, range: 0.7 });
+const setRig = Object.assign(rig(), { az: 36, el: 12, d: 9.4, tx: 1.4, ty: 0.3, tz: 1.3, shift: MOBILE ? 0 : -0.2, bokeh: 3.6, range: 0.3 });
+const salonRig = Object.assign(rig(), { az: -30, el: 33, d: 58, tx: 9, ty: 0, tz: 2, shift: MOBILE ? 0 : 0.2, bokeh: 1.4, range: 0.9 });
+const footRig = Object.assign(rig(), { az: 22, el: 20, d: 44, tx: 4, ty: 0, tz: 0, shift: 0, bokeh: 2.4, range: 0.4 });
+const _ra = rig(), _rb = rig(), _rc = rig();
+function replayRig(P, action, o) {
+ const k = clamp(Math.floor(P), 0, END_P), u = P - k;
+ fromShot(shotAt[Math.max(0, k - 1)], _ra);
+ fromShot(shotAt[k], _rb);
+ lerpRig(_ra, _rb, smooth(0, 0.5, u), o);
+ const close = clamp((12 - o.d) / 6);
+ o.shift = shiftReplay() * (0.6 + 0.4 * (1 - close));
+ o.bokeh = lerp(1.2, 3.4, close);
+ o.range = lerp(0.6, 0.32, close);
+ o.fov = 30;
+ if (action) { o.tx = lerp(o.tx, action.x, 0.22); o.tz = lerp(o.tz, action.z, 0.22); o.ty = lerp(o.ty, action.y * 0.5 + 0.2, 0.3); }
+ return o;
+}
+const cam = rig();
+const camT = new THREE.Vector3();
+let camInit = false;
+
+// ─── Scroll structure ──────────────────────────────────────────────────────────
+const secEls = ['.hero', '.replay', '.free', '.set', '.salon', '.foot'].map(s => document.querySelector(s));
+let tops = [];
+function measure() { tops = secEls.map(el => el.getBoundingClientRect().top + scrollY); }
+addEventListener('resize', measure);
+const replayEl = secEls[1];
+const GRADES = [
+ { gl: 0.78, gr: 0, gb: 0.5 }, // hero
+ { gl: 0.3, gr: 0.45, gb: 0.62 },// replay
+ { gl: 0.72, gr: 0, gb: 0.25 }, // free
+ { gl: 0.86, gr: 0, gb: 0.3 }, // set
+ { gl: 0.1, gr: 0.85, gb: 0.3 }, // salon
+ { gl: 0.3, gr: 0.3, gb: 0.9 }, // foot
+];
+function sectionCoord() {
+ const y = scrollY, vh = innerHeight;
+ let s = 0;
+ for (let b = 1; b < tops.length; b++) s += smooth(tops[b] - vh * 0.85, tops[b] - vh * 0.08, y);
+ return s;
+}
+// Replay progress -> target ply. The epilogue and a short hold close the section.
+function targetPly() {
+ const q = elementProgress(replayEl);
+ return clamp(Math.round(q * (END_P + 1) - 0.25), 0, END_P);
+}
+function scrollForPly(t) {
+ const r = replayEl.getBoundingClientRect();
+ const top = r.top + scrollY, span = r.height - innerHeight;
+ return top + span * clamp((t + 0.5) / (END_P + 1));
+}
+
+// ─── UI: score, caption, tag ───────────────────────────────────────────────────
+const listEl = document.querySelector('.score-list');
+const plyBtns = [];
+for (let m = 0; m < Math.ceil(PLY_COUNT / 2); m++) {
+ const li = document.createElement('li');
+ li.innerHTML = `<span class="n">${m + 1}.</span>`;
+ for (const k of [2 * m, 2 * m + 1]) {
+ if (k >= PLY_COUNT) { li.appendChild(document.createElement('span')); continue; }
+ const b = document.createElement('button');
+ b.type = 'button';
+ const san = PLIES[k][2];
+ const mark = san.match(/[!?]+$/)?.[0];
+ b.textContent = mark ? san.slice(0, -mark.length) : san;
+ if (mark) { b.classList.add('big'); b.dataset.mark = mark; }
+ b.setAttribute('aria-label', `Move ${m + 1}${k % 2 ? ', Black' : ', White'}: ${san}`);
+ b.addEventListener('click', () => window.__lenis?.scrollTo(scrollForPly(k + 1), { duration: 1.4 }));
+ li.appendChild(b);
+ plyBtns[k] = b;
+ }
+ listEl.appendChild(li);
+}
+const scoreWin = document.querySelector('.score-window');
+const barEl = document.querySelector('.score-bar i');
+const moveEl = document.querySelector('.score-move'), countEl = document.querySelector('.score-count');
+const capNum = document.querySelector('.caption-num'), capText = document.querySelector('.caption-text'), capNote = document.querySelector('.caption-note');
+const tagEl = document.querySelector('.tag'), tagSan = document.querySelector('.tag-san');
+let shownPly = -2, listY = 0;
+function setCaption(kc) {
+ if (kc === shownPly) return;
+ const dirUp = kc > shownPly;
+ shownPly = kc;
+ let num, text, note;
+ if (kc < 0) { num = 'White to move'; text = '1.'; note = 'The pieces are set. London, a June afternoon, 1851. Scroll to play each move.'; }
+ else if (kc >= PLY_COUNT) { num = '1–0'; text = 'Immortal.'; note = EPILOGUE; }
+ else { const m = Math.floor(kc / 2) + 1; num = `${m}${kc % 2 ? '…' : '.'} ${kc % 2 ? 'Black' : 'White'}`; text = PLIES[kc][2]; note = PLIES[kc][3]; }
+ const els = [capNum.parentElement, capNote];
+ gsap.killTweensOf(els);
+ gsap.to(els, { y: dirUp ? -14 : 14, opacity: 0, duration: 0.18, ease: 'power2.in', stagger: 0.03, onComplete: () => {
+ capNum.textContent = num; capText.textContent = text; capNote.textContent = note;
+ gsap.fromTo(els, { y: dirUp ? 18 : -18, opacity: 0 }, { y: 0, opacity: 1, duration: 0.6, ease: 'expo.out', stagger: 0.05 });
+ } });
+ plyBtns.forEach((b, i) => { b.classList.toggle('on', i === kc); b.classList.toggle('done', i < kc); });
+ if (kc < 0) { moveEl.textContent = 'Before the first move'; countEl.textContent = '0 / 23'; }
+ else if (kc >= PLY_COUNT) { moveEl.textContent = 'Checkmate · 1–0'; countEl.textContent = '23 / 23'; }
+ else { moveEl.textContent = kc % 2 ? 'Black moves' : 'White moves'; countEl.textContent = `${Math.floor(kc / 2) + 1} / 23`; }
+}
+
+// Set section: two cards anchored to the nearest white and black pieces.
+const noteCards = [...document.querySelectorAll('.note-card')];
+
+// ─── Free play ────────────────────────────────────────────────────────────────
+const free = { inited: false, W: 0, active: false, board: {}, drag: null, hover: null, hoverType: 6, dragged: false };
+function freeTarget(p, st, oP, oQ) {
+ if (st.lying) tipPose(p, sqPos(st.sq, _v2).clone(), st.dir ?? EPI_DIR, p.T.rest, p.yaw, oP, oQ);
+ else if (st.sq) upright(p, sqPos(st.sq, _v2), oP, oQ);
+ else gravePose(p, st.slot, oP, oQ);
+}
+function finalFreeStates() {
+ const out = {};
+ for (const p of PIECES) {
+ const sq = states[PLY_COUNT].sq[p.id];
+ out[p.id] = sq ? { sq, lying: p.id === 'be8', dir: EPI_DIR } : { sq: null, slot: states[PLY_COUNT].grave[p.id] };
+ }
+ return out;
+}
+function startFreeStates() {
+ const out = {};
+ for (const p of PIECES) out[p.id] = { sq: p.start };
+ return out;
+}
+function rebuildFreeBoard() {
+ free.board = {};
+ for (const p of PIECES) if (p.fs.sq) free.board[p.fs.sq] = p.id;
+}
+function initFree() {
+ free.inited = true;
+ const fs = finalFreeStates();
+ for (const p of PIECES) { p.fs = fs[p.id]; replayPose(p, END_P, p.fp, p.fq); }
+ rebuildFreeBoard();
+}
+function nextSlot(color) {
+ const used = new Set(PIECES.filter(p => p.color === color && p.fs && !p.fs.sq && p !== free.drag?.p).map(p => p.fs.slot));
+ let i = 0; while (used.has(i)) i++;
+ return i;
+}
+function flyTo(p, st, { dur = 0.9, arc = 0.6, delay = 0, ease: e = 'power2.inOut', land = true } = {}) {
+ p.fs = st;
+ const fromP = p.fp.clone(), fromQ = p.fq.clone();
+ const toP = new THREE.Vector3(), toQ = new THREE.Quaternion();
+ freeTarget(p, st, toP, toQ);
+ p.tween?.kill();
+ const o = { t: 0 };
+ p.tween = gsap.to(o, { t: 1, duration: dur, delay, ease: e, onUpdate: () => {
+ p.fp.lerpVectors(fromP, toP, o.t);
+ p.fp.y += arc * Math.sin(Math.PI * o.t);
+ p.fq.slerpQuaternions(fromQ, toQ, o.t);
+ }, onComplete: () => { p.tween = null; if (land && st.sq) { sound.clack(0.8); ripple(toP.x, toP.z, 0.7); } } });
+}
+const arrP = new THREE.Vector3(), arrQ = new THREE.Quaternion();
+function arrange(which) {
+ const target = which === 'start' ? startFreeStates() : finalFreeStates();
+ free.drag = null;
+ const order = [...PIECES].sort((a, b) => (target[a.id].sq ? 1 : 0) - (target[b.id].sq ? 1 : 0) || a.id.localeCompare(b.id));
+ order.forEach((p, i) => {
+ freeTarget(p, target[p.id], arrP, arrQ);
+ const d = p.fp.distanceTo(arrP);
+ flyTo(p, target[p.id], { dur: 0.9 + Math.min(d, 8) * 0.06, arc: d < 0.05 ? 0 : 0.35 + Math.min(d, 8) * 0.12, delay: i * 0.028, land: false });
+ });
+ gsap.delayedCall(1.3, () => sound.clack(0.5));
+ rebuildFreeBoardFrom(target);
+}
+function rebuildFreeBoardFrom(target) { free.board = {}; for (const [id, st] of Object.entries(target)) if (st.sq) free.board[st.sq] = id; }
+document.querySelectorAll('[data-arrange]').forEach(b => b.addEventListener('click', () => {
+ if (!free.inited) { P = END_P; initFree(); }
+ arrange(b.dataset.arrange);
+}));
+
+// Picking: ray against a capsule around each piece's axis (fast, no triangle raycast needed).
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
+const hitPt = new THREE.Vector3();
+function pick(px, py) {
+ ndc.set(px / innerWidth * 2 - 1, -(py / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ const o = ray.ray.origin, d = ray.ray.direction;
+ let best = null, bestT = Infinity;
+ for (const p of PIECES) {
+ const a = p.pos, b = _v1.set(0, p.T.h * 0.92, 0).applyQuaternion(p.quat).add(p.pos);
+ const t = rayCapsule(o, d, a, b, Math.max(0.3, p.T.rB * 0.95));
+ if (t < bestT) { bestT = t; best = p; }
+ }
+ return best;
+}
+function rayCapsule(o, d, a, b, r) {
+ const ab = _v2.subVectors(b, a), ao = _v3.subVectors(o, a);
+ const dd = d.dot(d), ee = ab.dot(ab), de = d.dot(ab), dao = d.dot(ao), eao = ab.dot(ao);
+ const den = dd * ee - de * de;
+ let t = den > 1e-6 ? (de * eao - ee * dao) / den : 0;
+ t = Math.max(0, t);
+ let s = clamp((eao + t * de) / ee);
+ t = Math.max(0, (s * de - dao) / dd);
+ const pc = _v4.copy(o).addScaledVector(d, t), qc = _v1.copy(a).addScaledVector(ab, s);
+ return pc.distanceTo(qc) < r ? t : Infinity;
+}
+function rayBoard(px, py, y = 0) {
+ ndc.set(px / innerWidth * 2 - 1, -(py / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ plane.constant = -y;
+ return ray.ray.intersectPlane(plane, hitPt);
+}
+let cur;
+addEventListener('pointerdown', e => {
+ if (!free.active || e.button > 0 || e.target !== canvas) return;
+ const p = pick(e.clientX, e.clientY);
+ if (!p) return;
+ p.tween?.kill(); p.tween = null;
+ const from = { ...p.fs };
+ if (p.fs.sq && free.board[p.fs.sq] === p.id) delete free.board[p.fs.sq];
+ free.drag = { p, from, x: p.fp.x, z: p.fp.z, vx: 0, vz: 0 };
+ free.dragged = true;
+ p.fs = { sq: null, slot: -1, held: true };
+ window.__lenis?.stop();
+ document.body.classList.add('dragging', 'has-dragged');
+ cur?.set('drag', 'Place');
+ sound.lift();
+ e.preventDefault();
+});
+addEventListener('pointermove', e => {
+ if (free.drag) {
+ const h = rayBoard(e.clientX, e.clientY, 0.0);
+ if (h) { free.drag.x = clamp(h.x, -EDGE - 3, EDGE + 3); free.drag.z = clamp(h.z, -EDGE - 1, EDGE + 1); }
+ return;
+ }
+ if (!free.active || e.target !== canvas) { if (free.hoverPiece) { free.hoverPiece = null; cur?.set(''); } return; }
+ const p = pick(e.clientX, e.clientY);
+ if (p !== free.hoverPiece) { free.hoverPiece = p; cur?.set(p ? 'drag' : '', p ? 'Lift' : ''); }
+}, { passive: true });
+addEventListener('touchmove', e => { if (free.drag) e.preventDefault(); }, { passive: false });
+function endDrag() {
+ const dr = free.drag;
+ if (!dr) return;
+ free.drag = null;
+ const p = dr.p;
+ window.__lenis?.start();
+ document.body.classList.remove('dragging');
+ cur?.set(free.hoverPiece ? 'drag' : '', free.hoverPiece ? 'Lift' : '');
+ const sq = xzSquare(p.fp.x, p.fp.z);
+ const occ = sq ? free.board[sq] : null;
+ const back = () => {
+ if (dr.from.sq) { free.board[dr.from.sq] = p.id; flyTo(p, { sq: dr.from.sq }, { dur: 0.6, arc: 0.3 }); }
+ else flyTo(p, { sq: null, slot: nextSlot(p.color) }, { dur: 0.7, arc: 0.4, land: false });
+ };
+ if (!sq) { back(); return; }
+ if (occ && byId[occ].color === p.color) { back(); return; }
+ if (occ) capture(byId[occ], p);
+ free.board[sq] = p.id;
+ flyTo(p, { sq }, { dur: 0.32, arc: 0, ease: 'power2.in' });
+}
+addEventListener('pointerup', endDrag);
+addEventListener('pointercancel', endDrag);
+function capture(v, by) {
+ const at = sqPos(v.fs.sq, new THREE.Vector3());
+ const dir = new THREE.Vector3(at.x - by.fp.x, 0, at.z - by.fp.z);
+ if (dir.lengthSq() < 1e-4) dir.set(v.color === 'w' ? 1 : -1, 0, 0);
+ dir.normalize();
+ delete free.board[v.fs.sq];
+ const wasLying = v.fs.lying;
+ const slot = nextSlot(v.color);
+ v.fs = { sq: null, slot };
+ v.tween?.kill();
+ const fromP = v.fp.clone(), fromQ = v.fq.clone();
+ const tp = new THREE.Vector3(), tq = new THREE.Quaternion(), gp = new THREE.Vector3(), gq = new THREE.Quaternion();
+ if (wasLying) { tp.copy(fromP); tq.copy(fromQ); } else tipPose(v, at, dir, v.T.rest, v.yaw, tp, tq);
+ gravePose(v, slot, gp, gq);
+ const o = { t: 0 };
+ sound.topple();
+ v.tween = gsap.to(o, { t: 1, duration: 1.5, ease: 'none', delay: 0.18, onUpdate: () => {
+ const a = clamp(o.t / 0.3), g = ease.io3(clamp((o.t - 0.28) / 0.72));
+ if (!wasLying) tipPose(v, at, dir, v.T.rest * ease.fall(a), v.yaw, v.fp, v.fq);
+ else { v.fp.copy(fromP); v.fq.copy(fromQ); }
+ if (g > 0) {
+ const d = tp.distanceTo(gp);
+ v.fp.lerpVectors(tp, gp, g); v.fp.y += Math.sin(Math.PI * g) * (0.85 + d * 0.07);
+ v.fq.slerpQuaternions(tq, gq, g);
+ }
+ }, onComplete: () => { v.tween = null; } });
+}
+function updateDrag(dt) {
+ const dr = free.drag;
+ if (!dr) return;
+ const p = dr.p;
+ const px = p.fp.x, pz = p.fp.z;
+ p.fp.x = damp(p.fp.x, dr.x, 16, dt);
+ p.fp.z = damp(p.fp.z, dr.z, 16, dt);
+ p.fp.y = damp(p.fp.y, 0.78, 10, dt);
+ dr.vx = damp(dr.vx, (p.fp.x - px) / Math.max(dt, 1e-3), 8, dt);
+ dr.vz = damp(dr.vz, (p.fp.z - pz) / Math.max(dt, 1e-3), 8, dt);
+ // Held from the crown: the base swings behind the motion.
+ _q1.setFromAxisAngle(UP, p.yaw);
+ _axis.set(dr.vz, 0, -dr.vx);
+ const sp = _axis.length();
+ if (sp > 1e-4) { _axis.divideScalar(sp); _q2.setFromAxisAngle(_axis, clamp(sp * 0.05, 0, 0.32)); _q1.premultiply(_q2); }
+ p.fq.slerp(_q1, 1 - Math.exp(-12 * dt));
+}
+
+// ─── Effects: ripple and sound hooks ───────────────────────────────────────────
+function ripple(x, z, s = 1) { hlMat.uniforms.uRip.value.set(x, z, 0, s); }
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+let P = +(DBG.get('ply') ?? 0), T = 0;
+let frozen = DBG.has('ply');
+let lastP = P;
+const action = new THREE.Vector3();
+const hlList = [];
+const sqIdx = sq => [FILES.indexOf(sq[0]), +sq[1] - 1];
+function setHighlights(t) {
+ hlList.length = 0;
+ const kc = Math.ceil(P - 1e-4) - 1;
+ const inFree = free.W > 0.5;
+ if (!inFree && kc >= 0 && kc < PLY_COUNT) {
+ const ply = plies[kc];
+ const uIn = kc === Math.floor(P) ? P - kc : 1;
+ hlList.push([ply.from, smooth(0, 0.3, uIn), 1], [ply.to, smooth(0.5, 0.95, uIn), 2]);
+ if (ply.check && !ply.mate) {
+ const ks = states[kc + 1].sq[ply.side === 'w' ? 'be8' : 'we1'];
+ hlList.push([ks, smooth(0.7, 1, uIn), 3]);
+ }
+ }
+ const net = inFree ? 0 : smooth(PLY_COUNT - 0.35, PLY_COUNT, P);
+ if (net > 0) {
+ const pulse = 0.78 + 0.22 * Math.sin(t * 2.2);
+ hlList.push(['d8', net, 3], ['e7', net * pulse, 4], ['d5', net * pulse, 4], ['g7', net * pulse, 4], ['c7', net, 5], ['e8', net, 5]);
+ }
+ // Until the first lift, the white king's square breathes: "start here".
+ if (free.active && !free.dragged && !free.drag && byId.we1?.fs?.sq) hlList.push([byId.we1.fs.sq, 0.35 + 0.65 * (0.5 + 0.5 * Math.sin(t * 3.2)), 6]);
+ if (free.drag) {
+ const sq = xzSquare(free.drag.p.fp.x, free.drag.p.fp.z);
+ if (sq) { const occ = free.board[sq]; hlList.push([sq, 1, occ ? (byId[occ].color === free.drag.p.color ? 5 : 7) : 6]); }
+ }
+ const u = hlMat.uniforms.uH.value;
+ for (let i = 0; i < HN; i++) {
+ const h = hlList[i];
+ if (!h) { u[i].z = 0; continue; }
+ const [f, r] = sqIdx(h[0]);
+ u[i].set(f, r, h[1], h[2]);
+ }
+}
+
+const gradeEl = document.querySelector('.grade');
+const root = document.documentElement.style;
+const body = document.body;
+const heroInner = document.querySelector('.hero-inner');
+const navLinks = [...document.querySelectorAll('.links a')];
+let introK = DBG.has('ply') || DBG.has('nointro') ? 1 : 0;
+const tmpRig = rig();
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ hlMat.uniforms.uTime.value = t;
+ hlMat.uniforms.uRip.value.z += dt;
+
+ // Replay clock: the displayed ply chases the scroll target at a tempo that always finishes a move.
+ T = frozen ? P : targetPly();
+ const sNow = sectionCoord();
+ // Off-screen, the game jumps straight to where the scroll says it is; on screen it is always played.
+ if (!frozen && (sNow < 0.3 || sNow > 1.7)) P = T;
+ if (!frozen) {
+ const kNow = clamp(Math.floor(P), 0, PLY_COUNT);
+ const base = 1.05 / (DUR[kNow] ?? 1);
+ const gap = T - P;
+ const speed = Math.min(16, Math.max(base, Math.abs(gap) * 1.6));
+ P = Math.abs(gap) < speed * dt ? T : P + Math.sign(gap) * speed * dt;
+ }
+ // Sounds and ripples on landing (forward only).
+ if (P > lastP) {
+ for (let k = Math.floor(lastP); k <= Math.floor(P) && k < PLY_COUNT; k++) {
+ const ply = plies[k];
+ const land = ply.victim ? 0.6 : 0.97, hit = 0.5;
+ if (lastP < k + land && P >= k + land) { const [x, z] = squareXZ(ply.to); ripple(x, z, ply.knight ? 1.2 : 0.8); sound.clack(ply.knight ? 1 : 0.7); }
+ if (ply.victim && lastP < k + hit && P >= k + hit) sound.topple();
+ }
+ if (lastP < PLY_COUNT + 0.72 && P >= PLY_COUNT + 0.72) sound.topple(0.7);
+ }
+ lastP = P;
+
+ // Section blend & free-play weight.
+ const s = sNow;
+ const si = Math.min(Math.floor(s), secEls.length - 2), sf = s - si;
+ const pastReplay = s > 1.5;
+ if (pastReplay && !free.inited && P >= END_P - 0.01) initFree();
+ free.W = damp(free.W, pastReplay && free.inited ? 1 : 0, 4.5, dt);
+ free.active = free.inited && s > 1.75 && s < 2.4;
+ if (!free.active && free.drag) endDrag();
+ if (!free.active && free.hoverPiece) { free.hoverPiece = null; cur?.set(''); }
+ body.classList.toggle('in-replay', s > 0.6 && s < 1.55);
+ body.classList.toggle('show-intro', s > 0.6 && s < 1.5 && P < 1.5);
+ body.classList.toggle('in-free', s > 1.7 && s < 2.45);
+ body.classList.toggle('at-top', scrollY < 40);
+ const gA = GRADES[si], gB = GRADES[si + 1];
+ const gm = MOBILE ? 1.45 : 1;
+ root.setProperty('--gl', Math.min(0.92, lerp(gA.gl, gB.gl, sf) * gm).toFixed(3));
+ root.setProperty('--gr', Math.min(0.92, lerp(gA.gr, gB.gr, sf) * gm).toFixed(3));
+ root.setProperty('--gb', Math.min(0.92, lerp(gA.gb, gB.gb, sf) * gm).toFixed(3));
+ navLinks.forEach((a, i) => a.classList.toggle('on', Math.round(s) === [1, 3, 4][i]));
+ heroInner.style.opacity = (1 - smooth(0.05, 0.55, s)).toFixed(3);
+
+ // Pieces.
+ updateDrag(dt);
+ let mover = null;
+ const kA = Math.floor(P);
+ if (P > kA && kA < PLY_COUNT) mover = byId[plies[kA].mover];
+ for (const p of PIECES) {
+ replayPose(p, P, p.pos, p.quat);
+ if (free.inited && free.W > 0.001) { p.pos.lerp(p.fp, free.W); p.quat.slerp(p.fq, free.W); }
+ p.mesh.position.copy(p.pos);
+ p.mesh.quaternion.copy(p.quat);
+ if (p.drop > 0) p.mesh.position.y += p.drop;
+ }
+ updateTrail(P);
+ setHighlights(t);
+
+ // Camera.
+ if (mover) action.copy(mover.pos);
+ else if (kA > 0 && kA <= PLY_COUNT) sqPos(plies[Math.min(kA, PLY_COUNT) - 1].to, action);
+ else action.set(0.4, 0, 0.5);
+ const rigs = [heroRig, replayRig(P, s > 0.5 && s < 1.6 ? action : null, _rc), freeRig, setRig, salonRig, footRig];
+ const target = lerpRig(rigs[si], rigs[si + 1], sf, tmpRig);
+ if (introK < 1) lerpRig(introRig, target, ease.io3(introK), target);
+ if (DBG.has('cam')) { const c = DBG.get('cam').split(',').map(Number); Object.assign(target, { az: c[0], el: c[1], d: c[2], tx: c[3], tz: c[4], ty: c[5] ?? 0.3, shift: c[6] ?? 0 }); }
+ if (MOBILE) { target.d *= 1.5; target.el = Math.min(88, target.el + 8); }
+ if (!camInit) { Object.assign(cam, target); camInit = true; }
+ const lam = introK < 1 ? 30 : 2.8;
+ let daz = target.az - cam.az; daz = ((daz + 540) % 360) - 180;
+ cam.az += daz * (1 - Math.exp(-lam * dt));
+ for (const k of ['el', 'd', 'tx', 'ty', 'tz', 'shift', 'fov', 'bokeh', 'range']) cam[k] = damp(cam[k], target[k], lam, dt);
+ const drag = free.drag ? 0.2 : 1;
+ const az = (cam.az + pointer.sx * 3.2 * drag + Math.sin(t * 0.11) * 1.1) * D;
+ const el = clamp(cam.el + pointer.sy * 1.8 * drag + Math.sin(t * 0.17) * 0.5, 3, 89) * D;
+ camT.set(cam.tx, cam.ty, cam.tz);
+ camera.position.set(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(cam.d).add(camT);
+ camera.lookAt(camT);
+ if (Math.abs(camera.fov - cam.fov) > 0.01) camera.fov = cam.fov;
+ const { w, h } = engine.size;
+ camera.setViewOffset(w, h, cam.shift * w, 0, w, h);
+ camera.updateProjectionMatrix();
+ if (dof) {
+ dof.cocMaterial.focusDistance = camera.position.distanceTo(_v1.copy(camT).lerp(action, 0.4));
+ dof.cocMaterial.focusRange = cam.d * cam.range;
+ dof.bokehScale = cam.bokeh;
+ }
+
+ // Lights: rims follow the camera around the board.
+ const fwd = _v1.set(camT.x - camera.position.x, 0, camT.z - camera.position.z).normalize();
+ const side = _v2.set(-fwd.z, 0, fwd.x);
+ rimA.position.copy(camT).addScaledVector(fwd, 9).addScaledVector(side, 5).setY(5.6);
+ rimB.position.copy(camT).addScaledVector(fwd, 8).addScaledVector(side, -6).setY(4.6);
+ rimA.target.position.copy(camT); rimB.target.position.copy(camT);
+ vol.uniforms.get('uDensity').value = 0.011 * (1 - smooth(22, 48, cam.el));
+ key.intensity = KEY_ON * lights.k;
+ dust.uniforms.uTime.value = t;
+ dust.uniforms.uLDir.value.subVectors(key.target.position, key.position).normalize();
+ dust.uniforms.uPower.value = lights.k * (1 - smooth(30, 60, cam.el)) * (1 - smooth(20, 40, cam.d));
+ rimA.intensity = RIM_A * lights.k; rimB.intensity = RIM_B * lights.k;
+
+ // HTML that follows the 3D.
+ if (body.classList.contains('in-replay')) {
+ const kc = Math.ceil(P - 1e-4) - 1;
+ setCaption(kc);
+ barEl.style.transform = `scaleX(${clamp(P / END_P).toFixed(4)})`;
+ const cur = Math.max(0, Math.min(kc, PLY_COUNT - 1));
+ const rowH = 30, wantY = Math.floor(cur / 2) * rowH - scoreWin.clientHeight * 0.42 + 30;
+ listY = damp(listY, Math.max(0, wantY), 6, dt);
+ listEl.style.transform = `translate3d(0, ${(-listY).toFixed(1)}px, 0)`;
+ const showTag = kc >= 0 && kc < PLY_COUNT && (Math.floor(P) !== kc || P - kc > 0.9) && !MOBILE;
+ tagEl.classList.toggle('on', showTag);
+ if (showTag) {
+ const p = byId[plies[kc].mover];
+ _v1.copy(p.pos).setY(p.pos.y + p.T.h + 0.1).project(camera);
+ tagSan.textContent = plies[kc].san;
+ tagEl.style.transform = `translate3d(calc(${((_v1.x + 1) / 2 * innerWidth).toFixed(1)}px - 50%), calc(${((1 - _v1.y) / 2 * innerHeight).toFixed(1)}px - 100%), 0)`;
+ }
+ } else tagEl.classList.remove('on');
+ updateNoteCards(s);
+
+ salon?.update(camera, KEY_ON * lights.k);
+ scene.fog.density = lerp(0.012, 0.0035, smooth(12, 60, cam.d));
+ const orbK = 1 - smooth(24, 38, cam.el);
+ for (const o of orbs) { o.visible = orbK > 0.01; o.material.color.setRGB(1, 0.66, 0.36).multiplyScalar(o.userData.k * orbK); }
+ if (!DBG.has('norefl')) reflection.update(scene, camera);
+});
+
+const cardPos = [{ x: 0, y: 0, init: false }, { x: 0, y: 0, init: false }];
+function updateNoteCards(s) {
+ const on = !MOBILE && s > 2.7 && s < 3.35;
+ const aims = [[0.12, 0.3], [0.5, -0.28]];
+ let taken = null;
+ noteCards.forEach((el, i) => {
+ el.classList.toggle('on', on);
+ if (!on) { cardPos[i].init = false; return; }
+ // an upright piece of that colour near the card's preferred spot, and never next to the other card's piece
+ let best = null, bestS = Infinity;
+ for (const p of PIECES) {
+ if (p.color !== (i ? 'b' : 'w') || !p.fs?.sq || p.fs.lying || free.drag?.p === p) continue;
+ _v1.copy(p.pos).setY(p.T.h * 0.8).project(camera);
+ if (Math.abs(_v1.x) > 0.8 || Math.abs(_v1.y) > 0.75) continue;
+ let score = Math.hypot(_v1.x - aims[i][0], _v1.y - aims[i][1]) + p.pos.distanceTo(camera.position) * 0.03;
+ if (taken && Math.hypot(_v1.x - taken.x, (_v1.y - taken.y) * 1.6) < 0.45) score += 3;
+ if (score < bestS) { bestS = score; best = { x: _v1.x, y: _v1.y }; }
+ }
+ if (!best) { el.classList.remove('on'); return; }
+ taken = best;
+ const x = Math.min((best.x + 1) / 2 * innerWidth + 60, innerWidth - el.offsetWidth - 24);
+ const y = clamp((1 - best.y) / 2 * innerHeight - el.offsetHeight / 2, 90, innerHeight - el.offsetHeight - 40);
+ const c = cardPos[i];
+ if (!c.init) { c.x = x; c.y = y; c.init = true; }
+ c.x += (x - c.x) * 0.12; c.y += (y - c.y) * 0.12;
+ el.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0)`;
+ });
+}
+
+// ─── The salon ────────────────────────────────────────────────────────────────
+let salon = null;
+function makeSalon() {
+ const pieceTypes = {};
+ for (const [type, root] of Object.entries(FAR)) {
+ root.updateMatrixWorld(true);
+ const mesh = firstMesh(root);
+ const geo = toFloatGeometry(mesh.geometry, mesh.matrixWorld);
+ const { cx, cz, y0, s } = TYPES[type].xf;
+ geo.translate(-cx, -y0, -cz); geo.scale(s, s, s);
+ geo.computeVertexNormals();
+ pieceTypes[type] = geo;
+ }
+ // Every other table is somewhere in the same game.
+ const at = [3, 9, 13, 17, 21, 24, 29, 33, 36, 39, 43];
+ const placements = [];
+ const pos = new THREE.Vector3(), quat = new THREE.Quaternion(), one = new THREE.Vector3(1, 1, 1), rq = new THREE.Quaternion();
+ TABLES.forEach((t, i) => {
+ const st = states[at[i % at.length]];
+ rq.setFromAxisAngle(UP, (i % 3 - 1) * 0.12);
+ for (const p of PIECES) {
+ restPose(p, st, pos, quat);
+ pos.applyQuaternion(rq).add(t);
+ quat.premultiply(rq);
+ placements.push({ type: p.type, color: p.color, matrix: new THREE.Matrix4().compose(pos, quat, one) });
+ }
+ });
+ return buildSalon({ scene, camera, tableY: TABLE_Y, edge: EDGE, pieceTypes, placements, boardTex: bt.albedo });
+}
+
+// ─── Utilities ────────────────────────────────────────────────────────────────
+function mulberry(a) { return () => { a |= 0; 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; }; }
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('gambit', { theme: 'dark', corner: 'bl' });
+cur = cursor({ color: '#dcc08a', blend: 'normal', size: 30 });
+magnetic();
+smoothScroll({ lerp: 0.08 });
+// In-page links glide when the target is near and cut when it is far (no whip-pan through forty-five shots).
+document.addEventListener('click', e => {
+ const a = e.target.closest?.('a[href^="#"]');
+ if (!a) return;
+ const el = document.querySelector(a.getAttribute('href'));
+ if (!el) return;
+ e.preventDefault();
+ const y = el.getBoundingClientRect().top + scrollY + (el.id === 'game' ? innerHeight * 0.6 : 0);
+ const far = Math.abs(y - scrollY) > innerHeight * 3;
+ window.__lenis?.scrollTo(y, far ? { immediate: true } : { duration: 1.6 });
+});
+const soundBtn = document.querySelector('.sound');
+soundBtn.addEventListener('click', () => { const on = sound.toggle(); soundBtn.setAttribute('aria-pressed', String(on)); if (on) sound.clack(0.8); });
+reveal('.panel h2', { type: 'lines', stagger: 0.1 });
+reveal('.lede', { type: 'lines', stagger: 0.05, y: '100%' });
+measure();
+const fontsReady = Promise.race([Promise.all([document.fonts.load('italic 500 60px "Bodoni Moda"'), document.fonts.ready]), new Promise(r => setTimeout(r, 2500))])
+ .then(() => { measure(); buildCoordinates(); });
+
+await Promise.all([...typeLoads, ...farLoads, fontsReady]);
+makePieces();
+salon = makeSalon();
+if (DBG.has('free')) { P = END_P; }
+// Warm every program with the lights on and every piece in view.
+lights.k = 1;
+for (const p of PIECES) { replayPose(p, 0, p.pos, p.quat); p.mesh.position.copy(p.pos); p.mesh.quaternion.copy(p.quat); }
+camera.position.set(0, 14, 14); camera.lookAt(0, 0, 0);
+renderer.compile(scene, camera);
+lights.k = 0;
+measure();
+engine.start();
+window.__gambit = { get P() { return P; }, setP(v) { P = v; }, freeze(v) { frozen = v !== null; if (frozen) P = v; }, byId, free, arrange, scrollForPly };
+window.__gambit.screenOf = (id, sq) => {
+ const v = sq ? sqPos(sq, new THREE.Vector3()) : byId[id].pos.clone().setY(byId[id].pos.y + byId[id].T.h * 0.55);
+ v.project(camera);
+ return [(v.x + 1) / 2, (1 - v.y) / 2];
+};
+window.__gotoPly = v => window.__lenis?.scrollTo(scrollForPly(v), { immediate: true });
+// Everything the intro reveals starts hidden before the loader lifts.
+const introEls = '.hero .eyebrow, .hero-sub, .hero-cta, .nav, .scroll-cue';
+gsap.set('.hero-title .ln > span', { yPercent: 105 });
+gsap.set(introEls, { opacity: 0, y: 16 });
+if (introK < 1) for (const p of PIECES) p.drop = 2.4;
+await loader.finish();
+
+// Intro: the lamp comes up, the pieces are set down in a wave, the camera settles low across the board.
+function startIntro() {
+ if (introK < 1) {
+ for (const p of PIECES) {
+ const [x, z] = squareXZ(p.start);
+ gsap.to(p, { drop: 0, duration: 1.25, ease: 'power3.out', delay: 0.3 + (Math.hypot(x - 0.5, z - 0.5) * 0.085) + (p.color === 'b' ? 0.1 : 0) });
+ }
+ gsap.to(lights, { k: 1, duration: 2.6, ease: 'power2.inOut', delay: 0.2 });
+ gsap.to({ v: 0 }, { v: 1, duration: 4, ease: 'none', onUpdate() { introK = this.targets()[0].v; } });
+ } else lights.k = 1;
+ gsap.to('.hero-title .ln > span', { yPercent: 0, duration: 1.8, ease: 'expo.out', stagger: 0.12, delay: 1.9 });
+ gsap.to(introEls, { opacity: 1, y: 0, duration: 1.4, ease: 'power3.out', stagger: 0.08, delay: 2.3 });
+}
diff --git a/examples/gambit/materials.js b/examples/gambit/materials.js
new file mode 100644
index 0000000..5d6d588
--- /dev/null
+++ b/examples/gambit/materials.js
@@ -0,0 +1,182 @@
+// Marble, walnut and brass for the board, plus the Carrara -> Nero Marquina material transform for the black set.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+
+export const BRASS = new THREE.Color('#b89b6a');
+
+/** The playing field: 8x8 inlaid slabs of Botticino (light) and Emperador (dark), each with its own veining. */
+export function boardTextures(renderer) {
+ const common = `
+ float h1(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+ // Domain-warped vein field: thin bright lines where the warped fbm crosses zero.
+ float veins(vec2 p, float seed, float per){
+ vec2 q = vec2(fbm(p + seed, per, 5, 0.55), fbm(p + seed * 1.7 + 4.2, per, 5, 0.55));
+ float n = fbm(p * 0.9 + q * 1.8 + seed * 0.3, per, 6, 0.52);
+ return n;
+ }`;
+ const albedo = bakeTexture(renderer, 2048, `${common}
+ // thin line where a warped field crosses zero; w = width
+ float vline(vec2 p, float seed, float w){
+ vec2 q = vec2(fbm(p * 0.7 + seed, 64.0, 4, 0.5), fbm(p * 0.7 + seed + 5.3, 64.0, 4, 0.5));
+ float n = fbm(p + q * 1.6, 64.0, 6, 0.55);
+ return 1.0 - smoothstep(0.0, w, abs(n));
+ }
+ void main(){
+ vec2 g = vUv * 8.0;
+ vec2 id = floor(g); vec2 f = fract(g);
+ float dark = mod(id.x + id.y + 1.0, 2.0); // uv origin is a1, which is dark
+ float s = h1(id), s2 = h1(id + 17.0);
+ float a = s * 6.2831; // each slab cut at its own angle
+ mat2 R = mat2(cos(a), -sin(a), sin(a), cos(a));
+ vec2 p = R * (f - 0.5) * vec2(2.4, 1.3) + id * 3.7;
+ float cloud = fbm(p * 0.8 + 9.0, 64.0, 5, 0.55);
+ float mott = fbm(p * 3.5 + 2.0, 64.0, 4, 0.6);
+ vec3 col;
+ if (dark > 0.5) {
+ // Emperador Dark: chocolate ground, paler patches, and a network of fine calcite veins
+ vec3 base = mix(vec3(0.030, 0.017, 0.010), vec3(0.070, 0.042, 0.026), smoothstep(-0.3, 0.45, cloud + mott * 0.35));
+ base *= 0.85 + 0.3 * s2;
+ float v1 = vline(p * 0.8, s * 13.0, 0.011) * smoothstep(-0.35, 0.2, cloud);
+ float v2 = vline(p * 1.6 + 4.0, s * 29.0, 0.006) * smoothstep(0.0, 0.35, cloud);
+ float v3 = vline(p * 3.1 + 8.0, s * 7.0, 0.004) * 0.5;
+ col = base + v1 * vec3(0.25, 0.215, 0.17) * 0.62 + v2 * vec3(0.2, 0.17, 0.13) * 0.45 + v3 * vec3(0.13, 0.1, 0.07) * 0.4;
+ } else {
+ // Botticino: warm cream, soft honey clouding, tiny fossil specks and hairline stylolites
+ vec3 base = mix(vec3(0.62, 0.54, 0.41), vec3(0.74, 0.67, 0.54), smoothstep(-0.45, 0.35, cloud));
+ base *= 0.95 + 0.07 * s2 + mott * 0.05;
+ float st = vline(p * 0.8 + 2.0, s * 11.0, 0.007);
+ float st2 = vline(p * 1.9, s * 23.0, 0.004) * 0.6;
+ float speck = smoothstep(0.62, 0.72, fbm(p * 14.0, 64.0, 3, 0.6)) * 0.5;
+ col = base * (1.0 - st * 0.32 - st2 * 0.2 - speck * 0.12);
+ }
+ gl_FragColor = vec4(sqrt(max(col, 0.0)), 1.0); // gamma-2 encoded, squared back in the material
+ }`);
+ const rough = bakeTexture(renderer, 1024, `
+ float h1(vec2 p){ return fract(sin(dot(p, vec2(41.3, 17.7))) * 43758.5453); }
+ void main(){
+ vec2 g = vUv * 8.0; vec2 id = floor(g);
+ float s = h1(id);
+ float wear = fbm(vUv * 6.0, 6.0, 5, 0.5);
+ float micro = fbm(vUv * 80.0, 80.0, 3, 0.5);
+ float r = 0.07 + s * 0.035 + max(wear, 0.0) * 0.12 + micro * 0.03;
+ gl_FragColor = vec4(1.0, clamp(r, 0.03, 1.0), 0.0, 1.0);
+ }`);
+ return { albedo, rough };
+}
+
+/** Black walnut: long straight grain with ray flecks and darker pores. uv.x runs along the grain. */
+export function walnutTextures(renderer) {
+ const albedo = bakeTexture(renderer, 1024, `
+ void main(){
+ vec2 p = vUv;
+ float warp = fbm(vec2(p.x * 3.0, p.y * 1.0), 3.0, 4, 0.5) * 0.6;
+ float grain = sin((p.y * 46.0 + warp * 8.0 + fbm(p * vec2(2.0, 18.0), 18.0, 4, 0.5) * 2.5) * 3.14159);
+ float fine = fbm(vec2(p.x * 6.0, p.y * 160.0), 160.0, 3, 0.6);
+ float pores = smoothstep(0.35, 0.6, fbm(vec2(p.x * 90.0, p.y * 420.0), 420.0, 2, 0.5));
+ vec3 lite = vec3(0.105, 0.058, 0.032), dark = vec3(0.038, 0.020, 0.011);
+ vec3 col = mix(dark, lite, 0.5 + 0.5 * grain);
+ col *= 0.82 + fine * 0.5;
+ col *= 1.0 - pores * 0.35;
+ gl_FragColor = vec4(sqrt(max(col, 0.0)), 1.0); // gamma-2 encoded, squared back in the material
+ }`);
+ const normal = fbmNormal(renderer, { size: 512, scale: 24, octaves: 4, strength: 0.35 });
+ return { albedo, normal };
+}
+
+/** Table leather: very dark, fine pebble. */
+export function leatherTextures(renderer) {
+ const normal = fbmNormal(renderer, { size: 512, scale: 48, octaves: 4, strength: 1.4 });
+ const rough = bakeTexture(renderer, 512, `void main(){ float r = 0.62 + fbm(vUv * 12.0, 12.0, 5, 0.55) * 0.25; gl_FragColor = vec4(1., clamp(r, .2, 1.), 0., 1.); }`);
+ return { normal, rough };
+}
+
+/** Board coordinates engraved into the walnut frame (a–h, 1–8) as a brass alpha mask. */
+export function coordinateTexture(frameW) {
+ const N = 2048, c = document.createElement('canvas');
+ c.width = c.height = N;
+ const g = c.getContext('2d');
+ const total = 8 + frameW * 2, px = N / total;
+ g.fillStyle = '#000'; g.fillRect(0, 0, N, N);
+ g.fillStyle = '#fff';
+ g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.font = `italic 500 ${Math.round(px * 0.3)}px "Bodoni Moda", "Didot", serif`;
+ const off = frameW * px * 0.5;
+ for (let i = 0; i < 8; i++) {
+ const cx = (frameW + i + 0.5) * px;
+ g.fillText('abcdefgh'[i], cx, N - off); // near White (bottom of texture = +z)
+ g.save(); g.translate(cx, off); g.rotate(Math.PI); g.fillText('abcdefgh'[i], 0, 0); g.restore();
+ const cy = (frameW + i + 0.5) * px;
+ g.fillText(String(8 - i), off, cy);
+ g.save(); g.translate(N - off, cy); g.rotate(Math.PI); g.fillText(String(8 - i), 0, 0); g.restore();
+ }
+ // fine inner brass line around the playing field is modelled; add a hairline border near the outer edge
+ g.strokeStyle = '#fff'; g.lineWidth = Math.max(2, px * 0.012);
+ const e = px * frameW * 0.16;
+ g.strokeRect(e, e, N - 2 * e, N - 2 * e);
+ const t = new THREE.CanvasTexture(c);
+ t.anisotropy = 16;
+ t.colorSpace = THREE.NoColorSpace;
+ return t;
+}
+
+/**
+ * Convert a Meshy (MeshStandard) marble material into a polished physical one.
+ * `black` remaps the Carrara base colour into Nero Marquina: near-black ground, veins turned to warm gold and bone.
+ */
+// Wrapped diffuse for the white stone: light bleeds past the terminator the way it does through marble.
+const WRAP = THREE.ShaderChunk.lights_physical_pars_fragment.replace(
+ 'reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );',
+ `float wrapNL = saturate( ( dot( geometryNormal, directLight.direction ) + 0.5 ) / 1.5 );
+ vec3 wrapIrr = wrapNL * directLight.color * vec3( 1.0, 0.9, 0.78 );
+ reflectedLight.directDiffuse += mix( irradiance, max( irradiance, wrapIrr ), 0.6 ) * BRDF_Lambert( material.diffuseContribution ) * ( 1.0 - F );`);
+
+export function marbleMaterial(src, { black = false, envIntensity = 1, veins = [0.1, 0.42] } = {}) {
+ const m = new THREE.MeshPhysicalMaterial({
+ map: src.map, normalMap: src.normalMap, normalScale: src.normalScale?.clone() ?? new THREE.Vector2(1, 1),
+ roughnessMap: src.roughnessMap, roughness: black ? 0.9 : 1.0, metalness: 0,
+ clearcoat: black ? 1 : 0.45, clearcoatRoughness: black ? 0.1 : 0.16,
+ envMapIntensity: envIntensity,
+ sheen: 0,
+ });
+ m.userData.black = black;
+ m.onBeforeCompile = sh => {
+ sh.uniforms.uVeinLo = { value: veins[0] };
+ sh.uniforms.uVeinHi = { value: veins[1] };
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nuniform float uVeinLo, uVeinHi;')
+ .replace('#include <map_fragment>', black ? `
+ #include <map_fragment>
+ {
+ // Veins are where the Carrara is darker than its neighbourhood (a low mip is the local average),
+ // so baked relief shading on the king does not all turn to gold.
+ const vec3 LUM = vec3(0.2126, 0.7152, 0.0722);
+ float L = dot(textureLod(map, vMapUv, 1.6).rgb, LUM); // slightly blurred: fine carving noise is not a vein
+ float La = dot(textureLod(map, vMapUv, 5.5).rgb, LUM);
+ float rel = clamp((La - L) / max(La, 1e-3), 0.0, 1.0);
+ float v = smoothstep(uVeinLo, uVeinHi, rel);
+ float strong = smoothstep(0.32, 0.75, rel);
+ vec3 ground = vec3(0.0105, 0.0098, 0.0092) * (0.75 + 0.5 * L);
+ vec3 gold = vec3(0.46, 0.30, 0.12);
+ vec3 bone = vec3(0.66, 0.62, 0.55);
+ diffuseColor.rgb = ground + mix(gold, bone, strong) * v * 0.62;
+ }` : `
+ #include <map_fragment>
+ {
+ // Carrara: an even bone ground with the veins pulled out crisply (relative to the local average).
+ const vec3 LUM = vec3(0.2126, 0.7152, 0.0722);
+ vec3 avg = textureLod(map, vMapUv, 5.5).rgb;
+ float L = dot(diffuseColor.rgb, LUM), La = dot(avg, LUM);
+ float rel = clamp((La - L) / max(La, 1e-3), 0.0, 1.0);
+ vec3 ground = mix(vec3(0.78, 0.75, 0.69), vec3(0.84, 0.81, 0.75), smoothstep(0.4, 0.8, La));
+ diffuseColor.rgb = ground * (1.0 - smoothstep(0.04, 0.5, rel) * 0.62) * mix(vec3(1.0), vec3(0.93, 0.93, 0.95), smoothstep(0.1, 0.4, rel));
+ }
+ `)
+ .replace('#include <lights_physical_pars_fragment>', WRAP)
+ .replace('#include <roughnessmap_fragment>', `
+ #include <roughnessmap_fragment>
+ roughnessFactor = clamp(roughnessFactor * ${black ? '0.55' : '1.1'}, ${black ? '0.08' : '0.2'}, 0.6);
+ `);
+ };
+ m.customProgramCacheKey = () => (black ? 'nero' : 'carrara');
+ return m;
+}
diff --git a/examples/gambit/salon.js b/examples/gambit/salon.js
new file mode 100644
index 0000000..5ab5f84
--- /dev/null
+++ b/examples/gambit/salon.js
@@ -0,0 +1,213 @@
+// The salon: eleven more tables under eleven lamps, every one replaying the Immortal Game at a different move.
+// Everything here is instanced and shaded with a cheap lamp-pool model, and lives on layer 1 so the
+// planar reflection and the shadow map never pay for it.
+import { THREE } from '../../src/core/engine.js';
+
+export const SPACING = 34;
+export const LAMP = new THREE.Vector3(-3.0, 15, 8.0); // lamp offset from each table centre (same as our key light)
+export const TABLES = [];
+for (const x of [-1, 0, 1, 2]) for (const z of [-1, 0, 1]) if (x || z) TABLES.push(new THREE.Vector3(x * SPACING, 0, z * SPACING));
+export const ALL_TABLES = [new THREE.Vector3(0, 0, 0), ...TABLES];
+
+const NL = ALL_TABLES.length;
+const lampUniform = ALL_TABLES.map(t => t.clone().add(LAMP));
+
+const FAR_VERT = /* glsl */`
+ varying vec3 vN; varying vec3 vW; varying vec3 vL;
+ #include <fog_pars_vertex>
+ void main(){
+ vec4 p = vec4(position, 1.0);
+ vec3 n = normal;
+ vL = position;
+ #ifdef USE_INSTANCING
+ p = instanceMatrix * p; n = mat3(instanceMatrix) * n;
+ #endif
+ vec4 w = modelMatrix * p;
+ vW = w.xyz; vN = normalize(mat3(modelMatrix) * n);
+ vec4 mvPosition = viewMatrix * w;
+ gl_Position = projectionMatrix * mvPosition;
+ #include <fog_vertex>
+ }`;
+const LAMP_GLSL = /* glsl */`
+ uniform vec3 uLamps[${NL}]; uniform float uPower; uniform vec3 uCam;
+ // the lamp over the nearest table
+ vec3 nearestLamp(vec3 w){
+ vec3 best = uLamps[0]; float bd = 1e9;
+ for (int i = 0; i < ${NL}; i++) { vec3 d = w - uLamps[i]; float q = d.x * d.x + d.z * d.z; if (q < bd) { bd = q; best = uLamps[i]; } }
+ return best;
+ }
+ vec3 shade(vec3 albedo, vec3 n, vec3 w, float gloss){
+ vec3 lp = nearestLamp(w);
+ vec3 dl = lp - w; float d = length(dl); vec3 l = dl / d;
+ vec3 aim = normalize(vec3(lp.x + 3.4, -0.34, lp.z - 8.2) - lp); // the shade points at its table
+ float cone = smoothstep(0.87, 0.97, dot(-l, aim));
+ float ndl = max(dot(n, l), 0.0);
+ vec3 v = normalize(uCam - w); vec3 h = normalize(l + v);
+ float spec = pow(max(dot(n, h), 0.0), 70.0) * gloss;
+ float fres = pow(1.0 - max(dot(n, v), 0.0), 4.0);
+ vec3 lampC = vec3(1.0, 0.86, 0.68) * uPower / (d * d) * 0.42;
+ return (albedo * (ndl * cone + 0.018) + spec * cone) * lampC * 1.0 + albedo * 0.004 + fres * gloss * 0.012;
+ }`;
+
+function farMaterial(frag, extra = {}) {
+ return new THREE.ShaderMaterial({
+ fog: true,
+ uniforms: THREE.UniformsUtils.merge([THREE.UniformsLib.fog, {
+ uLamps: { value: lampUniform }, uPower: { value: 1500 }, uCam: { value: new THREE.Vector3() }, uColor: { value: new THREE.Color() }, uGloss: { value: 0 },
+ ...extra,
+ }]),
+ vertexShader: FAR_VERT,
+ fragmentShader: /* glsl */`
+ uniform vec3 uColor; uniform float uGloss;
+ varying vec3 vN; varying vec3 vW; varying vec3 vL;
+ ${LAMP_GLSL}
+ #include <fog_pars_fragment>
+ ${frag}`,
+ });
+}
+const pieceFrag = /* glsl */`
+ void main(){
+ vec3 n = normalize(vN);
+ if (!gl_FrontFacing) n = -n;
+ gl_FragColor = vec4(shade(uColor, n, vW, uGloss), 1.0);
+ #include <fog_fragment>
+ }`;
+
+/**
+ * Build the room. `pieceTypes` maps type -> BufferGeometry (already normalised to the main set's scale),
+ * `placements` is a list of { type, color, matrix } for every far piece, `boardTex` the board albedo.
+ */
+export function buildSalon({ scene, camera, tableY, edge, pieceTypes, placements, boardTex }) {
+ const group = new THREE.Group();
+ group.name = 'salon';
+ const mats = [];
+ const track = m => { mats.push(m); return m; };
+
+ // Far pieces: one instanced mesh per type and colour.
+ const white = new THREE.Color(0.72, 0.68, 0.6), black = new THREE.Color(0.012, 0.011, 0.01);
+ for (const [type, geo] of Object.entries(pieceTypes)) for (const color of ['w', 'b']) {
+ const list = placements.filter(p => p.type === type && p.color === color);
+ if (!list.length) continue;
+ const mat = track(farMaterial(pieceFrag));
+ mat.uniforms.uColor.value.copy(color === 'w' ? white : black);
+ mat.uniforms.uGloss.value = color === 'w' ? 0.25 : 0.9;
+ const im = new THREE.InstancedMesh(geo, mat, list.length);
+ list.forEach((p, i) => im.setMatrixAt(i, p.matrix));
+ im.instanceMatrix.needsUpdate = true;
+ im.computeBoundingSphere();
+ group.add(im);
+ }
+
+ // Far boards: squares, brass fillet and walnut frame in one plane.
+ const boardMat = track(farMaterial(/* glsl */`
+ uniform sampler2D uBoard; uniform float uEdge;
+ void main(){
+ vec2 q = vL.xy; // plane local, -edge..edge
+ vec3 alb;
+ if (abs(q.x) < 4.0 && abs(q.y) < 4.0) { vec3 t = texture2D(uBoard, (q + 4.0) / 8.0).rgb; alb = t * t; }
+ else if (abs(q.x) < 4.05 && abs(q.y) < 4.05) alb = vec3(0.5, 0.36, 0.17);
+ else alb = vec3(0.05, 0.028, 0.016);
+ gl_FragColor = vec4(shade(alb, vec3(0.0, 1.0, 0.0), vW, 0.5), 1.0);
+ #include <fog_fragment>
+ }`, { uBoard: { value: null }, uEdge: { value: edge } }));
+ boardMat.uniforms.uBoard.value = boardTex; // render-target textures do not survive UniformsUtils.merge
+ const boards = new THREE.InstancedMesh(new THREE.PlaneGeometry(edge * 2, edge * 2), boardMat, TABLES.length);
+ const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), s1 = new THREE.Vector3(1, 1, 1);
+ const flat = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(1, 0, 0), -Math.PI / 2);
+ TABLES.forEach((t, i) => {
+ q.copy(flat).premultiply(new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), (i % 3 - 1) * 0.12));
+ boards.setMatrixAt(i, m4.compose(t.clone().setY(0.001), q, s1));
+ });
+ boards.computeBoundingSphere();
+ group.add(boards);
+
+ // Table tops (leather with a walnut rim), pedestals and feet for the other tables.
+ const topMat = track(farMaterial(/* glsl */`
+ void main(){
+ float r = length(vL.xz);
+ vec3 alb = (vN.y > 0.5 && r < 8.85) ? vec3(0.02, 0.016, 0.013) : vec3(0.06, 0.032, 0.018);
+ gl_FragColor = vec4(shade(alb, normalize(vN), vW, 0.25), 1.0);
+ #include <fog_fragment>
+ }`));
+ const tops = new THREE.InstancedMesh(new THREE.CylinderGeometry(9.4, 9.2, 0.36, 72), topMat, TABLES.length);
+ TABLES.forEach((t, i) => tops.setMatrixAt(i, m4.compose(t.clone().setY(tableY - 0.18), q.identity(), s1)));
+ tops.computeBoundingSphere();
+ group.add(tops);
+
+ const woodMat = track(farMaterial(pieceFrag));
+ woodMat.uniforms.uColor.value.setRGB(0.05, 0.028, 0.016);
+ woodMat.uniforms.uGloss.value = 0.3;
+ const floorY = tableY - 13;
+ const colGeo = new THREE.CylinderGeometry(0.9, 1.25, 12.6, 24).translate(0, tableY - 0.36 - 6.3, 0);
+ const footGeo = new THREE.CylinderGeometry(3.6, 4.0, 0.5, 40).translate(0, floorY + 0.25, 0);
+ for (const geo of [colGeo, footGeo]) {
+ const im = new THREE.InstancedMesh(geo, woodMat, ALL_TABLES.length);
+ ALL_TABLES.forEach((t, i) => im.setMatrixAt(i, m4.compose(t, q.identity(), s1)));
+ im.computeBoundingSphere();
+ group.add(im);
+ }
+
+ // Pendant lamps: a brass shade, a bulb and a cord over every table, including ours.
+ const shadeMat = track(farMaterial(/* glsl */`
+ void main(){
+ vec3 n = normalize(vN);
+ float inner = gl_FrontFacing ? 0.0 : 1.0;
+ float fr = pow(1.0 - abs(dot(n, normalize(uCam - vW))), 2.0);
+ vec3 c = mix(vec3(0.03, 0.022, 0.012) + fr * vec3(0.55, 0.4, 0.2) * 0.5 + max(n.y, 0.0) * vec3(0.4, 0.3, 0.15) * 0.06,
+ vec3(1.0, 0.78, 0.5) * 2.2, inner);
+ gl_FragColor = vec4(c, 1.0);
+ #include <fog_fragment>
+ }`));
+ shadeMat.side = THREE.DoubleSide;
+ const shadeGeo = new THREE.CylinderGeometry(0.55, 2.3, 1.7, 48, 1, true).translate(0, 0.2, 0);
+ const bulbGeo = new THREE.SphereGeometry(0.42, 20, 12);
+ const cordGeo = new THREE.CylinderGeometry(0.035, 0.035, 60, 6).translate(0, 31, 0);
+ const bulbMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 0.8, 0.55).multiplyScalar(14), fog: false });
+ const cordMat = track(farMaterial(pieceFrag));
+ cordMat.uniforms.uColor.value.setRGB(0.02, 0.02, 0.02);
+ const lipGeo = new THREE.TorusGeometry(2.3, 0.07, 8, 64).rotateX(Math.PI / 2).translate(0, -0.65, 0);
+ const lipMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 0.74, 0.44).multiplyScalar(3.2), fog: false });
+ const aimQ = new THREE.Quaternion();
+ for (const [geo, mat] of [[shadeGeo, shadeMat], [bulbGeo, bulbMat], [cordGeo, cordMat], [lipGeo, lipMat]]) {
+ const im = new THREE.InstancedMesh(geo, mat, ALL_TABLES.length);
+ ALL_TABLES.forEach((t, i) => {
+ const p = t.clone().add(LAMP);
+ // shades tilt toward their board; cords hang straight
+ if (geo === cordGeo) aimQ.identity();
+ else aimQ.setFromUnitVectors(new THREE.Vector3(0, -1, 0), t.clone().add(new THREE.Vector3(0.4, 0, -0.2)).sub(p).normalize());
+ im.setMatrixAt(i, m4.compose(p, aimQ, s1));
+ });
+ im.computeBoundingSphere();
+ group.add(im);
+ }
+
+ // Parquet floor: long walnut boards, each lamp's light spilling round its table's shadow.
+ const floorMat = track(farMaterial(/* glsl */`
+ float hh(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
+ void main(){
+ vec2 g = vW.xz / vec2(14.0, 2.4);
+ float row = floor(g.y);
+ g.x += hh(vec2(row, 3.0)) * 7.0;
+ vec2 id = vec2(floor(g.x), row), f = fract(g);
+ float seam = smoothstep(0.0, 0.02, f.y) * smoothstep(1.0, 0.98, f.y) * smoothstep(0.0, 0.004, f.x) * smoothstep(1.0, 0.996, f.x);
+ vec3 alb = mix(vec3(0.035, 0.019, 0.011), vec3(0.07, 0.04, 0.022), hh(id)) * (0.5 + 0.5 * seam);
+ vec3 lp = nearestLamp(vW);
+ float r = length(vW.xz - (lp.xz - vec2(-3.0, 8.0)));
+ float under = smoothstep(7.0, 12.5, r); // the table's own shadow
+ vec3 c = shade(alb, vec3(0.0, 1.0, 0.0), vW, 0.35) * mix(0.12, 1.0, under);
+ gl_FragColor = vec4(c, 1.0);
+ #include <fog_fragment>
+ }`));
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(420, 420), floorMat);
+ floor.rotation.x = -Math.PI / 2; floor.position.y = floorY;
+ group.add(floor);
+
+ group.traverse(o => { o.layers.set(1); o.castShadow = false; o.receiveShadow = false; });
+ scene.add(group);
+ camera.layers.enable(1);
+
+ return {
+ group,
+ update(cam, power) { for (const m of mats) { m.uniforms.uCam.value.copy(cam.position); m.uniforms.uPower.value = power; } },
+ };
+}
diff --git a/examples/gambit/style.css b/examples/gambit/style.css
new file mode 100644
index 0000000..d1ac114
--- /dev/null
+++ b/examples/gambit/style.css
@@ -0,0 +1,264 @@
+:root {
+ --black: #080706;
+ --ink: #ece5d8; /* bone */
+ --bone-2: #cfc6b6;
+ --muted: #8e8578;
+ --faint: rgba(236, 229, 216, .12);
+ --brass: #b89b6a;
+ --brass-hi: #dcc08a;
+ --crimson: #a8453a;
+ --serif: 'Bodoni Moda', 'Didot', 'Bodoni 72', Georgia, serif;
+ --sans: 'Inter', system-ui, -apple-system, sans-serif;
+ --gut: clamp(18px, 4vw, 56px);
+ --ply-h: 50vh;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--black); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 15px/1.6 var(--sans); background: var(--black); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+em { font-style: italic; }
+::selection { background: var(--brass); color: #120e08; }
+
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+/* legibility scrims that follow the section in view */
+.grade { position: fixed; inset: 0; z-index: 1; pointer-events: none; transition: opacity 1s ease;
+ background:
+ linear-gradient(90deg, rgba(8,7,6,var(--gl, .72)) 0%, rgba(8,7,6,0) 46%),
+ linear-gradient(270deg, rgba(8,7,6,var(--gr, 0)) 0%, rgba(8,7,6,calc(var(--gr, 0) * .75)) 40%, rgba(8,7,6,0) 62%),
+ linear-gradient(0deg, rgba(8,7,6,var(--gb, .55)) 0%, rgba(8,7,6,0) 34%); }
+
+.eyebrow { font: 500 11px/1.2 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: var(--brass); }
+
+/* ── loader ─────────────────────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--black); display: grid; place-content: center; justify-items: center; gap: 26px; }
+.tour { width: 168px; height: 168px; overflow: visible; }
+.tour-grid rect { fill: rgba(236,229,216,.035); }
+.tour-grid rect.d { fill: rgba(236,229,216,.075); }
+.tour-line { stroke: var(--brass); stroke-width: .55; stroke-linejoin: round; stroke-linecap: round; }
+.tour-knight { fill: var(--brass-hi); filter: drop-shadow(0 0 3px rgba(220,192,138,.8)); }
+.loader-brand { font: 400 30px/1 var(--serif); letter-spacing: .42em; text-transform: uppercase; margin-right: -.42em; }
+.loader-line { font: 400 italic 15px/1 var(--serif); color: var(--muted); letter-spacing: .02em; }
+.loader-pct { font-style: normal; font-variant-numeric: tabular-nums; color: var(--brass); display: inline-block; min-width: 2.2em; text-align: left; }
+
+/* ── nav ────────────────────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 22px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; justify-self: start; }
+.brand svg { width: 26px; height: 26px; color: var(--brass); }
+.brand span { font: 400 17px/1 var(--serif); letter-spacing: .38em; text-transform: uppercase; }
+.links { display: flex; gap: 38px; }
+.links a { text-decoration: none; font: 400 13px/1 var(--sans); letter-spacing: .02em; color: var(--bone-2); position: relative; padding: 6px 0; transition: color .3s; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: var(--brass); transform: scaleX(0); transform-origin: right; transition: transform .5s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after, .links a.on::after { transform: scaleX(1); transform-origin: left; }
+.links a.on { color: var(--ink); }
+.nav-right { justify-self: end; display: flex; align-items: center; gap: 22px; }
+.sound { display: flex; align-items: flex-end; gap: 2px; height: 16px; font: 500 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.sound i { width: 2px; height: 3px; background: currentColor; transition: height .3s; }
+.sound span { margin-left: 9px; align-self: center; }
+.sound[aria-pressed="true"] { color: var(--brass); }
+.sound[aria-pressed="true"] i { animation: eq 1.1s ease-in-out infinite; }
+.sound[aria-pressed="true"] i:nth-child(2) { animation-delay: -.3s; }
+.sound[aria-pressed="true"] i:nth-child(3) { animation-delay: -.6s; }
+.sound[aria-pressed="true"] i:nth-child(4) { animation-delay: -.8s; }
+@keyframes eq { 0%, 100% { height: 3px; } 50% { height: 12px; } }
+
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 0;
+ text-decoration: none; font: 500 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; white-space: nowrap;
+ transition: background .4s, color .4s, box-shadow .4s; }
+.btn-ghost { box-shadow: inset 0 0 0 1px rgba(184,155,106,.55); color: var(--ink); background: rgba(8,7,6,.35); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--brass-hi); background: rgba(184,155,106,.14); }
+.btn-solid { background: var(--brass); color: #140f08; }
+.btn-solid:hover { background: var(--brass-hi); box-shadow: 0 0 48px rgba(184,155,106,.35); }
+.link-arrow { font: 400 italic 18px/1 var(--serif); text-decoration: none; color: var(--bone-2); border-bottom: 1px solid rgba(184,155,106,.5); padding-bottom: 5px; transition: color .3s, border-color .3s; }
+.link-arrow:hover { color: var(--ink); border-color: var(--brass-hi); }
+
+/* ── hero ───────────────────────────────────────────────────────────────── */
+.hero { position: relative; z-index: 3; height: 118vh; pointer-events: none; }
+.hero-inner { position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; justify-content: flex-start; padding: 15vh var(--gut) 10vh; max-width: 1180px; isolation: isolate; }
+/* a soft pool of shadow behind the copy column, so text never sits on lit marble without contrast */
+.hero-inner::before { content: ''; position: absolute; z-index: -1; left: 0; top: 0; width: min(1000px, 78vw); height: 92vh; pointer-events: none;
+ background: radial-gradient(ellipse 62% 58% at 26% 42%, rgba(8,7,6,.72) 0%, rgba(8,7,6,.5) 45%, rgba(8,7,6,0) 100%); }
+.hero-bottom { margin-top: 34px; }
+.hero-title { font: 400 clamp(54px, 7.4vw, 126px)/.94 var(--serif); letter-spacing: -.028em; margin: 26px 0 0; font-optical-sizing: auto; }
+.hero-title .ln { display: block; overflow: hidden; padding-bottom: .06em; }
+.hero-title .ln > span { display: block; }
+.hero-title em { color: var(--brass-hi); font-weight: 400; }
+.hero-sub { max-width: 34em; text-shadow: 0 1px 20px rgba(8,7,6,.9); font: 300 clamp(15px, 1.15vw, 17px)/1.65 var(--sans); color: var(--bone-2); }
+.hero-cta { display: flex; align-items: center; gap: 34px; margin-top: 30px; pointer-events: auto; flex-wrap: wrap; }
+.scroll-cue { position: fixed; right: var(--gut); bottom: 6vh; z-index: 3; display: flex; align-items: center; gap: 14px; font: 500 10px/1 var(--sans); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); transition: opacity .6s; }
+.cue-line { width: 1px; height: 54px; background: rgba(236,229,216,.14); position: relative; overflow: hidden; }
+.cue-line i { position: absolute; left: 0; top: 0; width: 1px; height: 18px; background: var(--brass); animation: cue 2.2s cubic-bezier(.6,0,.2,1) infinite; }
+@keyframes cue { 0% { transform: translateY(-20px); } 100% { transform: translateY(58px); } }
+body:not(.at-top) .scroll-cue { opacity: 0 !important; }
+
+/* ── replay ─────────────────────────────────────────────────────────────── */
+.replay { position: relative; z-index: 3; height: calc(100vh + 47 * var(--ply-h)); pointer-events: none; }
+.replay-pin { position: sticky; top: 0; height: 100vh; }
+.replay-intro { position: absolute; left: var(--gut); top: 20vh; max-width: 25em; opacity: 0; transition: opacity .8s, transform .8s; transform: translateY(14px); }
+.replay-intro h2 { font: 400 clamp(38px, 4.4vw, 70px)/1 var(--serif); letter-spacing: -.02em; margin: 18px 0 20px; }
+.replay-intro p:last-child { color: var(--bone-2); font-weight: 300; max-width: 27em; }
+.show-intro .replay-intro { opacity: 1; transform: none; }
+
+.score { position: absolute; right: var(--gut); top: 96px; bottom: 36px; width: 300px; display: grid; grid-template-rows: auto 1fr auto; pointer-events: auto;
+ background: linear-gradient(180deg, rgba(14,12,10,.74), rgba(10,9,8,.6)); backdrop-filter: blur(14px) saturate(1.1); -webkit-backdrop-filter: blur(14px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px rgba(184,155,106,.18), 0 40px 80px -30px rgba(0,0,0,.8);
+ opacity: 0; transform: translateX(24px); transition: opacity .8s, transform .9s cubic-bezier(.2,.8,.2,1); }
+.in-replay .score { opacity: 1; transform: none; }
+.score-head { padding: 22px 24px 18px; border-bottom: 1px solid var(--faint); }
+.players { display: grid; gap: 4px; margin-top: 14px; font: 400 19px/1.25 var(--serif); }
+.players .vs { display: none; }
+.dot { display: inline-block; width: 8px; height: 8px; border-radius: 50%; margin-right: 10px; vertical-align: 2px; }
+.dot.w { background: #efe9dd; } .dot.b { background: #0b0a09; box-shadow: inset 0 0 0 1px #b89b6a; }
+.opening { margin-top: 10px; font-size: 11.5px; color: var(--muted); letter-spacing: .02em; }
+.score-window { position: relative; overflow: hidden; -webkit-mask-image: linear-gradient(transparent, #000 14%, #000 86%, transparent); mask-image: linear-gradient(transparent, #000 14%, #000 86%, transparent); }
+.score-list { list-style: none; padding: 30px 14px; will-change: transform; }
+.score-list li { display: grid; grid-template-columns: 34px 1fr 1fr; align-items: center; height: 30px; }
+.score-list .n { font: 400 12px/1 var(--sans); color: var(--muted); font-variant-numeric: tabular-nums; text-align: right; padding-right: 12px; }
+.score-list button { text-align: left; padding: 6px 10px; font: 400 16px/1 var(--serif); color: rgba(236,229,216,.42); position: relative; transition: color .35s, background .35s; border-radius: 1px; }
+.score-list button:hover { color: var(--ink); }
+.score-list button.done { color: var(--bone-2); }
+.score-list button.on { color: #140f08; background: var(--brass); }
+.score-list button.big { font-style: italic; }
+.score-list button.big::after { content: attr(data-mark); position: absolute; top: 3px; margin-left: 2px; font: 500 9px/1 var(--sans); letter-spacing: .05em; color: var(--brass); }
+.score-list button.on.big::after { color: #140f08; }
+.score-foot { padding: 16px 24px 20px; border-top: 1px solid var(--faint); }
+.score-bar { height: 1px; background: var(--faint); position: relative; }
+.score-bar i { position: absolute; left: 0; top: -.5px; height: 2px; width: 100%; background: var(--brass); transform-origin: left; transform: scaleX(0); }
+.score-foot p { display: flex; justify-content: space-between; margin-top: 12px; font: 500 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.score-count { color: var(--ink); font-variant-numeric: tabular-nums; }
+
+.caption { position: absolute; left: var(--gut); bottom: 11vh; max-width: min(40em, calc(100vw - 420px)); opacity: 0; transition: opacity .6s; }
+.in-replay .caption { opacity: 1; }
+.caption-san { display: flex; align-items: baseline; gap: 16px; font: 400 clamp(42px, 5vw, 84px)/1 var(--serif); letter-spacing: -.02em; }
+.caption-num { font: 400 13px/1 var(--sans); letter-spacing: .2em; color: var(--brass); text-transform: uppercase; }
+.caption-text { font-style: italic; }
+.caption-note { margin-top: 16px; max-width: 30em; font: 300 17px/1.55 var(--sans); color: var(--bone-2); text-shadow: 0 1px 18px rgba(0,0,0,.9); }
+.caption-san, .caption-note { will-change: transform, opacity; }
+
+.tag { position: fixed; left: 0; top: 0; z-index: 4; pointer-events: none; opacity: 0; transition: opacity .45s; display: grid; justify-items: center; }
+.tag.on { opacity: 1; }
+.tag-san { font: 400 italic 20px/1 var(--serif); color: var(--brass-hi); text-shadow: 0 2px 14px rgba(0,0,0,.85); white-space: nowrap; }
+.tag-line { width: 1px; height: 34px; margin-top: 8px; background: linear-gradient(var(--brass-hi), rgba(184,155,106,0)); }
+
+/* ── free play ──────────────────────────────────────────────────────────── */
+.free { position: relative; z-index: 3; height: 230vh; pointer-events: none; }
+.free-pin { position: sticky; top: 0; height: 100vh; }
+.free-copy { position: absolute; left: var(--gut); top: 50%; transform: translateY(-46%); max-width: 400px; opacity: 0; transition: opacity .8s; }
+.in-free .free-copy { opacity: 1; }
+.free-copy h2 { font: 400 clamp(38px, 3.9vw, 62px)/1.02 var(--serif); letter-spacing: -.02em; margin: 20px 0 22px; }
+.free-copy h2 em { color: var(--brass-hi); }
+.free-copy > p:not(.eyebrow) { color: var(--bone-2); font-weight: 300; }
+.free-actions { display: grid; gap: 10px; margin-top: 30px; justify-items: start; pointer-events: auto; }
+.free-hint { position: absolute; left: 50%; bottom: 7vh; transform: translateX(-50%); display: flex; align-items: center; gap: 14px; padding: 12px 20px 12px 16px;
+ font: 500 10.5px/1 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--ink);
+ background: rgba(10,9,8,.55); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(184,155,106,.3);
+ opacity: 0; transition: opacity .6s; }
+.in-free .free-hint { opacity: 1; }
+.has-dragged .free-hint { opacity: 0 !important; }
+.hand { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--brass); position: relative; }
+.hand::after { content: ''; position: absolute; inset: 5px; border-radius: 50%; background: var(--brass-hi); animation: pulse 1.8s ease-in-out infinite; }
+@keyframes pulse { 0%, 100% { transform: scale(.6); opacity: .6; } 50% { transform: scale(1.1); opacity: 1; } }
+
+/* ── content panels ─────────────────────────────────────────────────────── */
+.panel { position: relative; z-index: 3; padding: 22vh var(--gut); }
+.panel h2 { font: 400 clamp(46px, 6vw, 104px)/.96 var(--serif); letter-spacing: -.028em; margin: 22px 0 30px; }
+.panel h2 em { color: var(--brass-hi); }
+.lede { max-width: 32em; font: 300 clamp(16px, 1.25vw, 19px)/1.62 var(--sans); color: var(--bone-2); }
+
+.set { min-height: 190vh; }
+.set-copy { max-width: 540px; position: sticky; top: 14vh; }
+.specs { margin-top: 44px; display: grid; border-top: 1px solid var(--faint); }
+.specs div { display: grid; grid-template-columns: 110px 1fr; gap: 20px; padding: 16px 0; border-bottom: 1px solid var(--faint); }
+.specs dt { font: 500 10.5px/1.9 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--brass); }
+.specs dd { color: var(--bone-2); font-size: 14.5px; font-weight: 300; }
+.price-row { display: flex; align-items: center; justify-content: space-between; gap: 24px; margin-top: 38px; flex-wrap: wrap; }
+.price { font: 400 46px/1 var(--serif); letter-spacing: -.01em; }
+.price span { display: block; margin-top: 10px; font: 400 12px/1.4 var(--sans); letter-spacing: .02em; color: var(--muted); max-width: 22em; }
+.set-notes { position: fixed; inset: 0; z-index: 4; pointer-events: none; }
+.note-card { position: absolute; left: 0; top: 0; display: grid; gap: 3px; padding: 14px 18px 15px 20px; min-width: 190px;
+ background: rgba(10,9,8,.6); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(184,155,106,.26);
+ opacity: 0; transition: opacity .6s; will-change: transform; }
+.note-card.on { opacity: 1; }
+.note-card::before { content: ''; position: absolute; left: -46px; top: 50%; width: 46px; height: 1px; background: linear-gradient(90deg, rgba(220,192,138,0), var(--brass-hi)); }
+.note-card::after { content: ''; position: absolute; left: -50px; top: calc(50% - 3px); width: 7px; height: 7px; border-radius: 50%; box-shadow: 0 0 0 1px var(--brass-hi); }
+.note-card .nc-k { font: 500 9.5px/1 var(--sans); letter-spacing: .24em; text-transform: uppercase; color: var(--brass); }
+.note-card b { font: 400 21px/1.15 var(--serif); margin-top: 6px; }
+.note-card span:last-child { font-size: 12px; color: var(--muted); }
+
+.salon { min-height: 170vh; display: flex; justify-content: flex-end; }
+.salon-copy { max-width: 560px; position: sticky; top: 12vh; align-self: flex-start; }
+.evenings { list-style: none; margin-top: 44px; border-top: 1px solid var(--faint); }
+.evenings li { display: grid; grid-template-columns: 112px 1fr auto; gap: 20px; padding: 22px 0; border-bottom: 1px solid var(--faint); align-items: baseline; }
+.ev-day { font: 500 10.5px/1.6 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--brass); }
+.evenings h3 { font: 400 26px/1.1 var(--serif); margin-bottom: 8px; }
+.evenings p { color: var(--bone-2); font-size: 14.5px; font-weight: 300; }
+.ev-time { font: 400 italic 18px/1 var(--serif); color: var(--muted); }
+
+.foot { min-height: 100vh; display: grid; align-content: end; padding-bottom: 7vh;
+ background: linear-gradient(180deg, rgba(8,7,6,0) 0%, rgba(8,7,6,.55) 45%, rgba(8,7,6,.94) 100%); }
+.foot-title { font-size: clamp(88px, 15vw, 260px) !important; line-height: .86 !important; margin: 0 0 40px !important; }
+.foot-cta { display: flex; gap: 14px; flex-wrap: wrap; }
+.foot-cols { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 40px; margin-top: 12vh; padding-top: 30px; border-top: 1px solid var(--faint); color: var(--bone-2); font-size: 14px; font-weight: 300; line-height: 1.8; }
+.foot-cols .k { display: block; font: 500 10.5px/1 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--brass); margin-bottom: 14px; }
+.fine { margin-top: 44px; font-size: 11.5px; color: var(--muted); padding-left: 150px; }
+
+/* ── states ─────────────────────────────────────────────────────────────── */
+.dragging, .dragging * { user-select: none; }
+
+@media (max-width: 1100px) {
+ .caption { max-width: calc(100vw - 380px); }
+ .score { width: 270px; }
+}
+@media (max-width: 760px) {
+ :root { --ply-h: 42vh; }
+ .links, .sound span { display: none; }
+ .nav { grid-template-columns: 1fr auto; padding: 16px 18px; }
+ .nav .btn { height: 38px; padding: 0 14px; font-size: 10.5px; }
+ .nav-right { gap: 14px; }
+ .brand span { font-size: 15px; letter-spacing: .3em; }
+ .hero-inner { padding: 12vh 18px 10vh; }
+ .hero-inner::before { width: 100%; height: 78vh; background: linear-gradient(180deg, rgba(8,7,6,.9) 0%, rgba(8,7,6,.82) 55%, rgba(8,7,6,.4) 80%, rgba(8,7,6,0) 100%); }
+ .hero-bottom { margin-top: 20px; }
+ .hero-cta { margin-top: 22px; }
+ .hero-title { font-size: clamp(46px, 13.2vw, 64px); }
+ .hero-sub { font-size: 14.5px; text-shadow: 0 1px 16px rgba(0,0,0,.95), 0 0 2px rgba(0,0,0,.6); }
+ .hero-cta { gap: 22px; }
+ .scroll-cue { display: none; }
+ .replay-intro { top: 13vh; right: var(--gut); }
+ .replay-intro p:last-child { display: none; }
+ .score { top: 70px; bottom: auto; left: 18px; right: 18px; width: auto; height: auto; grid-template-rows: auto; }
+ .score-head, .score-window { display: none; }
+ .score-foot { padding: 10px 14px 12px; border-top: 0; }
+ .score-foot p { margin-top: 9px; }
+ .replay-intro { top: 150px; }
+ .caption { left: 18px; right: 18px; bottom: 64px; max-width: none; }
+ .caption-san { font-size: 40px; }
+ .caption-note { font-size: 14px; margin-top: 10px; }
+ .tag { display: none; }
+ .free-copy { top: 12vh; transform: none; right: 18px; max-width: none; }
+ .free-copy h2 { font-size: 34px; margin: 12px 0 12px; }
+ .free-copy > p:not(.eyebrow) { display: none; }
+ .free-actions { grid-auto-flow: column; margin-top: 16px; }
+ .free-actions .btn { height: 38px; padding: 0 12px; font-size: 9.5px; letter-spacing: .1em; }
+ .free-hint { bottom: 12vh; white-space: nowrap; font-size: 9.5px; }
+ .panel { padding: 16vh 18px; }
+ .set-copy, .salon-copy { position: relative; top: 0; }
+ .set, .salon { background: linear-gradient(180deg, rgba(8,7,6,.35), rgba(8,7,6,.78) 30%, rgba(8,7,6,.78) 70%, rgba(8,7,6,.35)); }
+ .set, .salon { min-height: 0; }
+ .specs div { grid-template-columns: 1fr; gap: 4px; }
+ .note-card { display: none; }
+ .evenings li { grid-template-columns: 1fr auto; }
+ .evenings li > div { grid-column: 1 / -1; grid-row: 2; }
+ .foot-cols { grid-template-columns: 1fr; gap: 24px; }
+ .fine { padding-left: 0; }
+ .price { font-size: 38px; }
+}
+
+/* the replay's opening card gets the same pool of shadow as the hero copy */
+.replay-intro { isolation: isolate; }
+.replay-intro::before { content: ''; position: absolute; z-index: -1; inset: -12vh -14vw -10vh -8vw; pointer-events: none;
+ background: radial-gradient(ellipse 55% 55% at 40% 48%, rgba(8,7,6,.72) 0%, rgba(8,7,6,.45) 50%, rgba(8,7,6,0) 100%); }
+.replay-intro p:last-child { text-shadow: 0 1px 18px rgba(8,7,6,.9); }
diff --git a/examples/hangar/audio.js b/examples/hangar/audio.js
new file mode 100644
index 0000000..892e693
--- /dev/null
+++ b/examples/hangar/audio.js
@@ -0,0 +1,78 @@
+// Hangar Nine — synthesized sound. Off by default; the nav toggle creates the AudioContext on a user gesture.
+export class Sound {
+ constructor() { this.on = false; this.ctx = null; this._charge = 0; }
+
+ toggle() {
+ this.on = !this.on;
+ if (this.on) this._init();
+ if (this.ctx) this.master.gain.setTargetAtTime(this.on ? 0.8 : 0, this.ctx.currentTime, 0.15);
+ return this.on;
+ }
+
+ _init() {
+ if (this.ctx) { this.ctx.resume(); return; }
+ const c = this.ctx = new AudioContext();
+ this.master = c.createGain(); this.master.gain.value = 0;
+ const comp = c.createDynamicsCompressor(); comp.threshold.value = -14; comp.ratio.value = 4;
+ this.master.connect(comp).connect(c.destination);
+ // noise source
+ const len = c.sampleRate * 2, buf = c.createBuffer(1, len, c.sampleRate), d = buf.getChannelData(0);
+ for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
+ this.noiseBuf = buf;
+ // charge hum: two detuned saws through a lowpass
+ this.hum = c.createGain(); this.hum.gain.value = 0;
+ this.humF = c.createBiquadFilter(); this.humF.type = 'lowpass'; this.humF.frequency.value = 120; this.humF.Q.value = 6;
+ this.oscs = [0, 7].map(det => { const o = c.createOscillator(); o.type = 'sawtooth'; o.frequency.value = 40; o.detune.value = det; o.connect(this.humF); o.start(); return o; });
+ this.humF.connect(this.hum).connect(this.master);
+ // room tone once powered
+ const room = c.createBufferSource(); room.buffer = buf; room.loop = true;
+ const rf = c.createBiquadFilter(); rf.type = 'lowpass'; rf.frequency.value = 180;
+ this.room = c.createGain(); this.room.gain.value = 0;
+ room.connect(rf).connect(this.room).connect(this.master); room.start();
+ this.drone = c.createOscillator(); this.drone.type = 'sine'; this.drone.frequency.value = 55;
+ this.droneG = c.createGain(); this.droneG.gain.value = 0;
+ this.drone.connect(this.droneG).connect(this.master); this.drone.start();
+ }
+
+ charge(v) {
+ if (!this.on || !this.ctx) return;
+ const t = this.ctx.currentTime;
+ this.hum.gain.setTargetAtTime(v > 0.001 ? 0.05 + v * 0.22 : 0, t, 0.05);
+ for (const o of this.oscs) o.frequency.setTargetAtTime(38 + v * v * 90, t, 0.05);
+ this.humF.frequency.setTargetAtTime(110 + v * 1900, t, 0.05);
+ }
+
+ _noise(dur, type, freq, q, gain, attack = 0.002, when = 0) {
+ const c = this.ctx, t = c.currentTime + when;
+ const s = c.createBufferSource(); s.buffer = this.noiseBuf;
+ const f = c.createBiquadFilter(); f.type = type; f.frequency.value = freq; f.Q.value = q;
+ const g = c.createGain(); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(gain, t + attack); g.gain.exponentialRampToValueAtTime(0.0008, t + dur);
+ s.connect(f).connect(g).connect(this.master); s.start(t, Math.random()); s.stop(t + dur + 0.05);
+ }
+ _tone(freq, dur, gain, type = 'sine', when = 0, attack = 0.004, glide = null) {
+ const c = this.ctx, t = c.currentTime + when;
+ const o = c.createOscillator(); o.type = type; o.frequency.setValueAtTime(freq, t);
+ if (glide) o.frequency.exponentialRampToValueAtTime(glide, t + dur);
+ const g = c.createGain(); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(gain, t + attack); g.gain.exponentialRampToValueAtTime(0.0008, t + dur);
+ o.connect(g).connect(this.master); o.start(t); o.stop(t + dur + 0.05);
+ }
+
+ /** Big contactor closing: thump + metallic ring + a short crackle. */
+ clank(v = 1) {
+ if (!this.on || !this.ctx) return;
+ this._tone(62, 0.5, 0.5 * v, 'sine', 0, 0.002, 34);
+ this._noise(0.18, 'bandpass', 900 + Math.random() * 500, 1.2, 0.35 * v);
+ this._tone(1320 + Math.random() * 200, 0.6, 0.03 * v, 'triangle');
+ this._tone(2210 + Math.random() * 300, 0.4, 0.02 * v, 'triangle');
+ }
+ drop() { if (!this.on || !this.ctx) return; this._tone(90, 1.4, 0.4, 'sine', 0, 0.01, 28); this.charge(0); }
+ hiss(dur = 2.2, v = 1) { if (!this.on || !this.ctx) return; this._noise(dur, 'highpass', 2400, 0.7, 0.25 * v, 0.03); this._noise(dur * 0.6, 'bandpass', 700, 0.6, 0.12 * v, 0.02); }
+ scan() { if (!this.on || !this.ctx) return; this._tone(220, 2.6, 0.05, 'sawtooth', 0, 0.2, 880); }
+ online() {
+ if (!this.on || !this.ctx) return;
+ for (const [f, g] of [[110, 0.12], [165, 0.08], [220, 0.06], [330, 0.035]]) this._tone(f, 3.6, g, 'sine', 0, 0.5);
+ const t = this.ctx.currentTime;
+ this.room.gain.setTargetAtTime(0.03, t, 1.5);
+ this.droneG.gain.setTargetAtTime(0.025, t, 2);
+ }
+}
diff --git a/examples/hangar/fx.js b/examples/hangar/fx.js
new file mode 100644
index 0000000..2b66fb4
--- /dev/null
+++ b/examples/hangar/fx.js
@@ -0,0 +1,299 @@
+// Hangar Nine — effects: mech hologram/scan/visor shader patch, scan sheet, steam, weld sparks, dust in beams.
+import * as THREE from 'three';
+
+// ─── Mech material patch ────────────────────────────────────────────────────────
+export function mechUniforms() {
+ return {
+ uScanY: { value: -10 }, uHolo: { value: 0 }, uBand: { value: 0 }, uHoloCol: { value: new THREE.Color(0.28, 0.9, 1.0) },
+ uFocus: { value: new THREE.Vector4(0, 0, 0, 1) }, uFocusAmt: { value: 0 }, uFocusCol: { value: new THREE.Color(0.28, 0.9, 1.0) },
+ uVisor: { value: 0 }, uVisorPos: { value: new THREE.Vector3(0, 10, 1) }, uVisorR: { value: 1.2 },
+ uXray: { value: 0 }, uTime: { value: 0 },
+ };
+}
+
+export function patchMech(mat, U) {
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, U);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vMW; varying vec3 vMN;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvMW = (modelMatrix * vec4(transformed, 1.0)).xyz; vMN = normalize(mat3(modelMatrix) * objectNormal);');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vMW; varying vec3 vMN;
+ uniform float uScanY, uHolo, uBand, uVisor, uVisorR, uFocusAmt, uXray, uTime;
+ uniform vec3 uHoloCol, uFocusCol, uVisorPos; uniform vec4 uFocus;`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ vec3 mechAlbedo = diffuseColor.rgb;
+ diffuseColor.rgb *= 1.0 - uXray * 0.55;`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ vec3 hp = vMW;
+ vec3 gq = hp / 0.34;
+ vec3 fw = max(fwidth(gq), vec3(1e-4));
+ vec3 d = abs(fract(gq - 0.5) - 0.5) / fw;
+ vec3 L = 1.0 - clamp(d / 1.15, 0.0, 1.0);
+ vec3 an = abs(normalize(vMN)); vec3 w = an * an * an * an; w /= (w.x + w.y + w.z + 1e-4);
+ float grid = max(L.y, L.z) * w.x + max(L.x, L.z) * w.y + max(L.x, L.y) * w.z;
+ grid *= clamp(1.4 - max(max(fw.x, fw.y), fw.z) * 2.2, 0.0, 1.0);
+ vec3 V = normalize(vViewPosition);
+ float fres = pow(1.0 - clamp(abs(dot(normal, V)), 0.0, 1.0), 2.6);
+ float below = 1.0 - smoothstep(uScanY - 0.03, uScanY + 0.03, hp.y);
+ float band = exp(-pow((hp.y - uScanY) * 2.4, 2.0));
+ float trail = exp(-max(uScanY - hp.y, 0.0) * 0.28);
+ float flick = 0.85 + 0.15 * sin(uTime * 31.0 + hp.y * 4.0);
+ vec3 holo = uHoloCol * (uHolo * below * (grid * 1.5 + fres * 0.9 + 0.025) * mix(0.35, 1.0, trail) * flick
+ + uBand * band * (0.6 + grid * 5.0 + fres * 2.5) * 2.6);
+ float fm = 1.0 - smoothstep(uFocus.w * 0.5, uFocus.w, distance(hp, uFocus.xyz));
+ holo += uFocusCol * uFocusAmt * fm * (grid * 1.7 + fres * 1.3 + 0.04) * flick;
+ totalEmissiveRadiance += holo;
+ // visor: orange pixels of the albedo, only around the head
+ float orange = smoothstep(0.05, 0.25, mechAlbedo.r - mechAlbedo.b) * smoothstep(0.02, 0.12, mechAlbedo.r - mechAlbedo.g * 1.25);
+ float hm = 1.0 - smoothstep(uVisorR * 0.45, uVisorR, distance(hp, uVisorPos));
+ totalEmissiveRadiance += vec3(1.0, 0.36, 0.05) * orange * hm * uVisor * 26.0;
+ }`);
+ };
+ mat.customProgramCacheKey = () => 'hn9-mech';
+ mat.needsUpdate = true;
+}
+
+// ─── Scan sheet: a horizontal laser plane that climbs the mech ─────────────────────
+export function scanSheet() {
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ uniforms: { uAmt: { value: 0 }, uTime: { value: 0 }, uCol: { value: new THREE.Color(0.28, 0.9, 1.0) } },
+ vertexShader: 'varying vec2 vP; void main(){ vP = position.xy; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `
+ uniform float uAmt, uTime; uniform vec3 uCol; varying vec2 vP;
+ void main(){
+ float r = length(vP);
+ float fall = smoothstep(6.8, 0.0, r);
+ float rings = pow(abs(sin(r * 3.0 - uTime * 4.0)), 40.0) * 0.35 * smoothstep(6.5, 2.0, r);
+ float ang = atan(vP.y, vP.x);
+ float ticks = step(0.94, fract(ang / 6.2831853 * 96.0)) * smoothstep(6.3, 6.2, r) * smoothstep(5.9, 6.0, r);
+ float edge = exp(-pow((r - 6.5) * 6.0, 2.0));
+ float a = (fall * fall * (0.035 + rings) + ticks * 0.9 + edge * 0.55) * uAmt;
+ gl_FragColor = vec4(uCol * a * 0.9, 1.0);
+ }`,
+ });
+ const m = new THREE.Mesh(new THREE.CircleGeometry(6.8, 128), mat);
+ m.rotation.x = -Math.PI / 2;
+ m.renderOrder = 6;
+ m.frustumCulled = false;
+ return m;
+}
+
+// ─── Instanced particle pools ───────────────────────────────────────────────────
+class Pool {
+ constructor(count, base) {
+ this.count = count;
+ this.geo = new THREE.InstancedBufferGeometry();
+ this.geo.index = base.index;
+ for (const k of Object.keys(base.attributes)) this.geo.setAttribute(k, base.attributes[k]);
+ this.aO = new THREE.InstancedBufferAttribute(new Float32Array(count * 3), 3);
+ this.aV = new THREE.InstancedBufferAttribute(new Float32Array(count * 3), 3);
+ const d = new Float32Array(count * 4);
+ for (let i = 0; i < count; i++) d[i * 4] = -1e4;
+ this.aD = new THREE.InstancedBufferAttribute(d, 4);
+ for (const a of [this.aO, this.aV, this.aD]) a.setUsage(THREE.DynamicDrawUsage);
+ this.geo.setAttribute('aO', this.aO); this.geo.setAttribute('aV', this.aV); this.geo.setAttribute('aD', this.aD);
+ this.geo.instanceCount = count;
+ this.i = 0;
+ this.dirty = false;
+ }
+ spawn(o, v, birth, life, a, b) {
+ const i = this.i; this.i = (this.i + 1) % this.count;
+ this.aO.array.set([o.x, o.y, o.z], i * 3);
+ this.aV.array.set([v.x, v.y, v.z], i * 3);
+ this.aD.array.set([birth, life, a, b], i * 4);
+ this.dirty = true;
+ }
+ flush() {
+ if (!this.dirty) return;
+ this.aO.needsUpdate = this.aV.needsUpdate = this.aD.needsUpdate = true;
+ this.dirty = false;
+ }
+}
+
+const _v = new THREE.Vector3(), _o = new THREE.Vector3();
+
+export class Steam {
+ constructor(noiseTex, count = 900) {
+ this.pool = new Pool(count, new THREE.PlaneGeometry(1, 1));
+ this.mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ blending: THREE.CustomBlending, blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor,
+ uniforms: { uTime: { value: 0 }, uNoise: { value: noiseTex }, uLight: { value: 1 }, uCol: { value: new THREE.Color(0.8, 0.84, 0.9) }, uWarm: { value: new THREE.Color(1.0, 0.25, 0.1) }, uWarmAmt: { value: 0 } },
+ vertexShader: `
+ attribute vec3 aO, aV; attribute vec4 aD;
+ uniform float uTime;
+ varying vec2 vUv; varying float vA; varying float vSeed; varying float vT; varying float vH;
+ void main(){
+ float age = uTime - aD.x; float t = age / aD.y;
+ if (t < 0.0 || t > 1.0) { gl_Position = vec4(0.0, 0.0, -2.0, 1.0); return; }
+ float drag = 1.6;
+ vec3 p = aO + aV * (1.0 - exp(-drag * age)) / drag + vec3(0.0, 0.7, 0.0) * age * age * 0.5;
+ p += vec3(sin(age * 1.3 + aD.w * 20.0), 0.0, cos(age * 1.1 + aD.w * 13.0)) * 0.35 * age;
+ float size = aD.z * (0.3 + 2.1 * sqrt(t));
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ float r = aD.w * 6.28 + age * (aD.w - 0.5) * 0.9;
+ vec2 c = mat2(cos(r), -sin(r), sin(r), cos(r)) * position.xy;
+ mv.xy += c * size;
+ gl_Position = projectionMatrix * mv;
+ vUv = uv; vT = t; vSeed = aD.w; vH = p.y;
+ vA = smoothstep(0.0, 0.05, t) * pow(1.0 - t, 1.5);
+ }`,
+ fragmentShader: `
+ uniform sampler2D uNoise; uniform float uLight, uWarmAmt; uniform vec3 uCol, uWarm;
+ varying vec2 vUv; varying float vA; varying float vSeed; varying float vT; varying float vH;
+ void main(){
+ vec2 q = vUv - 0.5; float r = length(q) * 2.0;
+ float n = texture2D(uNoise, vUv * 0.55 + vec2(vSeed * 7.3, vSeed * 3.1) + vT * 0.08).r;
+ float n2 = texture2D(uNoise, vUv * 1.3 - vec2(vSeed * 2.1, vT * 0.2)).r;
+ float a = smoothstep(1.0, 0.15, r) * smoothstep(0.15, 0.85, n * 0.7 + n2 * 0.5) * vA * 0.3;
+ a = clamp(a, 0.0, 1.0);
+ vec3 col = mix(uCol, uWarm, uWarmAmt) * uLight * (0.55 + n * 0.7) * (0.8 + smoothstep(2.0, 12.0, vH) * 0.5);
+ gl_FragColor = vec4(col * a, a);
+ }`,
+ });
+ this.mesh = new THREE.Mesh(this.pool.geo, this.mat);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 7;
+ }
+ burst(origin, dir, n, t, { speed = 6, spread = 0.35, life = 3.2, size = 1.2 } = {}) {
+ for (let k = 0; k < n; k++) {
+ _v.copy(dir).add(_o.set(Math.random() - 0.5, Math.random() - 0.5, Math.random() - 0.5).multiplyScalar(spread * 2)).normalize()
+ .multiplyScalar(speed * (0.55 + Math.random() * 0.6));
+ _o.copy(origin).add(new THREE.Vector3((Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3, (Math.random() - 0.5) * 0.3));
+ this.pool.spawn(_o, _v, t + Math.random() * 0.25, life * (0.7 + Math.random() * 0.6), size * (0.6 + Math.random() * 0.8), Math.random());
+ }
+ }
+ update(t) { this.mat.uniforms.uTime.value = t; this.pool.flush(); }
+}
+
+export class Sparks {
+ constructor(count = 1400) {
+ this.pool = new Pool(count, new THREE.PlaneGeometry(1, 1));
+ this.mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uRes: { value: new THREE.Vector2(1440, 900) }, uWidth: { value: 2.2 } },
+ vertexShader: `
+ attribute vec3 aO, aV; attribute vec4 aD;
+ uniform float uTime; uniform vec2 uRes; uniform float uWidth;
+ varying float vHeat; varying float vA; varying vec2 vUv;
+ vec3 posAt(float age){
+ vec3 g = vec3(0.0, -9.8, 0.0);
+ float vy = aV.y, y0 = aO.y;
+ float th = (vy + sqrt(vy * vy + 19.6 * y0)) / 9.8;
+ if (age < th) return aO + aV * age + 0.5 * g * age * age;
+ vec3 ph = aO + aV * th + 0.5 * g * th * th; ph.y = 0.02;
+ vec3 vh = aV + g * th;
+ vec3 nv = vec3(vh.x * 0.42, -vh.y * 0.26, vh.z * 0.42);
+ float a2 = age - th;
+ vec3 p = ph + nv * a2 + 0.5 * g * a2 * a2;
+ p.y = max(p.y, 0.02);
+ return p;
+ }
+ void main(){
+ float age = uTime - aD.x; float t = age / aD.y;
+ if (t < 0.0 || t > 1.0) { gl_Position = vec4(0.0, 0.0, -2.0, 1.0); return; }
+ vec3 h = posAt(age), tl = posAt(max(age - 0.045, 0.0));
+ vec4 ch = projectionMatrix * viewMatrix * vec4(h, 1.0);
+ vec4 ct = projectionMatrix * viewMatrix * vec4(tl, 1.0);
+ vec2 asp = vec2(uRes.x / uRes.y, 1.0);
+ vec2 dir = (ch.xy / ch.w - ct.xy / ct.w) * asp;
+ float l = length(dir);
+ dir = l > 1e-6 ? dir / l : vec2(0.0, 1.0);
+ vec2 nrm = vec2(-dir.y, dir.x) / asp;
+ float along = position.y + 0.5;
+ vec4 c = mix(ct, ch, along);
+ c.xy += nrm * position.x * (uWidth * aD.z) / uRes.y * 2.0 * c.w;
+ // stretch a little past the head so slow sparks still read as dots
+ c.xy += vec2(dir.x, dir.y) / asp * (along - 0.5) * (uWidth * aD.z) / uRes.y * 2.0 * c.w;
+ gl_Position = c;
+ vHeat = pow(1.0 - t, 1.3) * aD.w;
+ vA = 1.0 - smoothstep(0.7, 1.0, t);
+ vUv = vec2(position.x + 0.5, along);
+ }`,
+ fragmentShader: `
+ varying float vHeat; varying float vA; varying vec2 vUv;
+ void main(){
+ float x = 1.0 - abs(vUv.x - 0.5) * 2.0;
+ vec3 hot = vec3(1.0, 0.95, 0.8), mid = vec3(1.0, 0.55, 0.12), cold = vec3(0.6, 0.08, 0.01);
+ vec3 c = mix(cold, mix(mid, hot, smoothstep(0.55, 1.0, vHeat)), smoothstep(0.0, 0.55, vHeat));
+ gl_FragColor = vec4(c * (2.0 + vHeat * 10.0) * vA * x * vUv.y, 1.0);
+ }`,
+ });
+ this.mesh = new THREE.Mesh(this.pool.geo, this.mat);
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 8;
+ }
+ emit(origin, normal, n, t) {
+ for (let k = 0; k < n; k++) {
+ _v.set(Math.random() - 0.5, Math.random() - 0.3, Math.random() - 0.5).multiplyScalar(2).add(_o.copy(normal).multiplyScalar(1.3)).normalize()
+ .multiplyScalar(1.5 + Math.random() * 5.5);
+ this.pool.spawn(origin, _v, t, 0.6 + Math.random() * 1.6, 0.6 + Math.random() * 0.9, 0.7 + Math.random() * 0.3);
+ }
+ }
+ update(t) { this.mat.uniforms.uTime.value = t; this.pool.flush(); }
+}
+
+/** Dust motes that only exist where the floods and searchlight pass. */
+export class BeamDust {
+ constructor(count = 9000) {
+ const pos = new Float32Array(count * 3), seed = new Float32Array(count);
+ for (let i = 0; i < count; i++) {
+ const r = Math.sqrt(Math.random()) * 17, a = Math.random() * Math.PI * 2;
+ pos.set([Math.cos(a) * r, Math.random() * 20 + 0.3, Math.sin(a) * r + 1], i * 3);
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const L = 6;
+ this.mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: {
+ uTime: { value: 0 }, uDpr: { value: 1 }, uFall: { value: 0 },
+ uLP: { value: Array.from({ length: L }, () => new THREE.Vector3()) },
+ uLD: { value: Array.from({ length: L }, () => new THREE.Vector3(0, -1, 0)) },
+ uLC: { value: Array.from({ length: L }, () => new THREE.Vector4(0.9, 0, 0, 0)) }, // cos, rgb*power
+ },
+ vertexShader: `
+ attribute float seed; uniform float uTime, uDpr, uFall;
+ uniform vec3 uLP[${L}]; uniform vec3 uLD[${L}]; uniform vec4 uLC[${L}];
+ varying float vA; varying vec3 vC;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.04 + seed * 0.05);
+ p += vec3(sin(t * 3.1 + seed * 40.0), sin(t * 2.3 + seed * 13.0) * 0.6, cos(t * 2.7 + seed * 27.0)) * 0.8;
+ p.y -= uFall * (uTime * (1.5 + seed * 2.0));
+ p.y = mod(p.y, 20.0) + 0.3;
+ vec3 acc = vec3(0.0);
+ for (int i = 0; i < ${L}; i++) {
+ vec4 lc = uLC[i];
+ if (lc.y + lc.z + lc.w <= 0.0) continue;
+ vec3 d = p - uLP[i]; float dist = length(d);
+ float cone = smoothstep(lc.x, lc.x + 0.02, dot(d / dist, uLD[i]));
+ acc += lc.yzw * cone / (1.0 + dist * dist * 0.004);
+ }
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ vA = (0.35 + 0.65 * fract(seed * 91.7)) * smoothstep(1.5, 5.0, -mv.z);
+ vC = acc;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = min((1.0 + seed * 2.4) * (22.0 / -mv.z), 5.0) * uDpr;
+ }`,
+ fragmentShader: `varying float vA; varying vec3 vC; void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.0, d); gl_FragColor = vec4(vC * a * vA * 0.9, 1.0); }`,
+ });
+ this.points = new THREE.Points(geo, this.mat);
+ this.points.frustumCulled = false;
+ this.L = L;
+ }
+ setLight(i, light, power) {
+ const u = this.mat.uniforms;
+ light.updateMatrixWorld(); light.target.updateMatrixWorld();
+ u.uLP.value[i].setFromMatrixPosition(light.matrixWorld);
+ u.uLD.value[i].setFromMatrixPosition(light.target.matrixWorld).sub(u.uLP.value[i]).normalize();
+ const c = light.color;
+ u.uLC.value[i].set(Math.cos(light.angle * 0.92), c.r * power, c.g * power, c.b * power);
+ }
+}
diff --git a/examples/hangar/index.html b/examples/hangar/index.html
new file mode 100644
index 0000000..fa829fc
--- /dev/null
+++ b/examples/hangar/index.html
@@ -0,0 +1,245 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Hangar Nine — HN-9 “Warden” Test-Pilot Program</title>
+ <meta name="description" content="HN-9 “Warden”. Forty tons. One pilot. Hangar Nine is recruiting six test pilots for Cohort 09.">
+ <meta name="theme-color" content="#07080a">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Cpath d=%22M16 2 29 9.5v13L16 30 3 22.5v-13Z%22 fill=%22%23ffb000%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Chakra+Petch:ital,wght@0,400;0,500;0,600;0,700;1,500&family=Rajdhani:wght@400;500;600&family=Share+Tech+Mono&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body class="is-cold">
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="flash" aria-hidden="true"></div>
+ <div class="scrim scrim-l" aria-hidden="true"></div><div class="scrim scrim-r" aria-hidden="true"></div><div class="scrim scrim-b" aria-hidden="true"></div>
+
+ <!-- Loader: firmware boot behind two blast-door halves -->
+ <div class="loader" role="status" aria-live="polite">
+ <div class="ld-door ld-top"></div>
+ <div class="ld-door ld-bot"></div>
+ <div class="ld-bar"><i></i></div>
+ <div class="ld-in">
+ <div class="ld-up">
+ <div class="ld-head mono"><span>Hangar Nine Heavy Systems</span><span>HN-9 FW 4.12.0</span></div>
+ <p class="ld-num"><span class="ld-pct">000</span><i>%</i></p>
+ </div>
+ <ol class="ld-log mono ld-down">
+ <li data-at="0.02">› Bay 09 link established</li>
+ <li data-at="0.2">› Mounting chassis mesh A7-019</li>
+ <li data-at="0.45">› Loading actuator map ··· 41/41</li>
+ <li data-at="0.7">› Recon drone RD-3 docked</li>
+ <li data-at="0.92">› Warming shaders</li>
+ <li data-at="1">› Standby. Awaiting pilot.</li>
+ </ol>
+ </div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Hangar Nine home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><path d="M16 2 29 9.5v13L16 30 3 22.5v-13Z" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M19.5 17.2a4.2 4.2 0 1 1 .6-2.2V21l-2.8 2.4" fill="none" stroke="currentColor" stroke-width="2"/></svg>
+ <span>Hangar<b>Nine</b></span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#warden">The Warden</a>
+ <a href="#systems">Systems</a>
+ <a href="#numbers">Numbers</a>
+ <a href="#program">Program</a>
+ </nav>
+ <div class="nav-r">
+ <button class="snd mono" type="button" aria-pressed="false" aria-label="Toggle sound">Snd <span class="snd-bars"><i></i><i></i><i></i><i></i></span><span class="snd-state">Off</span></button>
+ <a class="btn btn-amber" href="#apply" data-magnetic>Apply · Cohort 09</a>
+ </div>
+ </header>
+
+ <!-- HUD frame: boots during power-up -->
+ <div class="hud" aria-hidden="true">
+ <i class="hc tl"></i><i class="hc tr"></i><i class="hc bl"></i><i class="hc br"></i>
+ <div class="hud-top mono"><span class="hud-id">HN-9 · A7-019</span><span class="hud-sep"></span><span class="hud-state">Reactor cold</span><span class="hud-sep"></span><span class="hud-clock">03:12:07</span></div>
+ <div class="hud-side mono">
+ <div class="rd"><span>RCTR</span><b class="rd-rctr">0.3%</b><i><em style="--v:.02"></em></i></div>
+ <div class="rd"><span>CORE</span><b class="rd-core">31°C</b><i><em style="--v:.05"></em></i></div>
+ <div class="rd"><span>HYD</span><b class="rd-hyd">0 bar</b><i><em style="--v:0"></em></i></div>
+ <div class="rd"><span>SYNC</span><b class="rd-sync">—</b><i><em style="--v:0"></em></i></div>
+ </div>
+ <div class="hud-scan"></div>
+ <div class="hud-reticle"><i></i><i></i><i></i><i></i><span class="mono">HN-9 WARDEN<br><b>PILOT SEAT · VACANT</b></span></div>
+ <ol class="hud-boot mono"></ol>
+ </div>
+
+ <!-- Hotspot markers (positioned from 3D) -->
+ <div class="spots" role="group" aria-label="Systems hotspots"></div>
+ <svg class="leader" aria-hidden="true"><line x1="0" y1="0" x2="0" y2="0"/><circle r="3"/></svg>
+ <div class="ruler" aria-hidden="true"><i class="ruler-line"></i><span class="ruler-top mono">11.4 m</span><span class="ruler-bot mono">0.0</span></div>
+
+ <!-- Press-and-hold gauge that follows the pointer in the hero -->
+ <div class="hold" aria-hidden="true">
+ <svg viewBox="0 0 100 100"><circle class="h-track" cx="50" cy="50" r="44"/><circle class="h-fill" cx="50" cy="50" r="44" pathLength="1"/></svg>
+ <span class="h-label mono">Hold</span>
+ </div>
+
+ <main id="top">
+ <section class="sec hero" data-shot="hero">
+ <div class="pin">
+ <div class="hero-copy">
+ <p class="eyebrow mono"><span class="blink"></span>Northfield Proving Ground · Bay 09 · 03:12 local</p>
+ <h1 class="title" aria-label="HN-9 Warden"><span class="t1">HN-9</span><span class="t2"><q>Warden</q></span></h1>
+ <p class="tag">Forty tons. <em>One pilot.</em></p>
+ <p class="lede">Hangar Nine is recruiting six test pilots for the Warden’s final certification year. It has been asleep since the last shift. Wake it up.</p>
+ </div>
+ <div class="ignite">
+ <button class="gauge" type="button" aria-label="Press and hold to power up the Warden">
+ <svg viewBox="0 0 160 160" aria-hidden="true">
+ <circle class="g-ticks" cx="80" cy="80" r="74"/>
+ <circle class="g-track" cx="80" cy="80" r="64"/>
+ <circle class="g-fill" cx="80" cy="80" r="64" pathLength="1"/>
+ </svg>
+ <span class="g-core"><span class="g-label">Hold to<br>initiate</span><span class="g-pct mono">00</span></span>
+ </button>
+ <div class="ignite-copy">
+ <p class="ignite-title mono">Cold start</p>
+ <p class="ignite-hint">Press and hold anywhere — or hold <kbd>Space</kbd> — to bring the reactor up.</p>
+ </div>
+ </div>
+ <p class="scroll-cue mono"><span><b>Move</b> to aim the drone’s searchlight</span><span><b>Scroll</b> to walk around it</span><i></i></p>
+ </div>
+ </section>
+
+ <section class="sec power" id="warden" data-shot="power">
+ <div class="pin">
+ <div class="block block-r">
+ <p class="kicker mono">01 — Cold start</p>
+ <h2>Standby to standing weight in <em>9.2&nbsp;seconds.</em></h2>
+ <p class="body">The Warden idles at 0.3% reactor draw — just enough to keep the gyros warm and the coolant moving. What you just did is the fastest cold start of any frame in its class. Every pilot in the program has done it a few hundred times, and every one of them still grins when the lights come on.</p>
+ <ol class="steps">
+ <li><b class="mono">T+0.0</b><span><strong>Ignition.</strong> The salt core reaches operating temperature in 3.1 s. You feel it through the seat first.</span></li>
+ <li><b class="mono">T+3.4</b><span><strong>Handshake.</strong> Forty-one actuators report in, heel to crown, in 0.6 s.</span></li>
+ <li><b class="mono">T+9.2</b><span><strong>Sync.</strong> The harness calibrates to your reflexes — not the other way round.</span></li>
+ </ol>
+ </div>
+ </div>
+ </section>
+
+ <div id="systems">
+ <section class="sec spec" data-shot="reactor" data-spot="0">
+ <div class="pin">
+ <article class="card card-l">
+ <p class="kicker mono"><span>02.1</span> Systems · Reactor</p>
+ <h3>A 42-megawatt heart, sealed for life.</h3>
+ <p class="body">A molten-salt core the size of a beer keg sits behind the chest plate. It is sealed at the factory and never opened again. It makes enough power for a small town and enough heat to boil the rain off the armour.</p>
+ <dl class="data mono"><div><dt>Output</dt><dd>42 MW cont.</dd></div><div><dt>Endurance</dt><dd>96 h</dd></div><div><dt>Failsafe</dt><dd>Passive drain-down</dd></div></dl>
+ </article>
+ </div>
+ </section>
+ <section class="sec spec" data-shot="actuators" data-spot="1">
+ <div class="pin">
+ <article class="card card-r">
+ <p class="kicker mono"><span>02.2</span> Systems · Actuators</p>
+ <h3>Forty-one joints that know when you flinch.</h3>
+ <p class="body">Every joint is an electro-hydraulic actuator with its own controller and its own opinion. The knees carry 1,900 kilonewtons at full stride and still correct for a loose paving slab in under a millisecond. You decide where to go. They decide not to fall over.</p>
+ <dl class="data mono"><div><dt>Joints</dt><dd>41</dd></div><div><dt>Response</dt><dd>0.8 ms</dd></div><div><dt>Knee load</dt><dd>1,900 kN</dd></div></dl>
+ </article>
+ </div>
+ </section>
+ <section class="sec spec" data-shot="armour" data-spot="2">
+ <div class="pin">
+ <article class="card card-l">
+ <p class="kicker mono"><span>02.3</span> Systems · Armour</p>
+ <h3>Bolted, not welded. On purpose.</h3>
+ <p class="body">Layered ceramic over a titanium lattice, hung in 212 panels. Every one comes off with a single socket size, so a four-person field crew can swap a shoulder in forty minutes — in the rain, at night, with you still in the seat.</p>
+ <dl class="data mono"><div><dt>Composite</dt><dd>180 mm</dd></div><div><dt>Panels</dt><dd>212</dd></div><div><dt>Field swap</dt><dd>40 min</dd></div></dl>
+ </article>
+ </div>
+ </section>
+ <section class="sec spec" data-shot="weapons" data-spot="3">
+ <div class="pin">
+ <article class="card card-r">
+ <p class="kicker mono"><span>02.4</span> Systems · Hardpoints</p>
+ <h3>The last thing you certify. The least interesting.</h3>
+ <p class="body">A six-barrel rotary on the right shoulder, a twelve-cell pod on the left, and a 2.1-metre forearm shield you will use more than both. Trials fire inert rounds only. Most of your hours go into lifting, bracing and walking — the Warden’s first deployments are disaster response.</p>
+ <dl class="data mono"><div><dt>Rotary</dt><dd>30 mm × 6</dd></div><div><dt>Pod</dt><dd>12 cells</dd></div><div><dt>Shield</dt><dd>2.1 m</dd></div></dl>
+ </article>
+ </div>
+ </section>
+ </div>
+
+ <section class="sec stats" id="numbers" data-shot="stats">
+ <div class="pin">
+ <div class="block block-l">
+ <p class="kicker mono">03 — The numbers the insurers asked about first</p>
+ <ul class="figs">
+ <li><b data-count="11.4" data-dec="1">0</b><i>m</i><span class="mono">Standing height, heel to crown</span></li>
+ <li><b data-count="40" data-dec="0">0</b><i>t</i><span class="mono">Mass with a full core — and one pilot</span></li>
+ <li><b data-count="42" data-dec="0">0</b><i>MW</i><span class="mono">Continuous reactor output</span></li>
+ <li><b data-count="68" data-dec="0">0</b><i>km/h</i><span class="mono">Top speed on flat ground. Yes, it runs.</span></li>
+ </ul>
+ </div>
+ </div>
+ </section>
+
+ <section class="sec program" id="program" data-shot="program">
+ <div class="pin">
+ <div class="block block-l wide">
+ <p class="kicker mono">04 — The test-pilot program · Cohort 09</p>
+ <h2>Six seats. Twenty-three weeks. <em>One very large first step.</em></h2>
+ <ol class="timeline">
+ <li><b class="mono">Wk 01–08</b><strong>Simulator</strong><span>A full-scale motion rig. You will fall over in here so you never do out there.</span></li>
+ <li><b class="mono">Wk 09–16</b><strong>Tethered</strong><span>The Warden on a sixty-tonne gantry harness. Your first real steps, with a safety net the size of a building.</span></li>
+ <li><b class="mono">Wk 17–23</b><strong>Untethered</strong><span>The proving ground: rubble fields, flooded streets, night work, rain.</span></li>
+ <li><b class="mono">Grad.</b><strong>Callsign</strong><span>Painted on a shoulder plate by the crew who kept you upright.</span></li>
+ </ol>
+ <div class="req">
+ <p class="mono req-t">You bring</p>
+ <ul>
+ <li>1,500+ hours rotary or fixed-wing — or five years running heavy plant</li>
+ <li>Sustained 5 g tolerance and a clean medical</li>
+ <li>Standing height 1.60–1.93 m. The seat is not adjustable; the pilot is.</li>
+ <li>Calm. We test for it.</li>
+ </ul>
+ </div>
+ </div>
+ <figure class="quote">
+ <img src="/img/hangar/pilot.webp" alt="Captain Ines Varga in a grey flight suit, helmet under her arm, in the hangar" width="960" height="1285" loading="lazy">
+ <blockquote>“The first step is the loudest thing you will ever feel. The second one is yours.”</blockquote>
+ <figcaption class="mono">Capt. Ines Varga · Pilot 004 · Cohort 03</figcaption>
+ </figure>
+ </div>
+ </section>
+
+ <section class="sec apply" id="apply" data-shot="apply">
+ <div class="pin">
+ <div class="cta">
+ <p class="kicker mono">05 — Applications close 14 November</p>
+ <h2 class="cta-title">Your shift<br>starts at <em>dawn.</em></h2>
+ <p class="body">Shortlisted candidates spend two days at Northfield: one in the simulator, one in the seat. Nobody arrives with mech experience. Nobody has any.</p>
+ <div class="cta-row">
+ <a class="btn btn-amber btn-lg" href="#apply" data-magnetic data-cursor="label" data-cursor-label="Go">Begin application</a>
+ <a class="btn btn-ghost btn-lg" href="#apply" data-magnetic>Pilot’s brief · PDF 2.4 MB</a>
+ </div>
+ <p class="cta-meta mono">2,418 applied for Cohort 08 · Six seats · Northfield, Gate C</p>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <footer class="foot">
+ <div class="foot-in">
+ <div class="foot-brand">
+ <p class="foot-mark">Hangar<b>Nine</b></p>
+ <p class="mono">Heavy Systems · Northfield Proving Ground · Bay 09</p>
+ </div>
+ <nav class="foot-cols" aria-label="Footer">
+ <div><p class="mono">Program</p><a href="#program">Cohort 09</a><a href="#numbers">Requirements</a><a href="#apply">Apply</a></div>
+ <div><p class="mono">Hangar</p><a href="#systems">The Warden</a><a href="#top">Safety record</a><a href="#top">Ground crew careers</a></div>
+ <div><p class="mono">Visit</p><span>Gate C, Northfield</span><span>Tours Saturdays, 10:00</span><span>Ear protection provided</span></div>
+ </nav>
+ <p class="foot-legal mono"><span>© 2026 Hangar Nine Heavy Systems — a fictional manufacturer.</span><span>The Warden is not for sale. The seats are.</span></p>
+ </div>
+ </footer>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/hangar/main.js b/examples/hangar/main.js
new file mode 100644
index 0000000..5c1c10d
--- /dev/null
+++ b/examples/hangar/main.js
@@ -0,0 +1,899 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { Effect, EffectPass } from 'postprocessing';
+import { fbmTexture } from '../../src/core/textures.js';
+import { HangarVolumetric } from './volumetric.js';
+import { buildHangar, BAYS_Z } from './world.js';
+import { mechUniforms, patchMech, scanSheet, Steam, Sparks, BeamDust } from './fx.js';
+import { Sound } from './audio.js';
+
+const DBG = new URLSearchParams(location.search);
+const D = Math.PI / 180;
+const MECH_H = 11.4;
+const HOLD_TIME = 1.9;
+const body = document.body;
+const reduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+// If the GPU drops the context (driver reset, tab starved), ask for it back and restart cleanly.
+canvas.addEventListener('webglcontextlost', e => e.preventDefault());
+canvas.addEventListener('webglcontextrestored', () => location.reload());
+let vol;
+const engine = new Engine({
+ canvas, fov: 38, near: 0.15, far: 300, dpr: 1.5, background: 0x040506,
+ post: {
+ ao: { aoRadius: 1.6, intensity: 2.4, distanceFalloff: 1.2 },
+ bloom: { intensity: 0.95, luminanceThreshold: 0.62, luminanceSmoothing: 0.32, radius: 0.84 },
+ pre: cam => [(vol = new HangarVolumetric(cam, { density: 0.022, noise: 0.92, noiseScale: 0.19, maxDist: 75, floorY: 0, hazeTop: 30, phase: 0.7 }))],
+ tone: DBG.get('tone') || 'aces',
+ vignette: { offset: 0.18, darkness: 0.86 },
+ noise: 0.075,
+ ca: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+// Clamp + NaN guard before bloom: 4000 cd floods on near-mirror metal can overflow half-float specular,
+// and one Inf pixel smeared by the bloom mip chain blacks out the whole frame.
+{
+ const clampFx = new Effect('HN9Clamp', `void mainImage(const in vec4 c, const in vec2 uv, out vec4 o){ vec3 v = c.rgb; if (any(isnan(v)) || any(isinf(v))) v = vec3(0.0); o = vec4(min(max(v, vec3(0.0)), vec3(64.0)), c.a); }`);
+ const { composer } = engine.post;
+ composer.addPass(new EffectPass(camera, clampFx), engine.post.ao ? 2 : 1);
+}
+// Hold distortion: radial RGB split + zoom streaks that build with the charge and spike at ignition.
+const surgeFx = new Effect('HN9Surge', `
+ uniform float uAmt;
+ void mainImage(const in vec4 c, const in vec2 uv, out vec4 o){
+ vec2 d = uv - 0.5; float r = length(d);
+ vec2 off = d * r * (0.004 + uAmt * 0.03);
+ vec3 col = vec3(texture2D(inputBuffer, uv + off).r, c.g, texture2D(inputBuffer, uv - off).b);
+ if (uAmt > 0.02) {
+ vec3 acc = col; float w = 1.0;
+ for (int i = 1; i < 7; i++) { float k = float(i) / 6.0; vec2 q = uv - d * k * 0.07 * uAmt; acc += texture2D(inputBuffer, q).rgb * (1.0 - k * 0.6); w += 1.0 - k * 0.6; }
+ col = mix(col, acc / w, clamp(uAmt * 1.4, 0.0, 0.85));
+ }
+ o = vec4(col, c.a);
+ }`, { uniforms: new Map([['uAmt', new THREE.Uniform(0)]]) });
+engine.post.composer.addPass(new EffectPass(camera, surgeFx));
+scene.fog = new THREE.FogExp2(0x06080b, 0.0105);
+
+const envLive = studioEnvironment(renderer, {
+ top: 0x262b33, bottom: 0x08090b, blur: 0.05, panels: [
+ { pos: [0, 9, 0], size: [2.2, 16], intensity: 5, color: 0xf0f3ff },
+ { pos: [-6, 9, 0], size: [1.6, 16], intensity: 3.2, color: 0xf0f3ff },
+ { pos: [6, 9, 0], size: [1.6, 16], intensity: 3.2, color: 0xf0f3ff },
+ { pos: [0, 2.5, 10], size: [9, 4], intensity: 1.1, color: 0xffd6a8 },
+ { pos: [-10, 3, -3], size: [3, 6], intensity: 0.9, color: 0xa8c8ff },
+ ],
+});
+const envCold = studioEnvironment(renderer, {
+ top: 0x0a0b0e, bottom: 0x020203, blur: 0.05, panels: [
+ { pos: [-7, 4, -5], size: [1.5, 3], intensity: 2.2, color: 0xff1a0a },
+ { pos: [7, 4, -5], size: [1.5, 3], intensity: 2.2, color: 0xff1a0a },
+ { pos: [0, 9, 0], size: [12, 1.5], intensity: 0.5, color: 0x5a78a8 },
+ ],
+});
+scene.environment = envCold;
+scene.environmentIntensity = 0.12;
+const hemi = new THREE.HemisphereLight(0x7088aa, 0x0c0a09, 0.02);
+scene.add(hemi);
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+const sound = new Sound();
+
+// ─── Loader ────────────────────────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+const ldLog = [...loaderEl.querySelectorAll('.ld-log li')];
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ loaderEl.querySelector('.ld-pct').textContent = String(Math.round(v * 100)).padStart(3, '0');
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ for (const li of ldLog) li.classList.toggle('on', v >= +li.dataset.at - 1e-3);
+ },
+ exit: async () => {
+ const tl = gsap.timeline();
+ tl.to('.ld-in', { opacity: 0, duration: 0.3 })
+ .to('.ld-bar', { opacity: 0, duration: 0.2 }, 0.2)
+ .to('.ld-top', { yPercent: -101, duration: 1.1, ease: 'power4.inOut' }, 0.25)
+ .to('.ld-bot', { yPercent: 101, duration: 1.1, ease: 'power4.inOut' }, 0.25);
+ await tl;
+ },
+});
+
+// ─── World ────────────────────────────────────────────────────────────────────
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+const mechP = assets.gltf('models/hangar/mech.glb');
+const droneP = assets.gltf('models/hangar/drone.glb');
+await Promise.race([
+ Promise.all(['700 100px "Chakra Petch"', '600 100px "Chakra Petch"'].map(f => document.fonts.load(f))),
+ new Promise(r => setTimeout(r, 2500)),
+]);
+const W = buildHangar({ scene, renderer, reflection, maxAniso: renderer.capabilities.getMaxAnisotropy() });
+
+// Volumetric registrations
+const floodVol = W.floods.map((f, i) => vol.add(f.light, { scale: i < 2 ? 0.0019 : 0.0003, range: 0.009, softness: 0.3 }));
+const beaconVol = W.beacons.map(b => vol.add(b.light, { scale: 0.006, range: 0.01, softness: 0.5 }));
+
+// Scene lights beyond the fixtures
+const strobe = new THREE.PointLight(0xff2210, 0, 34, 2);
+strobe.position.set(0, 9.5, -8.5);
+scene.add(strobe);
+const visorLight = new THREE.PointLight(0xff7a20, 0, 9, 2);
+scene.add(visorLight);
+const weldLight = new THREE.PointLight(0xa8d8ff, 0, 14, 2);
+scene.add(weldLight);
+const droneSpot = new THREE.SpotLight(0xe6f4ff, 0, 45, 0.15, 0.55, 2);
+scene.add(droneSpot, droneSpot.target);
+const droneVol = vol.add(droneSpot, { scale: 0.0055, range: 0.014, softness: 0.45 });
+const dawn = new THREE.SpotLight(0xffa860, 0, 0, 0.36, 0.7, 2);
+dawn.position.set(0, 17, 100);
+dawn.target.position.set(0, 0, -6);
+dawn.castShadow = true;
+dawn.shadow.mapSize.set(2048, 2048);
+dawn.shadow.camera.near = 50; dawn.shadow.camera.far = 150;
+dawn.shadow.bias = -0.0002; dawn.shadow.normalBias = 0.05;
+dawn.shadow.autoUpdate = false;
+dawn.shadow.needsUpdate = true;
+scene.add(dawn, dawn.target);
+const dawnVol = vol.add(dawn, { scale: 0.000006, range: 0.00004, softness: 0.6 });
+// Cold moonlight through the clerestory: the only non-red light before power-up.
+const moon = new THREE.SpotLight(0x7f9cd8, 0, 0, 0.1, 0.6, 2);
+moon.position.set(-29, 23, -16);
+moon.target.position.set(1.5, 4, -1.5);
+scene.add(moon, moon.target);
+const moonVol = vol.add(moon, { scale: 0.0045, range: 0.0006, softness: 0.6 });
+
+// FX
+const MU = mechUniforms();
+const sheet = scanSheet();
+scene.add(sheet);
+const steamNoise = fbmTexture(renderer, { size: 256, scale: 4, octaves: 5, contrast: 1.4, bias: 0.5 });
+const steam = new Steam(steamNoise);
+scene.add(steam.mesh);
+const sparks = new Sparks();
+scene.add(sparks.mesh);
+const dust = new BeamDust(DBG.has('nodust') ? 10 : 9000);
+scene.add(dust.points);
+engine.onResize((w, h, dpr) => { dust.mat.uniforms.uDpr.value = dpr; sparks.mat.uniforms.uRes.value.set(w, h); });
+// Weld glow billboard
+const glowTex = (() => {
+ const c = document.createElement('canvas'); c.width = c.height = 128;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ grd.addColorStop(0, 'rgba(255,255,255,1)'); grd.addColorStop(0.12, 'rgba(200,235,255,.9)'); grd.addColorStop(0.35, 'rgba(90,170,255,.25)'); grd.addColorStop(1, 'rgba(0,0,0,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
+ return new THREE.CanvasTexture(c);
+})();
+const weldGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: new THREE.Color(0, 0, 0), blending: THREE.AdditiveBlending, depthWrite: false, fog: false }));
+weldGlow.scale.setScalar(1.6);
+scene.add(weldGlow);
+const visorGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: new THREE.Color(0, 0, 0), blending: THREE.AdditiveBlending, depthWrite: false, depthTest: true, fog: false }));
+visorGlow.scale.set(2.8, 1.2, 1);
+scene.add(visorGlow);
+
+// ─── Mech + drone ───────────────────────────────────────────────────────────────
+const mechGroup = new THREE.Group();
+scene.add(mechGroup);
+const A = {}; // anchors
+let mechMesh = null;
+
+function probeSetup(mesh) {
+ mesh.updateMatrixWorld(true);
+ const p = mesh.geometry.attributes.position;
+ const out = new Float32Array(p.count * 3);
+ const v = new THREE.Vector3();
+ for (let i = 0; i < p.count; i++) { v.fromBufferAttribute(p, i).applyMatrix4(mesh.matrixWorld); out[i * 3] = v.x; out[i * 3 + 1] = v.y; out[i * 3 + 2] = v.z; }
+ return out;
+}
+/** First surface point along a thick ray (vertex based — fast on 250k verts, good enough for anchors). */
+function probe(P, o, dir, r = 0.25) {
+ let best = Infinity, bi = -1;
+ const r2 = r * r;
+ for (let i = 0; i < P.length; i += 3) {
+ const dx = P[i] - o.x, dy = P[i + 1] - o.y, dz = P[i + 2] - o.z;
+ const t = dx * dir.x + dy * dir.y + dz * dir.z;
+ if (t < 0 || t > best) continue;
+ const px = dx - dir.x * t, py = dy - dir.y * t, pz = dz - dir.z * t;
+ if (px * px + py * py + pz * pz < r2) { best = t; bi = i; }
+ }
+ return bi < 0 ? null : new THREE.Vector3(P[bi], P[bi + 1], P[bi + 2]);
+}
+
+const mechLoad = mechP.then(g => {
+ const m = g.scene;
+ normalize(m, MECH_H, { axis: 'y' });
+ prepModel(m, renderer, { env: 1.0, onMat: mat => { patchMech(mat, MU); } });
+ mechGroup.add(m);
+ mechGroup.updateMatrixWorld(true);
+ mechMesh = firstMesh(m);
+ const P = probeSetup(mechMesh);
+ let crown = 0;
+ for (let i = 0; i < P.length; i += 3) if (Math.abs(P[i]) < 0.45 && P[i + 1] > crown) crown = P[i + 1];
+ A.crown = crown;
+ const fwd = new THREE.Vector3(0, 0, -1);
+ A.visor = probe(P, new THREE.Vector3(0, crown - 0.62, 40), fwd, 0.22) ?? new THREE.Vector3(0, crown - 0.6, 1);
+ A.reactor = probe(P, new THREE.Vector3(0, MECH_H * 0.71, 40), fwd, 0.3) ?? new THREE.Vector3(0, 8, 1.5);
+ A.knee = probe(P, new THREE.Vector3(1.7, MECH_H * 0.31, 40), fwd, 0.35) ?? new THREE.Vector3(1.7, 3.5, 1);
+ A.shoulder = probe(P, new THREE.Vector3(40, MECH_H * 0.78, 0.2), new THREE.Vector3(-1, 0, 0), 0.4) ?? new THREE.Vector3(3.8, 8.9, 0);
+ {
+ // shoulder rotary: centroid of everything high on the -x side
+ const c = new THREE.Vector3(); let n = 0;
+ for (let i = 0; i < P.length; i += 3) if (P[i + 1] > MECH_H * 0.86 && P[i] < -1.3) { c.x += P[i]; c.y += P[i + 1]; c.z += P[i + 2]; n++; }
+ A.gun = n ? c.multiplyScalar(1 / n) : new THREE.Vector3(-2.6, 10.5, 0.8);
+ A.gun.y += 0.35;
+ }
+ A.weld = probe(P, new THREE.Vector3(40, MECH_H * 0.71, -1.6), new THREE.Vector3(-1, 0, 0), 0.3) ?? new THREE.Vector3(3.6, 8.1, -1.6);
+ A.normals = { reactor: new THREE.Vector3(0, 0, 1), knee: new THREE.Vector3(0.3, 0, 1).normalize(), shoulder: new THREE.Vector3(1, 0.1, 0).normalize(), gun: new THREE.Vector3(0, 1, 0.2).normalize() };
+ MU.uVisorPos.value.copy(A.visor).add(new THREE.Vector3(0, 0, -0.25));
+ visorLight.position.copy(A.visor).add(new THREE.Vector3(0, -0.4, 1.4));
+ visorGlow.position.copy(A.visor).add(new THREE.Vector3(0, 0, 0.15));
+ if (DBG.has('anchors')) console.warn('anchors', ['shoulder', 'gun', 'weld'].map(k => k + ':' + A[k].toArray().map(v => v.toFixed(2)).join(',')).join(' '));
+ buildArm(A.weld);
+});
+
+let drone = null;
+const droneGroup = new THREE.Group();
+scene.add(droneGroup);
+const droneLoad = droneP.then(g => {
+ const m = g.scene;
+ normalize(m, 1.7, { axis: 'max' });
+ prepModel(m, renderer, { env: 1.2 });
+ // centre vertically so it pivots about its body
+ m.position.y -= 0.35;
+ droneGroup.add(m);
+ // nav lights
+ for (const [x, c] of [[-0.8, 0xff2a14], [0.8, 0x2aff6a]]) {
+ const s = new THREE.Mesh(new THREE.SphereGeometry(0.045, 8, 6), new THREE.MeshBasicMaterial({ color: new THREE.Color(c).multiplyScalar(6) }));
+ s.position.set(x, -0.05, 0.1); droneGroup.add(s);
+ }
+ drone = m;
+});
+
+// Welding arm on the right tower reaching the mech's shoulder.
+let weldTip = new THREE.Vector3();
+const armMat = new THREE.MeshStandardMaterial({ color: 0xa87406, metalness: 0.4, roughness: 0.55 });
+const armDark = new THREE.MeshStandardMaterial({ color: 0x1c1f23, metalness: 0.7, roughness: 0.5 });
+const steelArm = new THREE.MeshStandardMaterial({ color: 0xb8bcc2, metalness: 1, roughness: 0.22 });
+function buildArm(tip) {
+ const base = new THREE.Vector3(W.T.xin + 0.2, W.levels[1] + 0.1, -4.4);
+ const t = tip.clone().add(new THREE.Vector3(0.55, 0.15, 0));
+ weldTip = tip.clone().add(new THREE.Vector3(0.06, 0, 0));
+ const shoulder = base.clone().add(new THREE.Vector3(0, 1.1, 0));
+ // two-bone IK: elbow up and back
+ const L1 = 2.3, L2 = 2.1;
+ const d = t.clone().sub(shoulder); const dl = Math.min(d.length(), L1 + L2 - 0.01);
+ const a = (L1 * L1 - L2 * L2 + dl * dl) / (2 * dl);
+ const h = Math.sqrt(Math.max(L1 * L1 - a * a, 0));
+ const dn = d.clone().normalize();
+ const up = new THREE.Vector3(0, 1, 0).addScaledVector(dn, -dn.y).normalize();
+ const elbow = shoulder.clone().addScaledVector(dn, a).addScaledVector(up, h);
+ const seg = (p0, p1, r, mat, round = true) => {
+ const len = p0.distanceTo(p1);
+ const g = round ? new THREE.CylinderGeometry(r * 0.5, r * 0.5, len, 18) : new THREE.BoxGeometry(r, len, r);
+ const m = new THREE.Mesh(g, mat);
+ m.position.copy(p0).add(p1).multiplyScalar(0.5);
+ m.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), p1.clone().sub(p0).normalize());
+ m.castShadow = true; m.receiveShadow = true;
+ scene.add(m);
+ return m;
+ };
+ const joint = (p, r, axis) => {
+ const m = new THREE.Mesh(new THREE.CylinderGeometry(r, r, r * 1.5, 24), armDark);
+ m.position.copy(p);
+ m.quaternion.setFromUnitVectors(new THREE.Vector3(0, 1, 0), axis);
+ m.castShadow = true; scene.add(m);
+ };
+ const side = new THREE.Vector3().subVectors(t, shoulder).cross(new THREE.Vector3(0, 1, 0)).normalize();
+ seg(base, shoulder, 0.62, armDark);
+ joint(shoulder, 0.36, side);
+ seg(shoulder, elbow, 0.46, armMat);
+ // hydraulic ram along the upper arm
+ seg(shoulder.clone().addScaledVector(up, 0.32).lerp(elbow, 0.08), elbow.clone().addScaledVector(up, 0.3).lerp(shoulder, 0.25), 0.12, steelArm);
+ joint(elbow, 0.3, side);
+ seg(elbow, t, 0.34, armMat);
+ joint(t, 0.2, side);
+ const nozzle = seg(t, weldTip, 0.12, armDark);
+ const baseBox = new THREE.Mesh(new THREE.CylinderGeometry(0.55, 0.65, 0.35, 24), armDark);
+ baseBox.position.copy(base); baseBox.castShadow = true; scene.add(baseBox);
+ weldGlow.position.copy(weldTip);
+ weldLight.position.copy(weldTip).add(new THREE.Vector3(0.4, 0, 0));
+}
+
+// ─── Page state ────────────────────────────────────────────────────────────────
+const S = {
+ surge: 0, charge: 0, holding: false, powered: false, live: 0, env: 0, beacon: 1,
+ scanY: -10, band: 0, holo: 0, visor: 0.06, drone: 0, weld: 0, shake: 0, door: 0, wave: 0, waveR: 0, settle: 0,
+};
+
+// ─── Camera shots ──────────────────────────────────────────────────────────────
+// az: degrees around the mech (0 = in front), side: look offset along camera-right (positive puts the mech left of centre)
+const SHOTS = {
+ hero: { az: -12, r: 25, y: 1.4, ly: 6.4, side: -7.2, fov: 38, mob: { rk: 1.1, ly: -3.6 } },
+ heroLive: { az: -16, r: 25.5, y: 1.8, ly: 7.2, side: -7.0, fov: 40, mob: { rk: 1.12, ly: -3.8 } },
+ power: { az: 36, r: 27, y: 6.2, ly: 8.8, side: 5.4, fov: 40, mob: { rk: 1.2 } },
+ reactor: { az: 12, r: 14, y: 7.8, ly: 8.0, side: -3.4, fov: 36 },
+ actuators: { az: 46, r: 17, y: 1.2, ly: 4.4, side: 4.4, fov: 42 },
+ armour: { az: 76, r: 13.5, y: 12.2, ly: 8.9, side: -3.3, fov: 38 },
+ weapons: { az: -80, r: 13.5, y: 13.2, ly: 10.2, side: 3.3, fov: 38 },
+ stats: { az: -24, r: 11.5, y: 0.45, ly: 6.2, side: -4.3, fov: 52 },
+ program: { az: 24, r: 11.5, y: 11.4, ly: 9.8, side: -4.0, fov: 40 },
+ apply: { az: 172, r: 30, y: 1.3, ly: 6, side: 0, fov: 40, look: [3.5, 8, 36], mob: { rk: 1, look: [1.5, 3.5, 36] } },
+};
+const sections = [...document.querySelectorAll('.sec')];
+const shotList = sections.map(s => s.dataset.shot);
+let holds = [];
+function measure() {
+ const vh = innerHeight;
+ holds = sections.map(s => { const r = s.getBoundingClientRect(); const top = r.top + scrollY; return top + (r.height - vh) / 2; });
+}
+measure();
+addEventListener('resize', measure);
+function scrollU() {
+ const y = scrollY;
+ if (y <= holds[0]) return 0;
+ for (let i = 0; i < holds.length - 1; i++) if (y < holds[i + 1]) return i + (y - holds[i]) / (holds[i + 1] - holds[i]);
+ return holds.length - 1 + Math.min(1, (y - holds[holds.length - 1]) / innerHeight);
+}
+
+const tmpA = new THREE.Vector3(), tmpB = new THREE.Vector3(), tmpC = new THREE.Vector3();
+function shotState(s, out) {
+ const portrait = camera.aspect < 0.85;
+ const pm = portrait ? (s.mob ?? {}) : {};
+ const az = (pm.az ?? s.az) * D, r = s.r * (portrait ? (pm.rk ?? 1.5) : 1);
+ const y = s.y + (portrait ? (pm.dy ?? 0) : 0);
+ out.pos.set(Math.sin(az) * r, y, Math.cos(az) * r);
+ const right = tmpC.set(Math.cos(az), 0, -Math.sin(az));
+ if (s.look && !pm.look) out.look.set(...s.look);
+ else if (pm.look) out.look.set(...pm.look);
+ // portrait: the copy sits in the lower half, so aim low and let the mech ride up the frame
+ else out.look.set(0, s.ly + (portrait ? (pm.ly ?? -3.2) : 0), 0).addScaledVector(right, portrait ? s.side * 0.1 : s.side);
+ out.fov = s.fov + (portrait ? 8 : 0);
+ out.az = portrait ? (pm.az ?? s.az) : s.az; out.r = r; out.y = y;
+ return out;
+}
+const mk = () => ({ pos: new THREE.Vector3(), look: new THREE.Vector3(), fov: 38, az: 0, r: 10, y: 1 });
+const sA = mk(), sB = mk(), sH = mk(), sHL = mk();
+const cam = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fov: 38 };
+function blendShots(u, out) {
+ const n = shotList.length - 1;
+ const i = Math.min(n - 1, Math.max(0, Math.floor(u)));
+ const f = smooth(0.12, 0.88, clamp(u - i));
+ const getShot = (k, o) => {
+ if (shotList[k] === 'hero') {
+ shotState(SHOTS.hero, sH); shotState(SHOTS.heroLive, sHL);
+ const L = S.live;
+ o.az = lerp(sH.az, sHL.az, L); o.r = lerp(sH.r, sHL.r, L) - S.charge * 1.6; o.y = lerp(sH.y, sHL.y, L);
+ o.look.lerpVectors(sH.look, sHL.look, L); o.fov = lerp(sH.fov, sHL.fov, L);
+ return o;
+ }
+ return shotState(SHOTS[shotList[k]], o);
+ };
+ getShot(i, sA); getShot(i + 1, sB);
+ let dAz = ((sB.az - sA.az + 540) % 360) - 180;
+ const az = (sA.az + dAz * f) * D;
+ const r = lerp(sA.r, sB.r, f) + Math.sin(f * Math.PI) * 2.5; // swing wide between stops
+ const y = lerp(sA.y, sB.y, f) + Math.sin(f * Math.PI) * 0.8;
+ out.pos.set(Math.sin(az) * r, y, Math.cos(az) * r);
+ out.look.lerpVectors(sA.look, sB.look, f);
+ out.fov = lerp(sA.fov, sB.fov, f);
+}
+
+// ─── Hotspots, reticle, ruler ─────────────────────────────────────────────────────
+const SPOTS = [
+ { key: 'reactor', label: '01 Reactor' },
+ { key: 'knee', label: '02 Actuators' },
+ { key: 'shoulder', label: '03 Armour' },
+ { key: 'gun', label: '04 Hardpoints' },
+];
+const spotsEl = document.querySelector('.spots');
+const specSecs = [...document.querySelectorAll('.sec.spec')];
+for (const [i, s] of SPOTS.entries()) {
+ const el = document.createElement('button');
+ el.className = 'spot'; el.type = 'button';
+ el.innerHTML = `<span>${s.label}</span>`;
+ el.setAttribute('aria-label', s.label);
+ el.addEventListener('click', () => { const sec = specSecs[i]; const y = sec.getBoundingClientRect().top + scrollY + (sec.offsetHeight - innerHeight) / 2; window.__lenis?.scrollTo(y, { duration: 1.6 }); });
+ spotsEl.appendChild(el);
+ s.el = el;
+}
+const leader = document.querySelector('.leader');
+const leaderLine = leader.querySelector('line'), leaderDot = leader.querySelector('circle');
+const reticle = document.querySelector('.hud-reticle');
+const hudEl = document.querySelector('.hud');
+const rulerEl = document.querySelector('.ruler');
+function project(v, out) {
+ tmpA.copy(v).project(camera);
+ out.x = (tmpA.x + 1) / 2 * innerWidth; out.y = (1 - tmpA.y) / 2 * innerHeight; out.vis = tmpA.z < 1 && Math.abs(tmpA.x) < 1.1 && Math.abs(tmpA.y) < 1.1;
+ return out;
+}
+const sp = { x: 0, y: 0, vis: false }, sp2 = { x: 0, y: 0, vis: false };
+
+// ─── HUD boot ─────────────────────────────────────────────────────────────────
+const bootEl = document.querySelector('.hud-boot');
+const rd = { rctr: document.querySelector('.rd-rctr'), core: document.querySelector('.rd-core'), hyd: document.querySelector('.rd-hyd'), sync: document.querySelector('.rd-sync') };
+const readout = { rctr: 0.3, core: 31, hyd: 0, sync: 0 };
+function renderReadout() {
+ rd.rctr.textContent = readout.rctr.toFixed(1) + '%';
+ rd.core.textContent = Math.round(readout.core) + '°C';
+ rd.hyd.textContent = Math.round(readout.hyd) + ' bar';
+ rd.sync.textContent = readout.sync > 0.5 ? readout.sync.toFixed(1) + '%' : '—';
+ const bars = document.querySelectorAll('.rd em');
+ bars[0].style.setProperty('--v', (readout.rctr / 100).toFixed(3));
+ bars[1].style.setProperty('--v', (readout.core / 700).toFixed(3));
+ bars[2].style.setProperty('--v', (readout.hyd / 340).toFixed(3));
+ bars[3].style.setProperty('--v', (readout.sync / 100).toFixed(3));
+}
+function bootLine(text, dim = false) {
+ const li = document.createElement('li');
+ li.textContent = text; if (dim) li.className = 'dim';
+ bootEl.appendChild(li);
+ while (bootEl.children.length > 7) bootEl.firstElementChild.remove();
+}
+const stateEl = document.querySelector('.hud-state');
+
+// ─── Power-up ─────────────────────────────────────────────────────────────────
+const flashEl = document.querySelector('.flash');
+function kick(a = 1) { S.shake = Math.max(S.shake, a); }
+function flicker(obj, key, to, { dur = 0.5, onUpdate } = {}) {
+ const tl = gsap.timeline({ onUpdate });
+ tl.to(obj, { [key]: to * 0.9, duration: 0.03 })
+ .to(obj, { [key]: to * 0.08, duration: 0.05 })
+ .to(obj, { [key]: to * 0.7, duration: 0.03, delay: 0.05 })
+ .to(obj, { [key]: to * 0.25, duration: 0.05 })
+ .to(obj, { [key]: to, duration: dur * 0.4, ease: 'power2.out', delay: 0.04 });
+ return tl;
+}
+function bayOn(i) {
+ const b = { v: 0 };
+ flicker(b, 'v', 1, { onUpdate: () => W.setBay(i, b.v) });
+ sound.clank(0.55);
+ kick(0.25);
+}
+function floodOn(i) {
+ const f = W.floods[i];
+ if (f.light.castShadow) { f.light.shadow.autoUpdate = true; f.light.shadow.needsUpdate = true; }
+ flicker(f, 'on', 1, { dur: 0.9 });
+ sound.clank(1);
+ kick(0.7);
+}
+function steamBurst(big = true) {
+ const t = engine.time;
+ const up = new THREE.Vector3(0, 1, 0);
+ for (const v of W.vents) steam.burst(v, up, big ? 26 : 8, t, { speed: big ? 9 : 5, spread: 0.18, life: big ? 4.2 : 3, size: big ? 1.6 : 1.1 });
+ if (A.crown) {
+ for (const s of [-1, 1]) {
+ steam.burst(new THREE.Vector3(s * 1.9, MECH_H * 0.78, -2.0), new THREE.Vector3(s * 0.6, 0.6, -1).normalize(), big ? 22 : 6, t, { speed: big ? 7 : 4, spread: 0.25, life: 3.4, size: 1.2 });
+ steam.burst(new THREE.Vector3(s * 1.5, MECH_H * 0.26, -0.8), new THREE.Vector3(s, 0.2, -0.5).normalize(), big ? 14 : 4, t + 0.15, { speed: big ? 6 : 3, spread: 0.3, life: 2.8, size: 0.9 });
+ }
+ }
+ sound.hiss(big ? 2.6 : 1.4, big ? 1 : 0.5);
+}
+
+function powerUp({ instant = false } = {}) {
+ if (S.powered) return;
+ S.powered = true;
+ S.holding = false;
+ body.classList.remove('is-cold', 'is-holding');
+ body.classList.add('is-booting');
+ stateEl.textContent = 'Power transfer';
+ if (instant) {
+ S.charge = 0; S.beacon = 0; S.env = 1; S.live = 1; S.visor = 1; S.drone = 1; S.weld = 1; S.holo = 0; S.band = 0; S.scanY = 20;
+ BAYS_Z.forEach((z, i) => W.setBay(i, 1));
+ W.floods.forEach(f => { f.on = 1; if (f.light.castShadow) f.light.shadow.autoUpdate = true; });
+ finishBoot(true);
+ return;
+ }
+ sound.drop();
+ const tl = gsap.timeline();
+ tl.to(S, { beacon: 0, duration: 0.18, ease: 'power2.in' }, 0)
+ .to(S, { charge: 0, duration: 0.5, ease: 'power2.in' }, 0)
+ .call(() => { kick(1.1); gsap.fromTo(flashEl, { opacity: 0.35 }, { opacity: 0, duration: 0.6, ease: 'expo.out' }); gsap.fromTo(S, { surge: 1 }, { surge: 0, duration: 1.1, ease: 'expo.out' }); }, null, 0.02)
+ .fromTo(S, { waveR: 0, wave: 1.6 }, { waveR: 34, wave: 0, duration: 1.8, ease: 'power2.out' }, 0.05);
+ BAYS_Z.forEach((z, i) => tl.call(() => bayOn(i), null, 0.45 + i * 0.19));
+ tl.call(() => { bootLine('Power transfer ··· OK'); stateEl.textContent = 'Lighting'; }, null, 0.5);
+ tl.call(() => floodOn(0), null, 0.95).call(() => floodOn(1), null, 1.12).call(() => floodOn(2), null, 1.78).call(() => floodOn(3), null, 1.95);
+ tl.call(() => bootLine('Bay lighting ··· 8/8'), null, 2.0);
+ tl.to(S, { env: 1, duration: 2.4, ease: 'power2.inOut' }, 0.7);
+ tl.to(S, { live: 1, duration: 6.4, ease: 'power2.inOut' }, 0.8);
+ tl.to(readout, { rctr: 100, core: 612, duration: 3.2, ease: 'power2.out', onUpdate: renderReadout }, 0.6);
+ tl.call(() => { steamBurst(true); kick(0.5); }, null, 2.25);
+ tl.call(() => bootLine('Reactor ··· 42.0 MW'), null, 2.4);
+ // the scan
+ tl.call(() => { sound.scan(); stateEl.textContent = 'Diagnostic scan'; gsap.fromTo('.hud-scan', { top: 0, opacity: 1 }, { top: '100%', opacity: 0.2, duration: 1.6, ease: 'power1.inOut', onComplete: () => gsap.set('.hud-scan', { opacity: 0 }) }); body.classList.add('is-scan'); }, null, 2.6);
+ tl.set(S, { scanY: -0.3, band: 1, holo: 1 }, 2.6)
+ .to(S, { scanY: MECH_H + 0.8, duration: 2.7, ease: 'power1.inOut' }, 2.6)
+ .to(readout, { hyd: 310, duration: 2.2, ease: 'power2.out', onUpdate: renderReadout }, 2.8)
+ .call(() => bootLine('Actuator bus ··· 41/41'), null, 3.3)
+ .call(() => bootLine('Armour integrity ··· 212/212'), null, 3.9)
+ .call(() => bootLine('Gyro sync ··· locked'), null, 4.5)
+ .to(S, { band: 0, duration: 0.5 }, 5.2)
+ .to(S, { holo: 0.0, duration: 3.2, ease: 'power2.out' }, 5.6);
+ // visor + settle
+ tl.call(() => {
+ flicker(S, 'visor', 1, { dur: 0.8 });
+ sound.online();
+ kick(0.9);
+ gsap.fromTo(S, { settle: 0 }, { settle: 1, duration: 1.4, ease: 'power2.out' });
+ bootLine('Optics ··· online');
+ }, null, 5.35);
+ tl.to(readout, { sync: 99.2, duration: 1.4, ease: 'power2.out', onUpdate: renderReadout }, 5.4);
+ tl.call(() => finishBoot(false), null, 5.8);
+ tl.to(S, { drone: 1, duration: 3.4, ease: 'power2.inOut' }, 6.0);
+ tl.set(S, { weld: 1 }, 6.8);
+}
+function finishBoot(instant) {
+ body.classList.remove('is-booting', 'is-scan');
+ body.classList.add('is-live');
+ stateEl.textContent = 'Online · pilot seat vacant';
+ if (instant) { Object.assign(readout, { rctr: 100, core: 612, hyd: 310, sync: 99.2 }); }
+ renderReadout();
+ bootLine('Pilot seat ··· vacant', true);
+ reticle.classList.add('lock');
+ document.querySelector('.g-label').innerHTML = 'Online';
+ document.querySelector('.g-pct').textContent = '100';
+ document.querySelector('.ignite-title').textContent = 'Warden online';
+ document.querySelector('.ignite-hint').textContent = 'Forty-one actuators, one empty seat. Scroll to walk around it.';
+}
+
+// ─── Hold input ─────────────────────────────────────────────────────────────────
+const gaugeEl = document.querySelector('.gauge');
+const gPct = document.querySelector('.g-pct');
+const holdEl = document.querySelector('.hold');
+const heroSec = document.querySelector('.sec.hero');
+let heroU = 0;
+const canHold = () => !S.powered && heroU < 0.6;
+function startHold(e) {
+ if (!canHold()) return;
+ sound.on && sound._init();
+ S.holding = true;
+ body.classList.add('is-holding');
+}
+function endHold() { S.holding = false; body.classList.remove('is-holding'); }
+addEventListener('pointerdown', e => {
+ if (e.button !== 0) return;
+ if (e.target.closest('a, .nav, .snd, .tw-nav, .card, .quote, .spot')) return;
+ startHold(e);
+});
+gaugeEl.addEventListener('pointerdown', e => { e.preventDefault(); startHold(e); });
+addEventListener('pointerup', endHold);
+addEventListener('pointercancel', endHold);
+addEventListener('blur', endHold);
+addEventListener('contextmenu', e => { if (!S.powered) e.preventDefault(); });
+addEventListener('keydown', e => {
+ if (e.code !== 'Space' || e.repeat || !canHold()) return;
+ e.preventDefault(); startHold(e);
+});
+addEventListener('keyup', e => { if (e.code === 'Space') endHold(); });
+gaugeEl.addEventListener('keydown', e => { if (e.key === 'Enter' && canHold()) { e.preventDefault(); powerUp(); } });
+
+// Sound toggle
+const sndBtn = document.querySelector('.snd');
+sndBtn.addEventListener('click', () => {
+ const on = sound.toggle();
+ sndBtn.setAttribute('aria-pressed', String(on));
+ sndBtn.querySelector('.snd-state').textContent = on ? 'On' : 'Off';
+ if (on && S.powered) sound.online();
+});
+
+// ─── Reveal helpers ─────────────────────────────────────────────────────────────
+for (const s of sections) {
+ if (s.classList.contains('hero')) continue;
+ const items = s.querySelectorAll('.kicker, h2, h3, .body, .steps li, .data, .figs li, .timeline li, .req, .quote, .cta-row, .cta-meta');
+ items.forEach((el, i) => { el.classList.add('rv'); el.style.setProperty('--i', i); });
+}
+const statsSec = document.querySelector('.sec.stats');
+let counted = false;
+function countUp() {
+ counted = true;
+ statsSec.querySelectorAll('[data-count]').forEach((el, i) => {
+ const o = { v: 0 }, to = +el.dataset.count, dec = +el.dataset.dec;
+ gsap.to(o, { v: to, duration: 1.8, delay: 0.15 + i * 0.12, ease: 'expo.out', onUpdate: () => { el.textContent = o.v.toFixed(dec); } });
+ });
+}
+const SCRIM = { hero: [1, 0, 0.3], power: [0, 1, 0], reactor: [1, 0, 0], actuators: [0, 1, 0], armour: [1, 0, 0], weapons: [0, 1, 0], stats: [1, 0, 0], program: [1, 0.6, 0.2], apply: [0.7, 0, 1] };
+const rootStyle = document.documentElement.style;
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+let u = 0, lastMove = -10, weldOn = false, weldNext = 0, puffNext = 8, clockT = 0;
+pointer.on('move', () => { lastMove = engine.time; });
+const footEl = document.querySelector('.foot');
+const navEl = document.querySelector('.nav');
+const clockEl = document.querySelector('.hud-clock');
+const baseSec = 7 * 60 + 3 * 3600 + 12 * 60;
+const droneTarget = new THREE.Vector3(), droneAim = new THREE.Vector3(0, 6, 0);
+const ray = new THREE.Raycaster();
+const aimPlane = new THREE.Plane();
+const parked = new THREE.Vector3(3.2, 12.9, -6.85);
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ MU.uTime.value = t;
+
+ // hold / charge
+ if (!S.powered) {
+ if (S.holding) S.charge = Math.min(1, S.charge + dt / HOLD_TIME);
+ else S.charge = Math.max(0, S.charge - dt * 1.1);
+ if (S.charge >= 1) powerUp();
+ }
+ const c = S.charge;
+ sound.charge(S.powered ? 0 : c);
+ rootStyle.setProperty('--c', c.toFixed(3));
+ surgeFx.uniforms.get('uAmt').value = (reduced ? 0.3 : 1) * Math.max(S.surge, c * c * 0.55);
+ if (!S.powered) {
+ gPct.textContent = String(Math.round(c * 100)).padStart(2, '0');
+ stateEl.textContent = c > 0.01 ? `Ignition ${Math.round(c * 100)}%` : 'Reactor cold';
+ readout.rctr = 0.3 + c * 11; readout.core = 31 + c * 90; renderReadout();
+ }
+
+ // scroll → camera
+ const target = scrollU();
+ u = damp(u, target, 4.2, dt);
+ heroU = u;
+ if (!S.powered && target > 0.45) powerUp();
+ blendShots(u, cam);
+ // shake: heavy, low frequency
+ S.shake = damp(S.shake, 0, 3.2, dt);
+ const sh = (S.shake * 0.12 + c * c * 0.05) * (reduced ? 0.2 : 1);
+ const sx = (Math.sin(t * 23.1) + Math.sin(t * 37.7) * 0.6) * sh, sy = (Math.sin(t * 29.3 + 1) + Math.sin(t * 41.9) * 0.5) * sh;
+ const right = tmpB.subVectors(cam.look, cam.pos).cross(camera.up).normalize();
+ camera.position.copy(cam.pos).addScaledVector(right, pointer.sx * 0.45 + sx).add(tmpC.set(0, pointer.sy * 0.25 + sy + Math.sin(t * 0.5) * 0.04, 0));
+ camera.lookAt(cam.look.x + sx * 0.5, cam.look.y + sy * 0.5, cam.look.z);
+ if (DBG.has('cam')) { const v = DBG.get('cam').split(',').map(Number); camera.position.set(v[0], v[1], v[2]); camera.lookAt(v[3], v[4], v[5]); if (v[6]) cam.fov = v[6]; }
+ if (Math.abs(camera.fov - cam.fov) > 0.01) { camera.fov = cam.fov; camera.updateProjectionMatrix(); }
+
+ // environment and lights
+ const live = S.env;
+ const door = S.door = DBG.has('door') ? +DBG.get('door') : smooth(7.25, 7.95, u);
+
+ scene.environment = live > 0.02 ? envLive : envCold;
+ scene.environmentIntensity = (live > 0.02 ? lerp(0.05, 0.24, live) : 0.1) * (1 - door * 0.55);
+ hemi.intensity = lerp(0.015, 0.3, live) * (1 - door * 0.6);
+ scene.fog.color.setRGB(lerp(0.005, 0.012, live), lerp(0.006, 0.014, live), lerp(0.008, 0.018, live));
+ vol.density = DBG.has('novol') ? 0 : lerp(0.026, 0.016, live);
+ if (DBG.has('noao')) engine.post.ao.enabled = false;
+ // beacons + strobe
+ const spin = t * (1.9 + c * 5);
+ for (const b of W.beacons) {
+ const a = spin + b.phase;
+ tmpA.set(Math.cos(a), -0.55, Math.sin(a)).normalize();
+ b.light.target.position.copy(b.pos).addScaledVector(tmpA, 10);
+ b.light.intensity = 130 * S.beacon;
+ tmpC.subVectors(camera.position, b.pos).setY(0).normalize();
+ const facing = Math.pow(Math.max(0, tmpA.x * tmpC.x + tmpA.z * tmpC.z), 10);
+ b.cap.material.color.setRGB(1, 0.04, 0.02).multiplyScalar((0.8 + facing * 14) * S.beacon + 0.15);
+ }
+ moon.intensity = lerp(380, 60, live) * (1 - door);
+ const ph = (t * (1 + c * 1.5)) % 1.4;
+ const strobeV = (ph < 0.05 ? 1 : 0) + (ph > 0.16 && ph < 0.21 ? 0.8 : 0);
+ strobe.intensity = (35 + strobeV * 300) * S.beacon;
+ W.redStripMat.color.setRGB(1, 0.05, 0.02).multiplyScalar(0.25 + S.beacon * 1.8 * (0.8 + strobeV * 0.4));
+ W.glassMat.color.setRGB(0.05, 0.07, 0.1).multiplyScalar(1 + live * 0.8);
+ // floods
+ const hazeGrade = lerp(1, 0.62, smooth(0.7, 1.9, u)) - smooth(5.3, 6, u) * 0.24 + smooth(6.2, 7, u) * 0.12;
+ for (const [i, f] of W.floods.entries()) {
+ floodVol[i].gain = hazeGrade * (i === 1 ? 1 - smooth(0.6, 0, Math.abs(u - 3)) * 0.7 : 1);
+ const g = f.on * (1 - door * 0.96);
+ f.light.intensity = f.power * g;
+ f.lensMat.color.setRGB(1, 0.97, 0.92).multiplyScalar(f.on * 40);
+ }
+ W.coneMat.uniforms.uTime.value = t;
+ // floor wave
+ W.floorU.uWave.value.set(S.waveR, S.wave);
+ // door + dawn
+ for (const d of W.doors) d.position.x = lerp(d.userData.closedX, d.userData.openX, door);
+ W.dawnMat.color.setScalar(door * 1.15);
+ dawn.intensity = 42000 * door;
+ dawn.shadow.autoUpdate = door > 0.001;
+
+ // mech shader state
+ MU.uScanY.value = S.scanY;
+ MU.uBand.value = S.band;
+ MU.uHolo.value = S.holo;
+ sheet.position.y = Math.max(0.05, S.scanY);
+ sheet.material.uniforms.uAmt.value = S.band;
+ sheet.material.uniforms.uTime.value = t;
+ let visor = S.visor;
+ if (!S.powered) visor = 0.13 + Math.sin(t * 1.1) * 0.05 + (c > 0.2 && Math.random() < c * 0.4 ? Math.random() * c * 0.8 : 0);
+ else visor *= 0.92 + Math.sin(t * 2.1) * 0.04 + Math.sin(t * 17) * 0.02;
+ MU.uVisor.value = visor;
+ visorLight.intensity = visor * 9;
+ visorGlow.material.color.setRGB(1, 0.42, 0.1).multiplyScalar(visor * 0.55);
+ // hotspot focus: amber reactor glow while charging, cyan system highlight in the spec sections
+ const specI = Math.round(u) - 2;
+ const specW = 1 - smooth(0.18, 0.45, Math.abs(u - Math.round(u)));
+ if (!S.powered || S.live < 0.9) {
+ if (A.reactor) MU.uFocus.value.set(A.reactor.x, A.reactor.y, A.reactor.z - 0.8, 1.2 + c * 2.2);
+ MU.uFocusCol.value.setRGB(1.0, 0.5, 0.05);
+ MU.uFocusAmt.value = c * 1.4;
+ } else if (specI >= 0 && specI < 4 && A.crown) {
+ const key = SPOTS[specI].key;
+ const rad = [2.4, 2.2, 2.4, 2.6][specI];
+ MU.uFocus.value.set(A[key].x, A[key].y, A[key].z, rad);
+ MU.uFocusCol.value.setRGB(0.28, 0.9, 1.0);
+ MU.uFocusAmt.value = damp(MU.uFocusAmt.value, specW * 0.9, 6, dt);
+ } else MU.uFocusAmt.value = damp(MU.uFocusAmt.value, 0, 6, dt);
+ MU.uXray.value = MU.uFocusAmt.value * 0.4 * (S.powered ? 1 : 0);
+ // settle after power: hydraulics take the weight
+ mechGroup.position.y = -Math.sin(S.settle * Math.PI) * 0.08 * (1 - S.settle * 0.5);
+
+ // drone
+ if (drone) {
+ const dT = S.drone;
+ const th = t * 0.19 + 1.2;
+ const R = 10.5;
+ tmpA.set(Math.sin(th) * R, 9.4 + Math.sin(t * 0.47) * 1.3, Math.cos(th) * R);
+ const lift = tmpC.copy(parked).lerp(tmpA, smooth(0.25, 1, dT));
+ lift.y += Math.sin(clamp(dT) * Math.PI) * 1.6 + (dT > 0 ? Math.sin(t * 2.3) * 0.05 : 0);
+ const prev = tmpB.copy(droneGroup.position);
+ droneGroup.position.copy(lift);
+ const vel = prev.sub(droneGroup.position).negate();
+ if (dT > 0.01) {
+ if (vel.lengthSq() > 1e-8) {
+ const want = Math.atan2(vel.x, vel.z);
+ const dy = ((want - droneGroup.rotation.y + Math.PI * 3) % (Math.PI * 2)) - Math.PI;
+ droneGroup.rotation.y += dy * (1 - Math.exp(-2 * dt));
+ }
+ droneGroup.rotation.z = damp(droneGroup.rotation.z, clamp(-vel.length() * 3, -0.25, 0.25), 3, dt);
+ }
+ // searchlight: follows the pointer after power-up, otherwise sweeps the mech
+ const user = S.powered && t - lastMove < 3.5 && u < 7 ? 1 : 0;
+ aimPlane.setFromNormalAndCoplanarPoint(tmpC.subVectors(camera.position, mechGroup.position).setY(0).normalize(), mechGroup.position);
+ ray.setFromCamera({ x: pointer.x, y: pointer.y }, camera);
+ if (user && ray.ray.intersectPlane(aimPlane, droneTarget)) {
+ droneTarget.y = clamp(droneTarget.y, 0.5, 12); droneTarget.x = clamp(droneTarget.x, -6, 6); droneTarget.z = clamp(droneTarget.z, -6, 6);
+ } else droneTarget.set(Math.sin(t * 0.61) * 2.4, 6 + Math.sin(t * 0.37) * 4.2, Math.cos(t * 0.53) * 1.2);
+ droneAim.lerp(droneTarget, 1 - Math.exp(-(user ? 6 : 2) * dt));
+ droneSpot.position.copy(droneGroup.position).add(tmpA.set(0, -0.35, 0));
+ droneSpot.target.position.copy(droneAim);
+ droneSpot.intensity = 700 * smooth(0.5, 1, dT);
+ }
+
+ // welding
+ if (S.weld > 0 && A.crown) {
+ if (t > weldNext) { weldOn = !weldOn; weldNext = t + (weldOn ? 2.2 + Math.random() * 3 : 0.4 + Math.random() * 0.9); }
+ if (weldOn) {
+ const n = Math.random() < 0.5 ? 2 : 5;
+ sparks.emit(weldTip, tmpA.set(1, -0.2, 0.3).normalize(), n, t);
+ const fl = 0.6 + Math.random() * 0.8;
+ weldLight.intensity = 38 * fl;
+ weldGlow.material.color.setRGB(0.8, 0.9, 1).multiplyScalar(fl * 1.6);
+ weldGlow.scale.setScalar(1.1 + Math.random() * 0.8);
+ } else { weldLight.intensity = damp(weldLight.intensity, 0, 20, dt); weldGlow.material.color.multiplyScalar(0.7); }
+ }
+ // ambient steam puffs once live
+ if (S.live > 0.99 && t > puffNext) { puffNext = t + 3.5 + Math.random() * 4; steamBurst(false); }
+ steam.mat.uniforms.uLight.value = lerp(0.12, 1.1, live) * (1 - door * 0.3);
+ steam.mat.uniforms.uWarmAmt.value = door * 0.4;
+ steam.update(t);
+ sparks.update(t);
+
+ // dust in beams
+ dust.mat.uniforms.uTime.value = t;
+ dust.mat.uniforms.uFall.value = 0;
+ W.floods.forEach((f, i) => dust.setLight(i, f.light, f.light.intensity * 0.00045));
+ dust.setLight(4, droneSpot, droneSpot.intensity * 0.0025);
+ dust.setLight(5, dawn, dawn.intensity * 0.00002);
+
+ // ─── HTML overlays ───
+ // sections on/off
+ sections.forEach((s, i) => {
+ const on = Math.abs(u - i) < 0.4 && (i > 0 || true);
+ if (on !== s._on) { s._on = on; s.classList.toggle('is-on', on); if (on && s === statsSec && !counted) countUp(); }
+ });
+ // scrims
+ const i0 = Math.min(shotList.length - 1, Math.floor(u)), i1 = Math.min(shotList.length - 1, i0 + 1), fu = smooth(0.2, 0.8, u - i0);
+ const s0 = SCRIM[shotList[i0]], s1 = SCRIM[shotList[i1]];
+ rootStyle.setProperty('--scrimL', lerp(s0[0], s1[0], fu).toFixed(3));
+ rootStyle.setProperty('--scrimR', lerp(s0[1], s1[1], fu).toFixed(3));
+ rootStyle.setProperty('--scrimB', lerp(s0[2], s1[2], fu).toFixed(3));
+ // hold gauge near the pointer
+ const showHold = !S.powered && pointer.active && u < 0.4 && !pointer.overUI;
+ body.classList.toggle('show-hold', showHold);
+ if (showHold) holdEl.style.transform = `translate3d(${pointer.px}px, ${pointer.py}px, 0)`;
+ // reticle on the visor
+ if (A.visor) {
+ project(A.visor, sp);
+ const showR = S.powered && S.live > 0.6 && sp.vis && (u < 1.4 || Math.abs(u - 7) < 0.4);
+ hudEl.classList.toggle('on-reticle', showR);
+ if (showR) reticle.style.transform = `translate3d(${sp.x.toFixed(1)}px, ${sp.y.toFixed(1)}px, 0)`;
+ }
+ // hotspots
+ const inSpecs = S.powered && u > 1.55 && u < 5.45;
+ let activeSpot = -1;
+ SPOTS.forEach((s, i) => {
+ const a = A[s.key];
+ if (!a) return;
+ project(a, sp);
+ tmpC.subVectors(camera.position, a).normalize();
+ const facing = tmpC.dot(A.normals[s.key]) > -0.2;
+ const isActive = Math.abs(u - (i + 2)) < 0.3;
+ const on = inSpecs && sp.vis && facing;
+ s.el.classList.toggle('on', on);
+ s.el.classList.toggle('dim', !isActive);
+ if (on) s.el.style.transform = `translate3d(${sp.x.toFixed(1)}px, ${sp.y.toFixed(1)}px, 0)`;
+ if (on && isActive) { activeSpot = i; sp2.x = sp.x; sp2.y = sp.y; }
+ });
+ leader.classList.toggle('on', activeSpot >= 0);
+ if (activeSpot >= 0) {
+ const card = specSecs[activeSpot].querySelector('.card').getBoundingClientRect();
+ const toLeft = card.left > sp2.x;
+ const ex = toLeft ? card.left : card.right, ey = clamp(sp2.y, card.top + 30, card.bottom - 30);
+ leaderLine.setAttribute('x1', sp2.x.toFixed(1)); leaderLine.setAttribute('y1', sp2.y.toFixed(1));
+ leaderLine.setAttribute('x2', ex.toFixed(1)); leaderLine.setAttribute('y2', ey.toFixed(1));
+ leaderDot.setAttribute('cx', ex.toFixed(1)); leaderDot.setAttribute('cy', ey.toFixed(1));
+ }
+ // height ruler in the numbers section
+ const showRuler = Math.abs(u - 6) < 0.35;
+ rulerEl.classList.toggle('on', showRuler);
+ if (showRuler) {
+ const rr = tmpB.subVectors(cam.look, cam.pos).cross(camera.up).normalize();
+ const base = tmpC.copy(rr).multiplyScalar(-4.7);
+ project(base, sp); const bx = sp.x, by = sp.y;
+ base.y = A.crown || MECH_H;
+ project(base, sp);
+ rulerEl.style.transform = `translate3d(${bx.toFixed(1)}px, ${sp.y.toFixed(1)}px, 0)`;
+ rulerEl.style.height = Math.max(0, by - sp.y).toFixed(1) + 'px';
+ }
+ // HUD clock
+ clockT += dt;
+ if (clockT > 1) {
+ clockT = 0;
+ const s = baseSec + Math.floor(t);
+ clockEl.textContent = [Math.floor(s / 3600) % 24, Math.floor(s / 60) % 60, s % 60].map(n => String(n).padStart(2, '0')).join(':');
+ }
+
+ reflection.update(scene, camera);
+ const footTop = footEl.getBoundingClientRect().top;
+ engine.paused = footTop <= 0;
+ navEl.classList.toggle('solid', footTop < 90);
+});
+// pointer over UI (for the hold gauge)
+addEventListener('pointerover', e => { pointer.overUI = !!e.target.closest?.('a, button:not(.gauge), .nav, .card, .quote, .tw-nav'); });
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('hangar', { theme: 'dark', corner: 'bl' });
+const cur = cursor({ color: '#ffb000', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? document.body : document.querySelector(id);
+ if (!el) return;
+ e.preventDefault();
+ let y = id === '#top' ? 0 : el.getBoundingClientRect().top + scrollY;
+ if (el.classList?.contains('sec')) y += (el.offsetHeight - innerHeight) / 2;
+ else if (el.firstElementChild?.classList.contains('sec')) y += (el.firstElementChild.offsetHeight - innerHeight) / 2;
+ lenis.scrollTo(y, { duration: 2 });
+}));
+
+const T0 = performance.now();
+await Promise.all([mechLoad, droneLoad]);
+const T1 = performance.now();
+// Warm every program with everything switched on, then return to the cold state.
+{
+ const save = { beacon: S.beacon };
+ W.floods.forEach(f => (f.light.intensity = 1));
+ dawn.intensity = 1; droneSpot.intensity = 1;
+ scene.environment = envLive;
+ renderer.compile(scene, camera);
+ scene.environment = envCold;
+ renderer.compile(scene, camera);
+ Object.assign(S, save);
+}
+const T2 = performance.now();
+if (DBG.has('t')) console.warn('boot', Math.round(T0), 'models', Math.round(T1 - T0), 'compile', Math.round(T2 - T1));
+measure();
+if (DBG.has('powered')) powerUp({ instant: true });
+engine.start();
+await loader.finish();
+window.__power = (instant = false) => powerUp({ instant });
+window.__S = S;
+gsap.from('.title > span', { yPercent: 30, opacity: 0, duration: 1.6, ease: 'expo.out', stagger: 0.1, delay: 0.1 });
+gsap.from('.eyebrow, .tag, .lede, .ignite, .nav', { opacity: 0, y: 16, duration: 1.2, ease: 'power3.out', stagger: 0.07, delay: 0.45 });
diff --git a/examples/hangar/style.css b/examples/hangar/style.css
new file mode 100644
index 0000000..e8b945f
--- /dev/null
+++ b/examples/hangar/style.css
@@ -0,0 +1,357 @@
+:root {
+ --bg: #07080a;
+ --ink: #e7e9eb;
+ --soft: #b7bec6;
+ --muted: #7f8891;
+ --line: rgba(231, 233, 235, .13);
+ --amber: #ffb000;
+ --amber-d: #c98a00;
+ --cyan: #62e6ff;
+ --red: #ff3a26;
+ --display: 'Chakra Petch', 'Arial Narrow', sans-serif;
+ --sans: 'Rajdhani', 'Arial Narrow', system-ui, sans-serif;
+ --mono: 'Share Tech Mono', ui-monospace, monospace;
+ --pad: clamp(16px, 4vw, 56px);
+ --scrimL: 0; --scrimR: 0; --scrimB: 0;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; -webkit-text-size-adjust: 100%; }
+body { font: 500 17px/1.5 var(--sans); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+.mono { font-family: var(--mono); font-size: 11.5px; letter-spacing: .14em; text-transform: uppercase; font-weight: 400; }
+kbd { font: 400 11px/1 var(--mono); padding: 3px 6px 2px; border-radius: 3px; box-shadow: inset 0 0 0 1px rgba(255,176,0,.45); color: var(--amber); }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+.flash { position: fixed; inset: 0; z-index: 40; pointer-events: none; opacity: 0; background: radial-gradient(120% 80% at 50% 30%, #fff 0%, #cfe9ff 40%, #000 100%); mix-blend-mode: screen; }
+.scrim { position: fixed; inset: 0; z-index: 1; pointer-events: none; }
+.scrim-l { background: linear-gradient(90deg, rgba(4,5,7,.86) 0%, rgba(4,5,7,.55) 26%, rgba(4,5,7,0) 50%); opacity: var(--scrimL); }
+.scrim-r { background: linear-gradient(270deg, rgba(4,5,7,.86) 0%, rgba(4,5,7,.55) 26%, rgba(4,5,7,0) 50%); opacity: var(--scrimR); }
+.scrim-b { background: linear-gradient(0deg, rgba(4,5,7,.9) 0%, rgba(4,5,7,.5) 30%, rgba(4,5,7,0) 58%); opacity: var(--scrimB); }
+
+/* ─── loader: firmware boot behind two blast-door halves; the seam is the progress bar ─── */
+.loader { position: fixed; inset: 0; z-index: 100; color: var(--ink); }
+.ld-door { position: absolute; left: 0; right: 0; height: 50.2%; background: #0a0b0d; }
+.ld-top { top: 0; background: linear-gradient(0deg, #111317, #0a0b0d 40%); }
+.ld-bot { bottom: 0; background: linear-gradient(180deg, #0e1013, #0a0b0d 40%); }
+.ld-top::after, .ld-bot::before { content: ''; position: absolute; left: 0; right: 0; height: 12px;
+ background: repeating-linear-gradient(-45deg, rgba(255,176,0,.22) 0 12px, #0b0b0b 12px 24px); }
+.ld-top::after { bottom: 0; } .ld-bot::before { top: 0; }
+.ld-bar { position: absolute; left: 0; right: 0; top: calc(50% - 12px); height: 24px; z-index: 1; pointer-events: none; }
+.ld-bar i { position: absolute; inset: 0; transform-origin: left; transform: scaleX(var(--p, 0));
+ background: repeating-linear-gradient(-45deg, var(--amber) 0 12px, #0b0b0b 12px 24px); box-shadow: 0 0 30px rgba(255,176,0,.35); }
+.ld-in { position: absolute; left: 50%; top: 50%; width: min(620px, 88vw); transform: translate(-50%, -50%); height: 0; z-index: 2; transition: opacity .4s; }
+.ld-up { position: absolute; left: 0; right: 0; bottom: 34px; display: grid; gap: 14px; }
+.ld-down { position: absolute; left: 0; right: 0; top: 34px; }
+.ld-head { display: flex; justify-content: space-between; color: var(--muted); font-size: 10.5px; }
+.ld-num { font: 600 clamp(84px, 14vw, 150px)/.8 var(--display); letter-spacing: -.04em; font-variant-numeric: tabular-nums; }
+.ld-num i { font-style: normal; font-size: .3em; color: var(--amber); margin-left: .1em; vertical-align: top; }
+.ld-log { list-style: none; display: grid; gap: 5px; color: #9aa2ab; font-size: 11px; }
+.ld-log li { opacity: 0; transform: translateX(-6px); transition: opacity .3s, transform .3s; }
+.ld-log li.on { opacity: 1; transform: none; }
+.ld-log li:last-child.on { color: var(--amber); }
+
+/* ─── nav ─────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 20px;
+ padding: 20px var(--pad); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav::before { content: ''; position: absolute; inset: 0; z-index: -1; background: rgba(7,8,10,.86); backdrop-filter: blur(12px); border-bottom: 1px solid var(--line); opacity: 0; transition: opacity .4s; }
+.nav.solid::before { opacity: 1; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 600 15px/1 var(--display); letter-spacing: .22em; text-transform: uppercase; }
+.brand b { color: var(--amber); font-weight: 600; margin-left: .35em; }
+.brand svg { width: 28px; height: 28px; color: var(--amber); }
+.links { display: flex; gap: clamp(18px, 2.6vw, 40px); }
+.links a { text-decoration: none; font: 600 13px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--soft); transition: color .25s; position: relative; }
+.links a::before { content: ''; position: absolute; left: -10px; top: 50%; width: 4px; height: 4px; margin-top: -2px; background: var(--amber); opacity: 0; transition: opacity .25s; }
+.links a:hover { color: #fff; } .links a:hover::before { opacity: 1; }
+.nav-r { display: flex; align-items: center; gap: 14px; }
+.snd { display: flex; align-items: center; gap: 8px; height: 40px; padding: 0 14px; color: var(--muted); border-radius: 2px; box-shadow: inset 0 0 0 1px var(--line); font-size: 10.5px; transition: color .3s, box-shadow .3s; }
+.snd:hover { color: var(--ink); box-shadow: inset 0 0 0 1px rgba(231,233,235,.3); }
+.snd-bars { display: flex; align-items: flex-end; gap: 2px; height: 12px; }
+.snd-bars i { width: 2px; height: 3px; background: currentColor; transition: height .2s; }
+.snd[aria-pressed="true"] { color: var(--amber); }
+.snd[aria-pressed="true"] .snd-bars i { animation: bars .9s ease-in-out infinite; }
+.snd[aria-pressed="true"] .snd-bars i:nth-child(2) { animation-delay: -.3s; } .snd[aria-pressed="true"] .snd-bars i:nth-child(3) { animation-delay: -.6s; } .snd[aria-pressed="true"] .snd-bars i:nth-child(4) { animation-delay: -.15s; }
+@keyframes bars { 0%, 100% { height: 3px; } 50% { height: 12px; } }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 42px; padding: 0 20px; text-decoration: none; white-space: nowrap;
+ font: 700 13px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase;
+ clip-path: polygon(10px 0, 100% 0, 100% calc(100% - 10px), calc(100% - 10px) 100%, 0 100%, 0 10px); transition: background .3s, color .3s, box-shadow .3s; }
+.btn-amber { background: var(--amber); color: #120c00; }
+.btn-amber:hover { background: #ffc740; box-shadow: 0 0 40px rgba(255,176,0,.5); }
+.btn-ghost { background: rgba(10,11,13,.45); color: var(--ink); box-shadow: inset 0 0 0 1px rgba(231,233,235,.28); backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--amber); color: #fff; }
+.btn-lg { height: 56px; padding: 0 30px; font-size: 14px; }
+
+/* ─── HUD ─────────────────────────────────────────── */
+.hud { position: fixed; inset: 0; z-index: 12; pointer-events: none; color: var(--cyan); }
+.hc { position: absolute; width: 26px; height: 26px; border: 0 solid rgba(98,230,255,.7); opacity: 0; transition: opacity .6s, transform .8s cubic-bezier(.2,.9,.2,1); }
+.hc.tl { left: calc(var(--pad) - 6px); top: 86px; border-width: 1px 0 0 1px; transform: translate(-30px, -30px); }
+.hc.tr { right: calc(var(--pad) - 6px); top: 86px; border-width: 1px 1px 0 0; transform: translate(30px, -30px); }
+.hc.bl { left: calc(var(--pad) - 6px); bottom: 70px; border-width: 0 0 1px 1px; transform: translate(-30px, 30px); }
+.hc.br { right: calc(var(--pad) - 6px); bottom: 26px; border-width: 0 1px 1px 0; transform: translate(30px, 30px); }
+.hud-top { position: absolute; top: 80px; left: 50%; transform: translateX(-50%); display: flex; align-items: center; gap: 12px; font-size: 10.5px; color: rgba(231,233,235,.55); white-space: nowrap; }
+.hud-sep { width: 18px; height: 1px; background: currentColor; opacity: .5; }
+.hud-state { color: var(--red); }
+.is-live .hud-state { color: var(--cyan); }
+.hud-side { position: absolute; right: var(--pad); top: 50%; transform: translateY(-50%); display: grid; gap: 14px; width: 132px; font-size: 10px; opacity: 0; transition: opacity .8s; }
+.rd { display: grid; grid-template-columns: 1fr auto; gap: 5px 8px; color: rgba(231,233,235,.5); }
+.rd b { font-weight: 400; color: var(--cyan); text-align: right; }
+.rd i { grid-column: 1 / -1; height: 2px; background: rgba(98,230,255,.14); position: relative; }
+.rd i em { position: absolute; inset: 0; transform-origin: left; transform: scaleX(var(--v)); background: var(--cyan); transition: transform .4s; }
+.hud-ruler { position: absolute; left: calc(var(--pad) - 6px); top: 50%; height: 36vh; transform: translateY(-50%); width: 10px; opacity: 0; transition: opacity .8s;
+ background: repeating-linear-gradient(180deg, rgba(98,230,255,.5) 0 1px, transparent 1px 12px) left / 6px 100% no-repeat, repeating-linear-gradient(180deg, rgba(98,230,255,.7) 0 1px, transparent 1px 60px) left / 10px 100% no-repeat; }
+.hud-ruler span { position: absolute; top: -20px; left: 0; font-size: 9px; }
+.hud-scan { position: absolute; left: 0; right: 0; top: 0; height: 2px; opacity: 0;
+ background: linear-gradient(90deg, transparent, rgba(98,230,255,.9) 20%, #fff 50%, rgba(98,230,255,.9) 80%, transparent);
+ box-shadow: 0 0 24px 4px rgba(98,230,255,.45), 0 -40vh 80px -20px rgba(98,230,255,.06); }
+.hud-reticle { position: absolute; left: 0; top: 0; width: 120px; height: 120px; margin: -60px 0 0 -60px; opacity: 0; transition: opacity .5s; }
+.hud-reticle i { position: absolute; width: 18px; height: 18px; border: 0 solid var(--cyan); transition: transform .9s cubic-bezier(.2,.9,.2,1); }
+.hud-reticle i:nth-child(1) { left: 0; top: 0; border-width: 1.5px 0 0 1.5px; }
+.hud-reticle i:nth-child(2) { right: 0; top: 0; border-width: 1.5px 1.5px 0 0; }
+.hud-reticle i:nth-child(3) { left: 0; bottom: 0; border-width: 0 0 1.5px 1.5px; }
+.hud-reticle i:nth-child(4) { right: 0; bottom: 0; border-width: 0 1.5px 1.5px 0; }
+.hud-reticle:not(.lock) i:nth-child(1) { transform: translate(-40px, -40px); } .hud-reticle:not(.lock) i:nth-child(2) { transform: translate(40px, -40px); }
+.hud-reticle:not(.lock) i:nth-child(3) { transform: translate(-40px, 40px); } .hud-reticle:not(.lock) i:nth-child(4) { transform: translate(40px, 40px); }
+.hud-reticle span { position: absolute; left: calc(100% + 16px); top: 6px; white-space: nowrap; font-size: 10px; line-height: 1.7; color: rgba(231,233,235,.75); }
+.hud-reticle span b { font-weight: 400; color: var(--amber); }
+.hud-reticle span::before { content: ''; position: absolute; right: calc(100% + 4px); top: 8px; width: 12px; height: 1px; background: var(--cyan); }
+.hud-boot { position: absolute; right: var(--pad); bottom: 84px; list-style: none; display: grid; gap: 3px; font-size: 10px; text-align: right; color: rgba(98,230,255,.8); }
+.hud-boot li { animation: bootIn .25s steps(3) both; }
+.hud-boot li.dim { color: rgba(231,233,235,.4); }
+@keyframes bootIn { from { opacity: 0; transform: translateX(8px); } }
+.is-live .hc, .is-booting .hc { opacity: 1; transform: none; }
+.is-booting .hud-side, .is-live .hud-ruler { opacity: 1; }
+.is-booting .hud-boot { opacity: 1; }
+.hud-boot { opacity: 0; transition: opacity 1.2s; }
+.hud.on-reticle .hud-reticle { opacity: 1; }
+
+/* hold gauge following the pointer */
+.hold { position: fixed; left: 0; top: 0; z-index: 25; width: 84px; height: 84px; margin: -42px 0 0 -42px; pointer-events: none; opacity: 0; transition: opacity .35s; will-change: transform; }
+.hold svg { width: 100%; height: 100%; transform: rotate(-90deg); overflow: visible; }
+.h-track { fill: none; stroke: rgba(255,176,0,.25); stroke-width: 1.2; stroke-dasharray: 2 4; }
+.h-fill { fill: none; stroke: var(--amber); stroke-width: 3; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--c, 0)); filter: drop-shadow(0 0 6px rgba(255,176,0,.8)); }
+.h-label { position: absolute; left: 50%; top: calc(100% + 8px); transform: translateX(-50%); color: var(--amber); font-size: 10px; white-space: nowrap; }
+.show-hold .hold { opacity: 1; }
+
+/* ─── sections ─────────────────────────────────────────── */
+main { position: relative; z-index: 3; pointer-events: none; }
+main a, main button, main .card, main .quote { pointer-events: auto; }
+.sec { position: relative; height: 170vh; }
+.sec.hero { height: 150vh; }
+.sec.spec { height: 150vh; }
+.sec.apply { height: 190vh; }
+.pin { position: sticky; top: 0; height: 100vh; height: 100svh; padding: 0 var(--pad); overflow: hidden; }
+
+.kicker { color: var(--amber); display: flex; align-items: center; gap: 10px; margin-bottom: 22px; }
+.kicker span { color: var(--ink); padding: 3px 6px 2px; box-shadow: inset 0 0 0 1px rgba(231,233,235,.25); }
+h2 { font: 600 clamp(38px, 4.6vw, 76px)/.98 var(--display); letter-spacing: -.02em; text-transform: uppercase; max-width: 13em; }
+h2 em, h3 em { font-style: normal; color: var(--amber); }
+.body { max-width: 34em; color: var(--soft); font-size: clamp(16px, 1.2vw, 19px); line-height: 1.5; font-weight: 500; }
+
+/* reveal: children of an inactive section sit down and fade */
+.sec .rv { opacity: 0; transform: translateY(26px); transition: opacity .7s cubic-bezier(.2,.8,.2,1), transform .9s cubic-bezier(.2,.8,.2,1); transition-delay: calc(var(--i, 0) * 70ms); }
+.sec.is-on .rv { opacity: 1; transform: none; }
+.sec .card, .sec .steps, .sec .timeline { opacity: 0; transition: opacity .5s ease; }
+.sec.is-on .card, .sec.is-on .steps, .sec.is-on .timeline { opacity: 1; transition-duration: .8s; }
+
+/* hero */
+.hero .pin { display: grid; align-content: end; padding-bottom: 12vh; }
+.hero-copy { max-width: 760px; }
+.eyebrow { color: var(--soft); display: flex; align-items: center; gap: 10px; margin-bottom: 22px; }
+.blink { width: 7px; height: 7px; border-radius: 50%; background: var(--red); box-shadow: 0 0 10px var(--red); animation: blink 1.2s steps(2) infinite; }
+.is-live .blink { background: var(--cyan); box-shadow: 0 0 10px var(--cyan); animation: none; }
+@keyframes blink { 50% { opacity: .15; } }
+.title { font: 700 clamp(72px, 10.2vw, 178px)/.8 var(--display); letter-spacing: -.035em; text-transform: uppercase; display: grid; }
+.title .t1 { color: transparent; -webkit-text-stroke: 1.5px rgba(231,233,235,.75); font-size: .62em; letter-spacing: -.01em; margin-bottom: .08em; }
+.title .t2 { color: var(--ink); }
+.title q { quotes: '“' '”'; }
+.title q::before, .title q::after { color: var(--amber); font-weight: 500; }
+.tag { margin-top: 22px; font: 600 clamp(22px, 2.3vw, 36px)/1 var(--display); text-transform: uppercase; letter-spacing: .02em; }
+.tag em { font-style: normal; color: var(--amber); }
+.lede { margin-top: 16px; max-width: 30em; color: var(--soft); font-size: clamp(16px, 1.25vw, 19px); }
+.ignite { margin-top: 34px; display: flex; align-items: center; gap: 22px; }
+.gauge { position: relative; width: 132px; height: 132px; flex: none; touch-action: none; -webkit-user-select: none; user-select: none; -webkit-touch-callout: none; }
+.gauge svg { position: absolute; inset: 0; width: 100%; height: 100%; transform: rotate(-90deg); overflow: visible; }
+.g-ticks { fill: none; stroke: rgba(231,233,235,.28); stroke-width: 6; stroke-dasharray: 1 6.75; }
+.g-track { fill: rgba(8,9,11,.55); stroke: rgba(255,176,0,.3); stroke-width: 1; }
+.g-fill { fill: none; stroke: var(--amber); stroke-width: 4; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--c, 0)); filter: drop-shadow(0 0 8px rgba(255,176,0,.9)); }
+.g-core { position: absolute; inset: 22px; border-radius: 50%; display: grid; place-content: center; text-align: center; gap: 4px; transition: background .3s;
+ background: radial-gradient(circle, rgba(255,176,0,calc(.08 + var(--c, 0) * .4)), rgba(255,176,0,0) 70%); }
+.g-label { font: 700 12px/1.05 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--amber); }
+.g-pct { font-size: 10px; color: var(--muted); }
+.gauge::after { content: ''; position: absolute; inset: -10px; border-radius: 50%; box-shadow: 0 0 0 1px rgba(255,176,0,.5); animation: ping 2.2s cubic-bezier(.2,.8,.2,1) infinite; }
+@keyframes ping { 0% { transform: scale(.75); opacity: .9; } 100% { transform: scale(1.25); opacity: 0; } }
+.is-holding .gauge::after { animation-duration: .5s; }
+.ignite-title { color: var(--red); margin-bottom: 6px; }
+.ignite-hint { max-width: 17em; font-size: 15px; color: var(--soft); line-height: 1.4; }
+.is-live .gauge::after { animation: none; opacity: 0; }
+.is-live .g-fill { stroke: var(--cyan); filter: drop-shadow(0 0 8px rgba(98,230,255,.8)); }
+.is-live .g-track { stroke: rgba(98,230,255,.35); }
+.is-live .g-label { color: var(--cyan); }
+.is-live .ignite-title { color: var(--cyan); }
+.scroll-cue { position: absolute; right: var(--pad); bottom: 7vh; display: grid; grid-template-columns: auto auto; align-items: center; gap: 8px 14px; justify-items: end; color: var(--soft); opacity: 0; transition: opacity .8s .4s; }
+.scroll-cue span { grid-column: 1; }
+.scroll-cue b { font-weight: 400; color: var(--amber); margin-right: 6px; }
+.scroll-cue i { grid-column: 2; grid-row: 1 / span 2; }
+.scroll-cue i { width: 1px; height: 46px; background: linear-gradient(var(--amber), transparent); animation: cue 1.8s ease-in-out infinite; transform-origin: top; }
+@keyframes cue { 0% { transform: scaleY(0); } 50% { transform: scaleY(1); } 100% { transform: scaleY(1); opacity: 0; } }
+.is-live .scroll-cue { opacity: 1; }
+
+/* blocks */
+.block { position: absolute; top: 50%; transform: translateY(-50%); max-width: 560px; }
+.block-l { left: var(--pad); }
+.block-r { right: calc(var(--pad) + 150px); }
+.block.wide { max-width: 760px; }
+.block h2 + .body { margin-top: 26px; }
+.steps { list-style: none; margin-top: 34px; display: grid; gap: 1px; background: var(--line); box-shadow: 0 0 0 1px var(--line); }
+.steps li { display: grid; grid-template-columns: 76px 1fr; gap: 14px; padding: 16px 18px; background: rgba(8,9,11,.72); backdrop-filter: blur(6px); color: var(--soft); font-size: 16px; line-height: 1.4; }
+.steps b { color: var(--amber); font-size: 11px; padding-top: 3px; }
+.steps strong { color: var(--ink); font-weight: 600; }
+
+/* spec cards */
+.card { position: absolute; top: 50%; transform: translateY(-50%); width: min(430px, calc(100vw - 2 * var(--pad))); padding: 30px 30px 28px;
+ background: linear-gradient(160deg, rgba(14,16,19,.82), rgba(8,9,11,.6)); backdrop-filter: blur(14px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(231,233,235,.1), 0 40px 80px -30px rgba(0,0,0,.9);
+ clip-path: polygon(0 0, calc(100% - 22px) 0, 100% 22px, 100% 100%, 22px 100%, 0 calc(100% - 22px)); }
+.card::before { content: ''; position: absolute; left: 0; top: 0; width: 64px; height: 2px; background: var(--amber); }
+.card-l { left: var(--pad); }
+.card-r { right: calc(var(--pad) + 150px); }
+.card h3 { font: 600 clamp(26px, 2.3vw, 36px)/1.02 var(--display); text-transform: uppercase; letter-spacing: -.01em; margin-bottom: 16px; }
+.card .body { font-size: 16.5px; }
+.data { margin-top: 24px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--line); box-shadow: 0 0 0 1px var(--line); font-size: 10px; }
+.data div { background: rgba(8,9,11,.85); padding: 12px 12px 11px; }
+.data dt { color: var(--muted); margin-bottom: 6px; }
+.data dd { color: var(--cyan); font-size: 12px; letter-spacing: .06em; }
+.spec .rv { transform: translateY(18px); }
+
+/* 3D-projected hotspot markers */
+.spots { position: fixed; inset: 0; z-index: 11; pointer-events: none; }
+.spot { position: absolute; left: 0; top: 0; width: 44px; height: 44px; margin: -22px 0 0 -22px; opacity: 0; transition: opacity .5s; pointer-events: none; }
+.spot.on { opacity: 1; pointer-events: auto; cursor: pointer; }
+.spot::before, .spot::after { content: ''; position: absolute; inset: 0; border-radius: 50%; }
+.spot::before { inset: 15px; background: var(--amber); box-shadow: 0 0 16px var(--amber); }
+.spot::after { box-shadow: inset 0 0 0 1px rgba(255,176,0,.8); animation: ping 1.8s cubic-bezier(.2,.8,.2,1) infinite; }
+.spot.on.dim { opacity: .5; }
+.spot.dim span { opacity: 0; }
+.spot.dim::before { inset: 18px; background: rgba(231,233,235,.8); box-shadow: none; }
+.spot.dim::after { animation: none; box-shadow: inset 0 0 0 1px rgba(231,233,235,.3); inset: 10px; }
+.spot span { position: absolute; left: 50%; top: calc(100% + 2px); transform: translateX(-50%); font: 400 9px/1 var(--mono); letter-spacing: .14em; color: var(--ink); white-space: nowrap; }
+.leader { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 11; pointer-events: none; opacity: 0; transition: opacity .4s; overflow: visible; }
+.leader line { stroke: rgba(255,176,0,.75); stroke-width: 1; stroke-dasharray: 3 3; }
+.leader circle { fill: var(--amber); }
+.leader.on { opacity: 1; }
+
+/* height ruler projected from 3D */
+.ruler { position: fixed; left: 0; top: 0; z-index: 11; pointer-events: none; opacity: 0; transition: opacity .5s; width: 1px; }
+.ruler.on { opacity: 1; }
+.ruler-line { position: absolute; left: 0; top: 0; bottom: 0; width: 1px; background: var(--cyan); box-shadow: 0 0 8px var(--cyan); }
+.ruler-line::before { content: ''; position: absolute; left: -6px; top: 0; bottom: 0; width: 13px;
+ background: repeating-linear-gradient(0deg, rgba(98,230,255,.8) 0 1px, transparent 1px calc(100% / 11.4)); -webkit-mask: linear-gradient(90deg, #000 30%, transparent 30% 70%, #000 70%); mask: linear-gradient(90deg, #000 30%, transparent 30% 70%, #000 70%); }
+.ruler span { position: absolute; left: 14px; color: var(--cyan); font-size: 11px; white-space: nowrap; }
+.ruler-top { top: -6px; } .ruler-bot { bottom: -6px; color: rgba(231,233,235,.5) !important; }
+
+/* stats */
+.figs { list-style: none; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 44px 56px; margin-top: 12px; }
+.figs li { position: relative; padding-top: 18px; border-top: 1px solid var(--line); }
+.figs li::before { content: ''; position: absolute; top: -1px; left: 0; width: 28px; height: 1px; background: var(--amber); }
+.figs b { font: 600 clamp(64px, 7.4vw, 128px)/.85 var(--display); letter-spacing: -.045em; font-variant-numeric: tabular-nums; }
+.figs i { font: 500 clamp(18px, 1.7vw, 28px)/1 var(--display); font-style: normal; color: var(--amber); margin-left: 8px; text-transform: uppercase; }
+.figs span { display: block; margin-top: 14px; color: var(--muted); max-width: 20em; font-size: 10.5px; line-height: 1.6; }
+.stats .block { max-width: 640px; }
+
+/* program */
+.timeline { list-style: none; margin-top: 36px; display: grid; grid-template-columns: repeat(4, 1fr); gap: 1px; background: var(--line); box-shadow: 0 0 0 1px var(--line); }
+.timeline li { background: rgba(8,9,11,.78); backdrop-filter: blur(8px); padding: 18px 16px 20px; display: grid; align-content: start; gap: 8px; }
+.timeline b { color: var(--amber); font-size: 10px; }
+.timeline strong { font: 600 20px/1 var(--display); text-transform: uppercase; }
+.timeline span { color: var(--soft); font-size: 14.5px; line-height: 1.38; }
+.req { margin-top: 30px; display: grid; grid-template-columns: 120px 1fr; gap: 18px; }
+.req-t { color: var(--muted); padding-top: 4px; }
+.req ul { list-style: none; display: grid; gap: 8px; color: var(--soft); font-size: 16px; line-height: 1.35; }
+.req li { position: relative; padding-left: 20px; }
+.req li::before { content: ''; position: absolute; left: 0; top: .5em; width: 8px; height: 8px; box-shadow: inset 0 0 0 1.5px var(--amber); }
+.quote { position: absolute; right: calc(var(--pad) + 150px); bottom: 9vh; width: 340px; display: grid; grid-template-columns: 110px 1fr; gap: 0 18px; align-items: start;
+ padding: 14px; background: rgba(8,9,11,.72); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px var(--line); }
+.quote img { grid-row: span 2; width: 110px; height: 146px; object-fit: cover; object-position: 50% 30%; filter: saturate(.85) contrast(1.05); }
+.quote blockquote { font: 500 18px/1.2 var(--display); text-transform: none; margin-top: 4px; }
+.quote figcaption { color: var(--muted); font-size: 9.5px; line-height: 1.6; margin-top: 10px; }
+
+/* apply */
+.apply .pin { display: grid; align-content: end; padding-bottom: 11vh; }
+.cta { max-width: 700px; }
+.cta-title { font-size: clamp(56px, 7.6vw, 132px); line-height: .86; }
+.cta .body { margin-top: 26px; }
+.cta-row { display: flex; flex-wrap: wrap; gap: 14px; margin-top: 34px; }
+.cta-meta { margin-top: 26px; color: var(--muted); }
+
+/* footer */
+.foot { position: relative; z-index: 5; background: var(--bg); border-top: 1px solid var(--line); padding: 90px var(--pad) 90px; }
+.foot::before { content: ''; position: absolute; left: 0; right: 0; top: -1px; height: 10px; background: repeating-linear-gradient(-45deg, var(--amber) 0 10px, #0b0b0b 10px 20px); opacity: .85; }
+.foot-in { max-width: 1320px; margin: 0 auto; display: grid; grid-template-columns: 1.3fr 2fr; gap: 60px; }
+.foot-mark { font: 700 clamp(44px, 6vw, 92px)/.9 var(--display); text-transform: uppercase; letter-spacing: -.02em; }
+.foot-mark b { color: var(--amber); font-weight: 700; }
+.foot-brand .mono { margin-top: 16px; color: var(--muted); }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr); gap: 30px; }
+.foot-cols div { display: grid; gap: 10px; align-content: start; }
+.foot-cols p { color: var(--amber); margin-bottom: 6px; }
+.foot-cols a, .foot-cols span { text-decoration: none; color: var(--soft); font-size: 16px; }
+.foot-cols a:hover { color: #fff; }
+.foot-legal { grid-column: 1 / -1; display: flex; justify-content: space-between; gap: 20px; flex-wrap: wrap; padding-top: 30px; border-top: 1px solid var(--line); color: var(--muted); font-size: 10px; }
+
+/* cold state: nothing but the headline, the gauge and the strobes */
+.is-cold .nav .links { opacity: .6; }
+
+@media (max-width: 1100px) {
+ .block-r, .card-r, .quote { right: var(--pad); }
+ .timeline { grid-template-columns: repeat(2, 1fr); }
+ .hud-side { display: none; }
+}
+@media (max-width: 760px) {
+ body { font-size: 16px; }
+ .links, .snd-state { display: none; }
+ .nav { padding: 14px var(--pad); }
+ .nav .btn { height: 36px; padding: 0 14px; font-size: 11px; }
+ .brand { font-size: 13px; letter-spacing: .16em; }
+ .snd { height: 36px; padding: 0 10px; }
+ .hud-top { top: 64px; font-size: 9px; gap: 8px; }
+ .hud-top .hud-clock, .hud-top .hud-sep:last-of-type { display: none; }
+ .hc.tl, .hc.tr { top: 60px; } .hc.bl { bottom: 64px; }
+ .hud-ruler, .hud-boot { display: none; }
+ .hud-reticle span { display: none; }
+ .hero .pin { padding-bottom: 76px; }
+ .title { font-size: clamp(64px, 20vw, 110px); }
+ .lede { font-size: 15.5px; }
+ .ignite { margin-top: 22px; gap: 16px; }
+ .gauge { width: 108px; height: 108px; }
+ .g-core { inset: 18px; }
+ .ignite-hint { font-size: 14px; }
+ .scroll-cue { display: none; }
+ .block, .card { top: auto; bottom: 76px; transform: none; left: var(--pad); right: var(--pad); max-width: none; width: auto; }
+ .card { padding: 22px 20px 20px; }
+ .card h3 { font-size: 24px; }
+ .card .body { font-size: 15px; }
+ h2 { font-size: clamp(32px, 9vw, 44px); }
+ .power .body { display: none; }
+ .steps li { grid-template-columns: 58px 1fr; padding: 12px 14px; font-size: 14.5px; }
+ .figs { gap: 26px 20px; }
+ .figs b { font-size: clamp(48px, 15vw, 72px); }
+ .figs span { font-size: 9.5px; }
+ .program .block { bottom: auto; top: 90px; }
+ .timeline { grid-template-columns: 1fr 1fr; margin-top: 22px; }
+ .timeline li { padding: 12px; }
+ .timeline span { font-size: 13px; }
+ .req { display: none; }
+ .quote { left: var(--pad); right: var(--pad); width: auto; bottom: 76px; grid-template-columns: 70px 1fr; }
+ .quote img { width: 70px; height: 92px; }
+ .quote blockquote { font-size: 15px; }
+ .apply .pin { padding-bottom: 80px; }
+ .cta-title { font-size: clamp(48px, 15vw, 76px); }
+ .btn-lg { height: 50px; padding: 0 20px; font-size: 12px; }
+ .foot-in, .foot-cols { grid-template-columns: 1fr; }
+ .hold { display: none; }
+ .leader, .ruler, .spot.dim { display: none; }
+ .eyebrow { font-size: 10px; letter-spacing: .1em; }
+ .foot-mark { font-size: 38px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .gauge::after, .spot::after, .scroll-cue i, .blink { animation: none !important; }
+}
diff --git a/examples/hangar/volumetric.js b/examples/hangar/volumetric.js
new file mode 100644
index 0000000..1c29561
--- /dev/null
+++ b/examples/hangar/volumetric.js
@@ -0,0 +1,141 @@
+// Page-local copy of src/core/volumetric.js, extended for the hangar:
+// up to 8 spotlights, lights at zero intensity are packed out on the CPU (so the red strobes, floods,
+// drone and dawn light only cost when they are on), a height-dependent haze layer and a cheap phase term
+// that brightens beams you look down (the Titanfall "god ray toward camera" look).
+import * as THREE from 'three';
+import { Effect, EffectAttribute, BlendFunction } from 'postprocessing';
+
+const N = 8;
+const frag = /* glsl */`
+uniform mat4 uProjInv;
+uniform mat4 uCamWorld;
+uniform vec3 uCamPos;
+uniform int uCount;
+uniform vec3 uLPos[${N}];
+uniform vec3 uLDir[${N}];
+uniform vec3 uLCol[${N}];
+uniform vec2 uLCone[${N}];
+uniform float uLRange[${N}];
+uniform float uDensity;
+uniform float uTime;
+uniform float uNoise;
+uniform float uNoiseScale;
+uniform float uMaxDist;
+uniform vec3 uWind;
+uniform float uFloorY;
+uniform float uHazeTop;
+uniform float uPhase;
+
+float vhash(vec3 p){ p = fract(p * 0.3183099 + .1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
+float vnoise(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(vhash(i), vhash(i + vec3(1,0,0)), f.x), mix(vhash(i + vec3(0,1,0)), vhash(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(vhash(i + vec3(0,0,1)), vhash(i + vec3(1,0,1)), f.x), mix(vhash(i + vec3(0,1,1)), vhash(i + vec3(1,1,1)), f.x), f.y), f.z);
+}
+
+void mainImage(const in vec4 inputColor, const in vec2 uv, const in float depth, out vec4 outputColor) {
+ if (uCount == 0) { outputColor = inputColor; return; }
+ vec4 clip = vec4(uv * 2. - 1., depth * 2. - 1., 1.);
+ vec4 vp = uProjInv * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vec4(vp.xyz, 1.)).xyz;
+ vec3 ro = uCamPos;
+ vec3 rd = wp - ro;
+ float len = min(length(rd), uMaxDist);
+ rd = normalize(rd);
+ const int STEPS = 36;
+ float stepL = len / float(STEPS);
+ float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))) + uTime * 0.61803);
+ vec3 acc = vec3(0.);
+ for (int i = 0; i < STEPS; i++) {
+ float t = (float(i) + jitter) * stepL;
+ vec3 p = ro + rd * t;
+ vec3 q = p * uNoiseScale + uWind * uTime;
+ float n = vnoise(q) * 0.62 + vnoise(q * 2.7 + 7.1) * 0.38;
+ float dens = uDensity * mix(1.0, n * n * 2.6, uNoise) * smoothstep(uFloorY - 0.2, uFloorY + 1.2, p.y) * (1.0 - smoothstep(uHazeTop * 0.6, uHazeTop, p.y) * 0.7);
+ for (int l = 0; l < ${N}; l++) {
+ if (l >= uCount) break;
+ vec3 d = p - uLPos[l];
+ float dist = max(length(d), 1e-3);
+ vec3 dn = d / dist;
+ float c = dot(dn, uLDir[l]);
+ float cone = smoothstep(uLCone[l].x, uLCone[l].y, c);
+ float att = 1.0 / (1.0 + dist * dist * uLRange[l]);
+ // forward scattering: beams glow brighter when they point at the viewer
+ float ph = 1.0 + uPhase * pow(max(dot(dn, -rd), 0.0), 6.0);
+ acc += uLCol[l] * cone * att * dens * stepL * ph;
+ }
+ }
+ outputColor = vec4(inputColor.rgb + acc, inputColor.a);
+}`;
+
+export class HangarVolumetric extends Effect {
+ constructor(camera, { density = 0.02, noise = 0.9, noiseScale = 0.22, maxDist = 70, wind = new THREE.Vector3(0.05, 0.12, 0.03), floorY = 0, hazeTop = 30, phase = 1.5 } = {}) {
+ const vec3s = () => Array.from({ length: N }, () => new THREE.Vector3());
+ super('HangarVolumetric', frag, {
+ attributes: EffectAttribute.DEPTH,
+ blendFunction: BlendFunction.NORMAL,
+ uniforms: new Map([
+ ['uProjInv', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamWorld', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamPos', new THREE.Uniform(new THREE.Vector3())],
+ ['uCount', new THREE.Uniform(0)],
+ ['uLPos', new THREE.Uniform(vec3s())],
+ ['uLDir', new THREE.Uniform(vec3s())],
+ ['uLCol', new THREE.Uniform(vec3s())],
+ ['uLCone', new THREE.Uniform(Array.from({ length: N }, () => new THREE.Vector2(0.9, 0.95)))],
+ ['uLRange', new THREE.Uniform(new Array(N).fill(0.01))],
+ ['uDensity', new THREE.Uniform(density)],
+ ['uTime', new THREE.Uniform(0)],
+ ['uNoise', new THREE.Uniform(noise)],
+ ['uNoiseScale', new THREE.Uniform(noiseScale)],
+ ['uMaxDist', new THREE.Uniform(maxDist)],
+ ['uWind', new THREE.Uniform(wind)],
+ ['uFloorY', new THREE.Uniform(floorY)],
+ ['uHazeTop', new THREE.Uniform(hazeTop)],
+ ['uPhase', new THREE.Uniform(phase)],
+ ]),
+ });
+ this.camera = camera;
+ this.lights = [];
+ this._d = new THREE.Vector3();
+ this._p = new THREE.Vector3();
+ }
+
+ /** Track a SpotLight. `scale` multiplies colour*intensity into the haze; `range` is quadratic falloff; `gain` is a live multiplier. */
+ add(light, { scale = 0.001, range = 0.01, softness = 0.2 } = {}) {
+ const e = { light, scale, range, softness, gain: 1 };
+ this.lights.push(e);
+ return e;
+ }
+
+ get density() { return this.uniforms.get('uDensity').value; }
+ set density(v) { this.uniforms.get('uDensity').value = v; }
+
+ update(renderer, inputBuffer, dt) {
+ const u = this.uniforms;
+ const cam = this.camera;
+ u.get('uProjInv').value.copy(cam.projectionMatrixInverse);
+ u.get('uCamWorld').value.copy(cam.matrixWorld);
+ u.get('uCamPos').value.setFromMatrixPosition(cam.matrixWorld);
+ u.get('uTime').value += dt;
+ let n = 0;
+ for (const e of this.lights) {
+ const { light, scale, range, softness, gain } = e;
+ const on = light.visible ? light.intensity * scale * gain : 0;
+ if (on < 1e-4 || n >= N) continue;
+ light.updateMatrixWorld();
+ light.target.updateMatrixWorld();
+ this._p.setFromMatrixPosition(light.matrixWorld);
+ this._d.setFromMatrixPosition(light.target.matrixWorld).sub(this._p).normalize();
+ u.get('uLPos').value[n].copy(this._p);
+ u.get('uLDir').value[n].copy(this._d);
+ u.get('uLCol').value[n].set(light.color.r * on, light.color.g * on, light.color.b * on);
+ const outer = Math.cos(light.angle);
+ const inner = Math.cos(light.angle * (1 - Math.max(light.penumbra, softness)));
+ u.get('uLCone').value[n].set(outer, inner);
+ u.get('uLRange').value[n] = range;
+ n++;
+ }
+ u.get('uCount').value = n;
+ }
+}
diff --git a/examples/hangar/world.js b/examples/hangar/world.js
new file mode 100644
index 0000000..c0a117c
--- /dev/null
+++ b/examples/hangar/world.js
@@ -0,0 +1,674 @@
+// Hangar Nine — procedural hangar: wet concrete with painted bay markings, corrugated walls, roof trusses,
+// an overhead crane, maintenance gantries, containers, floods, bay lamps, red strobes and the dawn door.
+import * as THREE from 'three';
+import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+
+export const HALL = { x: 31, zBack: -32, zFront: 36, h: 28, doorW: 15, doorH: 20 };
+export const BAYS_Z = [-28, -20, -12, -4, 4, 12, 20, 28];
+
+// ─── helpers ──────────────────────────────────────────────────────────────────
+const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _e = new THREE.Euler(), _s = new THREE.Vector3(1, 1, 1), _p = new THREE.Vector3();
+
+/** World-space box projection so every merged piece gets the same texel density (1 uv = 4 m). */
+function boxUV(geo, scale = 0.25) {
+ const p = geo.attributes.position, n = geo.attributes.normal;
+ const uv = new Float32Array(p.count * 2);
+ for (let i = 0; i < p.count; i++) {
+ const ax = Math.abs(n.getX(i)), ay = Math.abs(n.getY(i)), az = Math.abs(n.getZ(i));
+ let u, v;
+ if (ax >= ay && ax >= az) { u = p.getZ(i); v = p.getY(i); }
+ else if (az >= ay) { u = p.getX(i); v = p.getY(i); }
+ else { u = p.getX(i); v = p.getZ(i); }
+ uv[i * 2] = u * scale; uv[i * 2 + 1] = v * scale;
+ }
+ geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ return geo;
+}
+
+class Batch {
+ constructor(mat, { cast = true, receive = true, uv = true } = {}) { this.mat = mat; this.geos = []; this.cast = cast; this.receive = receive; this.uv = uv; }
+ put(geo, x, y, z, rx = 0, ry = 0, rz = 0) {
+ _e.set(rx, ry, rz); _q.setFromEuler(_e); _p.set(x, y, z);
+ geo.applyMatrix4(_m.compose(_p, _q, _s));
+ this.geos.push(geo.index ? geo.toNonIndexed() : geo);
+ return this;
+ }
+ box(w, h, d, x, y, z, rx, ry, rz) { return this.put(new THREE.BoxGeometry(w, h, d), x, y, z, rx, ry, rz); }
+ cyl(r0, r1, h, x, y, z, rx, ry, rz, seg = 12) { return this.put(new THREE.CylinderGeometry(r0, r1, h, seg), x, y, z, rx, ry, rz); }
+ /** Beam between two points. */
+ beam(a, b, w, d = w) {
+ const len = a.distanceTo(b);
+ const g = new THREE.BoxGeometry(w, len, d);
+ const mid = a.clone().add(b).multiplyScalar(0.5);
+ const dir = b.clone().sub(a).normalize();
+ _q.setFromUnitVectors(new THREE.Vector3(0, 1, 0), dir);
+ g.applyMatrix4(_m.compose(mid, _q, _s));
+ this.geos.push(g.toNonIndexed());
+ return this;
+ }
+ tube(a, b, r, seg = 10) {
+ const len = a.distanceTo(b);
+ const g = new THREE.CylinderGeometry(r, r, len, seg, 1, true);
+ const mid = a.clone().add(b).multiplyScalar(0.5);
+ _q.setFromUnitVectors(new THREE.Vector3(0, 1, 0), b.clone().sub(a).normalize());
+ g.applyMatrix4(_m.compose(mid, _q, _s));
+ this.geos.push(g.toNonIndexed());
+ return this;
+ }
+ build(parent) {
+ if (!this.geos.length) return null;
+ for (const g of this.geos) { if (this.uv) boxUV(g); for (const k of Object.keys(g.attributes)) if (!['position', 'normal', 'uv'].includes(k)) g.deleteAttribute(k); }
+ const mesh = new THREE.Mesh(mergeGeometries(this.geos, false), this.mat);
+ mesh.castShadow = this.cast; mesh.receiveShadow = this.receive;
+ parent.add(mesh);
+ return mesh;
+ }
+}
+
+function worldPosChunk(sh, name = 'vW') {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 ${name};`)
+ .replace('#include <project_vertex>', `#include <project_vertex>\n${name} = (modelMatrix * vec4(transformed, 1.0)).xyz;`);
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', `#include <common>\nvarying vec3 ${name};
+ float h13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+ float vn3(vec3 x){ vec3 i = floor(x), f = fract(x); f = f*f*(3.-2.*f);
+ return mix(mix(mix(h13(i), h13(i+vec3(1,0,0)), f.x), mix(h13(i+vec3(0,1,0)), h13(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(h13(i+vec3(0,0,1)), h13(i+vec3(1,0,1)), f.x), mix(h13(i+vec3(0,1,1)), h13(i+vec3(1,1,1)), f.x), f.y), f.z); }`);
+}
+
+/** Painted steel with diagonal hazard stripes in world space, worn at the edges. */
+function hazardMaterial({ freq = 1.1, rough = 0.62 } = {}) {
+ const m = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: rough, metalness: 0.25 });
+ m.onBeforeCompile = sh => {
+ worldPosChunk(sh, 'vHz');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <map_fragment>', `#include <map_fragment>
+ {
+ float s = smoothstep(0.47, 0.53, fract((vHz.x + vHz.z + vHz.y) * ${freq.toFixed(2)}));
+ float wear = vn3(vHz * 3.1) * 0.6 + vn3(vHz * 11.0) * 0.4;
+ vec3 amber = vec3(0.78, 0.36, 0.0) * (0.75 + wear * 0.35);
+ vec3 blk = vec3(0.012);
+ vec3 c = mix(blk, amber, s);
+ c = mix(c, vec3(0.05, 0.05, 0.05), smoothstep(0.62, 0.8, wear) * 0.8); // scuffed through to steel
+ diffuseColor.rgb = c;
+ }`);
+ };
+ m.customProgramCacheKey = () => 'hazard' + freq;
+ return m;
+}
+
+function canvasTex(w, h, draw, { srgb = true, flipY = true } = {}) {
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
+ const g = c.getContext('2d');
+ draw(g, w, h);
+ const t = new THREE.CanvasTexture(c);
+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;
+ t.flipY = flipY;
+ t.anisotropy = 8;
+ return t;
+}
+
+// ─── build ────────────────────────────────────────────────────────────────────
+export function buildHangar({ scene, renderer, reflection, maxAniso = 8 }) {
+ const root = new THREE.Group();
+ scene.add(root);
+ const out = { root };
+
+ // Materials ------------------------------------------------------------------
+ const steelRough = bakeTexture(renderer, 512, `void main(){ float r = 0.42 + fbm(vUv*4., 4., 5, .55)*0.35 + fbm(vUv*32., 32., 3, .5)*0.12; gl_FragColor = vec4(1., clamp(r,.12,1.), 0., 1.); }`);
+ const steelN = fbmNormal(renderer, { size: 512, scale: 6, octaves: 5, strength: 0.7 });
+ const steel = new THREE.MeshStandardMaterial({ color: 0x3b4046, metalness: 0.78, roughness: 1, roughnessMap: steelRough, normalMap: steelN, normalScale: new THREE.Vector2(0.4, 0.4) });
+ const darkSteel = new THREE.MeshStandardMaterial({ color: 0x1b1e22, metalness: 0.7, roughness: 1, roughnessMap: steelRough });
+ const crane = new THREE.MeshStandardMaterial({ color: 0xb87d08, metalness: 0.35, roughness: 1, roughnessMap: steelRough, normalMap: steelN, normalScale: new THREE.Vector2(0.5, 0.5) });
+ const hazard = hazardMaterial();
+ const rubber = new THREE.MeshStandardMaterial({ color: 0x0b0b0c, roughness: 0.85, metalness: 0 });
+
+ // corrugated cladding
+ const corrN = bakeTexture(renderer, 1024, `
+ float H(vec2 p){ return sin(p.x * 6.2831853 * 20.0) * 0.5 + fbm(p * 6., 6., 5, .55) * 0.9 + fbm(p*40., 40., 3, .5)*0.15; }
+ void main(){
+ float e = 1.0/1024.0;
+ float hx = H(vUv + vec2(e,0.)) - H(vUv - vec2(e,0.));
+ float hy = H(vUv + vec2(0.,e)) - H(vUv - vec2(0.,e));
+ vec3 n = normalize(vec3(-hx * 5.0, -hy * 5.0, 1.));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.);
+ }`);
+ const corrA = bakeTexture(renderer, 1024, `
+ void main(){
+ vec2 p = vUv;
+ float streak = fbm(vec2(p.x * 24., p.y * 1.5), 24., 5, .6);
+ float grime = fbm(p * 3., 3., 5, .6);
+ float seam = smoothstep(0.0, 0.006, abs(fract(p.x * 1.0) - 0.5) - 0.494);
+ vec3 c = vec3(0.034, 0.038, 0.044) * (0.75 + streak * 0.5) * (0.8 + grime * 0.6);
+ c = mix(c * 0.4, c, seam);
+ // rust weeping from the lower edge of each sheet
+ float rust = smoothstep(0.35, 0.0, fract(p.y)) * smoothstep(0.1, 0.5, fbm(vec2(p.x*30., p.y*3.)+1.7, 30., 4, .6)+.3);
+ c = mix(c, vec3(0.06, 0.028, 0.012), rust * 0.35);
+ gl_FragColor = vec4(c, 1.);
+ }`);
+ const corrR = bakeTexture(renderer, 512, `void main(){ float r = 0.55 + fbm(vec2(vUv.x*20., vUv.y*2.), 20., 5, .6)*0.35; gl_FragColor = vec4(1., clamp(r,.2,1.), 0., 1.); }`);
+ const cladding = new THREE.MeshStandardMaterial({ map: corrA, normalMap: corrN, roughnessMap: corrR, roughness: 1, metalness: 0.55, normalScale: new THREE.Vector2(1, 1) });
+ const containerMat = (hex) => new THREE.MeshStandardMaterial({ color: hex, map: corrA, normalMap: corrN, roughnessMap: corrR, roughness: 1, metalness: 0.35 });
+
+ // Floor ------------------------------------------------------------------------
+ const floorA = bakeTexture(renderer, 2048, `
+ float hh(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
+ void main(){
+ vec2 p = vUv;
+ vec2 g = p * 3.0; vec2 id = floor(g); vec2 f = fract(g);
+ float slab = hh(id);
+ float seam = min(min(f.x, 1.-f.x), min(f.y, 1.-f.y));
+ float line = smoothstep(0.0015, 0.004, seam);
+ float n = fbm(p * 36., 36., 6, .55);
+ float big = fbm(p * 4. + slab, 4., 5, .6);
+ float oil = smoothstep(0.12, 0.4, fbm(p * 5. + 3.1, 5., 5, .62));
+ float tyre = smoothstep(0.1, 0.3, fbm(vec2(p.x * 60., p.y * 2.), 60., 3, .5)) * smoothstep(0.2, 0.5, fbm(p*2.+9., 2., 3, .5)+.3);
+ vec3 base = vec3(0.105, 0.106, 0.108) * (0.82 + slab * 0.22) * (0.8 + n * 0.45) * (0.78 + big * 0.5);
+ base = mix(base, base * 0.35, oil * 0.55);
+ base = mix(base, base * 0.55, tyre * 0.4);
+ gl_FragColor = vec4(base * mix(0.25, 1.0, line), 1.0);
+ }`);
+ const floorR = bakeTexture(renderer, 2048, `
+ void main(){
+ vec2 p = vUv;
+ vec2 f = fract(p * 3.0);
+ float seam = min(min(f.x, 1.-f.x), min(f.y, 1.-f.y));
+ float wet = smoothstep(0.02, -0.08, fbm(p * 3. + 0.7, 3., 5, .55)); // puddles
+ float damp = smoothstep(0.1, -0.05, fbm(p * 1.5 + 4.1, 1.5, 4, .5));
+ float r = 0.5 + fbm(p * 18., 18., 4, .5) * 0.25;
+ r = mix(r, 0.3, damp * 0.8);
+ r = mix(r, 0.035, wet);
+ r = mix(0.9, r, smoothstep(0.001, 0.005, seam));
+ float wear = fbm(p * 40., 40., 4, .6) * 0.5 + 0.5;
+ gl_FragColor = vec4(wear, clamp(r, 0.03, 1.0), 0.0, 1.0);
+ }`);
+ const floorN = fbmNormal(renderer, { size: 1024, scale: 28, octaves: 5, strength: 0.5 });
+ for (const t of [floorA, floorR, floorN]) { t.repeat.set(1 / 12, 1 / 12); t.anisotropy = maxAniso; }
+ const floorMat = new THREE.MeshStandardMaterial({ map: floorA, roughnessMap: floorR, normalMap: floorN, normalScale: new THREE.Vector2(0.35, 0.35), roughness: 1, metalness: 0, envMapIntensity: 0.5 });
+
+ // painted markings (world metres drawn straight into the canvas)
+ const MK = { x0: -33, z0: -33, size: 72 };
+ const marks = canvasTex(2048, 2048, (g, W) => {
+ const k = W / MK.size;
+ g.setTransform(k, 0, 0, k, -MK.x0 * k, -MK.z0 * k);
+ const amber = '#e2a012', white = '#d9d6cc';
+ const hazardBand = (x, z, w, h, stripe = 0.9) => {
+ g.save(); g.beginPath(); g.rect(x, z, w, h); g.clip();
+ g.fillStyle = '#121212'; g.fillRect(x, z, w, h);
+ g.fillStyle = amber;
+ for (let s = x - h - 40; s < x + w + 40; s += stripe) { g.beginPath(); g.moveTo(s, z); g.lineTo(s + stripe / 2, z); g.lineTo(s + stripe / 2 + h, z + h); g.lineTo(s + h, z + h); g.fill(); }
+ g.restore();
+ };
+ const ring = (x0, z0, x1, z1, bw) => {
+ hazardBand(x0, z0, x1 - x0, bw); hazardBand(x0, z1 - bw, x1 - x0, bw);
+ hazardBand(x0, z0, bw, z1 - z0); hazardBand(x1 - bw, z0, bw, z1 - z0);
+ };
+ // Bay 09 pad
+ ring(-7.2, -7.5, 7.2, 6.6, 0.55);
+ // neighbouring bays, just outlines
+ g.strokeStyle = amber; g.lineWidth = 0.22;
+ g.strokeRect(-27.5, -14, 14, 20); g.strokeRect(13.5, -14, 14, 20);
+ // lane to the door
+ g.fillStyle = amber;
+ g.fillRect(-9.3, 7.5, 0.24, 29); g.fillRect(9.06, 7.5, 0.24, 29);
+ for (let z = 18; z < 35; z += 2.4) g.fillRect(-0.09, z, 0.18, 1.2);
+ // chevrons toward the door
+ g.lineWidth = 0.5; g.strokeStyle = amber;
+ for (let i = 0; i < 3; i++) { const z = 24 + i * 2.2; g.beginPath(); g.moveTo(-3, z); g.lineTo(0, z + 1.6); g.lineTo(3, z); g.stroke(); }
+ // walkway lines along the gantries
+ g.fillStyle = white;
+ for (const x of [-11.6, 11.4]) g.fillRect(x, -30, 0.18, 64);
+ // big bay number
+ g.save();
+ g.fillStyle = amber;
+ g.font = '700 7.4px "Chakra Petch", "Arial Black", sans-serif';
+ g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.fillText('09', 0, 12.4);
+ g.font = '600 0.62px "Chakra Petch", Arial, sans-serif';
+ g.fillStyle = white;
+ g.fillText('BAY 09 · MAX STANDING LOAD 45 T · KEEP CLEAR DURING COLD START', 0, 7.35);
+ g.font = '700 2.6px "Chakra Petch", Arial, sans-serif';
+ g.fillStyle = amber;
+ g.fillText('08', -20.5, -9); g.fillText('10', 20.5, -9);
+ g.restore();
+ // vents
+ g.fillStyle = '#0a0a0a';
+ for (const [x, z] of [[-4.6, 3.9], [4.6, 3.9], [-4.6, -4.9], [4.6, -4.9]]) g.fillRect(x - 0.8, z - 0.5, 1.6, 1.0);
+ }, { srgb: true, flipY: false });
+ marks.anisotropy = maxAniso;
+
+ const FLOOR = { x0: -60, x1: 60, z0: HALL.zBack, z1: 125 };
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(FLOOR.x1 - FLOOR.x0, FLOOR.z1 - FLOOR.z0, 1, 1), floorMat);
+ floor.rotation.x = -Math.PI / 2;
+ floor.position.set((FLOOR.x0 + FLOOR.x1) / 2, 0, (FLOOR.z0 + FLOOR.z1) / 2);
+ floor.receiveShadow = true;
+ // world-space uv so tiling is in metres
+ {
+ const p = floor.geometry.attributes.position, uv = floor.geometry.attributes.uv;
+ for (let i = 0; i < p.count; i++) uv.setXY(i, (p.getX(i) + floor.position.x), -(p.getY(i)) + floor.position.z);
+ }
+ root.add(floor);
+ reflection.hidden.push(floor);
+ reflection.patch(floorMat, { strength: 1.35, distort: 0.018, lodScale: 6.5, lodBias: 0.2, f0: 0.05 });
+ const floorU = {
+ uMarks: { value: marks }, uMarkBox: { value: new THREE.Vector3(MK.x0, MK.z0, MK.size) },
+ uPool: { value: Array.from({ length: 16 }, () => new THREE.Vector4(0, 0, 1, 0)) }, uPoolCol: { value: new THREE.Color(1.0, 0.93, 0.82) },
+ uWave: { value: new THREE.Vector2(0, 0) }, uWaveCol: { value: new THREE.Color(0.4, 0.9, 1.0) },
+ };
+ {
+ const prev = floorMat.onBeforeCompile;
+ floorMat.onBeforeCompile = (sh, r) => {
+ prev(sh, r);
+ Object.assign(sh.uniforms, floorU);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ uniform sampler2D uMarks; uniform vec3 uMarkBox; uniform vec4 uPool[16]; uniform vec3 uPoolCol; uniform vec2 uWave; uniform vec3 uWaveCol;
+ float gPaint = 0.0;`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ {
+ vec2 muv = (vReflW.xz - uMarkBox.xy) / uMarkBox.z;
+ vec4 mk = texture2D(uMarks, muv);
+ float inside = step(0.0, muv.x) * step(muv.x, 1.0) * step(0.0, muv.y) * step(muv.y, 1.0);
+ float wearN = texture2D(roughnessMap, vRoughnessMapUv * 2.7).r;
+ gPaint = mk.a * inside * smoothstep(0.28, 0.5, wearN);
+ diffuseColor.rgb = mix(diffuseColor.rgb, mk.rgb * 0.8, gPaint);
+ }`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ {
+ float wz = texture2D(roughnessMap, vRoughnessMapUv * 0.37 + 0.13).r;
+ float zone = smoothstep(17.0, 6.0, length(vReflW.xz - vec2(0.0, 3.0))) * smoothstep(0.38, 0.62, wz + 0.12);
+ roughnessFactor = mix(roughnessFactor, 0.045, zone * 0.9);
+ }
+ roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.32), gPaint);`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ vec3 pl = vec3(0.);
+ for (int i = 0; i < 16; i++) {
+ vec4 P = uPool[i];
+ if (P.w <= 0.0) continue;
+ vec2 d = vReflW.xz - P.xy;
+ pl += P.w * exp(-dot(d, d) / (P.z * P.z));
+ }
+ totalEmissiveRadiance += diffuseColor.rgb * pl * uPoolCol;
+ float rd = length(vReflW.xz) - uWave.x;
+ totalEmissiveRadiance += uWaveCol * uWave.y * (exp(-rd * rd * 3.0) + 0.25 * exp(-rd*rd*0.15) * step(rd, 0.0));
+ }`);
+ };
+ floorMat.customProgramCacheKey = () => 'hangar-floor';
+ }
+ out.floor = floor; out.floorU = floorU; out.floorMat = floorMat;
+
+ // Shell: walls, roof ------------------------------------------------------------
+ const shell = new Batch(cladding, { cast: false, receive: true });
+ const W = HALL.x, zc = (HALL.zBack + HALL.zFront) / 2, len = HALL.zFront - HALL.zBack;
+ shell.box(0.3, HALL.h, len, -W - 0.15, HALL.h / 2, zc);
+ shell.box(0.3, HALL.h, len, W + 0.15, HALL.h / 2, zc);
+ shell.box(W * 2 + 0.6, HALL.h, 0.3, 0, HALL.h / 2, HALL.zBack - 0.15);
+ // front wall with the door opening
+ const dw = HALL.doorW, dh = HALL.doorH;
+ shell.box(W - dw, HALL.h, 0.3, -(dw + (W - dw) / 2), HALL.h / 2, HALL.zFront + 0.15);
+ shell.box(W - dw, HALL.h, 0.3, dw + (W - dw) / 2, HALL.h / 2, HALL.zFront + 0.15);
+ shell.box(dw * 2, HALL.h - dh, 0.3, 0, dh + (HALL.h - dh) / 2, HALL.zFront + 0.15);
+ shell.box(W * 2, 0.3, len, 0, HALL.h + 0.15, zc);
+ shell.build(root);
+
+ // skirting / columns on the side walls
+ const frame = new Batch(darkSteel);
+ for (const z of BAYS_Z) for (const s of [-1, 1]) frame.box(0.9, HALL.h, 0.7, s * (W - 0.45), HALL.h / 2, z);
+ for (const s of [-1, 1]) frame.box(0.25, 0.9, len, s * (W - 0.2), 0.45, zc);
+ // clerestory mullions
+ for (const s of [-1, 1]) for (let z = HALL.zBack + 2; z < HALL.zFront - 1; z += 2) frame.box(0.2, 4.2, 0.12, s * (W - 0.1), 22.2, z);
+ // door header + jambs
+ frame.box(dw * 2 + 2, 1.4, 1.2, 0, dh + 0.7, HALL.zFront - 0.4);
+ for (const s of [-1, 1]) frame.box(1.2, dh, 1.2, s * (dw + 0.6), dh / 2, HALL.zFront - 0.4);
+ frame.build(root);
+ const doorHaz = new Batch(hazard);
+ doorHaz.box(dw * 2, 0.5, 1.25, 0, dh + 0.02, HALL.zFront - 0.4);
+ for (const s of [-1, 1]) doorHaz.box(1.25, 2.2, 1.25, s * (dw + 0.6), 1.1, HALL.zFront - 0.4);
+ doorHaz.build(root);
+
+ // clerestory glass: faint moonlight, the only cold light in the building before power-up
+ const glassMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0.05, 0.07, 0.1), fog: false });
+ const glassGeo = [];
+ for (const s of [-1, 1]) {
+ const g = new THREE.PlaneGeometry(len - 3, 4);
+ g.rotateY(s > 0 ? -Math.PI / 2 : Math.PI / 2);
+ g.translate(s * (W - 0.02), 22.2, zc);
+ glassGeo.push(g);
+ }
+ const glass = new THREE.Mesh(mergeGeometries(glassGeo), glassMat);
+ root.add(glass);
+ out.glassMat = glassMat;
+
+ // Roof trusses -----------------------------------------------------------------
+ const truss = new Batch(darkSteel, { cast: false });
+ const yB = 22, yT = 26;
+ for (const z of BAYS_Z) {
+ truss.box(W * 2, 0.45, 0.35, 0, yB, z);
+ truss.box(W * 2, 0.45, 0.35, 0, yT, z);
+ for (let x = -W + 1; x <= W - 1; x += 3) {
+ truss.box(0.18, yT - yB, 0.18, x, (yB + yT) / 2, z);
+ truss.beam(new THREE.Vector3(x, yB, z), new THREE.Vector3(x + 3, yT, z), 0.16);
+ }
+ }
+ for (let x = -W + 3; x < W; x += 6) truss.box(0.25, 0.3, len, x, yT + 0.35, zc);
+ // longitudinal bracing at the bottom chord
+ for (const x of [-15, 15]) truss.box(0.2, 0.2, len, x, yB - 0.1, zc);
+ truss.build(root);
+
+ // Overhead crane ------------------------------------------------------------------
+ const craneB = new Batch(crane);
+ const craneZ = 0.5, craneY = 19.4;
+ for (const dz of [-1.3, 1.3]) craneB.box(W * 2 - 1.6, 1.4, 0.6, 0, craneY, craneZ + dz);
+ for (const s of [-1, 1]) craneB.box(1.4, 1.0, 4.6, s * (W - 1.2), craneY + 0.2, craneZ);
+ // trolley + hoist
+ craneB.box(3.2, 1.2, 3.6, 3.2, craneY + 1.2, craneZ);
+ craneB.box(1.3, 1.4, 1.6, 3.2, craneY - 1.1, craneZ);
+ craneB.build(root);
+ const rails = new Batch(darkSteel, { cast: false });
+ for (const s of [-1, 1]) rails.box(0.6, 0.8, len, s * (W - 1.2), craneY - 0.6, zc);
+ rails.build(root);
+ const hook = new Batch(steel);
+ for (const dx of [-0.25, 0.25]) hook.tube(new THREE.Vector3(3.2 + dx, craneY - 1.8, craneZ), new THREE.Vector3(3.2 + dx, 15.6, craneZ), 0.03, 6);
+ hook.box(1.0, 1.1, 0.6, 3.2, 15.1, craneZ);
+ hook.build(root);
+ const hookHaz = new Batch(hazard);
+ hookHaz.box(1.05, 0.5, 0.65, 3.2, 14.4, craneZ);
+ hookHaz.put(new THREE.TorusGeometry(0.34, 0.1, 8, 18, Math.PI * 1.4), 3.2, 13.7, craneZ, 0, 0, -Math.PI * 0.2);
+ hookHaz.build(root);
+
+ // Maintenance gantries --------------------------------------------------------------
+ const gSteel = new Batch(steel);
+ const gHaz = new Batch(hazard);
+ const levels = [4.4, 8.4, 12.4];
+ const T = { z0: -7.6, z1: -2.8, xin: 6.4, xout: 9.8 };
+ for (const s of [-1, 1]) {
+ const xi = s * T.xin, xo = s * T.xout, xm = (xi + xo) / 2, wx = Math.abs(xo - xi);
+ for (const x of [xi, xo]) for (const z of [T.z0, T.z1]) gSteel.box(0.32, 13.6, 0.32, x, 6.8, z);
+ for (const y of levels) {
+ gSteel.box(wx + 0.3, 0.14, T.z1 - T.z0 + 0.3, xm, y, (T.z0 + T.z1) / 2);
+ gHaz.box(0.06, 0.2, T.z1 - T.z0 + 0.3, xi, y + 0.16, (T.z0 + T.z1) / 2);
+ gHaz.box(wx + 0.3, 0.2, 0.06, xm, y + 0.16, T.z1 + 0.14);
+ // rails on the outer + front side
+ for (const hy of [0.55, 1.1]) {
+ gSteel.box(0.05, 0.05, T.z1 - T.z0, xo, y + hy, (T.z0 + T.z1) / 2);
+ gSteel.box(wx, 0.05, 0.05, xm, y + hy, T.z1 + 0.1);
+ }
+ for (let z = T.z0; z <= T.z1 + 0.01; z += 1.2) gSteel.box(0.05, 1.1, 0.05, xo, y + 0.55, z);
+ // cantilevered service arm toward the mech
+ gSteel.box(1.8, 0.14, 1.6, s * (T.xin - 0.9), y, -3.6);
+ gHaz.box(0.06, 0.18, 1.6, s * (T.xin - 1.8), y + 0.15, -3.6);
+ }
+ // X bracing on the outer face
+ for (let i = 0; i < levels.length; i++) {
+ const y0 = i === 0 ? 0.2 : levels[i - 1], y1 = levels[i];
+ gSteel.beam(new THREE.Vector3(xo, y0, T.z0), new THREE.Vector3(xo, y1, T.z1), 0.12);
+ gSteel.beam(new THREE.Vector3(xo, y0, T.z1), new THREE.Vector3(xo, y1, T.z0), 0.12);
+ gSteel.beam(new THREE.Vector3(xi, y0, T.z0), new THREE.Vector3(xo, y1, T.z0), 0.12);
+ }
+ // stair flight on the outer side
+ const sx = s * (T.xout + 0.8);
+ gSteel.beam(new THREE.Vector3(sx, 0, T.z1 + 3.5), new THREE.Vector3(sx, levels[0], T.z0 + 0.3), 0.12, 1.1);
+ for (let k = 0; k < 16; k++) { const f = k / 16; gSteel.box(1.0, 0.05, 0.28, sx, f * levels[0], lerpN(T.z1 + 3.5, T.z0 + 0.3, f)); }
+ }
+ // top bridge behind the mech
+ gSteel.box(T.xin * 2, 0.16, 1.5, 0, levels[2], T.z0 + 0.75);
+ for (const hy of [0.55, 1.1]) gSteel.box(T.xin * 2, 0.05, 0.05, 0, levels[2] + hy, T.z0 + 1.5);
+ for (let x = -T.xin; x <= T.xin; x += 1.2) gSteel.box(0.05, 1.1, 0.05, x, levels[2] + 0.55, T.z0 + 1.5);
+ gHaz.box(T.xin * 2, 0.22, 0.06, 0, levels[2] + 0.17, T.z0 + 1.52);
+ gSteel.build(root); gHaz.build(root);
+
+ // Cable bundles drooping from the gantry into the mech's back
+ const cables = new Batch(rubber, { uv: false });
+ for (const [s, y, r] of [[-1, 10.2, 0.09], [1, 9.6, 0.11], [-1, 7.1, 0.07], [1, 6.2, 0.08]]) {
+ const a = new THREE.Vector3(s * T.xin, y, -4.2), b = new THREE.Vector3(s * 1.9, y - 0.4, -3.4);
+ const curve = new THREE.QuadraticBezierCurve3(a, new THREE.Vector3(s * 4.2, y - 2.6, -4.4), b);
+ const g = new THREE.TubeGeometry(curve, 24, r, 6, false);
+ cables.geos.push(g.toNonIndexed());
+ }
+ cables.build(root);
+
+ // Containers, drums, carts ------------------------------------------------------------
+ const cont = [containerMat(0x6a2f16), containerMat(0x1b3d42), containerMat(0x34383d), containerMat(0x5a4a1e)];
+ const cb = cont.map(m => new Batch(m));
+ const stacks = [
+ [-25.5, -22, 3, 0], [-25.5, -8, 2, 1], [-25.5, 18, 2, 2], [25.5, -20, 2, 3], [25.5, -6, 3, 2], [25.5, 16, 1, 0],
+ [-20.5, -24, 1, 2], [20.5, 24, 1, 1],
+ ];
+ for (const [x, z, n, c] of stacks) for (let i = 0; i < n; i++) cb[(c + i) % cont.length].box(2.44, 2.59, 12.2, x + (i % 2 ? 0.12 : 0), 1.3 + i * 2.6, z + (i % 2 ? -0.25 : 0));
+ cb.forEach(b => b.build(root));
+ const drumMat = new THREE.MeshStandardMaterial({ color: 0x1e3a55, roughness: 0.5, metalness: 0.6, roughnessMap: steelRough });
+ const drums = new Batch(drumMat);
+ for (const [x, z] of [[11.5, 3.2], [12.2, 3.9], [11.3, 4.4], [-12.4, -1.5], [-11.8, -0.8], [16, 9], [16.7, 9.5]]) drums.cyl(0.3, 0.3, 0.9, x, 0.45, z, 0, 0, 0, 16);
+ drums.build(root);
+ const carts = new Batch(darkSteel);
+ const cartHaz = new Batch(hazard);
+ for (const [x, z, r] of [[-12.5, 4.5, 0.3], [13.2, -1, -0.4]]) {
+ carts.box(1.8, 0.08, 0.9, x, 0.9, z, 0, r); carts.box(1.8, 0.08, 0.9, x, 0.35, z, 0, r);
+ carts.box(1.7, 0.5, 0.85, x, 1.2, z, 0, r);
+ for (const [dx, dz] of [[-0.85, -0.4], [0.85, -0.4], [-0.85, 0.4], [0.85, 0.4]]) carts.box(0.05, 0.9, 0.05, x + dx * Math.cos(r) + dz * Math.sin(r), 0.45, z - dx * Math.sin(r) + dz * Math.cos(r));
+ cartHaz.box(1.72, 0.12, 0.87, x, 1.5, z, 0, r);
+ }
+ // bollards along the lane
+ for (let z = 10; z <= 34; z += 6) for (const s of [-1, 1]) cartHaz.cyl(0.12, 0.12, 1.1, s * 10.2, 0.55, z, 0, 0, 0, 10);
+ carts.build(root); cartHaz.build(root);
+
+ // Floor vents (grates the steam comes out of)
+ const vents = [[-4.6, 3.9], [4.6, 3.9], [-4.6, -4.9], [4.6, -4.9]].map(([x, z]) => new THREE.Vector3(x, 0.02, z));
+ const grate = new Batch(darkSteel);
+ for (const v of vents) for (let i = -3; i <= 3; i++) grate.box(1.5, 0.05, 0.06, v.x, 0.03, v.z + i * 0.13);
+ grate.build(root);
+ out.vents = vents;
+
+ // Emergency red strips at the pad corners and along the walls (reflected in the wet floor)
+ const redStripMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 0.05, 0.02).multiplyScalar(2.2), toneMapped: true });
+ const redStrips = new Batch(redStripMat, { cast: false, receive: false, uv: false });
+ for (const s of [-1, 1]) {
+ for (let z = HALL.zBack + 4; z < HALL.zFront - 2; z += 8) redStrips.box(0.08, 0.08, 2.4, s * (W - 0.35), 0.95, z);
+ redStrips.box(1.6, 0.06, 0.06, s * 7.2, 0.05, 6.8); redStrips.box(1.6, 0.06, 0.06, s * 7.2, 0.05, -7.7);
+ }
+ redStrips.build(root);
+ out.redStripMat = redStripMat;
+ // exit signs
+ const exitTex = canvasTex(256, 96, (g) => {
+ g.fillStyle = '#062a12'; g.fillRect(0, 0, 256, 96);
+ g.fillStyle = '#58ff96'; g.font = '700 58px "Chakra Petch", Arial, sans-serif'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText('EXIT', 128, 52);
+ });
+ const exitMat = new THREE.MeshBasicMaterial({ map: exitTex, color: new THREE.Color(1.6, 1.6, 1.6) });
+ for (const [x, z, ry] of [[-W + 0.35, -16, Math.PI / 2], [W - 0.35, 8, -Math.PI / 2], [-W + 0.35, 24, Math.PI / 2]]) {
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(1.2, 0.45), exitMat);
+ m.position.set(x, 3.4, z); m.rotation.y = ry; root.add(m);
+ }
+
+ // Back wall stencil
+ const stencil = canvasTex(2048, 1024, (g, w, h) => {
+ g.clearRect(0, 0, w, h);
+ g.fillStyle = '#fff';
+ g.font = '700 760px "Chakra Petch", "Arial Black", sans-serif';
+ g.textAlign = 'left'; g.textBaseline = 'alphabetic';
+ g.fillText('09', 20, 780);
+ g.font = '600 118px "Chakra Petch", Arial, sans-serif';
+ g.fillText('HANGAR NINE', 40, 960);
+ // stencil bridges + wear
+ g.globalCompositeOperation = 'destination-out';
+ for (let i = 0; i < 2600; i++) { g.globalAlpha = Math.random() * 0.6; g.beginPath(); g.arc(Math.random() * w, Math.random() * h, Math.random() * 7, 0, 7); g.fill(); }
+ g.globalAlpha = 1;
+ g.fillRect(0, 380, w, 26);
+ }, { srgb: false });
+ const stencilMat = new THREE.MeshStandardMaterial({ color: 0x9a6a08, alphaMap: stencil, transparent: true, roughness: 0.8, metalness: 0, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2 });
+ const sten = new THREE.Mesh(new THREE.PlaneGeometry(22, 11), stencilMat);
+ sten.position.set(-12.5, 15.5, HALL.zBack + 0.02);
+ sten.receiveShadow = true;
+ root.add(sten);
+
+ // Door leaves (slide apart for the finale). Inner faces carry a split "09".
+ const doorFace = canvasTex(2048, 1400, (g, w, h) => {
+ g.fillStyle = '#101215'; g.fillRect(0, 0, w, h);
+ g.fillStyle = '#b07808';
+ g.font = '700 1150px "Chakra Petch", "Arial Black", sans-serif';
+ g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.fillText('09', w / 2, h / 2 + 60);
+ g.globalCompositeOperation = 'destination-over';
+ });
+ const leafW = dw + 0.4;
+ const doors = [];
+ for (const s of [-1, 1]) {
+ const face = doorFace.clone(); face.needsUpdate = true;
+ // seen from inside (looking +z) the +x leaf is on the left, so it carries the left half of the "09"
+ face.repeat.set(0.5, 1); face.offset.set(s > 0 ? 0 : 0.5, 0);
+ const faceMat = new THREE.MeshStandardMaterial({ map: face, roughness: 0.7, metalness: 0.4, normalMap: corrN, normalScale: new THREE.Vector2(0.8, 0.8) });
+ const geo = new THREE.BoxGeometry(leafW, dh - 0.2, 0.5);
+ const mats = [cladding, cladding, cladding, cladding, cladding, faceMat];
+ const m = new THREE.Mesh(geo, mats);
+ m.position.set(s * leafW / 2, (dh - 0.2) / 2, HALL.zFront - 1.3);
+ m.castShadow = true; m.receiveShadow = true;
+ m.userData.closedX = s * leafW / 2;
+ m.userData.openX = s * (dw + leafW / 2 + 0.6);
+ root.add(m);
+ doors.push(m);
+ }
+ out.doors = doors;
+
+ // Outside: dawn plate beyond the apron
+ const dawnTex = new THREE.TextureLoader().load(`${import.meta.env.BASE_URL}img/hangar/dawn.webp`);
+ dawnTex.colorSpace = THREE.SRGBColorSpace;
+ const dawnMat = new THREE.MeshBasicMaterial({ map: dawnTex, fog: false, color: new THREE.Color(0, 0, 0) });
+ const plateW = 190, plateH = plateW * 1536 / 2752;
+ const plate = new THREE.Mesh(new THREE.PlaneGeometry(plateW, plateH), dawnMat);
+ plate.rotation.y = Math.PI;
+ plate.position.set(0, 3.0 + (0.515 - 0.5) * plateH, 124);
+ root.add(plate);
+ out.dawnMat = dawnMat;
+
+ // Lighting fixtures ------------------------------------------------------------------
+ // Bay high-bay lamps: two per truss, switched bay by bay during the cold start.
+ const lampBody = new Batch(darkSteel, { cast: false });
+ const bays = BAYS_Z.map((z, i) => {
+ const lensMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0, 0, 0) });
+ const lens = [];
+ for (const x of [-15, 15]) {
+ lampBody.put(new THREE.CylinderGeometry(0.35, 0.75, 0.7, 16, 1, true), x, 21.2, z);
+ lampBody.tube(new THREE.Vector3(x, 21.55, z), new THREE.Vector3(x, 22, z), 0.04, 6);
+ const l = new THREE.Mesh(new THREE.CircleGeometry(0.66, 20), lensMat);
+ l.rotation.x = Math.PI / 2; l.position.set(x, 20.86, z);
+ root.add(l); lens.push(l);
+ }
+ return { z, lensMat, on: 0 };
+ });
+ lampBody.build(root);
+ out.bays = bays;
+
+ // Fake light cones under each bay lamp (cheap; the four hero floods get real raymarched beams).
+ const coneMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ uniforms: { uTime: { value: 0 } },
+ vertexShader: `
+ attribute float aOn;
+ varying float vOn; varying vec3 vN; varying vec3 vV; varying float vH; varying vec3 vW;
+ void main(){
+ vOn = aOn; vH = uv.y;
+ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz;
+ vN = normalize(mat3(modelMatrix) * normal);
+ vV = normalize(cameraPosition - w.xyz);
+ gl_Position = projectionMatrix * viewMatrix * w;
+ }`,
+ fragmentShader: `
+ uniform float uTime;
+ varying float vOn; varying vec3 vN; varying vec3 vV; varying float vH; varying vec3 vW;
+ float h13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+ float vn(vec3 x){ vec3 i = floor(x), f = fract(x); f = f*f*(3.-2.*f);
+ return mix(mix(mix(h13(i), h13(i+vec3(1,0,0)), f.x), mix(h13(i+vec3(0,1,0)), h13(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(h13(i+vec3(0,0,1)), h13(i+vec3(1,0,1)), f.x), mix(h13(i+vec3(0,1,1)), h13(i+vec3(1,1,1)), f.x), f.y), f.z); }
+ void main(){
+ if (vOn <= 0.001) discard;
+ float edge = pow(abs(dot(vN, vV)), 2.2);
+ float n = vn(vW * 0.35 + vec3(0.0, -uTime * 0.25, uTime * 0.08)) * 0.7 + 0.3;
+ float a = edge * pow(vH, 1.6) * n * vOn;
+ gl_FragColor = vec4(vec3(1.0, 0.92, 0.8) * a * 0.03, 1.0);
+ }`,
+ });
+ {
+ const geos = [];
+ for (const b of bays) for (const x of [-15, 15]) {
+ const g = new THREE.CylinderGeometry(0.62, 5.5, 20.6, 28, 1, true);
+ g.translate(x, 20.6 / 2 + 0.2, b.z);
+ const on = new Float32Array(g.attributes.position.count);
+ g.setAttribute('aOn', new THREE.BufferAttribute(on, 1));
+ b.coneRange = [geos.reduce((a, gg) => a + gg.attributes.position.count, 0), g.attributes.position.count];
+ geos.push(g);
+ }
+ const cg = mergeGeometries(geos);
+ const cones = new THREE.Mesh(cg, coneMat);
+ cones.frustumCulled = false;
+ cones.renderOrder = 5;
+ root.add(cones);
+ out.cones = cones; out.coneMat = coneMat;
+ out.setBay = (i, v) => {
+ const b = bays[i]; b.on = v;
+ b.lensMat.color.setRGB(1, 0.94, 0.84).multiplyScalar(v * 14);
+ const a = cg.attributes.aOn;
+ // two cones per bay, stored consecutively
+ const per = a.count / (bays.length * 2);
+ for (let k = i * 2 * per; k < (i * 2 + 2) * per; k++) a.array[k] = v;
+ a.needsUpdate = true;
+ floorU.uPool.value[i * 2].set(-15, b.z, 6.5, v * 1.1);
+ floorU.uPool.value[i * 2 + 1].set(15, b.z, 6.5, v * 1.1);
+ };
+ }
+
+ // Hero floods: 4 real spotlights with raymarched beams, crossing over the mech.
+ const floodBody = new Batch(darkSteel, { cast: false });
+ const floods = [
+ { pos: [-15, 21.2, -14], tgt: [2.6, 1.5, 2.5], power: 4200, shadow: true, angle: 0.2 },
+ { pos: [15, 21.2, -14], tgt: [-2.6, 1.5, 2.5], power: 3800, shadow: false, angle: 0.2 },
+ { pos: [-13, 21, 13], tgt: [2.4, 3.0, -1.2], power: 650, shadow: false, color: 0xffdcb4 },
+ { pos: [13, 21, 13], tgt: [-2.4, 3.0, -1.2], power: 900, shadow: true, color: 0xffe2c0 },
+ ].map(f => {
+ const light = new THREE.SpotLight(f.color ?? 0xe2eaff, 0, 80, f.angle ?? 0.27, 0.45, 2);
+ light.position.set(...f.pos);
+ light.target.position.set(...f.tgt);
+ if (f.shadow) {
+ light.castShadow = true;
+ light.shadow.mapSize.set(2048, 2048);
+ light.shadow.camera.near = 6; light.shadow.camera.far = 50;
+ light.shadow.bias = -0.00012; light.shadow.normalBias = 0.04;
+ light.shadow.autoUpdate = false;
+ light.shadow.needsUpdate = true;
+ }
+ root.add(light, light.target);
+ const dir = new THREE.Vector3(...f.tgt).sub(new THREE.Vector3(...f.pos)).normalize();
+ const q = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, -1, 0), dir);
+ const g = new THREE.CylinderGeometry(0.75, 0.9, 1.2, 20, 1, false);
+ g.applyQuaternion(q); g.translate(...f.pos);
+ floodBody.geos.push(g.toNonIndexed());
+ // yoke up to the truss
+ floodBody.tube(new THREE.Vector3(...f.pos), new THREE.Vector3(f.pos[0], 22, f.pos[2]), 0.08, 6);
+ const lensMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0, 0, 0) });
+ const lens = new THREE.Mesh(new THREE.CircleGeometry(0.72, 24), lensMat);
+ lens.position.set(...f.pos).addScaledVector(dir, 0.62);
+ lens.lookAt(lens.position.clone().add(dir));
+ root.add(lens);
+ return { ...f, light, lensMat, on: 0 };
+ });
+ floodBody.build(root);
+ out.floods = floods;
+
+ // Red rotating beacons on top of each gantry tower + a strobe behind the mech.
+ const beaconMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1, 0.04, 0.02) });
+ const beacons = [-1, 1].map((s, i) => {
+ const p = new THREE.Vector3(s * (T.xin + T.xout) / 2, 13.9, (T.z0 + T.z1) / 2);
+ const cap = new THREE.Mesh(new THREE.CylinderGeometry(0.22, 0.26, 0.42, 16), beaconMat);
+ cap.position.copy(p); root.add(cap);
+ const base = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.3, 0.14, 16), darkSteel);
+ base.position.copy(p).y -= 0.27; root.add(base);
+ const light = new THREE.SpotLight(0xff1a0a, 0, 60, 0.22, 0.5, 2);
+ light.position.copy(p);
+ root.add(light, light.target);
+ return { light, pos: p, phase: i * Math.PI, cap };
+ });
+ out.beacons = beacons; out.beaconMat = beaconMat;
+ out.T = T; out.levels = levels;
+ return out;
+}
+
+function lerpN(a, b, t) { return a + (b - a) * t; }
diff --git a/examples/horologie/finish.js b/examples/horologie/finish.js
new file mode 100644
index 0000000..33fd524
--- /dev/null
+++ b/examples/horologie/finish.js
@@ -0,0 +1,205 @@
+// Haute-horlogerie finishes as live shader code (crisp at any zoom — the macro shots depend on it),
+// plus the "iris": a noisy spherical front that dissolves the Meshy watch while the procedural calibre
+// appears inside it (complementary discard on the same world-space field).
+import * as THREE from 'three';
+
+export const FINISH = { none: 0, cotes: 1, perlage: 2, circular: 3, sunray: 4, snail: 5, mirror: 6 };
+
+const NOISE = /* glsl */`
+ float hHash(vec3 p){ return fract(sin(dot(p, vec3(127.1, 311.7, 74.7))) * 43758.5453); }
+ float hNoise(vec3 p){ vec3 i = floor(p), f = fract(p); f = f*f*(3.-2.*f);
+ return mix(mix(mix(hHash(i), hHash(i+vec3(1,0,0)), f.x), mix(hHash(i+vec3(0,1,0)), hHash(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(hHash(i+vec3(0,0,1)), hHash(i+vec3(1,0,1)), f.x), mix(hHash(i+vec3(0,1,1)), hHash(i+vec3(1,1,1)), f.x), f.y), f.z); }
+`;
+
+/** Shared iris uniforms (one set per dissolving object). */
+export function irisUniforms() {
+ return {
+ uIris: { value: 0 },
+ uIrisC: { value: new THREE.Vector3() },
+ uIrisR: { value: 1.2 },
+ uIrisGlow: { value: new THREE.Color(2.6, 1.45, 0.8) },
+ uIrisInv: { value: 0 },
+ };
+}
+
+/**
+ * Patch a standard/physical material.
+ * finish: FINISH.* on caps (|n.z| > .96 in object space); anglage: polish the 45° chamfers.
+ * iris: 1 = visible inside the front (procedural), 2 = visible outside (Meshy); u = irisUniforms().
+ * spring: hairspring breathing (rotates each vertex by uBal * (1 - aS)).
+ * recolor: case/strap tint for collection variants of the Meshy watch.
+ */
+export function patch(mat, { finish = 0, anglage = false, iris = 0, u = null, spring = false, recolor = null, params = {} } = {}) {
+ const P = {
+ uCotes: { value: new THREE.Vector3(Math.cos(0.42), Math.sin(0.42), 0.105) },
+ uPerl: { value: 0.046 },
+ uGrain: { value: 2400 },
+ uBevelRough: { value: 0.05 },
+ uSideRough: { value: 0.34 },
+ uCapRough: { value: mat.roughness },
+ uBal: { value: 0 },
+ uCaseTint: { value: new THREE.Color(1, 1, 1) },
+ uStrapTint: { value: new THREE.Color(1, 1, 1) },
+ uDialC: { value: new THREE.Vector3() },
+ uCaseR: { value: 1 },
+ uDLC: { value: 0 },
+ ...params,
+ };
+ mat.userData.u = P;
+ mat.defines = mat.defines || {};
+ if (finish || anglage) mat.defines.HORO_FINISH = finish;
+ if (anglage) mat.defines.HORO_ANGLAGE = 1;
+ if (iris) mat.defines.HORO_IRIS = iris;
+ if (spring) mat.defines.HORO_SPRING = 1;
+ if (recolor) mat.defines.HORO_RECOLOR = 1;
+ mat.onBeforeCompile = shader => {
+ Object.assign(shader.uniforms, P);
+ if (u) Object.assign(shader.uniforms, u);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vOP; varying vec3 vON; varying vec3 vAX; varying vec3 vAY; varying vec3 vIrisW;
+ uniform float uBal;
+ #ifdef HORO_SPRING
+ attribute float aS;
+ #endif`)
+ .replace('#include <beginnormal_vertex>', `#include <beginnormal_vertex>
+ #ifdef HORO_SPRING
+ float hsA = uBal * (1.0 - aS); float hsC = cos(hsA), hsS = sin(hsA);
+ objectNormal.xy = mat2(hsC, hsS, -hsS, hsC) * objectNormal.xy;
+ #endif`)
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ #ifdef HORO_SPRING
+ transformed.xy = mat2(hsC, hsS, -hsS, hsC) * transformed.xy * (1.0 + 0.012 * sin(uBal) * (1.0 - aS));
+ #endif
+ vOP = transformed; vON = objectNormal;
+ mat3 hM = mat3(modelViewMatrix);
+ vec4 hW = vec4(transformed, 1.0);
+ #ifdef USE_INSTANCING
+ hM = hM * mat3(instanceMatrix); hW = instanceMatrix * hW;
+ #endif
+ vAX = normalize(hM * vec3(1.0, 0.0, 0.0)); vAY = normalize(hM * vec3(0.0, 1.0, 0.0));
+ vIrisW = (modelMatrix * hW).xyz;`);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vOP; varying vec3 vON; varying vec3 vAX; varying vec3 vAY; varying vec3 vIrisW;
+ uniform vec3 uCotes; uniform float uPerl, uGrain, uBevelRough, uSideRough, uCapRough, uDLC, uCaseR;
+ uniform vec3 uCaseTint, uStrapTint, uDialC;
+ uniform float uIris, uIrisR, uIrisInv; uniform vec3 uIrisC, uIrisGlow;
+ ${NOISE}`)
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>
+ float irisEdge = 0.0;
+ #ifdef HORO_IRIS
+ {
+ // Fine, mostly geometric front: a clean sphere with a slight hand-drawn waver, thin warm edge.
+ vec3 ip = vIrisW / uIrisR;
+ float d = length(vIrisW - uIrisC) / uIrisR;
+ d += (hNoise(ip * 7.0) - 0.5) * 0.06 + (hNoise(ip * 23.0) - 0.5) * 0.018;
+ if (uIrisInv > 0.5) d = 2.2 - d; // recede from the outside in
+ float front = uIris * 2.3 - 0.12;
+ #if HORO_IRIS == 1
+ if (d > front && uIris < 0.998) discard;
+ irisEdge = 1.0 - smoothstep(0.0, 0.011, front - d);
+ #else
+ if (d < front && uIris > 0.002) discard;
+ irisEdge = 1.0 - smoothstep(0.0, 0.011, d - front);
+ #endif
+ irisEdge *= step(0.002, uIris) * step(uIris, 0.998);
+ }
+ #endif`)
+ .replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment>
+ #ifdef HORO_RECOLOR
+ {
+ vec3 c = diffuseColor.rgb;
+ float lum = dot(c, vec3(0.2126, 0.7152, 0.0722));
+ float mx = max(c.r, max(c.g, c.b)), mn = min(c.r, min(c.g, c.b));
+ float sat = (mx - mn) / max(mx, 1e-4);
+ float warm = step(c.b, c.g) * step(c.g, c.r);
+ vec3 q = (vOP - uDialC) / uCaseR;
+ float outer = max(smoothstep(0.75, 0.81, length(q.xy)), step(q.z, -0.3));
+ float metal = smoothstep(0.35, 0.7, metalnessFactor);
+ float caseW = metal * smoothstep(0.1, 0.26, sat) * warm * outer;
+ float strapW = (1.0 - metal) * (1.0 - smoothstep(0.1, 0.28, lum)) * outer;
+ diffuseColor.rgb = mix(diffuseColor.rgb, uCaseTint * clamp(lum / 0.42, 0.25, 1.6), caseW);
+ diffuseColor.rgb = mix(diffuseColor.rgb, uStrapTint * clamp(lum / 0.035, 0.3, 2.5), strapW);
+ roughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.34), caseW * uDLC);
+ }
+ #endif`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ #ifdef HORO_FINISH
+ {
+ vec3 on = normalize(vON);
+ float az = abs(on.z);
+ vec2 pert = vec2(0.0);
+ if (az > 0.96) {
+ vec2 p = vOP.xy;
+ roughnessFactor = uCapRough;
+ #if HORO_FINISH == 1
+ // Côtes de Genève: parallel bands, each a slight ramp, with the arcs of the boxwood wheel.
+ vec2 q = vec2(p.x * uCotes.x - p.y * uCotes.y, p.x * uCotes.y + p.y * uCotes.x);
+ float v = q.y / uCotes.z, f = fract(v);
+ float step2 = uCotes.z * 0.55;
+ float fx = (fract(q.x / step2) - 0.5) * step2;
+ float dd = length(vec2(fx, f * uCotes.z + uCotes.z * 0.75));
+ float ph = dd * 1500.0;
+ float g = sin(ph) * (1.0 - smoothstep(0.25, 0.9, fwidth(ph) / 6.2832));
+ float k = floor(v);
+ float jit = fract(sin(k * 91.7) * 4375.5) - 0.5;
+ float edge = smoothstep(0.035, 0.0, f) - smoothstep(0.965, 1.0, f);
+ vec2 tq = vec2(g * 0.03, (f - 0.5) * 0.3 + jit * 0.03 + edge * 0.22);
+ pert = vec2(tq.x * uCotes.x + tq.y * uCotes.y, -tq.x * uCotes.y + tq.y * uCotes.x);
+ roughnessFactor = mix(uCapRough * 0.75, uCapRough * 1.2, smoothstep(0.0, 1.0, f));
+ #elif HORO_FINISH == 2
+ // Perlage: overlapping grained circles, later rows on top.
+ vec2 q = p / uPerl, fq = floor(q), bl = vec2(0.0);
+ float best = -1e9;
+ for (int j = -1; j <= 1; j++) for (int i = -2; i <= 1; i++) {
+ vec2 cell = fq + vec2(float(i), float(j));
+ vec2 l = q - (cell + vec2(0.5 + mod(cell.y, 2.0) * 0.5, 0.5));
+ float o = cell.y * 173.0 + cell.x;
+ if (dot(l, l) < 0.62 && o > best) { best = o; bl = l; }
+ }
+ float rr = length(bl);
+ vec2 rad = bl / max(rr, 1e-4);
+ vec2 cid = floor(q - bl + 0.001);
+ vec2 tilt = vec2(fract(sin(dot(cid, vec2(12.99, 78.23))) * 43758.5), fract(sin(dot(cid, vec2(39.35, 11.13))) * 24634.6)) - 0.5;
+ float ph = rr * 70.0;
+ float g = sin(ph) * (1.0 - smoothstep(0.3, 0.9, fwidth(ph) / 6.2832));
+ pert = tilt * 0.22 + rad * 0.07 * smoothstep(0.0, 0.79, rr) + vec2(-rad.y, rad.x) * g * 0.06;
+ roughnessFactor = uCapRough * (0.8 + rr * 0.4);
+ #elif HORO_FINISH == 3
+ // Circular satin graining.
+ float rr = length(p); vec2 rad = p / max(rr, 1e-5);
+ float ph = rr * uGrain;
+ float g = sin(ph) * (1.0 - smoothstep(0.3, 0.9, fwidth(ph) / 6.2832));
+ float g2 = sin(rr * uGrain * 0.137 + 1.3);
+ pert = rad * (g * 0.045 + g2 * 0.018);
+ #elif HORO_FINISH == 4
+ // Sunray (soleil) brushing.
+ float rr = length(p); vec2 rad = p / max(rr, 1e-5);
+ float ph = atan(p.y, p.x) * 260.0;
+ float g = sin(ph) * (1.0 - smoothstep(0.3, 0.9, fwidth(ph) / 6.2832));
+ pert = vec2(-rad.y, rad.x) * g * 0.06;
+ #elif HORO_FINISH == 5
+ // Snailing / azurage: concentric guilloché grooves.
+ float rr = length(p); vec2 rad = p / max(rr, 1e-5);
+ float ph = rr * 640.0;
+ float g = sin(ph) * (1.0 - smoothstep(0.3, 0.9, fwidth(ph) / 6.2832));
+ pert = rad * g * 0.14;
+ #elif HORO_FINISH == 6
+ roughnessFactor = uCapRough;
+ #endif
+ }
+ #ifdef HORO_ANGLAGE
+ else if (az > 0.3) { roughnessFactor = uBevelRough; }
+ else { roughnessFactor = uSideRough; }
+ #endif
+ normal = normalize(normal + (vAX * pert.x + vAY * pert.y));
+ }
+ #endif`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ totalEmissiveRadiance += uIrisGlow * irisEdge;`);
+ };
+ mat.customProgramCacheKey = () => `horo:${finish}:${anglage ? 1 : 0}:${iris}:${spring ? 1 : 0}:${recolor ? 1 : 0}`;
+ return mat;
+}
diff --git a/examples/horologie/geo.js b/examples/horologie/geo.js
new file mode 100644
index 0000000..0323f7f
--- /dev/null
+++ b/examples/horologie/geo.js
@@ -0,0 +1,389 @@
+// Geometry kit for the procedural calibre: signed-distance outlines contoured with marching squares,
+// analytic gear/escape/ratchet profiles, and a chamfering extruder whose 45° bevel *is* the anglage.
+import * as THREE from 'three';
+
+export const TAU = Math.PI * 2;
+export const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
+export const lerp = (a, b, t) => a + (b - a) * t;
+const len = (x, y) => Math.sqrt(x * x + y * y);
+
+// ─── 2D signed distances ─────────────────────────────────────────────────────
+// Each primitive carries a bounding circle (.b = [cx, cy, R]) so unions can skip far-away parts.
+const withB = (f, cx, cy, R) => { f.b = [cx, cy, R]; return f; };
+export const circle = (cx, cy, r) => withB((x, y) => len(x - cx, y - cy) - r, cx, cy, r);
+export const ring = (cx, cy, r0, r1) => withB((x, y) => { const d = len(x - cx, y - cy); return Math.max(r0 - d, d - r1); }, cx, cy, r1);
+export function seg(ax, ay, bx, by, r, rb = r) {
+ const dx = bx - ax, dy = by - ay, L2 = dx * dx + dy * dy || 1;
+ return withB((x, y) => {
+ const px = x - ax, py = y - ay;
+ const h = clamp((px * dx + py * dy) / L2);
+ return len(px - dx * h, py - dy * h) - lerp(r, rb, h);
+ }, (ax + bx) / 2, (ay + by) / 2, Math.sqrt(L2) / 2 + Math.max(r, rb));
+}
+/** A tapered arm along a quadratic Bézier, as a chain of capsules. */
+export function arm(ax, ay, cx, cy, bx, by, r, rb = r, n = 14) {
+ const parts = [];
+ let px = ax, py = ay;
+ for (let i = 1; i <= n; i++) {
+ const t = i / n, u = 1 - t;
+ const x = u * u * ax + 2 * u * t * cx + t * t * bx, y = u * u * ay + 2 * u * t * cy + t * t * by;
+ parts.push(seg(px, py, x, y, lerp(r, rb, (i - 1) / n), lerp(r, rb, i / n)));
+ px = x; py = y;
+ }
+ return union(parts);
+}
+export function smin(a, b, k) { const h = Math.max(k - Math.abs(a - b), 0) / k; return Math.min(a, b) - h * h * k * 0.25; }
+function enclose(fs) {
+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
+ for (const f of fs) { const [cx, cy, R] = f.b; x0 = Math.min(x0, cx - R); y0 = Math.min(y0, cy - R); x1 = Math.max(x1, cx + R); y1 = Math.max(y1, cy + R); }
+ return [(x0 + x1) / 2, (y0 + y1) / 2, len(x1 - x0, y1 - y0) / 2];
+}
+export function union(fs, k = 0) {
+ const n = fs.length, B = fs.map(f => f.b);
+ const f = (x, y) => {
+ let d = 1e9;
+ for (let i = 0; i < n; i++) {
+ const b = B[i];
+ if (len(x - b[0], y - b[1]) - b[2] > d + k) continue;
+ const v = fs[i](x, y);
+ d = k ? smin(d, v, k) : Math.min(d, v);
+ }
+ return d;
+ };
+ return withB(f, ...enclose(fs));
+}
+export const subtract = (a, b, k = 0) => withB((x, y) => (k ? -smin(-a(x, y), b(x, y), k) : Math.max(a(x, y), -b(x, y))), ...a.b);
+
+// ─── Marching squares → closed loops (material always on the left of travel) ──
+export function contour(sdf, [x0, y0, x1, y1], res) {
+ x0 -= res * 2; y0 -= res * 2; x1 += res * 2; y1 += res * 2;
+ const nx = Math.ceil((x1 - x0) / res) + 1, ny = Math.ceil((y1 - y0) / res) + 1;
+ const F = new Float32Array(nx * ny);
+ // Narrow band: a coarse pass decides the sign far from the outline; exact samples only near it.
+ const C = 4, cnx = Math.ceil((nx - 1) / C) + 1, cny = Math.ceil((ny - 1) / C) + 1;
+ const G = new Float32Array(cnx * cny);
+ for (let j = 0; j < cny; j++) for (let i = 0; i < cnx; i++) G[j * cnx + i] = sdf(x0 + i * C * res, y0 + j * C * res);
+ const band = 2.2 * C * res;
+ for (let j = 0; j < ny; j++) {
+ const y = y0 + j * res, cj = Math.min(Math.floor(j / C), cny - 2), fy = j / C - cj;
+ for (let i = 0; i < nx; i++) {
+ const ci = Math.min(Math.floor(i / C), cnx - 2), fx = i / C - ci;
+ const g0 = G[cj * cnx + ci], g1 = G[cj * cnx + ci + 1], g2 = G[(cj + 1) * cnx + ci], g3 = G[(cj + 1) * cnx + ci + 1];
+ let v = (g0 * (1 - fx) + g1 * fx) * (1 - fy) + (g2 * (1 - fx) + g3 * fx) * fy;
+ if (Math.abs(v) < band) v = sdf(x0 + i * res, y);
+ if (i === 0 || j === 0 || i === nx - 1 || j === ny - 1) v = Math.max(v, res);
+ F[j * nx + i] = v === 0 ? 1e-9 : v;
+ }
+ }
+ const next = new Map();
+ for (let j = 0; j < ny - 1; j++) {
+ for (let i = 0; i < nx - 1; i++) {
+ const k = j * nx + i;
+ const a = F[k], b = F[k + 1], c = F[k + nx + 1], d = F[k + nx];
+ const code = (a < 0 ? 1 : 0) | (b < 0 ? 2 : 0) | (c < 0 ? 4 : 0) | (d < 0 ? 8 : 0);
+ if (code === 0 || code === 15) continue;
+ const eB = 2 * k, eT = 2 * (k + nx), eL = 2 * k + 1, eR = 2 * (k + 1) + 1;
+ const L = (p, q) => next.set(p, q);
+ const mid = (a + b + c + d) * 0.25 < 0;
+ switch (code) {
+ case 1: L(eB, eL); break; case 2: L(eR, eB); break; case 3: L(eR, eL); break;
+ case 4: L(eT, eR); break; case 6: L(eT, eB); break; case 7: L(eT, eL); break;
+ case 8: L(eL, eT); break; case 9: L(eB, eT); break; case 11: L(eR, eT); break;
+ case 12: L(eL, eR); break; case 13: L(eB, eR); break; case 14: L(eL, eB); break;
+ case 5: if (mid) { L(eB, eR); L(eT, eL); } else { L(eB, eL); L(eT, eR); } break;
+ case 10: if (mid) { L(eR, eT); L(eL, eB); } else { L(eR, eB); L(eL, eT); } break;
+ }
+ }
+ }
+ const P = (key, out) => {
+ const k = key >> 1, i = k % nx, j = (k - i) / nx;
+ if (key & 1) { const f0 = F[k], f1 = F[k + nx]; const t = f0 / (f0 - f1); out.push(x0 + i * res, y0 + (j + t) * res); }
+ else { const f0 = F[k], f1 = F[k + 1]; const t = f0 / (f0 - f1); out.push(x0 + (i + t) * res, y0 + j * res); }
+ };
+ const loops = [];
+ const seen = new Set();
+ for (const start of next.keys()) {
+ if (seen.has(start)) continue;
+ const pts = [];
+ let e = start;
+ while (e !== undefined && !seen.has(e)) { seen.add(e); P(e, pts); e = next.get(e); }
+ if (pts.length >= 8) loops.push(simplify(pts, res * 0.025));
+ }
+ return loops;
+}
+
+/** Drop nearly-collinear points (keeps curvature, removes marching-squares stair noise on straights). */
+export function simplify(pts, eps) {
+ const n = pts.length / 2;
+ if (n < 8) return pts;
+ const out = [pts[0], pts[1]];
+ let ax = pts[0], ay = pts[1];
+ for (let i = 1; i < n - 1; i++) {
+ const bx = pts[2 * i + 2], by = pts[2 * i + 3];
+ const cx = pts[2 * i], cy = pts[2 * i + 1];
+ const dx = bx - ax, dy = by - ay, L = len(dx, dy) || 1;
+ const dist = Math.abs((cx - ax) * dy - (cy - ay) * dx) / L;
+ if (dist > eps || L > eps * 400) { out.push(cx, cy); ax = cx; ay = cy; }
+ }
+ out.push(pts[2 * n - 2], pts[2 * n - 1]);
+ return out;
+}
+
+export function loopArea(p) { let a = 0; const n = p.length / 2; for (let i = 0; i < n; i++) { const j = (i + 1) % n; a += p[2 * i] * p[2 * j + 1] - p[2 * j] * p[2 * i + 1]; } return a / 2; }
+function inside(x, y, p) {
+ let c = false; const n = p.length / 2;
+ for (let i = 0, j = n - 1; i < n; j = i++) {
+ const xi = p[2 * i], yi = p[2 * i + 1], xj = p[2 * j], yj = p[2 * j + 1];
+ if ((yi > y) !== (yj > y) && x < (xj - xi) * (y - yi) / (yj - yi) + xi) c = !c;
+ }
+ return c;
+}
+export function reverseLoop(p) { const o = []; for (let i = p.length - 2; i >= 0; i -= 2) o.push(p[i], p[i + 1]); return o; }
+/** Pair outer loops (CCW) with the holes (CW) they contain. */
+export function groupLoops(loops) {
+ const outers = [], holes = [];
+ for (const l of loops) { const a = loopArea(l); (a > 0 ? outers : holes).push({ p: l, a: Math.abs(a) }); }
+ const groups = outers.map(o => ({ outer: o.p, holes: [], a: o.a }));
+ for (const h of holes) {
+ let best = null;
+ for (const g of groups) if (g.a > h.a && inside(h.p[0], h.p[1], g.outer) && (!best || g.a < best.a)) best = g;
+ if (best) best.holes.push(h.p);
+ }
+ return groups;
+}
+export const sdfShape = (sdf, bbox, res) => groupLoops(contour(sdf, bbox, res));
+
+// ─── Chamfering extruder ─────────────────────────────────────────────────────
+// Caps get normal ±Z, chamfers ±45°, walls are smooth along the outline except at sharp corners.
+// Object-space normals let the finish shader tell caps (Côtes, perlage…) from bevels (anglage) from flanks.
+export function extrude(groups, { depth, chamfer = 0, bottom = chamfer, sharp = 38 }) {
+ const pos = [], nor = [], idx = [];
+ const cs = Math.cos(sharp * Math.PI / 180);
+ const add = (x, y, z, a, b, c) => { pos.push(x, y, z); nor.push(a, b, c); return pos.length / 3 - 1; };
+ const quad = (a, b, c, d) => idx.push(a, b, c, a, c, d);
+ const k = Math.SQRT1_2;
+ const z0 = bottom, z1 = depth - chamfer;
+ for (const g of groups) {
+ const caps = [];
+ for (const loop of [g.outer, ...g.holes]) {
+ const n = loop.length / 2;
+ const ex = new Float64Array(n), ey = new Float64Array(n), vx = new Float64Array(n), vy = new Float64Array(n), sh = new Uint8Array(n);
+ for (let i = 0; i < n; i++) {
+ const j = (i + 1) % n;
+ const dx = loop[2 * j] - loop[2 * i], dy = loop[2 * j + 1] - loop[2 * i + 1], l = Math.hypot(dx, dy) || 1;
+ ex[i] = dy / l; ey[i] = -dx / l;
+ }
+ const top = [], bot = [];
+ for (let i = 0; i < n; i++) {
+ const p = (i - 1 + n) % n;
+ let sx = ex[p] + ex[i], sy = ey[p] + ey[i]; const l = Math.hypot(sx, sy) || 1; sx /= l; sy /= l;
+ vx[i] = sx; vy[i] = sy;
+ sh[i] = ex[p] * ex[i] + ey[p] * ey[i] < cs ? 1 : 0;
+ const miter = 1 / Math.max(sx * ex[i] + sy * ey[i], 0.4);
+ const x = loop[2 * i], y = loop[2 * i + 1];
+ top.push(x - sx * chamfer * miter, y - sy * chamfer * miter);
+ bot.push(x - sx * bottom * miter, y - sy * bottom * miter);
+ }
+ caps.push({ top, bot });
+ for (let i = 0; i < n; i++) {
+ const j = (i + 1) % n;
+ const ax = sh[i] ? ex[i] : vx[i], ay = sh[i] ? ey[i] : vy[i];
+ const bx = sh[j] ? ex[i] : vx[j], by = sh[j] ? ey[i] : vy[j];
+ const xi = loop[2 * i], yi = loop[2 * i + 1], xj = loop[2 * j], yj = loop[2 * j + 1];
+ if (z1 > z0 + 1e-7) quad(add(xi, yi, z0, ax, ay, 0), add(xj, yj, z0, bx, by, 0), add(xj, yj, z1, bx, by, 0), add(xi, yi, z1, ax, ay, 0));
+ if (chamfer > 0) quad(add(xi, yi, z1, ax * k, ay * k, k), add(xj, yj, z1, bx * k, by * k, k), add(top[2 * j], top[2 * j + 1], depth, bx * k, by * k, k), add(top[2 * i], top[2 * i + 1], depth, ax * k, ay * k, k));
+ if (bottom > 0) quad(add(bot[2 * i], bot[2 * i + 1], 0, ax * k, ay * k, -k), add(bot[2 * j], bot[2 * j + 1], 0, bx * k, by * k, -k), add(xj, yj, z0, bx * k, by * k, -k), add(xi, yi, z0, ax * k, ay * k, -k));
+ }
+ }
+ const V2 = a => { const o = []; for (let i = 0; i < a.length; i += 2) o.push(new THREE.Vector2(a[i], a[i + 1])); return o; };
+ for (const [key, z, nz] of [['top', depth, 1], ['bot', 0, -1]]) {
+ const outer = V2(caps[0][key]), holes = caps.slice(1).map(c => V2(c[key]));
+ const faces = THREE.ShapeUtils.triangulateShape(outer, holes);
+ const all = [outer, ...holes].flat();
+ const base = pos.length / 3;
+ for (const v of all) add(v.x, v.y, z, 0, 0, nz);
+ for (const [a, b, c] of faces) {
+ const A = all[a], B = all[b], C = all[c];
+ const cr = (B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x);
+ if ((cr > 0) === (nz > 0)) idx.push(base + a, base + b, base + c); else idx.push(base + a, base + c, base + b);
+ }
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geo.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ const uv = new Float32Array(pos.length / 3 * 2);
+ for (let i = 0; i < pos.length / 3; i++) { uv[2 * i] = pos[3 * i]; uv[2 * i + 1] = pos[3 * i + 1]; }
+ geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ geo.setIndex(idx);
+ geo.computeBoundingSphere();
+ return geo;
+}
+
+// ─── Tooth profiles (CCW loops) ──────────────────────────────────────────────
+/** Horological (cycloidal-style) teeth: radial dedendum flanks, elliptical ogival addendum. */
+export function gearLoop(N, rp, { add = 1.15, ded = 1.45, thick = 0.5, tip = 5, root = 4 } = {}) {
+ const m = 2 * rp / N, ra = rp + add * m, rf = rp - ded * m;
+ const P = TAU / N, hw = thick * P / 2;
+ const out = [];
+ const pol = (r, a) => out.push(r * Math.cos(a), r * Math.sin(a));
+ for (let q = 0; q < N; q++) {
+ const c = q * P;
+ for (let s = 1; s < root; s++) pol(rf, lerp(c - P + hw, c - hw, s / root));
+ pol(rf, c - hw);
+ for (let s = 0; s <= tip * 2; s++) { const t = s / (tip * 2) * Math.PI; pol(rp + (ra - rp) * Math.sin(t), c - hw * Math.cos(t)); }
+ pol(rf, c + hw);
+ }
+ return out;
+}
+export const rootRadius = (N, rp, ded = 1.45) => rp - ded * 2 * rp / N;
+
+/** Swiss-lever club teeth: a raked locking face, a short impulse plane, a concave back. */
+export function escapeLoop(N, ra) {
+ const P = TAU / N, rf = ra * 0.7, out = [];
+ const pol = (r, a) => out.push(r * Math.cos(a), r * Math.sin(a));
+ for (let q = 0; q < N; q++) {
+ const c = q * P;
+ pol(rf, c);
+ for (let s = 1; s <= 3; s++) { const t = s / 3; pol(lerp(rf, ra, t), c + P * 0.2 * t * t); }
+ pol(ra * 0.985, c + P * 0.28);
+ pol(ra * 0.955, c + P * 0.36);
+ for (let s = 1; s <= 5; s++) { const t = s / 6; pol(lerp(ra * 0.955, rf, Math.sin(t * Math.PI / 2)), c + P * lerp(0.36, 0.98, t)); }
+ }
+ return out;
+}
+
+/** Ratchet wheel: saw teeth with a small land at each tip. */
+export function ratchetLoop(N, rp) {
+ const m = 2 * rp / N, ra = rp + 0.85 * m, rf = rp - 1.05 * m, P = TAU / N, out = [];
+ const pol = (r, a) => out.push(r * Math.cos(a), r * Math.sin(a));
+ for (let q = 0; q < N; q++) {
+ const c = q * P;
+ pol(rf, c); pol(ra, c + P * 0.06); pol(ra, c + P * 0.16);
+ for (let s = 1; s <= 3; s++) pol(lerp(ra, rf, s / 4), c + P * lerp(0.16, 0.94, s / 4));
+ pol(rf, c + P * 0.94);
+ }
+ return out;
+}
+
+export function circleLoop(r, n = 160, cw = false) {
+ const out = [];
+ for (let i = 0; i < n; i++) { const a = (cw ? -1 : 1) * i / n * TAU; out.push(r * Math.cos(a), r * Math.sin(a)); }
+ return out;
+}
+
+/** Spoke windows for a wheel: annulus minus curved spokes, corners rounded. SDF negative inside a window. */
+export function spokeWindows({ n, rIn, rOut, w, curve = 0, round = 0.008, phase = 0, taper = 1 }) {
+ return (x, y) => {
+ const r = Math.sqrt(x * x + y * y), th = Math.atan2(y, x);
+ const t = clamp((r - rIn) / (rOut - rIn));
+ let d = Math.max(rIn + round - r, r - (rOut - round));
+ let best = 1e9;
+ for (let q = 0; q < n; q++) {
+ const a = phase + q * TAU / n + curve * t * t;
+ let da = th - a; da = ((da + Math.PI) % TAU + TAU) % TAU - Math.PI;
+ best = Math.min(best, Math.abs(da) * r - w * lerp(1, taper, t) / 2 - round);
+ }
+ return Math.max(d, -best) - round;
+ };
+}
+
+/** A wheel: analytic outline + contoured spoke windows, chamfered. */
+export function wheelGeometry({ outline, rOut, windows = null, depth, chamfer }) {
+ let holes = [];
+ if (windows) {
+ const R = rOut * 1.02;
+ holes = contour(windows, [-R, -R, R, R], Math.max(R / 380, 0.0006)).filter(l => loopArea(l) > 0).map(reverseLoop);
+ }
+ return extrude([{ outer: outline, holes }], { depth, chamfer });
+}
+
+// ─── Faceted 'tent' pieces (hands, applied indices): two flat facets meeting at a ridge ──
+export function tentGeometry(profile, { base = 0.004, ridge = 0.006 } = {}) {
+ // profile: [[y, halfWidth], ...] ordered along +Y. Built along Y, centred on X, sitting on z = 0.
+ const pos = [], nor = [], idx = [];
+ const add = (x, y, z, n) => { pos.push(x, y, z); nor.push(n.x, n.y, n.z); return pos.length / 3 - 1; };
+ const n = new THREE.Vector3(), a = new THREE.Vector3(), b = new THREE.Vector3();
+ for (const s of [-1, 1]) {
+ for (let i = 0; i < profile.length - 1; i++) {
+ const [y0, w0] = profile[i], [y1, w1] = profile[i + 1];
+ const P0 = [s * w0, y0, base], P1 = [s * w1, y1, base], C0 = [0, y0, base + ridge * Math.min(1, w0 * 60)], C1 = [0, y1, base + ridge * Math.min(1, w1 * 60)];
+ // facet normal from both triangles (either may be degenerate at a pointed end)
+ a.set(P1[0] - P0[0], P1[1] - P0[1], P1[2] - P0[2]); b.set(C1[0] - P0[0], C1[1] - P0[1], C1[2] - P0[2]);
+ n.crossVectors(a, b);
+ a.set(C0[0] - P0[0], C0[1] - P0[1], C0[2] - P0[2]);
+ n.add(new THREE.Vector3().crossVectors(b, a));
+ if (n.lengthSq() < 1e-20) n.set(0, 0, 1); else n.normalize();
+ if (n.z < 0) n.negate();
+ const i0 = add(...P0, n), i1 = add(...P1, n), i2 = add(...C1, n), i3 = add(...C0, n);
+ if (s > 0) idx.push(i0, i1, i2, i0, i2, i3); else idx.push(i0, i2, i1, i0, i3, i2);
+ // wall
+ n.set(s, -(w1 - w0) / Math.max(1e-5, y1 - y0), 0).normalize();
+ const j0 = add(s * w0, y0, 0, n), j1 = add(s * w1, y1, 0, n), j2 = add(s * w1, y1, base, n), j3 = add(s * w0, y0, base, n);
+ if (s > 0) idx.push(j0, j1, j2, j0, j2, j3); else idx.push(j0, j2, j1, j0, j3, j2);
+ }
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ geo.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ geo.setIndex(idx);
+ return geo;
+}
+
+// ─── Lathe helper around +Z (three's lathe spins around Y) ──
+export function latheZ(points, segments = 128) {
+ const g = new THREE.LatheGeometry(points.map(([r, z]) => new THREE.Vector2(r, z)), segments);
+ g.rotateX(Math.PI / 2);
+ return g;
+}
+export function cylZ(r, z0, z1, seg = 32, rTop = r) {
+ const g = new THREE.CylinderGeometry(rTop, r, z1 - z0, seg, 1);
+ g.rotateX(Math.PI / 2);
+ g.translate(0, 0, (z0 + z1) / 2);
+ return g;
+}
+
+// ─── Spiral ribbon with a rectangular section (mainspring, hairspring) ──
+// sample(s) → [r, θ]; writes into a preallocated geometry so it can be re-posed every frame.
+export class Ribbon {
+ constructor(n, { width, z0, z1, attr = false }) {
+ this.n = n; this.width = width; this.z0 = z0; this.z1 = z1;
+ const V = n * 6;
+ this.pos = new Float32Array(V * 3);
+ this.nor = new Float32Array(V * 3);
+ const idx = [];
+ for (let f = 0; f < 3; f++) for (let i = 0; i < n - 1; i++) {
+ const a = f * n * 2 + i * 2, b = a + 2;
+ idx.push(a, b + 1, b, a, a + 1, b + 1);
+ }
+ this.geo = new THREE.BufferGeometry();
+ this.geo.setAttribute('position', new THREE.BufferAttribute(this.pos, 3));
+ this.geo.setAttribute('normal', new THREE.BufferAttribute(this.nor, 3));
+ if (attr) {
+ const s = new Float32Array(V);
+ for (let f = 0; f < 3; f++) for (let i = 0; i < n; i++) s[f * n * 2 + i * 2] = s[f * n * 2 + i * 2 + 1] = i / (n - 1);
+ this.geo.setAttribute('aS', new THREE.BufferAttribute(s, 1));
+ }
+ this.geo.setIndex(idx);
+ }
+ pose(rs, ths) {
+ const { n, width: w, z0, z1, pos, nor } = this;
+ const put = (v, x, y, z, nx, ny, nz) => { pos[v * 3] = x; pos[v * 3 + 1] = y; pos[v * 3 + 2] = z; nor[v * 3] = nx; nor[v * 3 + 1] = ny; nor[v * 3 + 2] = nz; };
+ for (let i = 0; i < n; i++) {
+ const r = rs[i], c = Math.cos(ths[i]), s = Math.sin(ths[i]);
+ const ri = r - w / 2, ro = r + w / 2;
+ // top face (inner, outer)
+ put(i * 2, ri * c, ri * s, z1, 0, 0, 1); put(i * 2 + 1, ro * c, ro * s, z1, 0, 0, 1);
+ // outer wall (bottom, top)
+ put(n * 2 + i * 2, ro * c, ro * s, z1, c, s, 0); put(n * 2 + i * 2 + 1, ro * c, ro * s, z0, c, s, 0);
+ // inner wall
+ put(n * 4 + i * 2, ri * c, ri * s, z0, -c, -s, 0); put(n * 4 + i * 2 + 1, ri * c, ri * s, z1, -c, -s, 0);
+ }
+ this.geo.attributes.position.needsUpdate = true;
+ this.geo.attributes.normal.needsUpdate = true;
+ this.geo.computeBoundingSphere();
+ }
+}
+
+/** Re-express a geometry built in XY (+Z up) into another frame via a basis. */
+export function rebase(geo, m) { geo.applyMatrix4(m); return geo; }
diff --git a/examples/horologie/index.html b/examples/horologie/index.html
new file mode 100644
index 0000000..7f515d7
--- /dev/null
+++ b/examples/horologie/index.html
@@ -0,0 +1,233 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Aurel Horologie — Calibre AH-01 Skeleton Tourbillon</title>
+ <meta name="description" content="An independent Genevan watchmaker. Two hundred and eleven parts, one heartbeat: the calibre AH-01 skeleton tourbillon, taken apart.">
+ <meta name="theme-color" content="#f3efe7">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%2213%22 fill=%22%23f3efe7%22 stroke=%22%239a6a41%22 stroke-width=%222%22/%3E%3Cpath d=%22M16 5v22M6.5 10.5l19 11M6.5 21.5l19-11%22 stroke=%22%2316213d%22 stroke-width=%221.4%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;1,300;1,400;1,500&family=Montserrat:wght@400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <svg class="loader-gauge" viewBox="0 0 200 200" aria-hidden="true">
+ <circle class="lg-track" cx="100" cy="100" r="86"/>
+ <circle class="lg-fill" cx="100" cy="100" r="86"/>
+ <g class="lg-ticks"></g>
+ <g class="lg-balance">
+ <circle cx="100" cy="100" r="34" fill="none" stroke="currentColor" stroke-width="2.4"/>
+ <path d="M100 66V134M70.6 83L129.4 117M70.6 117L129.4 83" stroke="currentColor" stroke-width="1.6"/>
+ <circle cx="100" cy="100" r="4" fill="currentColor"/>
+ </g>
+ <path class="lg-spring" d="M100 100m0-6a6 6 0 1 1-6 6a9 9 0 1 1 9 9a12 12 0 1 1-12-12a15 15 0 1 1 15 15a18 18 0 1 1-18-18" fill="none" stroke="currentColor" stroke-width=".8"/>
+ </svg>
+ <p class="loader-h"><span class="loader-n">0</span><small>h</small></p>
+ <p class="loader-line caps">Winding the mainspring</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Aurel Horologie — home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="11.5" fill="none" stroke="currentColor" stroke-width="1"/><path d="M16 4.5v23M6 10.2l20 11.6M6 21.8l20-11.6" stroke="currentColor" stroke-width=".7"/><circle cx="16" cy="16" r="2.2" fill="currentColor"/></svg>
+ <span class="brand-name">Aurel</span>
+ <span class="brand-sub caps">Horologie · Genève</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#calibre">Calibre AH-01</a>
+ <a href="#finishing">Finishing</a>
+ <a href="#collection">Collection</a>
+ <a href="#atelier">Atelier</a>
+ </nav>
+ <div class="nav-r">
+ <button class="sound caps" type="button" aria-pressed="true" data-cursor="link"><i></i><span>Sound</span></button>
+ <a class="btn btn-line" href="#appointment" data-magnetic>Request an appointment</a>
+ </div>
+ </header>
+
+ <main>
+ <section class="hero" id="top" aria-label="Introduction">
+ <div class="hero-inner">
+ <p class="eyebrow caps">Calibre AH-01 &nbsp;·&nbsp; Skeleton tourbillon &nbsp;·&nbsp; Genève</p>
+ <h1 class="hero-title"><span class="ln">Two hundred and</span><span class="ln">eleven parts.</span><span class="ln"><em>One heartbeat.</em></span></h1>
+ <p class="hero-lede">Every component of the AH-01 is cut, bevelled and polished by hand in our atelier on the Rue des Granges. Scroll, and we will take it apart for you.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#appointment" data-magnetic>Request an appointment</a>
+ <a class="btn-text caps" href="#calibre">Open the case <span aria-hidden="true">↓</span></a>
+ </div>
+ </div>
+ <dl class="hero-spec caps">
+ <div><dt>Case</dt><dd>40 mm, 18k 5N rose gold</dd></div>
+ <div><dt>Reserve</dt><dd>72 hours</dd></div>
+ <div><dt>Frequency</dt><dd>28,800 vph</dd></div>
+ </dl>
+ <p class="hint caps" aria-hidden="true"><span class="hint-dot"></span>Move to tilt the watch &nbsp;·&nbsp; scroll to open the case</p>
+ </section>
+
+ <section class="calibre" id="calibre" aria-label="The calibre, exploded">
+ <div class="stage">
+ <article class="step" data-k="1">
+ <p class="fig caps">Fig. I &nbsp;—&nbsp; The case, opened</p>
+ <h2>Remove the gold, and what is left is <em>a machine.</em></h2>
+ <p>AH-01 is a hand-wound skeleton tourbillon: 211 parts and 31 jewels, and not one of them hidden behind a dial. Keep scrolling and we will take it apart, layer by layer, in the order it was put together.</p>
+ </article>
+ <article class="step" data-k="2">
+ <p class="fig caps">Fig. II &nbsp;—&nbsp; Exploded along the axis</p>
+ <h2>Twelve layers. <em>6.1 millimetres.</em></h2>
+ <p>Sapphire, hands, chapter ring, bridges, winding works, going train, tourbillon, barrel, mainplate, case. Every wheel here is turning at its true ratio — and the hands are showing your time.</p>
+ <ul class="spec caps"><li><b>32.4</b> mm calibre</li><li><b>31</b> jewels</li><li><b>211</b> parts</li></ul>
+ </article>
+ <article class="step" data-k="3">
+ <p class="fig caps">Fig. III &nbsp;—&nbsp; Energy</p>
+ <h2>Hold the crown. <em>Feel the ratchet.</em></h2>
+ <p>Forty-two centimetres of mainspring, coiled in a toothed drum. Each turn of the crown winds it tighter around the arbor while the click stops it slipping back. Thirty turns buy three days.</p>
+ <p class="step-hint caps"><span class="hint-dot"></span>Press and hold the crown, or the gauge</p>
+ </article>
+ <article class="step" data-k="4">
+ <p class="fig caps">Fig. IV &nbsp;—&nbsp; Transmission</p>
+ <h2>Four wheels turn days <em>into seconds.</em></h2>
+ <p>The barrel turns once every eight hours. The centre wheel turns once an hour and carries the minute hand. The third wheel steps it up again, until the tourbillon cage turns exactly once a minute.</p>
+ <ul class="spec caps"><li><b>96 : 12</b> barrel</li><li><b>80 : 10</b> centre</li><li><b>75 : 10</b> third</li></ul>
+ </article>
+ <article class="step" data-k="5">
+ <p class="fig caps">Fig. V &nbsp;—&nbsp; Regulation &nbsp;·&nbsp; shown at ⅒ speed</p>
+ <h2>Eight times a second, <em>it lets go.</em></h2>
+ <p>The pallet fork unlocks the escape wheel by half a tooth and returns a small push to the balance. The balance swings almost three quarters of a turn each way; its hairspring, thinner than a human hair, keeps the beat. The whole escapement rides in a cage that turns once a minute, averaging out gravity.</p>
+ <ul class="spec caps"><li><b>4</b> Hz</li><li><b>290°</b> amplitude</li><li><b>0.29</b> g cage</li></ul>
+ </article>
+ <ol class="rail caps" aria-hidden="true">
+ <li data-k="1">I</li><li data-k="2">II</li><li data-k="3">III</li><li data-k="4">IV</li><li data-k="5">V</li>
+ </ol>
+ </div>
+ </section>
+
+ <section class="finishing" id="finishing" aria-label="Finishing">
+ <div class="stage">
+ <header class="fin-head" data-k="6">
+ <p class="fig caps">Finishing</p>
+ <h2>What no one will see, <em>we polish anyway.</em></h2>
+ </header>
+ <article class="fin" data-k="6">
+ <p class="fin-n"><b>3</b><span class="caps">hours per movement</span></p>
+ <h3>Côtes de Genève</h3>
+ <p>Waves drawn across every bridge with a boxwood wheel, one pass per stripe, aligned from bridge to bridge as if they had been cut from a single plate of metal.</p>
+ </article>
+ <article class="fin" data-k="7">
+ <p class="fin-n"><b>4,000</b><span class="caps">circles on one mainplate</span></p>
+ <h3>Perlage</h3>
+ <p>Overlapping circles grained into the mainplate one at a time with a spinning peg. They scatter the light — and catch the dust that would otherwise find its way to the pivots.</p>
+ </article>
+ <article class="fin" data-k="8">
+ <p class="fin-n"><b>64</b><span class="caps">inward angles, by hand</span></p>
+ <h3>Anglage</h3>
+ <p>Every edge filed to forty-five degrees and polished with gentian wood until it throws a single line of light. An inward angle cannot be made by a machine. AH-01 has sixty-four.</p>
+ </article>
+ </div>
+ </section>
+
+ <section class="collection" id="collection" aria-label="The collection">
+ <div class="stage">
+ <header class="col-head" data-k="9">
+ <p class="fig caps">Reassembled</p>
+ <h2>Assembled twice. <em>Once to test, once to keep.</em></h2>
+ <p>Each AH-01 is fully assembled, regulated in six positions for three weeks, then taken down again for its final finishing — and put together for the last time by the same pair of hands.</p>
+ </header>
+ <header class="refs-head" data-k="10">
+ <p class="fig caps">The collection</p>
+ <h2>Three references. <em>One calibre.</em></h2>
+ </header>
+ <div class="refs" data-k="10">
+ <article class="ref">
+ <p class="caps ref-n">Ref. AH-01 · P</p>
+ <h3>Glacier</h3>
+ <p>950 platinum, rhodium-plated bridges, midnight-blue alligator.</p>
+ <p class="price">CHF 64,000</p>
+ </article>
+ <article class="ref ref-main">
+ <p class="caps ref-n">Ref. AH-01 · R</p>
+ <h3>Rose</h3>
+ <p>18k 5N rose gold, anthracite bridges, hand-stitched brown alligator.</p>
+ <p class="price">CHF 48,000</p>
+ </article>
+ <article class="ref">
+ <p class="caps ref-n">Ref. AH-01 · N &nbsp;·&nbsp; 12 pieces</p>
+ <h3>Nuit</h3>
+ <p>Black DLC titanium over rose-gold wheels, matte black calfskin.</p>
+ <p class="price">CHF 56,000</p>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <section class="atelier" id="atelier" aria-label="The atelier">
+ <div class="stage">
+ <div class="at" data-k="11">
+ <p class="fig caps">Atelier &nbsp;·&nbsp; Rue des Granges, Genève</p>
+ <h2>Six watchmakers. <em>Thirty-eight watches a year.</em></h2>
+ <p>We could make more. We would rather each watch be made by one person, from the first file stroke to the last screw — and signed under the balance bridge, where only another watchmaker will ever read it.</p>
+ <dl class="stats">
+ <div><dt>6</dt><dd class="caps">watchmakers at the bench</dd></div>
+ <div><dt>38</dt><dd class="caps">watches a year</dd></div>
+ <div><dt>11</dt><dd class="caps">months for each one</dd></div>
+ <div><dt>420</dt><dd class="caps">hours of hand finishing</dd></div>
+ </dl>
+ <p class="bench caps">At the bench &nbsp;—&nbsp; Élise Aurel, founder · Jonas Favre · Aiko Tanabe · Matteo Rinaldi · Clara Vuille · Samuel Dufour</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="cta" id="appointment" aria-label="Appointments">
+ <div class="cta-inner" data-k="12">
+ <p class="fig caps">Appointments &nbsp;·&nbsp; 2027 allocation opens in March</p>
+ <h2>Your watch begins <em>with a conversation.</em></h2>
+ <p>Visits are by appointment at the atelier, Tuesday to Friday. Tell us a little about yourself and the watch you imagine; we answer every letter within two days.</p>
+ <div class="cta-row">
+ <a class="btn btn-solid" href="mailto:[email protected]" data-magnetic>Request an appointment</a>
+ <a class="btn-text caps" href="#calibre">Revisit the calibre <span aria-hidden="true">↑</span></a>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot">
+ <div class="foot-top">
+ <p class="foot-word">Aurel</p>
+ <p class="foot-line">Made by hand in Geneva, <em>since 2009.</em></p>
+ </div>
+ <div class="foot-cols caps">
+ <p>Aurel Horologie SA<br>Rue des Granges 14<br>1204 Genève, Suisse</p>
+ <p><a href="#atelier">Atelier</a><br><a href="#collection">Collection</a><br><a href="#appointment">Service &amp; restoration</a></p>
+ <p><a href="#top">Journal</a><br><a href="#top">Press</a><br><a href="#top">Instagram</a></p>
+ <p>© 2026 Aurel Horologie SA<br>Poinçon de Genève<br>Swiss made</p>
+ </div>
+ </footer>
+ </main>
+
+ <svg class="orbit" viewBox="0 0 400 400" aria-hidden="true">
+ <defs><path id="obPath" d="M200,200 m-166,0 a166,166 0 1,1 332,0 a166,166 0 1,1 -332,0"/></defs>
+ <circle cx="200" cy="200" r="196" class="ob-c"/>
+ <g class="ob-rot"><g class="ob-ticks"></g><circle cx="200" cy="7" r="2.4" class="ob-dot"/></g>
+ <text class="ob-t"><textPath href="#obPath" startOffset="0">Aurel Horologie · Genève · Calibre AH-01 · Tourbillon squelette · 28,800 A/h · 72 heures ·</textPath></text>
+ <path d="M4 200H40M360 200H396" class="ob-c"/>
+ </svg>
+ <div class="labels" aria-hidden="true"><svg class="leaders"></svg></div>
+ <div class="crown-hint" aria-hidden="true"><i></i><b></b><span class="caps">Hold to wind</span></div>
+ <aside class="reserve" aria-label="Power reserve">
+ <button class="reserve-btn" type="button" data-cursor="drag" data-cursor-label="Hold" aria-label="Press and hold to wind the mainspring">
+ <svg viewBox="0 0 120 120" aria-hidden="true">
+ <circle class="rv-track" cx="60" cy="60" r="50"/>
+ <circle class="rv-fill" cx="60" cy="60" r="50"/>
+ <g class="rv-ticks"></g>
+ </svg>
+ <span class="rv-val"><b>24</b><small>h</small></span>
+ </button>
+ <p class="rv-label caps"><span>Power reserve</span><em>Hold to wind</em></p>
+ </aside>
+ <div class="toast caps" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/horologie/lab.js b/examples/horologie/lab.js
new file mode 100644
index 0000000..ddcd416
--- /dev/null
+++ b/examples/horologie/lab.js
@@ -0,0 +1,29 @@
+import { Engine, THREE, studioEnvironment } from '../../src/core/engine.js';
+import { buildMovement } from './movement.js';
+import { makeStudio } from './studio.js';
+import { irisUniforms } from './finish.js';
+const q = new URLSearchParams(location.search);
+const eng = new Engine({ canvas: document.getElementById('c'), fov: +(q.get('fov') ?? 30), near: 0.02, far: 80, background: 0xf3efe7,
+ post: { tone: 'neutral', bloom: q.has('nobloom') ? false : { intensity: 0.4, luminanceThreshold: 1.3, luminanceSmoothing: 0.3 }, ao: q.has('noao') ? false : { aoRadius: 0.12, intensity: 2, distanceFalloff: 1 }, vignette: false, noise: 0.02 } });
+const { scene, camera, renderer } = eng;
+renderer.setClearColor(new THREE.Color(1.114, 1.073, 0.995));
+const studio = makeStudio(renderer, scene, { front: +(q.get('front') ?? 1.4), dome: +(q.get('dome') ?? 1) });
+const u = irisUniforms(); u.uIris.value = 1;
+const t0 = performance.now();
+const mv = await buildMovement({ u });
+document.getElementById('i').textContent = `build ${Math.round(performance.now() - t0)}ms`;
+let tris = 0; mv.root.traverse(o => { if (o.isMesh && o.geometry.index) tris += o.geometry.index.count / 3; });
+document.getElementById('i').textContent += ` · ${Math.round(tris / 1000)}k tris`;
+const rig = new THREE.Group(); rig.add(mv.root); scene.add(rig);
+rig.rotation.x = +(q.get('rx') ?? 0) * Math.PI / 180;
+rig.rotation.y = +(q.get('ry') ?? 0) * Math.PI / 180;
+rig.rotation.z = +(q.get('rz') ?? 0) * Math.PI / 180;
+mv.setExplode(+(q.get('e') ?? 0));
+mv.st.w = +(q.get('w') ?? 0.34);
+const d = +(q.get('d') ?? 5), az = +(q.get('az') ?? 0) * Math.PI / 180, el = +(q.get('el') ?? 0) * Math.PI / 180;
+const tx = +(q.get('tx') ?? 0), ty = +(q.get('ty') ?? 0), tz = +(q.get('tz') ?? 0);
+camera.position.set(tx + d * Math.sin(az) * Math.cos(el), ty + d * Math.sin(el), tz + d * Math.cos(az) * Math.cos(el));
+camera.lookAt(tx, ty, tz);
+eng.onTick(dt => mv.update(dt, { timeScale: +(q.get('ts') ?? 1) }));
+renderer.compile(scene, camera);
+eng.start(); setTimeout(() => { window.__ready = true; }, 600);
diff --git a/examples/horologie/main.js b/examples/horologie/main.js
new file mode 100644
index 0000000..649232c
--- /dev/null
+++ b/examples/horologie/main.js
@@ -0,0 +1,537 @@
+import { Engine, THREE, prepModel, damp, clamp, smooth, lerp } from '../../src/core/engine.js';
+import { DepthOfFieldEffect } from 'postprocessing';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { buildMovement } from './movement.js';
+import { patch, irisUniforms } from './finish.js';
+import { makeStudio, IVORY_HDR } from './studio.js';
+import { ContactShadow } from './shadow.js';
+
+const Q = new URLSearchParams(location.search);
+const D2R = Math.PI / 180;
+const MOBILE = () => innerWidth / innerHeight < 0.8;
+
+// ─── Engine ───────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let dof = null;
+const engine = new Engine({
+ canvas, fov: 30, near: 0.05, far: 120, dpr: 1.75, background: 0xf3efe7,
+ post: {
+ tone: 'neutral',
+ ao: { aoRadius: 0.16, intensity: 2.1, distanceFalloff: 1.1 },
+ bloom: { intensity: 0.55, luminanceThreshold: 1.3, luminanceSmoothing: 0.25, radius: 0.62 },
+ vignette: false, noise: 0.022, ca: 0.0005,
+ pre: cam => (Q.has('nodof') ? [] : [(dof = new DepthOfFieldEffect(cam, { focusDistance: 8, focusRange: 3, bokehScale: 0, resolutionScale: 0.5 }))]),
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.setClearColor(IVORY_HDR, 1);
+const studio = makeStudio(renderer, scene, { front: 2.1, dome: 1.4 });
+
+// Ivory cyclorama: a full-screen HDR gradient drawn behind everything (lands on #f3efe7 after neutral tone mapping).
+const backdrop = new THREE.Mesh(new THREE.BufferGeometry().setAttribute('position', new THREE.Float32BufferAttribute([-1, -1, 0, 3, -1, 0, -1, 3, 0], 3)),
+ new THREE.ShaderMaterial({
+ depthWrite: false, depthTest: false,
+ uniforms: { uC: { value: IVORY_HDR.clone() }, uRes: { value: new THREE.Vector2(1, 1) }, uFocus: { value: new THREE.Vector2(0.62, 0.52) } },
+ vertexShader: 'void main(){ gl_Position = vec4(position.xy, 1.0, 1.0); }',
+ fragmentShader: `uniform vec3 uC; uniform vec2 uRes, uFocus;
+ void main(){ vec2 uv = gl_FragCoord.xy / uRes; vec2 d = (uv - uFocus) * vec2(uRes.x / uRes.y, 1.0);
+ float r = length(d); vec3 c = uC * mix(1.035, 0.93, smoothstep(0.1, 1.15, r));
+ c *= mix(1.0, 0.97, smoothstep(0.35, -0.2, uv.y));
+ gl_FragColor = vec4(c, 1.0); }`,
+ }));
+backdrop.frustumCulled = false; backdrop.renderOrder = -10;
+scene.add(backdrop);
+engine.onResize((w, h, dpr) => backdrop.material.uniforms.uRes.value.set(w * dpr, h * dpr));
+
+const shadow = new ContactShadow(renderer, scene, { width: 18, depth: 11, y: -2.75, res: 512, far: 5.2, blur: 3.4, opacity: 0.55 });
+shadow.hidden.push(backdrop);
+
+// ─── Loader ──────────────────────────────────────────────────────────────────
+const assets = new Assets();
+const loaderEl = document.querySelector('.loader');
+{
+ const g = loaderEl.querySelector('.lg-ticks');
+ for (let i = 0; i <= 72; i += 6) { const a = (i / 72) * Math.PI * 2 - Math.PI / 2, r0 = i % 24 ? 90 : 89, r1 = i % 24 ? 94 : 98;
+ g.insertAdjacentHTML('beforeend', `<line x1="${100 + Math.cos(a) * r0}" y1="${100 + Math.sin(a) * r0}" x2="${100 + Math.cos(a) * r1}" y2="${100 + Math.sin(a) * r1}"/>`); }
+}
+let buildP = 0;
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => { const p = Math.min(v * 0.75 + buildP * 0.25, 1); loaderEl.style.setProperty('--p', p); loaderEl.querySelector('.loader-n').textContent = Math.round(p * 72); },
+ exit: () => gsap.timeline()
+ .to('.loader-gauge', { scale: 1.08, duration: 0.5, ease: 'power2.out' })
+ .to(loaderEl, { clipPath: 'inset(0 0 100% 0)', duration: 1.1, ease: 'expo.inOut' }, 0.25),
+});
+
+// ─── Rig: the Meshy watch and the procedural calibre share one frame (dial centre at origin, dial → +Z) ──
+const rig = new THREE.Group();
+scene.add(rig);
+const irisA = irisUniforms();
+const pointer = new Pointer({ lambda: 5 });
+
+const watchLoad = assets.gltf('models/horologie/watch.glb');
+const mvBuild = buildMovement({ u: irisA, yieldFn: () => new Promise(r => { buildP = Math.min(buildP + 0.1, 1); setTimeout(r, 0); }) });
+
+function prepWatch(src) {
+ src.updateMatrixWorld(true);
+ const mesh = firstMesh(src);
+ const pos = mesh.geometry.attributes.position, v = new THREE.Vector3();
+ let zmin = 1e9, zmax = -1e9;
+ for (let i = 0; i < pos.count; i++) { v.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld); zmin = Math.min(zmin, v.z); zmax = Math.max(zmax, v.z); }
+ const slab = zmax - 0.1 * (zmax - zmin);
+ const bb = new THREE.Box2(new THREE.Vector2(1e9, 1e9), new THREE.Vector2(-1e9, -1e9));
+ for (let i = 0; i < pos.count; i++) { v.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld); if (v.z > slab) bb.expandByPoint(new THREE.Vector2(v.x, v.y)); }
+ const c = bb.getCenter(new THREE.Vector2()), r = (bb.max.x - bb.min.x) / 2;
+ const s = 1.205 / r;
+ const holder = new THREE.Group();
+ holder.add(src);
+ src.scale.setScalar(s);
+ src.position.set(-c.x * s, -c.y * s, 0.335 - zmax * s);
+ src.updateMatrixWorld(true);
+ const inv = mesh.matrixWorld.clone().invert();
+ const dialC = new THREE.Vector3(0, 0, 0.335).applyMatrix4(inv);
+ const caseR = 1.205 / mesh.matrixWorld.getMaxScaleOnAxis();
+ return { holder, mesh, dialC, caseR };
+}
+
+// ─── Keyframes (world space unless camL/lookL: rig-local) ────────────────────
+// s = keyframe index along the page; each segment eases with a short hold at both ends.
+const KF = [
+ { id: 'hero', sec: 'top', p: 0, cam: [0, 0.15, 10.6], look: [0.25, 0.02, 0], fov: 30, rig: [1.95, 0.12, 0, -6, -32, 5], explode: 0, iris: 0, tilt: 1, ts: 1, m: { rig: [0, -2.7, 0, -6, -32, 5], cam: [0, -0.55, 16.5], look: [0, -0.55, 0] } },
+ { id: 'open', sec: 'calibre', p: 0.045, cam: [0.4, 0, 7.8], look: [0.4, 0, 0], fov: 30, rig: [1.55, 0, 0, -6, 14, 0], explode: 0, iris: 1, irisEase: [0.3, 0.62], tilt: 0.5, ts: 1, m: { rig: [0, 1.05, 0, -6, 14, 0], cam: [0, 0.2, 12.5], look: [0, 0.2, 0] } },
+ { id: 'exploded', sec: 'calibre', p: 0.24, cam: [0.35, 0.05, 12.6], look: [0.35, 0.05, 0], fov: 30, rig: [1.75, -0.45, 0, -41.8, 41.3, -20], explode: 1, iris: 1, tilt: 0.35, ts: 1, m: { rig: [0.1, 0.9, 0, -58, 22, -24], cam: [0, 0.35, 19], look: [0, 0.35, 0] } },
+ { id: 'barrel', sec: 'calibre', p: 0.45, orbit: [0.4, 0.3, -0.38, -40, 5, 4.6], shift: -0.5, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.2, ts: 1, dof: 3.5, fr: 1.3, focus: 'barrel', gap: [8, 0.6], fly: { dial: 3.5, hands: 4, crystal: 5 } },
+ { id: 'train', sec: 'calibre', p: 0.65, orbit: [-0.05, 0.0, 0.1, -32, 2, 4.1], shift: -0.6, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.2, ts: 1, dof: 2.2, fr: 1.8, focus: 'train', gap: [0.22, 0.25], fly: { plate: -8, case: -8.5, caseback: -9, bridges: 3.2, winding: 3.4, dial: 3.8, hands: 4.2, crystal: 5 } },
+ { id: 'escapement', sec: 'calibre', p: 0.86, orbit: [0, -0.47, 0.86, 12, -2, 2.95], shift: -0.62, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.15, ts: 0.1, dof: 4, fr: 0.6, focus: 'cage', gap: [6, 0.6], fly: { dial: 3.5, hands: 4, crystal: 5 } },
+ { id: 'cotes', sec: 'finishing', p: 0.14, orbit: [-0.5, 0.12, 1.1, 30, 10, 1.2], shift: 0.3, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.08, ts: 1, dof: 6, fr: 0.3, focus: 'bridges', gap: 0.95 },
+ { id: 'perlage', sec: 'finishing', p: 0.5, orbit: [-0.55, -0.12, -1.34, -30, 10, 1.2], shift: 0.3, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.08, ts: 1, dof: 6, fr: 0.3, focus: 'plate', gap: 0.95 },
+ { id: 'anglage', sec: 'finishing', p: 0.86, orbit: [0.37, -0.36, 1.21, 60, 6, 1.05], shift: 0.25, fov: 30, rig: [1.9, 0, 0, -41.8, 41.3, -20], m: { rig: [0.15, 0.55, 0, -58, 22, -24] }, explode: 1, iris: 1, tilt: 0.08, ts: 1, dof: 3.5, fr: 0.35, focus: 'bridges', gap: 0.95 },
+ { id: 'assembled', sec: 'collection', p: 0.07, cam: [0, 0.1, 12.2], look: [0, -0.2, 0], fov: 30, rig: [0, 0.55, 0, -8, -30, 5], explode: 0, iris: 0, irisEase: [0.36, 0.66], tilt: 0.8, ts: 1, m: { cam: [0, 0.2, 17], look: [0, 0.2, 0], rig: [0, 1.6, 0, -8, -30, 5] } },
+ { id: 'collection', sec: 'collection', p: 0.5, cam: [0, 0.35, 15.2], look: [0, 0.1, 0], fov: 30, rig: [0, 0.55, 0, -4, -24, 4], explode: 0, iris: 0, irisEase: [0.05, 0.3], tilt: 0.5, ts: 1, coll: 1, m: { cam: [0, 0.2, 21], look: [0, -0.2, 0], rig: [0, 0.2, 0.8, -4, -24, 4] } },
+ { id: 'atelier', sec: 'atelier', p: 0.42, cam: [0, 0.2, 7.6], look: [0.35, 0.05, 0], fov: 30, rig: [1.7, -0.3, 0, -52, 24, 18], explode: 0.26, iris: 1, irisEase: [0.5, 0.66], ease: [0.46, 0.92], collEase: [0.45, 0.6], tilt: 0.5, ts: 1, bare: 1, dof: 1.2, fr: 2.5, m: { rig: [0, 1.0, 0, -52, 24, 18], cam: [0, 0.4, 13], look: [0, 0.4, 0] } },
+ { id: 'cta', sec: 'appointment', p: 0.25, cam: [0, 0.1, 10.4], look: [-0.6, 0.05, 0], fov: 30, rig: [1.7, 0.05, 0, -6, -34, 5], explode: 0, iris: 0, irisEase: [0.3, 0.6], tilt: 1, ts: 1, m: { rig: [0, 2.3, 0, -6, -34, 5], cam: [0, 0.5, 16.5], look: [0, 0.5, 0] } },
+];
+window.__KF = KF;
+if (Q.has('kf')) { // tuning overrides: ?kf=3&camL=x,y,z&lookL=x,y,z (or cam/look, rig=px,py,pz,rx,ry,rz)
+ const k = KF[Math.floor(+Q.get('kf'))];
+ for (const key of ['camL', 'lookL', 'cam', 'look', 'rig', 'orbit']) if (Q.has(key)) k[key] = Q.get(key).split(',').map(Number);
+ if (Q.has('shift')) k.shift = +Q.get('shift');
+ if (Q.has('dofv')) k.dof = +Q.get('dofv');
+}
+const COLL = [
+ { pos: [-3.45, 0.55, -0.4], mpos: [-1.75, 1.2, -2.6], tint: [0.6, 0.61, 0.64], strap: [0.018, 0.03, 0.085], dlc: 0 }, // Glacier: platinum, midnight strap
+ { pos: [3.45, 0.55, -0.4], mpos: [1.75, 1.2, -2.6], tint: [0.055, 0.055, 0.06], strap: [0.012, 0.012, 0.013], dlc: 1 }, // Nuit: DLC, black calf
+];
+
+const kfY = new Array(KF.length).fill(0);
+function measure() {
+ for (let i = 0; i < KF.length; i++) {
+ const k = KF[i], el = document.getElementById(k.sec);
+ const top = el.getBoundingClientRect().top + scrollY;
+ kfY[i] = top + k.p * Math.max(0, el.offsetHeight - innerHeight);
+ }
+ // Where each copy block sits, so it can fade before sliding under the nav when its stage scrolls away.
+ for (const el of steps ?? []) {
+ const sec = el.closest('section'), r = sec.getBoundingClientRect();
+ el._secTop = r.top + scrollY; el._secH = sec.offsetHeight; el._sticky = !!el.closest('.stage'); el._y = el.offsetTop;
+ }
+}
+function scrollS(y = scrollY) {
+ if (y <= kfY[0]) return 0;
+ for (let i = 0; i < KF.length - 1; i++) if (y < kfY[i + 1]) return i + (y - kfY[i]) / Math.max(1, kfY[i + 1] - kfY[i]);
+ return KF.length - 1;
+}
+window.__goto = i => { measure(); const y = kfY[Math.floor(i)] + (i % 1) * ((kfY[Math.floor(i) + 1] ?? kfY[Math.floor(i)]) - kfY[Math.floor(i)]); window.__lenis?.scrollTo(y, { immediate: true, force: true }); S = i; };
+
+const tmpM = new THREE.Matrix4(), tmpQ = new THREE.Quaternion(), tmpE = new THREE.Euler(), tmpV = new THREE.Vector3(), tmpV2 = new THREE.Vector3();
+// Phones get their own framing: subject above or below the copy card instead of beside it.
+const V = k => (MOBILE() && k.m ? { ...k, ...k.m } : k);
+function kfRig(k0, outP, outQ) {
+ const k = V(k0), r = k.rig;
+ outP.set(r[0], r[1], r[2]);
+ if (MOBILE() && !k0.m?.rig) outP.x *= 0.1;
+ outQ.setFromEuler(tmpE.set(r[3] * D2R, r[4] * D2R, r[5] * D2R));
+}
+const tmpQ2 = new THREE.Quaternion(), tmpUp = new THREE.Vector3();
+function kfCam(k0, outC, outL) {
+ const k = V(k0), mob = MOBILE();
+ if (k.orbit) {
+ // Orbit a rig-local target, measured from the overview direction (world +Z seen from the rig).
+ kfRig(k0, tmpV, tmpQ);
+ const [tx, ty, tz, yaw, pitch, d0] = k.orbit, dist = d0 * (mob ? 1.3 : 1);
+ const v = tmpV2.set(0, 0, 1).applyQuaternion(tmpQ2.copy(tmpQ).invert());
+ const phi = Math.atan2(v.y, v.x) + yaw * D2R, th = Math.asin(clamp(v.z, -1, 1)) + pitch * D2R;
+ outL.set(tx, ty, tz);
+ outC.set(tx + dist * Math.cos(th) * Math.cos(phi), ty + dist * Math.cos(th) * Math.sin(phi), tz + dist * Math.sin(th));
+ tmpM.compose(tmpV, tmpQ, new THREE.Vector3(1, 1, 1));
+ outC.applyMatrix4(tmpM); outL.applyMatrix4(tmpM);
+ const fw = tmpV2.subVectors(outL, outC).normalize();
+ const shift = mob ? 0 : k.shift;
+ if (shift) { const r = tmpUp.crossVectors(fw, camera.up).normalize(); outC.addScaledVector(r, shift); outL.addScaledVector(r, shift); }
+ if (mob) { const r = tmpUp.crossVectors(fw, camera.up).normalize(); const up = r.cross(fw).normalize(); const lift = -0.28 * dist * Math.tan(15 * D2R); outC.addScaledVector(up, lift); outL.addScaledVector(up, lift); }
+ return;
+ }
+ if (k.camL) {
+ kfRig(k0, tmpV, tmpQ);
+ tmpM.compose(tmpV, tmpQ, new THREE.Vector3(1, 1, 1));
+ outC.set(...k.camL).applyMatrix4(tmpM); outL.set(...k.lookL).applyMatrix4(tmpM);
+ } else {
+ outC.set(...k.cam); outL.set(...k.look);
+ if (mob && !k0.m?.cam) { outC.x = outL.x = 0; outC.z *= 1.5; }
+ }
+}
+const A = { p: new THREE.Vector3(), q: new THREE.Quaternion(), c: new THREE.Vector3(), l: new THREE.Vector3() };
+const B = { p: new THREE.Vector3(), q: new THREE.Quaternion(), c: new THREE.Vector3(), l: new THREE.Vector3() };
+const ST = { rigP: new THREE.Vector3(), rigQ: new THREE.Quaternion(), cam: new THREE.Vector3(), look: new THREE.Vector3(), fov: 30, explode: 0, iris: 0, tilt: 1, ts: 1, coll: 0, bokeh: 0, fr: 3 };
+const ease = f => smooth(0.2, 0.8, f);
+const LAYER_DZ = { caseback: -2.3, case: -1.8, plate: -1.15, fixed: -0.72, barrel: -0.3, train: 0.14, cage: 0.55, bridges: 1.02, winding: 1.4, dial: 1.8, hands: 2.15, crystal: 2.6 };
+const GAP = Object.fromEntries(Object.keys(LAYER_DZ).map(k => [k, 0]));
+function gapOf(k, name) {
+ if (!k.focus || !k.gap) return 0;
+ const d = LAYER_DZ[name] - LAYER_DZ[k.focus];
+ const [down, up] = Array.isArray(k.gap) ? k.gap : [k.gap, k.gap];
+ return Math.abs(d) < 1e-3 ? 0 : d > 0 ? up : -down;
+}
+function evalState(s) {
+ const i = clamp(Math.floor(s), 0, KF.length - 1), j = Math.min(i + 1, KF.length - 1), f = s - i;
+ const a = KF[i], b = KF[j], e = b.ease ? smooth(b.ease[0], b.ease[1], f) : ease(f);
+ kfRig(a, A.p, A.q); kfRig(b, B.p, B.q); kfCam(a, A.c, A.l); kfCam(b, B.c, B.l);
+ ST.rigP.lerpVectors(A.p, B.p, e); ST.rigQ.slerpQuaternions(A.q, B.q, e);
+ ST.cam.lerpVectors(A.c, B.c, e); ST.look.lerpVectors(A.l, B.l, e);
+ // Between two close-ups, pull out and push back in so the mid-flight frame still shows the stack.
+ if (a.orbit && b.orbit) { const k = 1 + 0.75 * Math.sin(e * Math.PI); tmpV.subVectors(ST.cam, ST.look).multiplyScalar(k); ST.cam.copy(ST.look).add(tmpV); }
+ else ST.cam.y += Math.sin(e * Math.PI) * A.c.distanceTo(B.c) * 0.06; // arc long moves so they never pass through parts
+ ST.fov = lerp(a.fov, b.fov, e);
+ ST.explode = lerp(a.explode, b.explode, smooth(0.08, 0.95, f));
+ const ie = b.irisEase ? smooth(b.irisEase[0], b.irisEase[1], f) : e;
+ ST.iris = lerp(a.iris, b.iris, ie);
+ ST.tilt = lerp(a.tilt, b.tilt, e);
+ ST.ts = Math.exp(lerp(Math.log(a.ts), Math.log(b.ts), e));
+ ST.coll = lerp(a.coll ?? 0, b.coll ?? 0, b.collEase ? smooth(b.collEase[0], b.collEase[1], f) : b.coll ? smooth(0.2, 0.5, f) : smooth(0.08, 0.32, f));
+ ST.bokeh = lerp(a.dof ?? 0, b.dof ?? 0, e);
+ for (const n in GAP) GAP[n] = lerp(gapOf(a, n), gapOf(b, n), e);
+ for (const n in GAP) GAP[n] += lerp(a.fly?.[n] ?? 0, b.fly?.[n] ?? 0, e);
+ const bare = lerp(a.bare ?? 0, b.bare ?? 0, e);
+ GAP.caseback -= bare * 12; GAP.case -= bare * 10; GAP.crystal += bare * 12;
+ ST.bare = bare;
+ ST.fr = lerp(a.fr ?? 3, b.fr ?? 3, e);
+ return ST;
+}
+
+// ─── Labels projected from 3D anchors ────────────────────────────────────────
+// side: 'u' = above-left of the stack, 'd' = below-right (perpendicular to the projected axis); off = leader length (px).
+const LABELS = [
+ { a: 'crystal', t: 'Sapphire crystal', s: 'anti-reflective, both faces', k: [2], side: 'u', off: 70 },
+ { a: 'hands', t: 'Hands', s: 'flame-blued steel', k: [], side: 'd', off: 90 },
+ { a: 'dial', t: 'Chapter ring', s: 'azurage, applied batons', k: [], side: 'u', off: 90 },
+ { a: 'bridges', t: 'Bridges', s: 'Côtes de Genève', k: [2, 6], side: 'd', off: 70 },
+ { a: 'winding', t: 'Winding works', s: 'ratchet & crown wheel', k: [3], side: 'u', off: 70 },
+ { a: 'barrel', t: 'Barrel', s: '72 h reserve', k: [2, 3, 4], side: 'u', off: 175, offk: { 3: 70, 4: 70 } },
+ { a: 'train', t: 'Going train', s: 'centre & third wheels', k: [4], side: 'd', off: 90 },
+ { a: 'tourbillon', t: 'Tourbillon', s: 'one turn a minute', k: [2, 4, 5], side: 'd', off: 150, offk: { 4: 80, 5: 80 } },
+ { a: 'escapement', t: 'Escapement', s: '28,800 vph', k: [5], side: 'd', off: 90 },
+ { a: 'balance', t: 'Balance & hairspring', s: '4 Hz, breathing', k: [5], side: 'u', off: 90 },
+ { a: 'plate', t: 'Mainplate', s: 'perlage', k: [2, 7], side: 'u', off: 60 },
+ { a: 'crown', t: 'Crown', s: 'press & hold to wind', k: [2], side: 'd', off: 60 },
+ { a: 'tbridge', t: 'Tourbillon bridge', s: 'black polish, 45° anglage', k: [8], side: 'u', off: 90 },
+ { a: 'caseback', t: 'Caseback', s: 'Nº 07 / 38', k: [2], side: 'd', off: 55 },
+];
+const labelsEl = document.querySelector('.labels'), svg = labelsEl.querySelector('.leaders');
+const NS = 'http://www.w3.org/2000/svg';
+for (const L of LABELS) {
+ L.el = document.createElement('div'); L.el.className = 'label'; L.el.innerHTML = `<b>${L.t}</b><span>${L.s}</span>`; labelsEl.appendChild(L.el);
+ L.path = document.createElementNS(NS, 'path'); L.dot = document.createElementNS(NS, 'circle'); L.ring = document.createElementNS(NS, 'circle');
+ L.dot.setAttribute('r', 2.2); L.dot.setAttribute('class', 'dot'); L.ring.setAttribute('r', 6); L.ring.setAttribute('class', 'ring');
+ svg.append(L.path, L.dot, L.ring);
+ L.w = 0;
+}
+
+// ─── Steps (HTML copy tied to keyframes) ─────────────────────────────────────
+var steps = [...document.querySelectorAll('[data-k]')].filter(el => !el.closest('.rail'));
+for (const el of steps) { const ks = [...el.closest('section').querySelectorAll('[data-k]')].filter(e => !e.closest('.rail')).map(e => +e.dataset.k); el._first = +el.dataset.k === Math.min(...ks); el._last = +el.dataset.k === Math.max(...ks); }
+const railItems = [...document.querySelectorAll('.rail li')];
+const railEl = document.querySelector('.rail');
+const heroEl = document.querySelector('.hero');
+const orbitEl = document.querySelector('.orbit');
+{
+ const g = orbitEl.querySelector('.ob-ticks');
+ let h = '';
+ for (let i = 0; i < 120; i++) { const a = i / 120 * Math.PI * 2, big = i % 10 === 0, mid = i % 2 === 0; const r0 = big ? 180 : mid ? 186 : 189, r1 = 193;
+ h += `<line x1="${(200 + Math.cos(a) * r0).toFixed(2)}" y1="${(200 + Math.sin(a) * r0).toFixed(2)}" x2="${(200 + Math.cos(a) * r1).toFixed(2)}" y2="${(200 + Math.sin(a) * r1).toFixed(2)}" class="${big ? 'b' : ''}"/>`; }
+ g.innerHTML = h;
+}
+const orbitRot = orbitEl.querySelector('.ob-rot');
+
+// ─── Winding interaction ─────────────────────────────────────────────────────
+const reserveEl = document.querySelector('.reserve'), reserveBtn = reserveEl.querySelector('.reserve-btn');
+const rvVal = reserveEl.querySelector('.rv-val b');
+const crownHintEl = document.querySelector('.crown-hint');
+const crownTurnEl = crownHintEl.querySelector('span');
+const toastEl = document.querySelector('.toast');
+const soundBtn = document.querySelector('.sound');
+{
+ const g = reserveEl.querySelector('.rv-ticks');
+ for (let i = 0; i <= 72; i += 12) { const a = (i / 72) * Math.PI * 2 - Math.PI / 2; g.insertAdjacentHTML('beforeend', `<line x1="${60 + Math.cos(a) * 54}" y1="${60 + Math.sin(a) * 54}" x2="${60 + Math.cos(a) * 57.5}" y2="${60 + Math.sin(a) * 57.5}"/>`); }
+}
+let toastT;
+function toast(msg, ms = 2600) { toastEl.textContent = msg; toastEl.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => toastEl.classList.remove('on'), ms); }
+soundBtn.addEventListener('click', () => { soundBtn.setAttribute('aria-pressed', soundBtn.getAttribute('aria-pressed') === 'true' ? 'false' : 'true'); try { ac ??= new AudioContext(); ac.resume?.(); } catch { /* no audio */ } });
+let ac = null;
+function tick(kind = 'click') {
+ if (soundBtn.getAttribute('aria-pressed') !== 'true') return;
+ try {
+ ac ??= new AudioContext();
+ const t = ac.currentTime, len = kind === 'full' ? 0.25 : kind === 'beat' ? 0.06 : 0.03;
+ const buf = ac.createBuffer(1, Math.ceil(ac.sampleRate * len), ac.sampleRate), d = buf.getChannelData(0);
+ for (let i = 0; i < d.length; i++) { const k = i / d.length; d[i] = (Math.random() * 2 - 1) * Math.exp(-k * (kind === 'full' ? 9 : kind === 'beat' ? 14 : 26)); }
+ const src = ac.createBufferSource(); src.buffer = buf;
+ const bp = ac.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = kind === 'full' ? 1800 : kind === 'beat' ? 1150 : 3600 + Math.random() * 900; bp.Q.value = kind === 'full' ? 3 : kind === 'beat' ? 4 : 1.6;
+ const g = ac.createGain(); g.gain.value = kind === 'full' ? 0.22 : kind === 'beat' ? 0.1 : 0.14;
+ src.connect(bp).connect(g).connect(ac.destination); src.start(t);
+ } catch { /* sound is a nicety */ }
+}
+const wind = { holding: false, from: 0, fx: 0, full: false, wound: false };
+let mv = null, cursorApi = null;
+function startWind() {
+ if (!mv || wind.holding) return;
+ wind.holding = true; wind.from = mv.st.w; wind.wound = true;
+ reserveEl.classList.add('holding');
+ try { ac ??= new AudioContext(); ac.resume?.(); } catch { /* no audio */ }
+}
+function endWind() {
+ if (!wind.holding) return;
+ wind.holding = false;
+ reserveEl.classList.remove('holding');
+ const gained = mv.st.w - wind.from;
+ if (gained > 0.01) mv.st.boost = Math.min(1.25, 0.25 + gained * 2.4);
+}
+reserveBtn.addEventListener('pointerdown', e => { e.preventDefault(); startWind(); });
+addEventListener('pointerup', endWind); addEventListener('pointercancel', endWind); addEventListener('blur', endWind);
+const ray = new THREE.Raycaster(), ndc = new THREE.Vector2();
+let overCrown = false;
+function crownUnder(e) {
+ if (!mv || S < 1.7 || S > 5.6) return false;
+ ndc.set(e.clientX / innerWidth * 2 - 1, -(e.clientY / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ return ray.intersectObject(mv.crownHit, false).length > 0;
+}
+canvas.addEventListener('pointerdown', e => { if (crownUnder(e)) { e.preventDefault(); startWind(); } });
+addEventListener('pointermove', e => {
+ const o = crownUnder(e);
+ if (o !== overCrown) { overCrown = o; cursorApi?.set(o ? 'drag' : '', o ? 'Hold' : ''); canvas.style.cursor = o ? 'grab' : ''; }
+}, { passive: true });
+
+// ─── Frame loop ───────────────────────────────────────────────────────────────
+let S = Q.has('kf') ? +Q.get('kf') : 0;
+let started = false, intro = { spin: 0, sweep: 0 }, lastBeat = null;
+let watch = null, clones = [];
+const tiltQ = new THREE.Quaternion(), footEl = document.querySelector('.foot'), ctaEl = document.querySelector('.cta'), navEl = document.querySelector('.nav');
+const irisCenter = new THREE.Vector3();
+
+engine.onTick((dt, t) => {
+ if (!mv) return;
+ pointer.update(dt);
+ if (!Q.has('kf')) S = damp(S, scrollS(), 7, dt);
+ const st = evalState(S);
+ window.__S = S;
+
+ // Rig: keyframed pose + pointer tilt + a slow float.
+ rig.position.copy(st.rigP);
+ rig.position.y += Math.sin(t * 0.7) * 0.035 * st.tilt;
+ tiltQ.setFromEuler(tmpE.set(-pointer.sy * 0.16 * st.tilt, pointer.sx * 0.3 * st.tilt + intro.spin, 0));
+ rig.quaternion.copy(tiltQ).multiply(st.rigQ);
+
+ // Winding: the barrel fills; the camera leans in a touch; a light sweep crosses the metal.
+ if (wind.holding) {
+ const before = mv.st.clicks;
+ mv.st.w = Math.min(1, mv.st.w + dt / 3.2);
+ if (mv.st.clicks !== before) { tick(); wind.pulse = 1; }
+ if (mv.st.w >= 1 && !wind.full) { wind.full = true; tick('full'); toast('Fully wound · seventy-two hours'); endWind(); }
+ } else if (S < 2.2 || S > 5.8) {
+ mv.st.w = damp(mv.st.w, 0.34, 0.08, dt); if (mv.st.w < 0.95) wind.full = false;
+ }
+ wind.fx = damp(wind.fx, wind.holding ? 1 : 0, wind.holding ? 3 : 1.5, dt);
+ wind.pulse = damp(wind.pulse ?? 0, 0, 14, dt);
+ mv.materials.spring.emissive.setRGB(1.0, 0.5, 0.26).multiplyScalar(wind.fx * (0.9 + 1.1 * wind.pulse));
+ mv.materials.roseSun.emissive.setRGB(1.0, 0.6, 0.35).multiplyScalar(wind.fx * 0.12 * wind.pulse);
+
+ camera.position.copy(st.cam);
+ camera.position.lerp(st.look, 0.12 * wind.fx);
+ camera.lookAt(st.look);
+ if (camera.fov !== st.fov) { camera.fov = st.fov; camera.updateProjectionMatrix(); }
+
+ mv.setExplode(st.explode, GAP);
+ for (const n of ['caseback', 'case', 'crystal']) mv.layers[n].g.visible = st.bare < 0.6;
+ mv.update(dt, { timeScale: st.ts });
+ if (dof) { dof.cocMaterial.focusDistance = camera.position.distanceTo(st.look); dof.cocMaterial.focusRange = st.fr; dof.bokehScale = st.bokeh; }
+
+ // Iris between the Meshy watch and the procedural calibre.
+ rig.updateMatrixWorld();
+ irisCenter.set(0, 0, 0.15).applyMatrix4(rig.matrixWorld);
+ irisA.uIris.value = st.iris; irisA.uIrisC.value.copy(irisCenter); irisA.uIrisR.value = 1.2;
+ if (watch) watch.holder.visible = st.iris < 0.999;
+ mv.root.visible = st.iris > 0.001;
+ for (const c of clones) {
+ const k = clamp(st.coll);
+ c.u.uIris.value = 1 - k;
+ c.u.uIrisInv.value = S > 10 ? 1 : 0;
+ c.holder.visible = k > 0.001;
+ c.holder.position.set(...(MOBILE() ? c.mpos : c.pos));
+ c.holder.position.y += Math.sin(t * 0.7 + c.pos[0]) * 0.035;
+ c.holder.quaternion.copy(rig.quaternion);
+ c.holder.updateMatrixWorld();
+ c.u.uIrisC.value.set(0, 0, 0.15).applyMatrix4(c.holder.matrixWorld);
+ }
+
+ // Environment turns with the pointer (glints travel across the gold) plus the intro/wind sweeps.
+ // Finishing: the studio lights sweep across the stripes and perlage as you scroll.
+ const finSweep = smooth(5.3, 6, S) * (1 - smooth(8.3, 9, S)) * (S - 7) * 0.9;
+ scene.environmentRotation.y = pointer.sx * 0.45 * st.tilt + intro.sweep + wind.fx * 0.5 * Math.sin(t * 1.4) + finSweep;
+ // Escapement at ⅒ speed: a soft tock on every beat, once sound has been unlocked by a gesture.
+ if (ac && Math.abs(S - 5) < 0.45 && mv.st.beat !== lastBeat) { if (lastBeat !== null) tick('beat'); }
+ lastBeat = mv.st.beat;
+
+ // HTML: hero fade, steps, rail, labels, HUD.
+ heroEl.style.opacity = 1 - smooth(0.7, 0.95, S);
+ { // editorial dial scale framing the hero watch
+ const ov = 1 - smooth(0.02, 0.3, S) + (1 - smooth(0.02, 0.3, Math.abs(S - 12)));
+ orbitEl.style.opacity = clamp(ov) * (started ? 1 : 0);
+ if (ov > 0.001) {
+ tmpV.set(0, 0, 0.1).applyMatrix4(rig.matrixWorld).project(camera);
+ tmpV2.set(1.25, 0, 0.1).applyMatrix4(rig.matrixWorld);
+ const cx = (tmpV.x + 1) / 2 * innerWidth, cy = (1 - tmpV.y) / 2 * innerHeight;
+ const d = camera.position.distanceTo(rig.position), px = 1.62 / (2 * d * Math.tan(camera.fov * D2R / 2)) * innerHeight;
+ orbitEl.style.transform = `translate3d(${(cx - px).toFixed(1)}px, ${(cy - px).toFixed(1)}px, 0) scale(${(px / 200).toFixed(4)})`;
+ orbitRot.style.transform = `rotate(${(-(mv.st.secs % 60) * 6).toFixed(2)}deg)`;
+ }
+ }
+ heroEl.style.transform = `translate3d(0, ${-smooth(0, 0.6, S) * 40}px, 0)`;
+ for (const el of steps) {
+ const k = +el.dataset.k;
+ // Crossfade only between steps of the same pinned stage; a stage's first/last step scrolls in/out with it, fully opaque.
+ let vv = (el._first ? 1 : smooth(k - 0.55, k - 0.45, S)) * (el._last ? 1 : 1 - smooth(k + 0.45, k + 0.55, S));
+ const y = scrollY, pinEnd = el._secTop + el._secH - innerHeight;
+ const stageTop = !el._sticky ? el._secTop - y : y < el._secTop ? el._secTop - y : y > pinEnd ? pinEnd - y : 0;
+ vv *= smooth(64, 150, stageTop + el._y);
+ el.style.setProperty('--v', vv.toFixed(3));
+ el.classList.toggle('is-v', vv > 0.002);
+ }
+ railEl.style.setProperty('--rail', smooth(0.6, 1, S) * (1 - smooth(5.4, 5.8, S)));
+ railItems.forEach(li => li.classList.toggle('on', Math.round(S) === +li.dataset.k));
+
+ drawLabels();
+ const hud = S > 2.55 && S < 5.45;
+ reserveEl.classList.toggle('on', hud);
+ reserveEl.style.setProperty('--w', mv.st.w.toFixed(4));
+ reserveEl.classList.toggle('full', mv.st.w > 0.995);
+ rvVal.textContent = Math.round(mv.st.w * 72);
+ const crownA = mv.anchors.crown;
+ crownA.getWorldPosition(tmpV).project(camera);
+ const showHint = (Math.abs(S - 3) < 0.35 && mv.st.w < 0.97) || wind.fx > 0.05;
+ crownHintEl.classList.toggle('on', showHint);
+ crownHintEl.classList.toggle('winding', wind.holding);
+ if (wind.holding) crownTurnEl.textContent = `Turn ${Math.min(30, Math.round(mv.st.w * 30))} / 30`;
+ else crownTurnEl.textContent = mv.st.w > 0.97 ? 'Fully wound' : 'Hold to wind';
+ // Hover can change under a still pointer while the camera moves.
+ if (pointer.active && Math.round(t * 60) % 6 === 0) { const o = crownUnder({ clientX: pointer.px, clientY: pointer.py }); if (o !== overCrown) { overCrown = o; cursorApi?.set(o ? 'drag' : '', o ? 'Hold' : ''); } }
+ if (showHint) crownHintEl.style.transform = `translate3d(${((tmpV.x + 1) / 2 * innerWidth).toFixed(1)}px, ${((1 - tmpV.y) / 2 * innerHeight).toFixed(1)}px, 0)`;
+
+ // Contact shadow follows the subject; skip rendering once the footer covers the canvas.
+ shadow.setCenter(rig.position.x * 0.8, 0);
+ if (!engine.paused && (Math.round(t * 60) % 2 === 0)) shadow.update();
+ const footTop = footEl.getBoundingClientRect().top;
+ engine.paused = footTop <= 0;
+ ctaEl.style.opacity = clamp((footTop - innerHeight * 0.5) / (innerHeight * 0.3)).toFixed(3);
+ navEl.classList.toggle('on-dark', footTop < 70);
+});
+
+const axA = new THREE.Vector3(), axB = new THREE.Vector3();
+function drawLabels() {
+ const vw = innerWidth, vh = innerHeight, mob = MOBILE();
+ // Screen-space direction of the rig axis → callouts leave perpendicular to it.
+ axA.set(0, 0, -1).applyMatrix4(rig.matrixWorld).project(camera);
+ axB.set(0, 0, 1).applyMatrix4(rig.matrixWorld).project(camera);
+ let ax = (axB.x - axA.x) * vw, ay = -(axB.y - axA.y) * vh;
+ const al = Math.hypot(ax, ay) || 1; ax /= al; ay /= al;
+ let nx = ay, ny = -ax; // perpendicular; make 'u' point upward
+ if (ny > 0) { nx = -nx; ny = -ny; }
+ if (al < 30) { nx = -0.5; ny = -0.86; } // axis toward the camera: fall back to up-left
+ const scale = mob ? 0.5 : Math.min(1.2, vw / 1440);
+ for (const L of LABELS) {
+ let w = 0;
+ for (const k of L.k) w = Math.max(w, 1 - smooth(0.34, 0.48, Math.abs(S - k)));
+ if (mob && Math.abs(S - 2) < 0.5) w = 0; // the overview is too dense on a phone
+ w = smooth(0.25, 1, w);
+ const o = mv.anchors[L.a];
+ if (w < 0.01 || !o) { if (L.w > 0) { L.el.style.opacity = 0; L.path.style.opacity = L.dot.style.opacity = L.ring.style.opacity = 0; } L.w = 0; continue; }
+ L.w = w;
+ o.getWorldPosition(tmpV).project(camera);
+ if (tmpV.z > 1) { L.el.style.opacity = 0; continue; }
+ const x = (tmpV.x + 1) / 2 * vw, y = (1 - tmpV.y) / 2 * vh;
+ const sg = L.side === 'u' ? 1 : -1, len = (L.offk?.[Math.round(S)] ?? L.off) * scale * (0.55 + 0.45 * w);
+ const ex = x + nx * sg * len, ey = y + ny * sg * len;
+ const hx = Math.sign(nx * sg || -1), fx = ex + hx * 26 * scale, fy = ey;
+ L.path.setAttribute('d', `M${x.toFixed(1)},${y.toFixed(1)}L${ex.toFixed(1)},${ey.toFixed(1)}L${fx.toFixed(1)},${fy.toFixed(1)}`);
+ L.dot.setAttribute('cx', x); L.dot.setAttribute('cy', y); L.ring.setAttribute('cx', x); L.ring.setAttribute('cy', y);
+ L.path.style.opacity = L.dot.style.opacity = L.ring.style.opacity = w;
+ L.lw = L.el.offsetWidth || L.lw || 120;
+ const lx = hx > 0 ? fx + 8 : fx - 8 - L.lw;
+ L.el.classList.toggle('l', hx < 0); L.el.classList.toggle('r', hx > 0);
+ L.el.style.opacity = w;
+ L.el.style.transform = `translate3d(${clamp(lx, 8, vw - L.lw - 8).toFixed(1)}px, ${(fy - 11).toFixed(1)}px, 0)`;
+ }
+}
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('horologie', { theme: 'light', corner: 'bl' });
+cursorApi = cursor({ color: '#16213d', blend: 'normal', size: 30 });
+magnetic();
+smoothScroll({ lerp: 0.08 });
+measure();
+addEventListener('resize', measure);
+new ResizeObserver(measure).observe(document.body);
+
+const [gltf, calibre] = await Promise.all([watchLoad, mvBuild]);
+mv = calibre;
+rig.add(mv.root);
+watch = prepWatch(gltf.scene);
+rig.add(watch.holder);
+prepModel(watch.holder, renderer, { cast: false, receive: true, env: 1.25, onMat: m => patch(m, { iris: 2, u: irisA }) });
+// Collection variants share the Meshy geometry with recoloured, independently dissolving materials.
+for (const c of COLL) {
+ const src = gltf.scene.clone(true);
+ const u = irisUniforms();
+ u.uIris.value = 1;
+ src.traverse(o => {
+ if (!o.isMesh) return;
+ o.material = o.material.clone();
+ patch(o.material, { iris: 2, u, recolor: true, params: { uCaseTint: { value: new THREE.Color(...c.tint) }, uStrapTint: { value: new THREE.Color(...c.strap) },
+ uDialC: { value: watch.dialC.clone() }, uCaseR: { value: watch.caseR }, uDLC: { value: c.dlc } } });
+ o.castShadow = false; o.receiveShadow = true;
+ });
+ const holder = new THREE.Group(); holder.add(src); scene.add(holder);
+ clones.push({ ...c, holder, u });
+}
+mv.root.traverse(o => { if (o.isMesh && o.material?.isMeshPhysicalMaterial && o.material.transmission > 0) o.castShadow = false; });
+
+// Compile every program in every state before the first frame.
+evalState(S);
+irisA.uIris.value = 0.5; for (const c of clones) { c.holder.visible = true; c.u.uIris.value = 0.5; }
+mv.setExplode(1);
+renderer.compile(scene, camera);
+engine.render(0); shadow.update();
+mv.setExplode(0);
+engine.start();
+await loader.finish();
+started = true;
+window.__dbg = () => { const r = {}; for (const k of ['train', 'barrel', 'tourbillon']) { const v = mv.anchors[k].getWorldPosition(new THREE.Vector3()); const p = v.clone().project(camera); r[k] = [v.x.toFixed(2), v.y.toFixed(2), v.z.toFixed(2), p.x.toFixed(2), p.y.toFixed(2)]; } r.look = ST.look.toArray().map(x => x.toFixed(2)); r.cam = camera.position.toArray().map(x => x.toFixed(2)); r.S = S; r.gap = { ...GAP }; r.trainZ = mv.layers.train.g.position.z; return JSON.stringify(r); };
+window.__crownXY = () => { const v = mv.crownHit.getWorldPosition(new THREE.Vector3()).project(camera); return [(v.x + 1) / 2 * innerWidth, (1 - v.y) / 2 * innerHeight]; };
+window.__ready = true;
+if (!Q.has('kf') && scrollY < 10) {
+ gsap.fromTo(intro, { spin: -1.1, sweep: -1.6 }, { spin: 0, sweep: 0, duration: 2.6, ease: 'expo.out' });
+ gsap.from('.hero-title .ln', { yPercent: 60, opacity: 0, duration: 1.8, ease: 'expo.out', stagger: 0.1, delay: 0.1 });
+ gsap.from('.eyebrow, .hero-lede, .hero-cta, .hero-spec, .hint, .nav', { opacity: 0, y: 16, duration: 1.4, ease: 'power3.out', stagger: 0.07, delay: 0.5 });
+}
diff --git a/examples/horologie/movement.js b/examples/horologie/movement.js
new file mode 100644
index 0000000..5fc412c
--- /dev/null
+++ b/examples/horologie/movement.js
@@ -0,0 +1,451 @@
+// Calibre AH-01 — a fully procedural skeleton tourbillon, built at load time.
+// Units: the mainplate has radius 1 (≈ 15 mm). Dial side faces +Z. 12 o'clock is +Y, 3 o'clock is +X.
+// "Inverted" construction like the Meshy reference: bridges face the dial, the mainplate faces the caseback.
+import * as THREE from 'three';
+import {
+ TAU, clamp, lerp, circle, ring, seg, arm, union, subtract, sdfShape, extrude, gearLoop, rootRadius, escapeLoop,
+ ratchetLoop, circleLoop, spokeWindows, wheelGeometry, tentGeometry, latheZ, cylZ, Ribbon, reverseLoop,
+} from './geo.js';
+import { patch, FINISH } from './finish.js';
+
+const smooth = (a, b, v) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };
+
+// ─── Layout (pitch radii chosen so every pair meshes at its true centre distance) ──
+const O = [0, 0];
+const BARREL = { N: 96, rp: 0.39 }; // m = 0.008125
+const CPIN = { N: 12 }; // centre pinion meshes the barrel
+const B = [0, BARREL.rp + BARREL.rp * CPIN.N / BARREL.N]; // (0, 0.43875)
+const CENTER = { N: 80, rp: 0.30 }; // m = 0.0075, 1 rev / hour
+const TPIN = { N: 10, rp: 0.30 * 10 / 80 }; // third pinion
+const TH = [Math.cos(225 * Math.PI / 180) * (CENTER.rp + TPIN.rp), Math.sin(225 * Math.PI / 180) * (CENTER.rp + TPIN.rp)];
+const T = [0, -0.47]; // tourbillon axis
+const dTT = Math.hypot(TH[0] - T[0], TH[1] - T[1]);
+const THIRD = { N: 75, rp: dTT * 75 / 85 }; // third wheel
+const CAGEPIN = { N: 10, rp: dTT * 10 / 85 }; // cage pinion (the 'fourth wheel')
+const FIXED = { N: 96, rp: 0.2 * 96 / 104 }; // fixed wheel under the cage
+const EPIN = { N: 8, rp: 0.2 * 8 / 104 }; // escape pinion rolls around it
+const E_LOCAL = [0, -0.2]; // escape arbor in the cage frame
+const ESC = { N: 20, ra: 0.066 };
+const RATCHET = { N: 72, rp: 0.30 };
+const CROWNW = { N: 36, rp: 0.15 };
+const CW = [B[0] + Math.cos(-35 * Math.PI / 180) * 0.45, B[1] + Math.sin(-35 * Math.PI / 180) * 0.45];
+const angleOf = (a, b) => Math.atan2(b[1] - a[1], b[0] - a[0]);
+/** Angle of gear B driven by gear A (tooth of A at the contact line sits in a gap of B). */
+const mesh = (a, NA, NB, delta) => -(NA / NB) * (a - delta) + delta + Math.PI + Math.PI / NB;
+
+export const SPEC = { B, O, TH, T, CW };
+
+// ─── Materials ────────────────────────────────────────────────────────────────
+function materials(u) {
+ const S = (o, f = {}) => patch(new THREE.MeshStandardMaterial({ metalness: 1, envMapIntensity: 1, ...o }), { iris: 1, u, ...f });
+ const Ph = (o, f = {}) => patch(new THREE.MeshPhysicalMaterial({ metalness: 1, envMapIntensity: 1, ...o }), { iris: 1, u, ...f });
+ const rg = new THREE.Color('#f0bb93');
+ return {
+ roseWheel: S({ color: rg, roughness: 0.24 }, { finish: FINISH.circular, anglage: true, params: { uBevelRough: { value: 0.06 }, uSideRough: { value: 0.3 } } }),
+ roseSun: S({ color: rg, roughness: 0.26 }, { finish: FINISH.sunray, anglage: true }),
+ rosePolish: Ph({ color: rg, roughness: 0.1, clearcoat: 0.3, clearcoatRoughness: 0.08 }),
+ roseSatin: S({ color: rg, roughness: 0.3 }),
+ bridge: S({ color: '#98a0ad', roughness: 0.2 }, { finish: FINISH.cotes, anglage: true, params: { uBevelRough: { value: 0.04 } } }),
+ plate: S({ color: '#8d929c', roughness: 0.34 }, { finish: FINISH.perlage, anglage: true }),
+ mirror: S({ color: '#6a6f79', roughness: 0.03 }, { finish: FINISH.mirror, anglage: true, params: { uBevelRough: { value: 0.03 }, uSideRough: { value: 0.18 } } }),
+ cage: S({ color: '#d7dbe1', roughness: 0.12 }, { finish: FINISH.mirror, anglage: true, params: { uSideRough: { value: 0.22 } } }),
+ steel: S({ color: '#d9dce1', roughness: 0.16 }, { finish: FINISH.circular, anglage: true, params: { uGrain: { value: 5200 } } }),
+ steelPlain: S({ color: '#cfd3d9', roughness: 0.14 }),
+ blue: S({ color: '#2a4fd0', roughness: 0.16 }, { finish: FINISH.mirror, anglage: true, params: { uSideRough: { value: 0.2 } } }),
+ blueLathe: S({ color: '#2a4fd0', roughness: 0.14 }),
+ slot: S({ color: '#0a0c12', roughness: 0.5, metalness: 0.4 }),
+ gold: S({ color: '#f0cf95', roughness: 0.18 }, { finish: FINISH.mirror, anglage: true }),
+ dial: S({ color: '#39404d', roughness: 0.36, metalness: 0.85 }, { finish: FINISH.snail, anglage: true }),
+ print: S({ color: rg, roughness: 0.3 }),
+ spring: S({ color: '#c9d2e0', roughness: 0.2, side: THREE.DoubleSide }),
+ hair: S({ color: '#8fa6d8', roughness: 0.18, side: THREE.DoubleSide }, { spring: true }),
+ ruby: patch(new THREE.MeshPhysicalMaterial({
+ color: '#ff3d6a', metalness: 0, roughness: 0.04, transmission: 1, thickness: 0.03, ior: 1.76,
+ attenuationColor: new THREE.Color('#a8001f'), attenuationDistance: 0.02, specularIntensity: 1, envMapIntensity: 1.6,
+ }), { iris: 1, u }),
+ sapphire: patch(new THREE.MeshPhysicalMaterial({
+ color: '#ffffff', metalness: 0, roughness: 0.0, transmission: 1, thickness: 0.05, ior: 1.77, envMapIntensity: 1.3,
+ specularIntensity: 1, transparent: false,
+ }), { iris: 1, u }),
+ };
+}
+
+// ─── Build ───────────────────────────────────────────────────────────────────
+export async function buildMovement({ u, yieldFn = () => new Promise(r => setTimeout(r, 0)) }) {
+ const M = materials(u);
+ const root = new THREE.Group();
+ root.name = 'calibre';
+ const layers = {};
+ const layer = (name, dz, delay = 0) => { const g = new THREE.Group(); g.name = name; root.add(g); layers[name] = { g, dz, delay, sub: [] }; return g; };
+ const put = (parent, geo, mat, x = 0, y = 0, z = 0, name = '') => {
+ const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.castShadow = true; m.receiveShadow = true; m.name = name; parent.add(m); return m;
+ };
+ const anchors = {};
+ const anchor = (name, parent, x, y, z) => { const o = new THREE.Object3D(); o.position.set(x, y, z); parent.add(o); anchors[name] = o; return o; };
+
+ // Shared small parts.
+ const jewelGeo = latheZ([[0, 0.0075], [0.006, 0.0078], [0.012, 0.0074], [0.019, 0.006], [0.02, 0.0], [0.0001, 0.0]], 40);
+ const chatonGeo = latheZ([[0.019, 0.0072], [0.03, 0.0068], [0.034, 0.004], [0.034, 0.0], [0.019, 0.0]], 48);
+ const screwGeo = latheZ([[0, 0.013], [0.012, 0.0122], [0.02, 0.009], [0.024, 0.004], [0.024, 0.0], [0.0001, 0]], 40);
+ const slotGeo = new THREE.BoxGeometry(0.05, 0.0055, 0.006); slotGeo.translate(0, 0, 0.0112);
+ const jewel = (parent, x, y, z, big = 1) => {
+ const g = new THREE.Group(); g.position.set(x, y, z); g.scale.setScalar(big); parent.add(g);
+ const c = put(g, chatonGeo, M.rosePolish); c.castShadow = false;
+ const j = put(g, jewelGeo, M.ruby, 0, 0, 0.0005); j.castShadow = false;
+ return g;
+ };
+ const screw = (parent, x, y, z, rot = Math.random() * Math.PI, mat = M.blueLathe) => {
+ const g = new THREE.Group(); g.position.set(x, y, z); g.rotation.z = rot; parent.add(g);
+ put(g, screwGeo, mat); const s = put(g, slotGeo, M.slot); s.castShadow = false;
+ return g;
+ };
+ const arbor = (parent, x, y, z0, z1, r = 0.011) => put(parent, cylZ(r, z0, z1, 20), M.steelPlain, x, y, 0);
+
+ // ── Layers (dz = offset when fully exploded) ──
+ const Lback = layer('caseback', -2.3, 0.0);
+ const Lcase = layer('case', -1.8, 0.05);
+ const Lplate = layer('plate', -1.15, 0.12);
+ const Lfixed = layer('fixed', -0.72, 0.18);
+ const Lbarrel = layer('barrel', -0.3, 0.2);
+ const Ltrain = layer('train', 0.14, 0.2);
+ const Lcage = layer('cage', 0.55, 0.18);
+ const Lbridges = layer('bridges', 1.02, 0.12);
+ const Lwind = layer('winding', 1.4, 0.1);
+ const Ldial = layer('dial', 1.8, 0.06);
+ const Lhands = layer('hands', 2.15, 0.03);
+ const Ltop = layer('crystal', 2.6, 0.0);
+
+ // ── Mainplate (perlage, skeletonised) ──
+ const plateSdf = union([
+ ring(0, 0, 0.86, 1.0),
+ circle(...O, 0.095), circle(...B, 0.1), circle(...TH, 0.075), ring(...T, 0.325, 0.385),
+ seg(...O, ...B, 0.042), seg(...O, ...TH, 0.036), seg(...O, 0.93, -0.06, 0.04, 0.05), seg(...O, 0, -0.1, 0.05),
+ arm(...B, -0.45, 0.72, -0.72, 0.6, 0.038, 0.05), arm(...B, 0.45, 0.72, 0.72, 0.6, 0.038, 0.05),
+ arm(...TH, -0.6, -0.2, -0.9, -0.2, 0.034, 0.05), seg(...O, -0.92, 0.1, 0.03, 0.045),
+ seg(...T, T[0], T[1] + 0.34, 0.018), seg(...T, T[0] + 0.3, T[1] - 0.17, 0.018), seg(...T, T[0] - 0.3, T[1] - 0.17, 0.018), circle(...T, 0.05),
+ ], 0.05);
+ const plateGeo = extrude(sdfShape(plateSdf, [-1, -1, 1, 1], 0.0032), { depth: 0.06, chamfer: 0.009 });
+ put(Lplate, plateGeo, M.plate, 0, 0, -0.2, 'mainplate');
+ anchor('plate', Lplate, -0.83, 0.48, -0.14);
+ for (const [x, y] of [O, B, TH, T]) jewel(Lplate, x, y, -0.198, 1.0).rotation.x = Math.PI;
+ await yieldFn();
+
+ // ── Fixed wheel (stationary; the escape pinion rolls around it) ──
+ const fixedGeo = wheelGeometry({ outline: gearLoop(FIXED.N, FIXED.rp, { tip: 3, root: 2 }), rOut: FIXED.rp,
+ windows: spokeWindows({ n: 3, rIn: 0.055, rOut: rootRadius(FIXED.N, FIXED.rp) - 0.018, w: 0.022, curve: 0.5 }), depth: 0.014, chamfer: 0.0016 });
+ const fixedWheel = put(Lfixed, fixedGeo, M.steel, T[0], T[1], -0.14, 'fixed');
+ for (let i = 0; i < 3; i++) { const a = i * TAU / 3 + 0.3; screw(Lfixed, T[0] + Math.cos(a) * 0.036, T[1] + Math.sin(a) * 0.036, -0.126, a, M.steelPlain).scale.setScalar(0.55); }
+ await yieldFn();
+
+ // ── Barrel: drum teeth, wall, spoked floor & cover, mainspring, arbor ──
+ const barrel = new THREE.Group(); barrel.position.set(B[0], B[1], 0); Lbarrel.add(barrel);
+ const drumTeeth = wheelGeometry({ outline: gearLoop(BARREL.N, BARREL.rp, { tip: 3, root: 2 }), rOut: BARREL.rp,
+ windows: spokeWindows({ n: 5, rIn: 0.075, rOut: 0.33, w: 0.03, curve: 0.9, round: 0.012 }), depth: 0.022, chamfer: 0.0022 });
+ const drum = new THREE.Group(); barrel.add(drum);
+ put(drum, drumTeeth, M.roseWheel, 0, 0, -0.135);
+ put(drum, extrude([{ outer: circleLoop(0.37, 220), holes: [circleLoop(0.345, 220, true)] }], { depth: 0.085, chamfer: 0.003 }), M.roseWheel, 0, 0, -0.113);
+ const coverGeo = wheelGeometry({ outline: circleLoop(0.372, 240), rOut: 0.372,
+ windows: spokeWindows({ n: 5, rIn: 0.075, rOut: 0.325, w: 0.03, curve: -0.9, round: 0.012 }), depth: 0.012, chamfer: 0.0025 });
+ const cover = new THREE.Group(); barrel.add(cover);
+ put(cover, coverGeo, M.roseSun, 0, 0, -0.026);
+ layers.barrel.sub.push({ g: cover, dz: 0.3 });
+ const springRib = new Ribbon(900, { width: 0.0062, z0: -0.106, z1: -0.04 });
+ const springMesh = put(barrel, springRib.geo, M.spring); springMesh.frustumCulled = false;
+ const springG = new THREE.Group(); barrel.add(springG); springG.add(springMesh);
+ layers.barrel.sub.push({ g: springG, dz: 0.15 });
+ const barrelArbor = new THREE.Group(); barrel.add(barrelArbor);
+ put(barrelArbor, cylZ(0.05, -0.12, -0.02, 36), M.steel);
+ put(barrelArbor, cylZ(0.022, -0.2, 0.1, 24), M.steelPlain);
+ put(barrelArbor, new THREE.BoxGeometry(0.02, 0.012, 0.06), M.steelPlain, 0.052, 0, -0.07);
+ anchor('barrel', barrel, -0.26, 0.26, -0.03);
+ await yieldFn();
+
+ // ── Going train: centre wheel + pinion, third wheel + pinion ──
+ const center = new THREE.Group(); Ltrain.add(center);
+ put(center, wheelGeometry({ outline: gearLoop(CENTER.N, CENTER.rp, { tip: 3, root: 2 }), rOut: CENTER.rp,
+ windows: spokeWindows({ n: 5, rIn: 0.05, rOut: rootRadius(CENTER.N, CENTER.rp) - 0.02, w: 0.024, curve: 1.1, round: 0.01 }), depth: 0.016, chamfer: 0.002 }), M.roseWheel, 0, 0, -0.052);
+ put(center, extrude([{ outer: gearLoop(CPIN.N, BARREL.rp * CPIN.N / BARREL.N, { add: 0.95, ded: 1.3, thick: 0.44, tip: 4 }), holes: [] }], { depth: 0.036, chamfer: 0.0012 }), M.steel, 0, 0, -0.14);
+ arbor(center, 0, 0, -0.205, 0.215, 0.012);
+ put(center, cylZ(0.03, -0.058, -0.03, 32), M.steel);
+ const third = new THREE.Group(); third.position.set(TH[0], TH[1], 0); Ltrain.add(third);
+ put(third, wheelGeometry({ outline: gearLoop(THIRD.N, THIRD.rp, { tip: 3, root: 2 }), rOut: THIRD.rp,
+ windows: spokeWindows({ n: 4, rIn: 0.045, rOut: rootRadius(THIRD.N, THIRD.rp) - 0.018, w: 0.022, curve: 0.9, round: 0.01 }), depth: 0.014, chamfer: 0.0018 }), M.roseWheel, 0, 0, -0.032);
+ put(third, extrude([{ outer: gearLoop(TPIN.N, TPIN.rp, { add: 0.95, ded: 1.3, thick: 0.44, tip: 4 }), holes: [] }], { depth: 0.03, chamfer: 0.001 }), M.steel, 0, 0, -0.06);
+ arbor(third, 0, 0, -0.2, 0.09, 0.009);
+ put(third, cylZ(0.024, -0.036, -0.016, 28), M.steel);
+ anchor('train', third, -0.2, -0.05, -0.016);
+ await yieldFn();
+
+ // ── Tourbillon cage: pinion, frames, pillars, escape wheel, pallet fork, balance, hairspring ──
+ const cageRoot = new THREE.Group(); cageRoot.position.set(T[0], T[1], -0.02); Lcage.add(cageRoot);
+ const cage = new THREE.Group(); cageRoot.add(cage);
+ put(cage, extrude([{ outer: gearLoop(CAGEPIN.N, CAGEPIN.rp, { add: 0.95, ded: 1.3, thick: 0.44, tip: 4 }), holes: [] }], { depth: 0.028, chamfer: 0.001 }), M.steel, 0, 0, -0.022);
+ const frameSdf = top => subtract(union([
+ ring(0, 0, 0.268, 0.3),
+ ...[90, 210, 330].map(d => { const a = d * Math.PI / 180; const c = Math.cos(a), s = Math.sin(a);
+ return top ? arm(0, 0, 0.12 * Math.cos(a + 0.6), 0.12 * Math.sin(a + 0.6), 0.284 * c, 0.284 * s, 0.03, 0.016) : seg(0, 0, 0.284 * c, 0.284 * s, 0.016, 0.022); }),
+ circle(0, 0, 0.045),
+ ...(top ? [] : [circle(...E_LOCAL, 0.03), seg(0, 0, ...E_LOCAL, 0.013), circle(0, -0.115, 0.022)]),
+ ...[30, 150, 270].map(d => circle(0.284 * Math.cos(d * Math.PI / 180), 0.284 * Math.sin(d * Math.PI / 180), 0.026)),
+ ], 0.028), circle(0, 0, 0.012));
+ const lowerFrame = put(cage, extrude(sdfShape(frameSdf(false), [-0.31, -0.31, 0.31, 0.31], 0.0012), { depth: 0.018, chamfer: 0.0035 }), M.cage, 0, 0, 0.012);
+ const upper = new THREE.Group(); cage.add(upper);
+ put(upper, extrude(sdfShape(frameSdf(true), [-0.31, -0.31, 0.31, 0.31], 0.0012), { depth: 0.018, chamfer: 0.0035 }), M.cage, 0, 0, 0.13);
+ for (const d of [30, 150, 270]) { const a = d * Math.PI / 180; put(upper, cylZ(0.011, 0.03, 0.13, 18), M.cage, 0.284 * Math.cos(a), 0.284 * Math.sin(a), 0); }
+ jewel(upper, 0, 0, 0.148, 0.8);
+ // Seconds pointer riding on the cage.
+ const pointer = put(upper, tentGeometry([[0.03, 0], [0.05, 0.009], [0.2, 0.006], [0.262, 0]], { base: 0.003, ridge: 0.003 }), M.blue, 0, 0, 0.149);
+ pointer.rotation.z = Math.PI / 2;
+ layers.cage.sub.push({ g: upper, dz: 0.34 });
+ // Escape wheel + pinion.
+ const esc = new THREE.Group(); esc.position.set(...E_LOCAL, 0); cage.add(esc);
+ put(esc, wheelGeometry({ outline: escapeLoop(ESC.N, ESC.ra), rOut: ESC.ra,
+ windows: spokeWindows({ n: 4, rIn: 0.014, rOut: ESC.ra * 0.62, w: 0.008, curve: 0.8, round: 0.003 }), depth: 0.01, chamfer: 0.0009 }), M.steel, 0, 0, 0.042);
+ put(esc, extrude([{ outer: gearLoop(EPIN.N, EPIN.rp, { add: 0.95, ded: 1.3, thick: 0.44, tip: 4 }), holes: [] }], { depth: 0.03, chamfer: 0.0007 }), M.steel, 0, 0, -0.123);
+ arbor(esc, 0, 0, -0.125, 0.07, 0.005);
+ jewel(cage, ...E_LOCAL, 0.03, 0.5);
+ // Pallet fork: pivot between escape wheel and balance, lever toward the roller.
+ const fork = new THREE.Group(); fork.position.set(0, -0.115, 0); cage.add(fork);
+ const fk = (x, y) => [y, -x]; // design along +x (toward the escape wheel) → world −Y
+ const forkLocal = union([
+ circle(0, 0, 0.011), seg(0, 0, 0.034, 0.044, 0.0062, 0.0045), seg(0, 0, 0.034, -0.044, 0.0062, 0.0045),
+ seg(0, 0, -0.07, 0, 0.0055, 0.0035), seg(-0.066, 0.004, -0.081, 0.009, 0.0026), seg(-0.066, -0.004, -0.081, -0.009, 0.0026),
+ ], 0.006);
+ const forkSdf = (x, y) => forkLocal(-y, x); // rotate design −90°
+ put(fork, extrude(sdfShape((x, y) => forkSdf(x, y), [-0.06, -0.06, 0.06, 0.1], 0.0005), { depth: 0.008, chamfer: 0.0012 }), M.steel, 0, 0, 0.045);
+ for (const s of [1, -1]) {
+ const st = put(fork, new THREE.BoxGeometry(0.012, 0.007, 0.008), M.ruby, ...fk(0.037, s * 0.046), 0.049); st.rotation.z = s * 0.5; st.castShadow = false;
+ }
+ jewel(cage, 0, -0.115, 0.03, 0.4);
+ // Balance: glucydur rim, three spokes, timing screws; hairspring breathing above it.
+ const bal = new THREE.Group(); bal.position.z = 0.07; cage.add(bal);
+ const balSdf = union([ring(0, 0, 0.165, 0.186), ...[0, 120, 240].map(d => { const a = (d + 90) * Math.PI / 180; return seg(0, 0, 0.175 * Math.cos(a), 0.175 * Math.sin(a), 0.009, 0.007); }), circle(0, 0, 0.026)], 0.012);
+ put(bal, extrude(sdfShape(balSdf, [-0.19, -0.19, 0.19, 0.19], 0.0009), { depth: 0.014, chamfer: 0.0022 }), M.gold, 0, 0, 0);
+ const balScrewGeo = latheZ([[0, 0.009], [0.006, 0.0085], [0.0085, 0.005], [0.0085, 0], [0.0001, 0]], 20);
+ for (let i = 0; i < 10; i++) { const a = i * TAU / 10 + 0.3; put(bal, balScrewGeo, M.gold, Math.cos(a) * 0.1755, Math.sin(a) * 0.1755, 0.014); }
+ put(bal, cylZ(0.006, -0.05, 0.075, 16), M.steelPlain);
+ put(bal, cylZ(0.022, -0.012, 0.0, 28), M.steelPlain); // roller
+ const hairRib = new Ribbon(760, { width: 0.0036, z0: 0.022, z1: 0.034, attr: true });
+ { const rs = new Float32Array(760), ths = new Float32Array(760);
+ for (let i = 0; i < 760; i++) { const s = i / 759; rs[i] = lerp(0.032, 0.13, s) + (s > 0.93 ? (s - 0.93) * 0.3 : 0); ths[i] = s * 7.5 * TAU; }
+ hairRib.pose(rs, ths); }
+ const hair = new THREE.Mesh(hairRib.geo, M.hair); hair.frustumCulled = false; hair.castShadow = true;
+ const hairG = new THREE.Group(); hairG.position.z = 0.07; cage.add(hairG); hairG.add(hair);
+ put(hairG, new THREE.BoxGeometry(0.018, 0.012, 0.02), M.steelPlain, 0.14, 0.025, 0.028); // stud
+ layers.cage.sub.push({ g: bal, dz: 0.2 }, { g: hairG, dz: 0.24 });
+ anchor('escapement', cage, 0, -0.2, 0.05);
+ anchor('balance', bal, -0.16, 0.08, 0.014);
+ anchor('tourbillon', cageRoot, 0.26, -0.15, 0.08);
+ await yieldFn();
+
+ // ── Bridges (Côtes de Genève, anglage, blued screws, jewels in gold chatons) ──
+ const F1 = [-0.74, 0.54], F2 = [0.88, 0.2], F3 = [-0.88, -0.22], F4 = [0.87, -0.2], F5 = [-0.9, 0.14], F6 = [-0.63, -0.64], F7 = [0.63, -0.64];
+ const barrelBridge = union([
+ ring(...B, 0.335, 0.405), circle(...B, 0.1),
+ ...[100, 220, 340].map(d => { const r = d * Math.PI / 180; return seg(...B, B[0] + Math.cos(r) * 0.37, B[1] + Math.sin(r) * 0.37, 0.05, 0.034); }),
+ arm(-0.33, 0.62, -0.62, 0.66, ...F1, 0.06, 0.07), circle(...F1, 0.075),
+ seg(...B, ...CW, 0.05), circle(...CW, 0.075), arm(...CW, 0.66, 0.2, ...F2, 0.058, 0.07), circle(...F2, 0.075),
+ ], 0.07);
+ const trainBridge = union([
+ circle(...O, 0.085), circle(...TH, 0.072), seg(...O, ...TH, 0.058, 0.052), arm(...TH, -0.62, -0.13, ...F3, 0.052, 0.068),
+ arm(...O, 0.42, 0.04, ...F4, 0.058, 0.066), arm(...O, -0.4, 0.12, ...F5, 0.044, 0.062), circle(...F3, 0.075), circle(...F4, 0.075), circle(...F5, 0.07),
+ ], 0.07);
+ const tBridge = union([
+ circle(...T, 0.078), arm(...F6, -0.42, -0.14, ...T, 0.074, 0.05), arm(...T, 0.42, -0.14, ...F7, 0.05, 0.074), circle(...F6, 0.08), circle(...F7, 0.08),
+ ], 0.06);
+ const bb = put(Lbridges, extrude(sdfShape(subtract(barrelBridge, circle(...B, 0.024)), [-0.9, -0.05, 1.0, 0.95], 0.0026), { depth: 0.06, chamfer: 0.008 }), M.bridge, 0, 0, 0.03, 'barrel bridge');
+ await yieldFn();
+ put(Lbridges, extrude(sdfShape(trainBridge, [-1, -0.4, 1, 0.3], 0.0026), { depth: 0.06, chamfer: 0.008 }), M.bridge, 0, 0, 0.03, 'train bridge');
+ await yieldFn();
+ put(Lbridges, extrude(sdfShape(tBridge, [-0.78, -0.78, 0.78, -0.3], 0.0022), { depth: 0.055, chamfer: 0.016 }), M.mirror, 0, 0, 0.14, 'tourbillon bridge');
+ for (const p of [F1, F2, F3, F4, F5]) screw(Lbridges, ...p, 0.09);
+ for (const p of [F6, F7]) screw(Lbridges, ...p, 0.19);
+ for (const p of [O, TH, CW]) jewel(Lbridges, ...p, 0.09, p === O ? 1.15 : 1);
+ jewel(Lbridges, ...T, 0.19, 1.1);
+ anchor('bridges', Lbridges, 0.8, -0.22, 0.09);
+ anchor('tbridge', Lbridges, 0.42, -0.42, 0.19);
+ await yieldFn();
+
+ // ── Winding works on top of the barrel bridge: ratchet (sunray), crown wheel, click ──
+ const ratchet = new THREE.Group(); ratchet.position.set(B[0], B[1], 0.092); Lwind.add(ratchet);
+ put(ratchet, wheelGeometry({ outline: ratchetLoop(RATCHET.N, RATCHET.rp), rOut: RATCHET.rp,
+ windows: spokeWindows({ n: 6, rIn: 0.07, rOut: 0.255, w: 0.028, curve: 0.7, round: 0.012 }), depth: 0.018, chamfer: 0.0028 }), M.roseSun, 0, 0, 0);
+ screw(ratchet, 0, 0, 0.018, 0.3, M.blueLathe).scale.setScalar(1.6);
+ const crownWheel = new THREE.Group(); crownWheel.position.set(CW[0], CW[1], 0.092); Lwind.add(crownWheel);
+ put(crownWheel, wheelGeometry({ outline: gearLoop(CROWNW.N, CROWNW.rp, { tip: 3, root: 2 }), rOut: CROWNW.rp,
+ windows: spokeWindows({ n: 4, rIn: 0.04, rOut: 0.118, w: 0.022, curve: 0.6, round: 0.01 }), depth: 0.016, chamfer: 0.0024 }), M.roseSun, 0, 0, 0);
+ screw(crownWheel, 0, 0, 0.016, 0.9, M.blueLathe).scale.setScalar(1.2);
+ // Click: pivoted pawl that drops into each ratchet tooth.
+ const clickPivot = [B[0] - 0.36, B[1] + 0.06];
+ const click = new THREE.Group(); click.position.set(...clickPivot, 0.092); Lwind.add(click);
+ const clickSdf = union([circle(0, 0, 0.026), arm(0, 0, 0.03, 0.06, 0.07, 0.07, 0.016, 0.008)], 0.012);
+ put(click, extrude(sdfShape(clickSdf, [-0.04, -0.04, 0.09, 0.1], 0.0008), { depth: 0.014, chamfer: 0.0022 }), M.steel, 0, 0, 0);
+ screw(click, 0, 0, 0.014, 0.2).scale.setScalar(0.75);
+ anchor('winding', Lwind, CW[0] + 0.1, CW[1] - 0.08, 0.11);
+ await yieldFn();
+
+ // ── Chapter ring with applied rose-gold batons and a printed minute track ──
+ put(Ldial, extrude([{ outer: circleLoop(1.0, 360), holes: [circleLoop(0.86, 320, true)] }], { depth: 0.018, chamfer: 0.004 }), M.dial, 0, 0, 0.19);
+ const baton = tentGeometry([[0, 0], [0.004, 0.009], [0.07, 0.009], [0.078, 0]], { base: 0.006, ridge: 0.006 });
+ const ticks = [];
+ for (let i = 0; i < 12; i++) {
+ const a = Math.PI / 2 - i * TAU / 12;
+ for (const off of i === 0 ? [-0.022, 0.022] : [0]) {
+ const m = put(Ldial, baton, M.rosePolish, 0, 0, 0.208);
+ const r = 0.885, ox = Math.cos(a - Math.PI / 2) * off, oy = Math.sin(a - Math.PI / 2) * off;
+ m.position.set(Math.cos(a) * r + ox, Math.sin(a) * r + oy, 0.208); m.rotation.z = a - Math.PI / 2;
+ }
+ }
+ { const g = []; for (let i = 0; i < 60; i++) { if (i % 5 === 0) continue; const a = i * TAU / 60; const b = new THREE.BoxGeometry(0.0035, 0.022, 0.0016); b.translate(0, 0.978, 0.0008); b.rotateZ(-a); g.push(b); }
+ const merged = mergeGeos(g); put(Ldial, merged, M.print, 0, 0, 0.208); }
+ anchor('dial', Ldial, -0.7, -0.7, 0.21);
+
+ // ── Hands: flame-blued, faceted ──
+ const minute = new THREE.Group(); minute.position.z = 0.236; Lhands.add(minute);
+ const hour = new THREE.Group(); hour.position.z = 0.222; Lhands.add(hour);
+ const handProfile = (L, W, tail) => { const p = [[-tail, 0], [-tail + 0.012, W * 0.55], [-0.04, W * 0.5], [0, W * 1.25], [0.05, W * 0.8]];
+ for (let i = 1; i <= 10; i++) { const t = i / 10; p.push([lerp(0.05, L, t), W * Math.pow(Math.sin(Math.PI * (0.14 + t * 0.86)), 0.7) * (1 - t * 0.2)]); }
+ p[p.length - 1][1] = 0; return p; };
+ put(minute, tentGeometry(handProfile(0.8, 0.026, 0.15), { base: 0.003, ridge: 0.006 }), M.blue);
+ put(hour, tentGeometry(handProfile(0.56, 0.034, 0.12), { base: 0.003, ridge: 0.007 }), M.blue);
+ put(minute, cylZ(0.024, 0, 0.007, 36), M.blue);
+ put(hour, cylZ(0.034, 0, 0.006, 36), M.blue);
+ put(Lhands, cylZ(0.012, 0.215, 0.248, 20), M.steelPlain);
+ anchor('hands', minute, 0, 0.5, 0.01);
+
+ // ── Case: bezel + sapphire (top), case middle + lugs + crown (middle), caseback (bottom) ──
+ const bezel = latheZ([[1.005, 0.275], [1.015, 0.318], [1.05, 0.33], [1.12, 0.326], [1.175, 0.31], [1.205, 0.28], [1.212, 0.24], [1.206, 0.2], [1.19, 0.2], [1.01, 0.2], [1.005, 0.275]], 220);
+ put(Ltop, bezel, M.rosePolish);
+ put(Ltop, latheZ([[0, 0.318], [0.6, 0.314], [0.9, 0.305], [1.012, 0.296], [1.012, 0.27], [0, 0.272]], 160), M.sapphire).castShadow = false;
+ anchor('crystal', Ltop, -0.9, 0.52, 0.33);
+ put(Lcase, latheZ([[1.03, 0.19], [1.19, 0.19], [1.215, 0.13], [1.222, 0.0], [1.21, -0.14], [1.18, -0.24], [1.14, -0.27], [1.03, -0.27], [1.03, 0.19]], 220), M.rosePolish);
+ const crown = new THREE.Group(); crown.position.set(1.222, 0, -0.04); Lbarrel.add(crown); // keyless works explode with the movement
+ { const neck = cylZ(0.055, 0, 0.06, 32); neck.rotateY(Math.PI / 2); put(crown, neck, M.rosePolish);
+ const fl = extrude([{ outer: gearLoop(26, 0.125, { add: 0.5, ded: 0.55, thick: 0.62, tip: 3, root: 3 }), holes: [] }], { depth: 0.1, chamfer: 0.012 });
+ fl.rotateY(Math.PI / 2); fl.translate(0.055, 0, 0);
+ const flutes = put(crown, fl, M.rosePolish);
+ const cap = latheZ([[0, 0.03], [0.07, 0.026], [0.105, 0.012], [0.112, 0], [0.0001, 0]], 48); cap.rotateY(Math.PI / 2); cap.translate(0.155, 0, 0);
+ put(crown, cap, M.rosePolish);
+ const stem = cylZ(0.012, 0, 0.72, 16); stem.rotateY(-Math.PI / 2); stem.translate(0.02, 0, 0); put(crown, stem, M.steelPlain);
+ crown.userData.flutes = flutes; }
+ const crownHit = new THREE.Mesh(new THREE.SphereGeometry(0.24, 16, 12), new THREE.MeshBasicMaterial({ visible: false }));
+ crownHit.position.set(0.12, 0, 0); crown.add(crownHit);
+ anchor('crown', crown, 0.2, 0.0, 0.08);
+ put(Lback, latheZ([[0.84, -0.27], [1.16, -0.27], [1.19, -0.29], [1.17, -0.33], [1.1, -0.345], [0.86, -0.34], [0.84, -0.3], [0.84, -0.27]], 220), M.rosePolish);
+ put(Lback, latheZ([[0, -0.29], [0.86, -0.29], [0.86, -0.325], [0, -0.33]], 120), M.sapphire).castShadow = false;
+ anchor('caseback', Lback, 1.0, -0.58, -0.3);
+
+ // ─── Animation state ──
+ const st = {
+ psi: 0, boost: 0, w: 0.34, t0: 0, explode: 0, windRate: 0,
+ arbor: 0, ratchetPhase: 0, clicks: 0, amp: 0,
+ };
+ const now = new Date();
+ st.t0 = now.getHours() * 3600 + now.getMinutes() * 60 + now.getSeconds() + now.getMilliseconds() / 1000;
+ const dOT = angleOf(O, TH), dThT = angleOf(TH, T), dOB = angleOf(O, B), dBC = angleOf(B, CW), dE = Math.atan2(E_LOCAL[1], E_LOCAL[0]);
+
+ // Mainspring posing: area-conserving packs on the arbor (wound) and on the drum wall (let down).
+ const ra = 0.05, rw = 0.338, pitch = 0.0112, rb = ra + 12 * pitch, A = rb * rb - ra * ra;
+ const NS = springRib.n, rs = new Float32Array(NS), ths = new Float32Array(NS);
+ let posedW = -1;
+ function poseSpring(w, arborAngle) {
+ const ww = clamp(w, 0.02, 0.98);
+ let th = 0;
+ for (let i = 0; i < NS; i++) {
+ const s = i / (NS - 1);
+ const rA = Math.sqrt(ra * ra + Math.min(s, ww) * A + Math.max(0, s - ww) * A * 0.02);
+ const rW = Math.sqrt(Math.max(ra * ra, rw * rw - (1 - s) * A));
+ const k = smooth(ww - 0.035, ww + 0.035, s);
+ const r = lerp(rA, rW, k);
+ rs[i] = r;
+ if (i > 0) th += (A / pitch) / (NS - 1) / ((r + rs[i - 1]) / 2);
+ ths[i] = th;
+ }
+ // inner end rides on the arbor
+ for (let i = 0; i < NS; i++) ths[i] += arborAngle;
+ springRib.pose(rs, ths);
+ }
+
+ // extra: { layerName: additional z } — used to open the stack around the part in focus.
+ function setExplode(e, extra = null) {
+ st.explode = e;
+ for (const k in layers) {
+ const L = layers[k];
+ const p = smooth(L.delay, L.delay + 0.72, e);
+ L.g.position.z = L.dz * p + (extra?.[k] ?? 0);
+ for (const s of L.sub) s.g.position.z = s.dz * p;
+ }
+ crown.position.x = 1.222 + 0.62 * smooth(0.1, 0.8, e);
+ }
+
+ function update(dt, { timeScale = 1 } = {}) {
+ st.boost *= Math.exp(-dt * 1.6);
+ const rate = timeScale * (1 + st.boost * 1.6);
+ const amp = (205 + 105 * st.w + 25 * st.boost) * Math.PI / 180;
+ st.amp = amp;
+ st.psi += TAU * 4 * rate * dt;
+ const uu = st.psi / Math.PI, n = Math.floor(uu + 0.5), s = uu - n;
+ const k = smooth(-0.075, 0.075, s);
+ const half = n - 1 + k;
+ const secs = st.t0 + half / 8;
+ st.secs = secs;
+ const side = (n % 2 === 0) ? 1 : -1;
+ st.beat = n;
+ // Balance & hairspring
+ const balA = amp * Math.sin(st.psi);
+ bal.rotation.z = balA;
+ M.hair.userData.u.uBal.value = balA;
+ fork.rotation.z = 0.16 * side * (2 * k - 1);
+ // Train (centre wheel is the master: it carries the minutes)
+ const cA = -TAU * secs / 3600;
+ center.rotation.z = cA;
+ const thA = mesh(cA, CENTER.N, TPIN.N, dOT);
+ third.rotation.z = thA;
+ const cageA = mesh(thA, THIRD.N, CAGEPIN.N, dThT);
+ cage.rotation.z = cageA;
+ esc.rotation.z = mesh(-cageA, FIXED.N, EPIN.N, dE);
+ drum.rotation.z = mesh(cA, CPIN.N, BARREL.N, dOB);
+ cover.rotation.z = drum.rotation.z;
+ minute.rotation.z = cA;
+ hour.rotation.z = -TAU * secs / 43200;
+ // Winding: 8 arbor turns from let-down to fully wound.
+ const arborA = -TAU * 8 * st.w;
+ barrelArbor.rotation.z = arborA;
+ ratchet.rotation.z = arborA;
+ crownWheel.rotation.z = mesh(arborA, RATCHET.N, CROWNW.N, dBC);
+ crown.rotation.x = -crownWheel.rotation.z * 2;
+ const tooth = (-arborA / (TAU / RATCHET.N));
+ const ph = tooth - Math.floor(tooth);
+ click.rotation.z = -0.1 * (1 - ph) * (1 - ph) + 0.02;
+ st.clicks = Math.floor(tooth);
+ if (Math.abs(posedW - st.w) > 1e-5) { poseSpring(st.w, arborA); posedW = st.w; }
+ }
+ update(0);
+ setExplode(0);
+
+ return { root, layers, anchors, crown, crownHit, st, update, setExplode, materials: M };
+}
+
+function flipWinding(geo) {
+ const idx = geo.index.array;
+ for (let i = 0; i < idx.length; i += 3) { const t = idx[i + 1]; idx[i + 1] = idx[i + 2]; idx[i + 2] = t; }
+ const n = geo.attributes.normal;
+ geo.index.needsUpdate = true; n.needsUpdate = true;
+}
+
+function mergeGeos(list) {
+ let count = 0, icount = 0;
+ for (const g of list) { count += g.attributes.position.count; icount += g.index.count; }
+ const pos = new Float32Array(count * 3), nor = new Float32Array(count * 3), idx = new Uint32Array(icount);
+ let o = 0, io = 0;
+ for (const g of list) {
+ pos.set(g.attributes.position.array, o * 3); nor.set(g.attributes.normal.array, o * 3);
+ const gi = g.index.array; for (let i = 0; i < gi.length; i++) idx[io + i] = gi[i] + o;
+ o += g.attributes.position.count; io += gi.length;
+ }
+ const out = new THREE.BufferGeometry();
+ out.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ out.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ out.setIndex(new THREE.BufferAttribute(idx, 1));
+ return out;
+}
diff --git a/examples/horologie/shadow.js b/examples/horologie/shadow.js
new file mode 100644
index 0000000..f1ff755
--- /dev/null
+++ b/examples/horologie/shadow.js
@@ -0,0 +1,70 @@
+// Soft contact shadow for a floating object over the ivory cyclorama: an orthographic depth pass
+// from the floor looking up, blurred twice, laid on the floor as a darkening layer.
+import * as THREE from 'three';
+import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
+import { HorizontalBlurShader } from 'three/examples/jsm/shaders/HorizontalBlurShader.js';
+import { VerticalBlurShader } from 'three/examples/jsm/shaders/VerticalBlurShader.js';
+
+export class ContactShadow {
+ constructor(renderer, scene, { width = 16, depth = 10, y = -2.6, res = 512, far = 5, blur = 3.2, opacity = 0.6, color = 0x1b2236 } = {}) {
+ this.renderer = renderer; this.scene = scene; this.blur = blur;
+ const opts = { type: THREE.HalfFloatType };
+ this.rt = new THREE.WebGLRenderTarget(res, res * depth / width, opts);
+ this.rt2 = new THREE.WebGLRenderTarget(res, res * depth / width, opts);
+ this.cam = new THREE.OrthographicCamera(-width / 2, width / 2, depth / 2, -depth / 2, 0, far);
+ this.cam.rotation.x = Math.PI / 2; // look up (+Y)
+ this.cam.position.set(0, y, 0);
+ this.depthMat = new THREE.ShaderMaterial({
+ uniforms: { uFar: { value: far } },
+ vertexShader: `#include <common>
+ varying float vH;
+ void main(){ vec4 wp = modelMatrix * vec4(position, 1.0);
+ #ifdef USE_INSTANCING
+ wp = modelMatrix * instanceMatrix * vec4(position, 1.0);
+ #endif
+ vH = wp.y; gl_Position = projectionMatrix * viewMatrix * wp; }`,
+ fragmentShader: `uniform float uFar; uniform float uY; varying float vH;
+ void main(){ float h = clamp((vH - uY) / uFar, 0.0, 1.0); gl_FragColor = vec4(vec3(0.0), pow(1.0 - h, 2.2)); }`,
+ side: THREE.DoubleSide,
+ });
+ this.depthMat.uniforms.uY = { value: y };
+ this.blurH = new FullScreenQuad(new THREE.ShaderMaterial(HorizontalBlurShader));
+ this.blurV = new FullScreenQuad(new THREE.ShaderMaterial(VerticalBlurShader));
+ this.plane = new THREE.Mesh(new THREE.PlaneGeometry(width, depth), new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { map: { value: this.rt.texture }, uOpacity: { value: opacity }, uColor: { value: new THREE.Color(color) } },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `uniform sampler2D map; uniform float uOpacity; uniform vec3 uColor; varying vec2 vUv;
+ void main(){ float a = texture2D(map, vec2(vUv.x, 1.0 - vUv.y)).a; vec2 e = smoothstep(0.0, 0.12, vUv) * smoothstep(0.0, 0.12, 1.0 - vUv);
+ gl_FragColor = vec4(uColor, a * uOpacity * e.x * e.y); }`,
+ }));
+ this.plane.rotation.x = -Math.PI / 2;
+ this.plane.position.y = y + 0.002;
+ this.plane.renderOrder = -1;
+ scene.add(this.plane);
+ this.hidden = [this.plane];
+ }
+ setCenter(x, z) { this.cam.position.x = x; this.cam.position.z = z; this.plane.position.x = x; this.plane.position.z = z; }
+ update() {
+ const { renderer: r, scene } = this;
+ const vis = this.hidden.map(o => o.visible);
+ this.hidden.forEach(o => { o.visible = false; });
+ const prevBg = scene.background, prevOv = scene.overrideMaterial, prevRT = r.getRenderTarget();
+ const prevClear = r.getClearColor(new THREE.Color()), prevAlpha = r.getClearAlpha();
+ const prevAuto = r.shadowMap.autoUpdate;
+ r.shadowMap.autoUpdate = false;
+ scene.background = null; scene.overrideMaterial = this.depthMat;
+ r.setRenderTarget(this.rt); r.setClearColor(0x000000, 0); r.clear();
+ r.render(scene, this.cam);
+ scene.overrideMaterial = prevOv; scene.background = prevBg;
+ for (let i = 0; i < 2; i++) {
+ this.blurH.material.uniforms.tDiffuse.value = this.rt.texture; this.blurH.material.uniforms.h.value = this.blur / 256 * (i + 1);
+ r.setRenderTarget(this.rt2); this.blurH.render(r);
+ this.blurV.material.uniforms.tDiffuse.value = this.rt2.texture; this.blurV.material.uniforms.v.value = this.blur / 256 * (i + 1);
+ r.setRenderTarget(this.rt); this.blurV.render(r);
+ }
+ r.setRenderTarget(prevRT); r.setClearColor(prevClear, prevAlpha);
+ r.shadowMap.autoUpdate = prevAuto;
+ this.hidden.forEach((o, i) => { o.visible = vis[i]; });
+ }
+}
diff --git a/examples/horologie/studio.js b/examples/horologie/studio.js
new file mode 100644
index 0000000..c6d21b1
--- /dev/null
+++ b/examples/horologie/studio.js
@@ -0,0 +1,43 @@
+// Studio for metals on ivory: long softboxes over a mid-dark dome so polished parts carry both
+// bright strip highlights and deep reflections. Shared by the page and the lab.
+import { THREE, studioEnvironment } from '../../src/core/engine.js';
+
+export function makeEnv(renderer, { front = 1.4, dome = 1 } = {}) {
+ return studioEnvironment(renderer, {
+ top: new THREE.Color(0x6e6e74).multiplyScalar(dome).getHex(), bottom: 0x121214,
+ panels: [
+ { pos: [0, 8, 2], size: [14, 1.6], intensity: 7, color: 0xffffff }, // long overhead strip
+ { pos: [2, 7, -3], size: [6, 4], intensity: 2.2, color: 0xfffaf4 }, // broad overhead box
+ { pos: [-8, 2, 3], size: [1.4, 10], intensity: 5.5, color: 0xfff1e4 }, // warm left strip
+ { pos: [7, 3, -1], size: [1.0, 9], intensity: 4.5, color: 0xe9f0ff }, // cool right strip
+ { pos: [0, 2, 10], size: [9, 5], intensity: front, color: 0xfff6ee }, // front diffuser
+ { pos: [0, 5, -8], size: [10, 1.4], intensity: 4, color: 0xffffff }, // back strip (rims)
+ { pos: [-5, -4, 5], size: [6, 1.2], intensity: 1.6, color: 0xffe8d6 }, // low warm kicker
+ ],
+ blur: 0.035,
+ });
+}
+
+export function makeStudio(renderer, scene, opts = {}) {
+ const env = makeEnv(renderer, opts);
+ scene.environment = env;
+ // A lost/restored context (heavy GPU contention) wipes the PMREM target: rebuild it.
+ renderer.domElement.addEventListener('webglcontextrestored', () => { scene.environment = makeEnv(renderer, opts); });
+ scene.environmentIntensity = 1;
+ const key = new THREE.DirectionalLight(0xfff3e6, 2.6);
+ key.position.set(-3.5, 6, 5);
+ key.castShadow = true;
+ key.shadow.mapSize.set(2048, 2048);
+ Object.assign(key.shadow.camera, { left: -3.6, right: 3.6, top: 3.6, bottom: -3.6, near: 0.5, far: 24 });
+ key.shadow.bias = -0.0002; key.shadow.normalBias = 0.004; key.shadow.radius = 2;
+ scene.add(key, key.target);
+ const rim = new THREE.DirectionalLight(0xdce6ff, 1.6);
+ rim.position.set(5, 2.5, -6);
+ scene.add(rim, rim.target);
+ const fill = new THREE.HemisphereLight(0xfff6ec, 0x2a2c33, 0.35);
+ scene.add(fill);
+ return { env, key, rim, fill };
+}
+
+// Tone-mapped (Khronos neutral) HDR value that lands on ivory #f3efe7 after the post stack.
+export const IVORY_HDR = new THREE.Color(1.114, 1.073, 0.995);
diff --git a/examples/horologie/style.css b/examples/horologie/style.css
new file mode 100644
index 0000000..eec8d73
--- /dev/null
+++ b/examples/horologie/style.css
@@ -0,0 +1,250 @@
+:root {
+ --ivory: #f3efe7;
+ --paper: #ece6db;
+ --navy: #16213d;
+ --ink: #1a2440;
+ --ink-2: rgba(29, 35, 48, .86);
+ --ink-3: rgba(29, 35, 48, .62);
+ --line: rgba(22, 33, 61, .14);
+ --rose: #c89b6d;
+ --rose-deep: #9a6a41;
+ --serif: 'Cormorant Garamond', 'Times New Roman', serif;
+ --sans: 'Montserrat', 'Helvetica Neue', Arial, sans-serif;
+ --pad: clamp(18px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--ivory); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+html.lenis, html.lenis body { height: auto; }
+body { font: 400 19px/1.5 var(--serif); background: transparent; overflow-x: hidden; }
+a { color: inherit; text-decoration: none; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+em { font-style: italic; font-weight: 300; color: var(--rose-deep); }
+.caps { font-family: var(--sans); font-size: 10.5px; line-height: 1.5; letter-spacing: .22em; text-transform: uppercase; font-weight: 500; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, .nav, .reserve, .foot { pointer-events: auto; }
+
+/* ─── Loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--ivory); display: grid; place-content: center; justify-items: center; gap: 10px; color: var(--navy); }
+.loader-gauge { width: 190px; height: 190px; overflow: visible; }
+.lg-track { fill: none; stroke: var(--line); stroke-width: 1; }
+.lg-fill { fill: none; stroke: var(--rose); stroke-width: 1.6; stroke-linecap: round; transform: rotate(-90deg); transform-origin: 100px 100px;
+ stroke-dasharray: 540.35; stroke-dashoffset: calc(540.35 * (1 - var(--p, 0))); transition: stroke-dashoffset .2s linear; }
+.lg-ticks line { stroke: var(--ink-3); stroke-width: .8; }
+.lg-balance { transform-origin: 100px 100px; animation: balance .25s cubic-bezier(.45, 0, .55, 1) infinite alternate; color: var(--navy); }
+.lg-spring { color: var(--rose-deep); opacity: .8; transform-origin: 100px 100px; animation: breathe .25s cubic-bezier(.45, 0, .55, 1) infinite alternate; }
+@keyframes balance { from { transform: rotate(-150deg); } to { transform: rotate(150deg); } }
+@keyframes breathe { from { transform: rotate(-40deg) scale(.96); } to { transform: rotate(40deg) scale(1.04); } }
+.loader-h { font: 300 44px/1 var(--serif); font-variant-numeric: lining-nums tabular-nums; margin-top: 8px; }
+.loader-h small { font-size: 20px; margin-left: 4px; color: var(--ink-3); }
+.loader-line { color: var(--ink-3); }
+
+/* ─── Nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 20px var(--pad); color: var(--navy); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav { transition: color .5s; }
+.nav.on-dark { color: #f3efe7; } .nav.on-dark .links a, .nav.on-dark .sound, .nav.on-dark .brand-sub { color: rgba(243, 239, 231, .72); }
+.nav.on-dark .btn-line { color: #f3efe7; box-shadow: inset 0 0 0 1px rgba(243, 239, 231, .4); background: rgba(22, 33, 61, .3); }
+.brand { display: flex; align-items: center; gap: 12px; justify-self: start; }
+.brand svg { width: 28px; height: 28px; color: var(--rose-deep); }
+.brand-name { font: 500 27px/1 var(--serif); letter-spacing: .08em; }
+.brand-sub { color: var(--ink-3); font-size: 9px; padding-left: 12px; border-left: 1px solid var(--line); }
+.links { display: flex; gap: 36px; }
+.links a { font: 500 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink-2); position: relative; padding: 6px 0; transition: color .3s; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: var(--rose); transform: scaleX(0); transform-origin: right; transition: transform .5s cubic-bezier(.2, .8, .2, 1); }
+.links a:hover { color: var(--navy); }
+.links a:hover::after { transform: scaleX(1); transform-origin: left; }
+.nav-r { justify-self: end; display: flex; align-items: center; gap: 22px; }
+.sound { display: flex; align-items: center; gap: 8px; color: var(--ink-2); font-size: 9.5px; }
+.sound i { width: 16px; height: 10px; background: linear-gradient(90deg, currentColor 0 1px, transparent 1px 3px) 0 50% / 3px 100% repeat-x; opacity: .7;
+ -webkit-mask: linear-gradient(0deg, #000 0 100%); animation: eq 1s steps(4) infinite; }
+.sound[aria-pressed="false"] i { animation: none; transform: scaleY(.25); }
+@keyframes eq { 0% { transform: scaleY(.4); } 50% { transform: scaleY(1); } 100% { transform: scaleY(.6); } }
+.btn { display: inline-flex; align-items: center; justify-content: center; height: 46px; padding: 0 26px; border-radius: 999px; white-space: nowrap;
+ font: 500 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; transition: background .4s, color .4s, box-shadow .4s; }
+.btn-line { box-shadow: inset 0 0 0 1px rgba(22, 33, 61, .32); color: var(--navy); background: rgba(243, 239, 231, .5); backdrop-filter: blur(10px); }
+.btn-line:hover { box-shadow: inset 0 0 0 1px var(--navy); background: var(--navy); color: var(--ivory); }
+.btn-solid { background: var(--navy); color: var(--ivory); }
+.btn-solid:hover { background: #22305a; box-shadow: 0 16px 40px -12px rgba(22, 33, 61, .45); }
+.btn-text { display: inline-flex; gap: 10px; align-items: center; color: var(--navy); padding: 8px 0; border-bottom: 1px solid var(--rose); }
+
+/* ─── Hero ───────────────────────────────────────────────── */
+.hero { position: relative; height: 100vh; min-height: 640px; padding: 0 var(--pad); display: grid; align-content: center; }
+.hero-inner { max-width: min(720px, 50vw); margin-top: 2vh; }
+.eyebrow { color: var(--rose-deep); margin-bottom: 26px; }
+.hero-title { font: 300 clamp(48px, 6.2vw, 112px)/.93 var(--serif); letter-spacing: -.028em; color: var(--navy); }
+.hero-title .ln { display: block; }
+.hero-title em { color: var(--rose-deep); font-weight: 300; }
+.hero-lede { max-width: 25em; margin: 30px 0 38px; font-size: clamp(18px, 1.35vw, 21px); line-height: 1.5; color: var(--ink-2); }
+.hero-cta { display: flex; align-items: center; gap: 34px; flex-wrap: wrap; }
+.hero-spec { position: absolute; right: var(--pad); bottom: 40px; display: flex; gap: 44px; color: var(--ink-2); }
+.hero-spec dt { color: var(--ink-3); font-size: 9px; margin-bottom: 4px; }
+.hero-spec dd { color: var(--navy); }
+.hint { position: absolute; left: var(--pad); bottom: 82px; color: var(--ink-3); display: flex; align-items: center; gap: 12px; white-space: nowrap; }
+.hint-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--rose); box-shadow: 0 0 0 0 rgba(200, 155, 109, .6); animation: ping 2s infinite; display: inline-block; }
+@keyframes ping { 0% { box-shadow: 0 0 0 0 rgba(200, 155, 109, .55); } 80%, 100% { box-shadow: 0 0 0 12px rgba(200, 155, 109, 0); } }
+
+/* ─── Pinned stages ──────────────────────────────────────── */
+.calibre { height: 860vh; position: relative; }
+.finishing { height: 480vh; position: relative; }
+.collection { height: 380vh; position: relative; }
+.atelier { height: 230vh; position: relative; }
+.stage { position: sticky; top: 0; height: 100vh; overflow: hidden; }
+[data-k] { --v: 0; }
+.step, .fin, .fin-head, .col-head, .refs, .refs-head, .at, .cta-inner { opacity: var(--v); transform: translate3d(0, calc((1 - var(--v)) * 22px), 0); visibility: hidden; }
+.is-v { visibility: visible; }
+.step { position: absolute; left: var(--pad); top: 50%; margin-top: -200px; width: min(430px, 33vw); }
+.fig { color: var(--rose-deep); margin-bottom: 20px; display: flex; align-items: center; gap: 14px; }
+.fig::before { content: ''; width: 28px; height: 1px; background: var(--rose); }
+h2 { font: 300 clamp(38px, 3.9vw, 66px)/.98 var(--serif); letter-spacing: -.022em; color: var(--navy); margin-bottom: 22px; }
+.step p:not(.fig):not(.step-hint) { color: var(--ink-2); font-size: clamp(17px, 1.25vw, 20px); }
+.spec { list-style: none; display: flex; gap: 28px; margin-top: 26px; padding-top: 18px; border-top: 1px solid var(--line); color: var(--ink-3); font-size: 9px; }
+.spec b { display: block; font: 400 26px/1 var(--serif); letter-spacing: 0; color: var(--navy); margin-bottom: 6px; text-transform: none; }
+.step-hint { margin-top: 26px; color: var(--navy); display: flex; align-items: center; gap: 12px; }
+.rail { position: absolute; left: calc(var(--pad) * .38); top: 50%; transform: translateY(-50%); list-style: none; display: grid; gap: 14px; color: var(--ink-3); font-size: 9px; opacity: var(--rail, 0); transition: opacity .5s; }
+.rail li { position: relative; transition: color .4s; }
+.rail li.on { color: var(--navy); }
+.rail li.on::before { content: ''; position: absolute; left: -12px; top: 50%; width: 5px; height: 5px; margin-top: -3px; border-radius: 50%; background: var(--rose); }
+
+/* copy stays legible when metal passes behind it */
+.stage h2, .stage p, .cta h2, .cta p { text-shadow: 0 0 16px rgba(243, 239, 231, .92), 0 0 3px rgba(243, 239, 231, .75); }
+
+/* finishing */
+.fin-head { position: absolute; left: var(--pad); top: 13vh; width: min(560px, 42vw); padding: 26px 30px 6px; background: rgba(243, 239, 231, .74); backdrop-filter: blur(14px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px rgba(22, 33, 61, .1), 0 30px 70px -40px rgba(22, 33, 61, .45); }
+.fin { position: absolute; left: var(--pad); bottom: 11vh; width: min(420px, 34vw); padding: 28px 30px 30px; background: rgba(243, 239, 231, .72); backdrop-filter: blur(14px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px rgba(22, 33, 61, .1), 0 30px 70px -40px rgba(22, 33, 61, .45); }
+.fin h3 { font: 400 34px/1 var(--serif); color: var(--navy); margin: 16px 0 12px; }
+.fin p { color: var(--ink-2); font-size: 18px; }
+.fin-n { display: flex; align-items: baseline; gap: 14px; padding-bottom: 14px; border-bottom: 1px solid var(--line); }
+.fin-n b { font: 300 46px/1 var(--serif); color: var(--rose-deep); }
+.fin-n span { color: var(--ink-3); font-size: 9px; }
+
+/* collection */
+.col-head { position: absolute; left: 50%; bottom: 8vh; width: min(760px, 86vw); margin-left: calc(min(760px, 86vw) / -2); text-align: center; }
+.col-head h2 { margin-bottom: 16px; }
+.col-head .fig { justify-content: center; }
+.col-head .fig::after { content: ''; width: 28px; height: 1px; background: var(--rose); }
+.col-head p:not(.fig) { color: var(--ink-2); max-width: 36em; margin: 0 auto; }
+.refs { position: absolute; left: var(--pad); right: var(--pad); bottom: 7vh; display: grid; grid-template-columns: repeat(3, 1fr); gap: 3vw; }
+.refs-head { position: absolute; left: 0; right: 0; top: 12vh; text-align: center; }
+.refs-head .fig { justify-content: center; }
+.refs-head .fig::after { content: ''; width: 28px; height: 1px; background: var(--rose); }
+.ref { text-align: center; padding-top: 18px; border-top: 1px solid var(--line); }
+.ref-n { color: var(--ink-3); font-size: 9px; }
+.ref h3 { font: 300 40px/1 var(--serif); color: var(--navy); margin: 10px 0 8px; font-style: italic; }
+.ref p:not(.caps):not(.price) { color: var(--ink-2); font-size: 16.5px; max-width: 22em; margin: 0 auto; line-height: 1.4; }
+.price { margin-top: 12px; font: 500 11px/1 var(--sans); letter-spacing: .22em; color: var(--rose-deep); }
+
+/* atelier */
+.at { position: absolute; left: var(--pad); top: 50%; transform: translate3d(0, calc(-50% + (1 - var(--v)) * 22px), 0); width: min(520px, 40vw); }
+.at > p:not(.fig):not(.bench) { color: var(--ink-2); font-size: clamp(17px, 1.3vw, 20px); }
+.stats { display: grid; grid-template-columns: repeat(2, 1fr); gap: 26px 30px; margin: 34px 0 28px; padding-top: 26px; border-top: 1px solid var(--line); }
+.stats dt { font: 300 58px/1 var(--serif); color: var(--navy); letter-spacing: -.02em; }
+.stats dd { color: var(--ink-3); font-size: 9px; margin-top: 8px; }
+.bench { color: var(--ink-3); font-size: 9px; line-height: 2; }
+
+/* cta + footer */
+.cta { position: relative; height: 110vh; display: grid; align-content: center; padding: 0 var(--pad); }
+.cta-inner { width: min(560px, 44vw); }
+.cta-inner > p:not(.fig) { color: var(--ink-2); max-width: 27em; }
+.cta-inner h2 { font-size: clamp(44px, 5vw, 84px); }
+.cta-row { display: flex; gap: 34px; align-items: center; margin-top: 36px; flex-wrap: wrap; }
+.foot { position: relative; background: var(--navy); color: #e9e3d7; padding: 12vh var(--pad) 90px; }
+.foot-top { display: flex; justify-content: space-between; align-items: flex-end; gap: 40px; flex-wrap: wrap; border-bottom: 1px solid rgba(233, 227, 215, .16); padding-bottom: 50px; }
+.foot-word { font: 300 clamp(90px, 16vw, 260px)/.8 var(--serif); letter-spacing: -.04em; color: #f3efe7; }
+.foot-line { font: 300 clamp(24px, 2.4vw, 38px)/1.1 var(--serif); color: rgba(233, 227, 215, .8); }
+.foot-line em { color: var(--rose); }
+.foot-cols { display: grid; grid-template-columns: repeat(4, 1fr); gap: 30px; margin-top: 40px; color: rgba(233, 227, 215, .56); font-size: 9.5px; line-height: 2.1; }
+.foot-cols a:hover { color: #fff; }
+
+/* ─── Hero dial scale (anchored to the 3D watch) ─────────── */
+.orbit { position: fixed; left: 0; top: 0; width: 400px; height: 400px; z-index: 1; pointer-events: none; transform-origin: 0 0; opacity: 0; overflow: visible; }
+.ob-c { fill: none; stroke: rgba(22, 33, 61, .16); stroke-width: .6; }
+.ob-ticks line { stroke: rgba(22, 33, 61, .28); stroke-width: .5; }
+.ob-ticks line.b { stroke: var(--rose-deep); stroke-width: .8; }
+.ob-rot { transform-origin: 200px 200px; }
+.ob-dot { fill: var(--rose); }
+.ob-t { font: 500 7px/1 var(--sans); letter-spacing: .32em; text-transform: uppercase; fill: rgba(22, 33, 61, .42); }
+
+/* ─── 3D-anchored labels ─────────────────────────────────── */
+.labels { position: fixed; inset: 0; z-index: 6; pointer-events: none; }
+.leaders { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.leaders path { fill: none; stroke: rgba(22, 33, 61, .5); stroke-width: 1; }
+.leaders circle.dot { fill: var(--navy); }
+.leaders circle.ring { fill: none; stroke: rgba(22, 33, 61, .4); stroke-width: 1; }
+.label { position: absolute; left: 0; top: 0; white-space: nowrap; will-change: transform, opacity; opacity: 0; }
+.leaders path, .leaders circle { opacity: 0; }
+.label b { display: block; font: 600 9.5px/1.2 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--navy); }
+.label span { display: block; font: italic 400 17px/1.25 var(--serif); color: var(--rose-deep); margin-top: 3px; }
+.label.r { text-align: left; } .label.l { text-align: right; }
+
+/* ─── Winding ────────────────────────────────────────────── */
+.crown-hint { position: fixed; left: 0; top: 0; z-index: 7; pointer-events: none; opacity: 0; transition: opacity .5s; }
+.crown-hint.on { opacity: 1; }
+.crown-hint i { position: absolute; left: -26px; top: -26px; width: 52px; height: 52px; border-radius: 50%; box-shadow: inset 0 0 0 1px var(--rose-deep); animation: crownPing 1.8s cubic-bezier(.2, .8, .2, 1) infinite; }
+.crown-hint span { position: absolute; left: 36px; top: -7px; color: var(--navy); white-space: nowrap; }
+.crown-hint b { position: absolute; left: -44px; top: -44px; width: 88px; height: 88px; border-radius: 50%; opacity: 0; transform: scale(.7);
+ background: repeating-conic-gradient(from 0deg, var(--rose-deep) 0 1.2deg, transparent 1.2deg 12deg);
+ -webkit-mask: radial-gradient(circle, transparent 36px, #000 37px, #000 43px, transparent 44px); mask: radial-gradient(circle, transparent 36px, #000 37px, #000 43px, transparent 44px);
+ transition: opacity .35s, transform .5s cubic-bezier(.2, .8, .2, 1); animation: crownTurn 1.1s linear infinite paused; }
+.crown-hint.winding b { opacity: 1; transform: none; animation-play-state: running; }
+.crown-hint.winding i { animation-duration: .7s; }
+.crown-hint.winding span { left: 54px; color: var(--rose-deep); font-variant-numeric: tabular-nums; }
+@keyframes crownTurn { to { transform: rotate(-360deg); } }
+@keyframes crownPing { 0% { transform: scale(.6); opacity: 1; } 100% { transform: scale(1.5); opacity: 0; } }
+.reserve { position: fixed; left: var(--pad); bottom: 66px; z-index: 12; display: flex; align-items: center; gap: 16px; opacity: 0; transform: translateY(12px); transition: opacity .6s, transform .6s; pointer-events: none; }
+.reserve.on { opacity: 1; transform: none; pointer-events: auto; }
+.reserve-btn { position: relative; width: 92px; height: 92px; border-radius: 50%; background: rgba(243, 239, 231, .7); backdrop-filter: blur(12px);
+ box-shadow: 0 20px 50px -26px rgba(22, 33, 61, .5), inset 0 0 0 1px rgba(22, 33, 61, .1); touch-action: none; -webkit-user-select: none; user-select: none; transition: transform .3s; }
+.reserve-btn:active, .reserve.holding .reserve-btn { transform: scale(.96); }
+.reserve-btn svg { position: absolute; inset: 0; width: 100%; height: 100%; }
+.rv-track { fill: none; stroke: var(--line); stroke-width: 2; }
+.rv-fill { fill: none; stroke: var(--rose); stroke-width: 2.4; stroke-linecap: round; transform: rotate(-90deg); transform-origin: 60px 60px; stroke-dasharray: 314.16; stroke-dashoffset: calc(314.16 * (1 - var(--w, .3))); }
+.rv-ticks line { stroke: var(--ink-3); stroke-width: 1; }
+.rv-val { position: absolute; inset: 0; display: grid; place-content: center; grid-auto-flow: column; align-items: baseline; font: 300 30px/1 var(--serif); color: var(--navy); font-variant-numeric: lining-nums tabular-nums; }
+.rv-val small { font-size: 15px; color: var(--ink-3); margin-left: 2px; }
+.rv-label { display: grid; gap: 4px; color: var(--ink-3); font-size: 9px; }
+.rv-label em { font: italic 400 17px/1 var(--serif); letter-spacing: 0; text-transform: none; color: var(--rose-deep); }
+.reserve.full .rv-fill { stroke: var(--navy); }
+.toast { position: fixed; left: 50%; bottom: 44px; z-index: 40; transform: translate(-50%, 16px); padding: 14px 24px; border-radius: 999px; background: var(--navy); color: var(--ivory);
+ opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; white-space: nowrap; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+@media (max-width: 900px) {
+ .links, .brand-sub, .sound span { display: none; }
+ .nav { grid-template-columns: 1fr auto; padding: 16px 18px; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 9px; letter-spacing: .16em; }
+ .hero { align-content: start; padding-top: 16vh; }
+ .hero-inner { max-width: none; }
+ .hero-title { font-size: clamp(42px, 12vw, 64px); }
+ .hero-lede { font-size: 17px; margin: 18px 0 22px; max-width: 21em; }
+ .hero-spec { display: none; }
+ .hero-cta { gap: 22px; } .hero-cta .btn-text { display: none; }
+ .hint { display: none; }
+ .step, .fin, .at { left: 18px; right: 18px; width: auto; top: auto; bottom: 70px; margin-top: 0; }
+ .step { padding: 22px 20px; background: rgba(243, 239, 231, .78); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--line); }
+ .step h2, .at h2 { font-size: 32px; margin-bottom: 12px; }
+ .step p:not(.fig):not(.step-hint) { font-size: 16px; line-height: 1.4; }
+ .step .spec { display: none; }
+ .fin { padding: 20px; bottom: 70px; } .fin h3 { font-size: 28px; } .fin p { font-size: 16px; }
+ .fin-head { top: 11vh; left: 18px; right: 18px; width: auto; } .fin-head h2 { font-size: 34px; }
+ .rail { display: none; }
+ .col-head { bottom: 76px; } .col-head h2 { font-size: 32px; } .col-head p:not(.fig) { font-size: 16px; }
+ .refs { grid-template-columns: 1fr; gap: 10px; bottom: 76px; }
+ .refs-head { top: 10vh; } .refs-head h2 { font-size: 34px; }
+ .ref { display: grid; grid-template-columns: auto 1fr auto; align-items: baseline; gap: 12px; text-align: left; padding-top: 10px; }
+ .ref h3 { font-size: 26px; margin: 0; order: -1; } .ref p:not(.caps):not(.price) { display: none; } .price { margin: 0; }
+ .at { top: auto; transform: translate3d(0, calc((1 - var(--v)) * 22px), 0); bottom: 70px; padding: 20px; background: rgba(243, 239, 231, .8); backdrop-filter: blur(12px); }
+ .at > p:not(.fig):not(.bench) { display: none; }
+ .stats { margin: 16px 0 0; padding-top: 16px; gap: 14px; } .stats dt { font-size: 38px; }
+ .bench { display: none; }
+ .cta { align-content: end; padding-bottom: 12vh; }
+ .cta-inner { width: auto; }
+ .cta-inner h2 { font-size: 40px; }
+ .foot-cols { grid-template-columns: 1fr 1fr; }
+ .reserve { left: auto; right: 16px; bottom: auto; top: 76px; }
+ .reserve-btn { width: 76px; height: 76px; } .rv-val { font-size: 24px; } .rv-label { display: none; }
+ .label span { font-size: 14px; } .label b { font-size: 8.5px; }
+}
diff --git a/examples/keeper/audio.js b/examples/keeper/audio.js
new file mode 100644
index 0000000..27b5225
--- /dev/null
+++ b/examples/keeper/audio.js
@@ -0,0 +1,81 @@
+// Optional storm soundscape, synthesised (no files): rain hiss, wind, surf rumble, thunder, fog horn.
+// Never starts on its own — only after the visitor turns it on.
+export class StormAudio {
+ constructor() { this.on = false; this.ctx = null; this.level = { storm: 1 }; }
+
+ _noise(seconds = 4, brown = false) {
+ const ctx = this.ctx, len = ctx.sampleRate * seconds, buf = ctx.createBuffer(2, len, ctx.sampleRate);
+ for (let c = 0; c < 2; c++) {
+ const d = buf.getChannelData(c);
+ let last = 0;
+ for (let i = 0; i < len; i++) {
+ const w = Math.random() * 2 - 1;
+ if (brown) { last = (last + 0.02 * w) / 1.02; d[i] = last * 3.5; } else d[i] = w;
+ }
+ }
+ const src = ctx.createBufferSource(); src.buffer = buf; src.loop = true;
+ return src;
+ }
+
+ _build() {
+ const ctx = this.ctx = new AudioContext();
+ this.master = ctx.createGain(); this.master.gain.value = 0; this.master.connect(ctx.destination);
+ // rain: bright hiss
+ const rain = this._noise(3); const rf = ctx.createBiquadFilter(); rf.type = 'highpass'; rf.frequency.value = 1800;
+ this.rainG = ctx.createGain(); this.rainG.gain.value = 0.09;
+ rain.connect(rf).connect(this.rainG).connect(this.master); rain.start();
+ // wind: band-passed noise with a slow howl
+ const wind = this._noise(5); const wf = ctx.createBiquadFilter(); wf.type = 'bandpass'; wf.frequency.value = 420; wf.Q.value = 1.4;
+ const lfo = ctx.createOscillator(); lfo.frequency.value = 0.09; const lg = ctx.createGain(); lg.gain.value = 260; lfo.connect(lg).connect(wf.frequency); lfo.start();
+ this.windG = ctx.createGain(); this.windG.gain.value = 0.12;
+ wind.connect(wf).connect(this.windG).connect(this.master); wind.start();
+ // surf: brown rumble with swells
+ const surf = this._noise(6, true); const sf = ctx.createBiquadFilter(); sf.type = 'lowpass'; sf.frequency.value = 380;
+ this.surfG = ctx.createGain(); this.surfG.gain.value = 0.5;
+ const sl = ctx.createOscillator(); sl.frequency.value = 0.13; const sg = ctx.createGain(); sg.gain.value = 0.22; sl.connect(sg).connect(this.surfG.gain); sl.start();
+ surf.connect(sf).connect(this.surfG).connect(this.master); surf.start();
+ }
+
+ toggle() {
+ this.on = !this.on;
+ if (this.on && !this.ctx) this._build();
+ if (!this.ctx) return this.on;
+ this.ctx.resume();
+ this.master.gain.cancelScheduledValues(this.ctx.currentTime);
+ this.master.gain.setTargetAtTime(this.on ? 0.8 : 0, this.ctx.currentTime, 0.4);
+ return this.on;
+ }
+
+ setStorm(s) {
+ if (!this.ctx) return;
+ const t = this.ctx.currentTime;
+ this.rainG.gain.setTargetAtTime(0.1 * s * s, t, 0.5);
+ this.windG.gain.setTargetAtTime(0.03 + 0.12 * s, t, 0.5);
+ this.surfG.gain.setTargetAtTime(0.18 + 0.4 * s, t, 0.5);
+ }
+
+ thunder(delay = 1.5, power = 1) {
+ if (!this.on || !this.ctx) return;
+ const ctx = this.ctx, t = ctx.currentTime + delay;
+ const n = this._noise(4, true); n.loop = false;
+ const f = ctx.createBiquadFilter(); f.type = 'lowpass'; f.frequency.setValueAtTime(900, t); f.frequency.exponentialRampToValueAtTime(90, t + 3.5);
+ const g = ctx.createGain(); g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(0.9 * power, t + 0.08);
+ g.gain.setTargetAtTime(0.35 * power, t + 0.3, 0.3); g.gain.exponentialRampToValueAtTime(0.001, t + 3.8);
+ n.connect(f).connect(g).connect(this.master); n.start(t); n.stop(t + 4);
+ }
+
+ /** The fog signal: a low, two-tone diaphone. */
+ horn() {
+ if (!this.on || !this.ctx) return;
+ const ctx = this.ctx, t = ctx.currentTime + 0.1;
+ for (const [f0, at, dur] of [[98, 0, 1.6], [73, 1.7, 2.2]]) {
+ const o = ctx.createOscillator(); o.type = 'sawtooth'; o.frequency.value = f0;
+ const o2 = ctx.createOscillator(); o2.type = 'square'; o2.frequency.value = f0 * 1.005;
+ const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 520; lp.Q.value = 3;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0, t + at); g.gain.linearRampToValueAtTime(0.18, t + at + 0.25);
+ g.gain.setValueAtTime(0.18, t + at + dur - 0.3); g.gain.linearRampToValueAtTime(0, t + at + dur);
+ o.connect(lp); o2.connect(lp); lp.connect(g).connect(this.master);
+ o.start(t + at); o2.start(t + at); o.stop(t + at + dur + 0.1); o2.stop(t + at + dur + 0.1);
+ }
+ }
+}
diff --git a/examples/keeper/beams.js b/examples/keeper/beams.js
new file mode 100644
index 0000000..890c299
--- /dev/null
+++ b/examples/keeper/beams.js
@@ -0,0 +1,201 @@
+// Lighthouse beams as a post effect. Unlike a generic raymarch, each view ray is first intersected
+// analytically with the two beam cones, so all samples land inside the light: crisp shafts to the horizon
+// for ~24 samples a pixel. Rain sheets and wind-blown mist modulate the density; Henyey-Greenstein
+// phase makes the beam blaze when it swings toward you. An analytic point-light integral adds the halo
+// around the lantern, and a glare streak fires when a beam crosses the lens.
+import * as THREE from 'three';
+import { Effect, EffectAttribute, BlendFunction } from 'postprocessing';
+
+const frag = /* glsl */`
+uniform mat4 uProjInv;
+uniform mat4 uCamWorld;
+uniform vec3 uCamPos;
+uniform vec3 uLamp;
+uniform vec3 uDir0;
+uniform vec3 uDir1;
+uniform vec2 uCos;
+uniform vec3 uCol;
+uniform float uDensity;
+uniform float uRange;
+uniform float uTime;
+uniform float uRain;
+uniform float uMaxDist;
+uniform vec3 uWind;
+uniform vec3 uHalo;
+uniform vec3 uGlare;
+uniform vec2 uLampUV;
+uniform float uLampDist;
+uniform float uAspect;
+uniform float uFlash;
+
+float h31(vec3 p){ p = fract(p * 0.3183099 + .1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
+float vn(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(h31(i), h31(i + vec3(1,0,0)), f.x), mix(h31(i + vec3(0,1,0)), h31(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(h31(i + vec3(0,0,1)), h31(i + vec3(1,0,1)), f.x), mix(h31(i + vec3(0,1,1)), h31(i + vec3(1,1,1)), f.x), f.y), f.z);
+}
+
+// Is the lantern visible from the camera? (average a few depth taps so glazing bars don't flicker it)
+float lampVis(){
+ if (uLampUV.x < 0.0 || uLampUV.x > 1.0 || uLampUV.y < 0.0 || uLampUV.y > 1.0) return 0.0;
+ float v = 0.0;
+ for (int i = 0; i < 5; i++) {
+ vec2 o = i == 0 ? vec2(0.0) : vec2(cos(float(i) * 1.5708), sin(float(i) * 1.5708)) * 0.006;
+ vec2 q = uLampUV + o;
+ vec4 c = vec4(q * 2. - 1., readDepth(q) * 2. - 1., 1.);
+ vec4 p = uProjInv * c; p /= p.w;
+ v += step(uLampDist - 1.3, length(p.xyz));
+ }
+ return v / 5.0;
+}
+
+vec2 isect(vec2 a, vec2 b){ return vec2(max(a.x, b.x), min(a.y, b.y)); }
+
+// Interval of the ray inside the forward nappe of a cone (apex A, axis D, cos half-angle c), clipped to [0, tmax].
+vec2 coneSpan(vec3 ro, vec3 rd, vec3 A, vec3 D, float c, float tmax){
+ vec3 co = ro - A;
+ float rdD = dot(rd, D), coD = dot(co, D);
+ float c2 = c * c;
+ float a = rdD * rdD - c2;
+ float b = 2.0 * (rdD * coD - dot(rd, co) * c2);
+ float cc = coD * coD - dot(co, co) * c2;
+ vec2 lim = vec2(0.0, tmax);
+ // forward half-line: dot(P - A, D) > 0
+ vec2 fwd = abs(rdD) < 1e-5 ? (coD > 0.0 ? vec2(-1e9, 1e9) : vec2(1.0, 0.0))
+ : (rdD > 0.0 ? vec2(-coD / rdD, 1e9) : vec2(-1e9, -coD / rdD));
+ float disc = b * b - 4.0 * a * cc;
+ if (disc < 0.0) {
+ if (cc > 0.0) return isect(isect(vec2(-1e9, 1e9), fwd), lim);
+ return vec2(1.0, 0.0);
+ }
+ float sq = sqrt(disc);
+ float r0 = (-b - sq) / (2.0 * a), r1 = (-b + sq) / (2.0 * a);
+ if (r0 > r1) { float t = r0; r0 = r1; r1 = t; }
+ if (a < 0.0) return isect(isect(vec2(r0, r1), fwd), lim);
+ vec2 p1 = isect(isect(vec2(-1e9, r0), fwd), lim);
+ vec2 p2 = isect(isect(vec2(r1, 1e9), fwd), lim);
+ return p1.y > p1.x ? p1 : p2;
+}
+
+float hg(float c, float g){ float g2 = g * g; return (1.0 - g2) / pow(1.0 + g2 - 2.0 * g * c, 1.5) * 0.0796; }
+
+vec3 marchBeam(vec3 ro, vec3 rd, vec3 D, float tmax, float jit){
+ vec2 s = coneSpan(ro, rd, uLamp, D, uCos.x, tmax);
+ if (s.y <= s.x) return vec3(0.0);
+ const int STEPS = 24;
+ float len = s.y - s.x;
+ // spend samples near the lamp where the beam is narrow and bright
+ float acc = 0.0;
+ float prevT = s.x;
+ for (int i = 0; i < STEPS; i++) {
+ float u = (float(i) + jit) / float(STEPS);
+ float t = s.x + len * u * u;
+ float dt = len * (2.0 * u) / float(STEPS);
+ vec3 p = ro + rd * t;
+ vec3 l = p - uLamp;
+ float dist = max(length(l), 1e-3);
+ vec3 T = l / dist;
+ float cosA = dot(T, D);
+ float cone = smoothstep(uCos.x, uCos.y, cosA);
+ // hot core down the middle of the shaft
+ cone *= 0.55 + 0.45 * smoothstep(uCos.y, 1.0, cosA);
+ float att = 1.0 / (1.0 + dist * dist * uRange) * smoothstep(0.3, 1.2, dist);
+ vec3 q = p * 0.33 + uWind * uTime * 1.6;
+ float n = vn(q) * 0.6 + vn(q * 2.7 + 3.7) * 0.4;
+ // rain: thin fast streaks slanted by the wind, plus slow sheets of heavier rain
+ vec3 rq = vec3(p.x * 5.5 + p.y * 1.6, p.y * 0.28 + uTime * 13.0, p.z * 5.5);
+ float streak = vn(rq);
+ streak = smoothstep(0.55, 0.95, streak);
+ float sheet = vn(vec3(p.x * 0.12 + uTime * 0.35, p.y * 0.05, p.z * 0.12));
+ float dens = uDensity * (0.55 + 0.9 * n) * mix(1.0, 0.35 + 2.4 * streak + 0.6 * sheet, uRain);
+ float ph = hg(dot(T, -rd), 0.38) * 6.0 + 0.5;
+ acc += cone * att * dens * ph * dt;
+ }
+ return uCol * acc;
+}
+
+void mainImage(const in vec4 inputColor, const in vec2 uv, const in float depth, out vec4 outputColor) {
+ vec4 clip = vec4(uv * 2. - 1., depth * 2. - 1., 1.);
+ vec4 vp = uProjInv * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vec4(vp.xyz, 1.)).xyz;
+ vec3 ro = uCamPos;
+ vec3 rd = wp - ro;
+ float sceneD = length(rd);
+ rd /= sceneD;
+ float tmax = min(sceneD, uMaxDist);
+ float jit = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))) + uTime * 0.618);
+ vec3 acc = marchBeam(ro, rd, uDir0, tmax, jit) + marchBeam(ro, rd, uDir1, tmax, jit);
+
+ // Halo: analytic in-scattering of the lantern (the glass itself doesn't count as an occluder).
+ vec3 toL = uLamp - ro;
+ float tc = dot(toL, rd);
+ float dp = max(length(ro + rd * tc - uLamp), 0.05);
+ float T = sceneD > uLampDist - 1.2 ? 1e5 : sceneD;
+ float hi = (atan((T - tc) / dp) - atan(-tc / dp)) / dp;
+ acc += uHalo * hi;
+
+ // Glare: a beam crossing the lens flares the whole frame and streaks horizontally.
+ if (uGlare.r + uGlare.g > 0.001) {
+ vec2 dl = (uv - uLampUV) * vec2(uAspect, 1.0);
+ float streak = exp(-abs(dl.y) * 140.0) * exp(-abs(dl.x) * 2.4);
+ float star = exp(-length(dl) * 10.0);
+ acc += uGlare * lampVis() * (streak * 1.3 + star * 0.8 + 0.012);
+ }
+
+ outputColor = vec4(inputColor.rgb + acc, inputColor.a);
+}`;
+
+export class BeamEffect extends Effect {
+ constructor(camera, { density = 0.06, range = 0.00035, maxDist = 900, cone = [0.084, 0.05] } = {}) {
+ super('BeamEffect', frag, {
+ attributes: EffectAttribute.DEPTH,
+ blendFunction: BlendFunction.NORMAL,
+ uniforms: new Map([
+ ['uProjInv', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamWorld', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamPos', new THREE.Uniform(new THREE.Vector3())],
+ ['uLamp', new THREE.Uniform(new THREE.Vector3())],
+ ['uDir0', new THREE.Uniform(new THREE.Vector3(1, 0, 0))],
+ ['uDir1', new THREE.Uniform(new THREE.Vector3(-1, 0, 0))],
+ ['uCos', new THREE.Uniform(new THREE.Vector2(Math.cos(cone[0]), Math.cos(cone[1])))],
+ ['uCol', new THREE.Uniform(new THREE.Color())],
+ ['uDensity', new THREE.Uniform(density)],
+ ['uRange', new THREE.Uniform(range)],
+ ['uTime', new THREE.Uniform(0)],
+ ['uRain', new THREE.Uniform(1)],
+ ['uMaxDist', new THREE.Uniform(maxDist)],
+ ['uWind', new THREE.Uniform(new THREE.Vector3(0.9, -0.4, 0.3))],
+ ['uHalo', new THREE.Uniform(new THREE.Color())],
+ ['uGlare', new THREE.Uniform(new THREE.Color())],
+ ['uLampUV', new THREE.Uniform(new THREE.Vector2(0.5, 0.5))],
+ ['uLampDist', new THREE.Uniform(10)],
+ ['uAspect', new THREE.Uniform(1.6)],
+ ['uFlash', new THREE.Uniform(0)],
+ ]),
+ });
+ this.camera = camera;
+ this.cone = cone;
+ this._v = new THREE.Vector3();
+ }
+
+ setCone(outer, inner) {
+ this.cone = [outer, inner];
+ this.uniforms.get('uCos').value.set(Math.cos(outer), Math.cos(inner));
+ }
+
+ update(renderer, inputBuffer, dt) {
+ const u = this.uniforms, cam = this.camera;
+ u.get('uProjInv').value.copy(cam.projectionMatrixInverse);
+ u.get('uCamWorld').value.copy(cam.matrixWorld);
+ u.get('uCamPos').value.setFromMatrixPosition(cam.matrixWorld);
+ u.get('uTime').value += dt;
+ u.get('uAspect').value = cam.aspect;
+ const lamp = u.get('uLamp').value;
+ const p = this._v.copy(lamp).applyMatrix4(cam.matrixWorldInverse);
+ const behind = p.z > 0;
+ p.applyMatrix4(cam.projectionMatrix);
+ if (behind) u.get('uLampUV').value.set(-10, -10);
+ else u.get('uLampUV').value.set(p.x * 0.5 + 0.5, p.y * 0.5 + 0.5);
+ u.get('uLampDist').value = lamp.distanceTo(u.get('uCamPos').value);
+ }
+}
diff --git a/examples/keeper/fx.js b/examples/keeper/fx.js
new file mode 100644
index 0000000..eb37686
--- /dev/null
+++ b/examples/keeper/fx.js
@@ -0,0 +1,276 @@
+// Weather: wind-driven rain streaks that only exist where light finds them, spray that bursts off the
+// rock, distress flares, and fractal lightning bolts.
+import { THREE, lerp } from '../../src/core/engine.js';
+
+const LIGHT_GLSL = /* glsl */`
+ uniform vec3 uLamp, uBeamDir[2];
+ uniform vec2 uBeamCos;
+ uniform float uBeamI, uAmb, uFlash;
+ uniform vec3 uFlarePos, uFlareCol;
+ float beamLight(vec3 p){
+ vec3 l = p - uLamp; float d = length(l); vec3 t = l / d;
+ float c = smoothstep(uBeamCos.x, uBeamCos.y, dot(t, uBeamDir[0])) + smoothstep(uBeamCos.x, uBeamCos.y, dot(t, uBeamDir[1]));
+ return c * uBeamI / (1.0 + d * d * 0.0012) * smoothstep(0.5, 2.0, d) + uBeamI * 0.08 / (1.0 + d * d * 0.05);
+ }
+ vec3 flareLight(vec3 p){ vec3 v = uFlarePos - p; return uFlareCol / (1.0 + dot(v, v) * 0.02); }
+`;
+
+export function lightUniforms() {
+ return {
+ uLamp: { value: new THREE.Vector3() },
+ uBeamDir: { value: [new THREE.Vector3(1, 0, 0), new THREE.Vector3(-1, 0, 0)] },
+ uBeamCos: { value: new THREE.Vector2(0.99, 0.997) },
+ uBeamI: { value: 1 },
+ uAmb: { value: 0.02 },
+ uFlash: { value: 0 },
+ uFlarePos: { value: new THREE.Vector3(0, -100, 0) },
+ uFlareCol: { value: new THREE.Color(0, 0, 0) },
+ };
+}
+
+/** Rain: instanced camera-facing streaks in a box that follows the camera. */
+export function createRain(shared, { count = 42000, box = [150, 62, 150] } = {}) {
+ const base = new THREE.PlaneGeometry(1, 1);
+ const geo = new THREE.InstancedBufferGeometry();
+ geo.index = base.index;
+ geo.setAttribute('position', base.getAttribute('position'));
+ const seed = new Float32Array(count * 4);
+ for (let i = 0; i < count * 4; i++) seed[i] = Math.random();
+ geo.setAttribute('seed', new THREE.InstancedBufferAttribute(seed, 4));
+ geo.instanceCount = count;
+ const uniforms = {
+ ...shared,
+ uTime: { value: 0 },
+ uCam: { value: new THREE.Vector3() },
+ uBox: { value: new THREE.Vector3(...box) },
+ uVel: { value: new THREE.Vector3(11, -30, 4) },
+ uAmount: { value: 1 },
+ uLen: { value: 1.1 },
+ uWidth: { value: 0.024 },
+ };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: /* glsl */`
+ ${LIGHT_GLSL}
+ attribute vec4 seed;
+ uniform float uTime, uAmount, uLen, uWidth;
+ uniform vec3 uCam, uBox, uVel;
+ varying float vA; varying vec2 vC; varying vec3 vCol;
+ void main(){
+ vec3 vel = uVel * (0.82 + seed.w * 0.36);
+ vec3 origin = vec3(uCam.x - uBox.x * 0.5, -1.5, uCam.z - uBox.z * 0.5);
+ vec3 p = seed.xyz * uBox + vel * uTime;
+ p = mod(p - origin, uBox) + origin;
+ vec3 dir = normalize(vel);
+ vec3 pos = p - dir * uLen * (0.6 + seed.w * 0.8) * (position.y + 0.5);
+ vec3 toCam = normalize(uCam - pos);
+ vec3 side = normalize(cross(dir, toCam));
+ float camD = length(uCam - pos);
+ pos += side * position.x * uWidth * (1.0 + camD * 0.012);
+ float on = step(seed.w, uAmount) * smoothstep(0.6, 3.0, camD);
+ float b = beamLight(p);
+ vCol = vec3(1.0, 0.86, 0.6) * b * 3.2 + vec3(0.55, 0.65, 0.85) * (uAmb + uFlash * 1.6) + flareLight(p) * 0.5;
+ vA = on * (0.45 + seed.y * 0.55);
+ vC = position.xy + 0.5;
+ gl_Position = projectionMatrix * viewMatrix * vec4(pos, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA; varying vec2 vC; varying vec3 vCol;
+ void main(){
+ float a = (1.0 - abs(vC.x * 2.0 - 1.0)) * smoothstep(0.0, 0.6, vC.y) * smoothstep(1.0, 0.85, vC.y);
+ gl_FragColor = vec4(vCol * a * vA, 1.0);
+ }`,
+ });
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.frustumCulled = false;
+ mesh.renderOrder = 5;
+ return { mesh, uniforms };
+}
+
+/** Spray and spume: CPU particles, soft sprites, lit by the beam, lightning and flares. */
+export function createSpray(shared, { count = 6000 } = {}) {
+ const pos = new Float32Array(count * 3), vel = new Float32Array(count * 3), life = new Float32Array(count), max = new Float32Array(count), size = new Float32Array(count);
+ const alpha = new Float32Array(count);
+ life.fill(-1);
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3).setUsage(THREE.DynamicDrawUsage));
+ geo.setAttribute('aSize', new THREE.BufferAttribute(size, 1).setUsage(THREE.DynamicDrawUsage));
+ geo.setAttribute('aAlpha', new THREE.BufferAttribute(alpha, 1).setUsage(THREE.DynamicDrawUsage));
+ const uniforms = { ...shared, uDpr: { value: 1 }, uH: { value: 900 } };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: /* glsl */`
+ ${LIGHT_GLSL}
+ attribute float aSize, aAlpha;
+ uniform float uDpr, uH;
+ varying float vA; varying vec3 vCol;
+ void main(){
+ vec4 mv = modelViewMatrix * vec4(position, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = aSize * uH * projectionMatrix[1][1] * 0.5 / -mv.z;
+ float b = beamLight(position);
+ vCol = vec3(1.0, 0.9, 0.72) * b * 1.1 + vec3(0.6, 0.7, 0.85) * (uAmb * 2.2 + uFlash * 1.2) + flareLight(position) * 0.4;
+ vA = aAlpha;
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA; varying vec3 vCol;
+ void main(){
+ vec2 c = gl_PointCoord - 0.5;
+ float d = length(c);
+ float a = smoothstep(0.5, 0.0, d);
+ a *= a;
+ gl_FragColor = vec4(vCol * a * vA, 1.0);
+ }`,
+ });
+ const points = new THREE.Points(geo, mat);
+ points.frustumCulled = false;
+ points.renderOrder = 4;
+ let cursor = 0;
+ const api = {
+ points, uniforms,
+ /** Emit a burst at world position p, thrown along (nx, nz) and upward. */
+ burst(p, nx, nz, n = 90, power = 1) {
+ for (let k = 0; k < n; k++) {
+ const i = cursor; cursor = (cursor + 1) % count;
+ pos[i * 3] = p.x + (Math.random() - 0.5) * 1.4;
+ pos[i * 3 + 1] = p.y + Math.random() * 0.4;
+ pos[i * 3 + 2] = p.z + (Math.random() - 0.5) * 1.4;
+ const up = (2.5 + Math.random() * 6) * power;
+ const out = (1 + Math.random() * 3) * power;
+ vel[i * 3] = nx * out + (Math.random() - 0.5) * 1.8;
+ vel[i * 3 + 1] = up;
+ vel[i * 3 + 2] = nz * out + (Math.random() - 0.5) * 1.8;
+ max[i] = life[i] = 0.8 + Math.random() * 1.2;
+ }
+ },
+ update(dt, wind) {
+ for (let i = 0; i < count; i++) {
+ if (life[i] <= 0) { alpha[i] = 0; size[i] = 0; continue; }
+ life[i] -= dt;
+ const k = i * 3;
+ vel[k + 1] -= 12 * dt;
+ vel[k] += (wind.x * 5 - vel[k]) * dt * 0.6;
+ vel[k + 2] += (wind.y * 5 - vel[k + 2]) * dt * 0.6;
+ pos[k] += vel[k] * dt; pos[k + 1] += vel[k + 1] * dt; pos[k + 2] += vel[k + 2] * dt;
+ const f = 1 - life[i] / max[i];
+ const big = (i % 7) === 0;
+ size[i] = big ? lerp(0.6, 3.2, Math.sqrt(f)) : lerp(0.07, 0.22, f);
+ alpha[i] = (big ? 0.07 : 0.3) * (1 - f) * Math.min(1, f * 8) * (pos[k + 1] > -0.4 ? 1 : 0);
+ }
+ geo.attributes.position.needsUpdate = true;
+ geo.attributes.aSize.needsUpdate = true;
+ geo.attributes.aAlpha.needsUpdate = true;
+ },
+ };
+ return api;
+}
+
+/** Lightning bolt: a fractal polyline drawn as a camera-facing ribbon. */
+export function createBolt() {
+ const MAXP = 900;
+ const pa = new Float32Array(MAXP * 2 * 3), pb = new Float32Array(MAXP * 2 * 3), side = new Float32Array(MAXP * 2), wid = new Float32Array(MAXP * 2);
+ const idx = [];
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pa, 3));
+ geo.setAttribute('aNext', new THREE.BufferAttribute(pb, 3));
+ geo.setAttribute('aSide', new THREE.BufferAttribute(side, 1));
+ geo.setAttribute('aW', new THREE.BufferAttribute(wid, 1));
+ const uniforms = { uI: { value: 0 } };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false,
+ vertexShader: /* glsl */`
+ attribute vec3 aNext; attribute float aSide, aW;
+ varying float vS; varying float vW;
+ void main(){
+ vec4 a = modelViewMatrix * vec4(position, 1.0);
+ vec4 b = modelViewMatrix * vec4(aNext, 1.0);
+ vec2 d = normalize(b.xy - a.xy + 1e-5);
+ a.xy += vec2(-d.y, d.x) * aSide * aW * (-a.z) * 0.0026 + vec2(-d.y, d.x) * aSide * 0.35;
+ vS = aSide; vW = aW;
+ gl_Position = projectionMatrix * a;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform float uI; varying float vS; varying float vW;
+ void main(){
+ float a = 1.0 - abs(vS);
+ vec3 c = mix(vec3(0.55, 0.6, 1.0), vec3(1.0), a * a);
+ gl_FragColor = vec4(c * a * uI * 14.0, 1.0);
+ }`,
+ });
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.frustumCulled = false;
+ mesh.visible = false;
+
+ function build(start, end) {
+ const segs = [];
+ const rec = (a, b, disp, depth, w) => {
+ if (depth === 0 || segs.length > MAXP - 4) { segs.push([a, b, w]); return; }
+ const m = a.clone().lerp(b, 0.5 + (Math.random() - 0.5) * 0.1);
+ const len = a.distanceTo(b);
+ m.x += (Math.random() - 0.5) * disp * len; m.z += (Math.random() - 0.5) * disp * len; m.y += (Math.random() - 0.5) * disp * len * 0.3;
+ rec(a, m, disp, depth - 1, w);
+ rec(m, b, disp, depth - 1, w);
+ if (depth > 3 && Math.random() < 0.28 && w > 0.4) {
+ const dir = b.clone().sub(a).multiplyScalar(0.7);
+ dir.x += (Math.random() - 0.5) * len * 0.9; dir.z += (Math.random() - 0.5) * len * 0.9;
+ rec(m, m.clone().add(dir), disp * 1.1, depth - 2, w * 0.45);
+ }
+ };
+ rec(start, end, 0.5, 8, 1);
+ idx.length = 0;
+ let v = 0;
+ for (const [a, b, w] of segs) {
+ for (let s = 0; s < 2; s++) {
+ const i = v + s;
+ pa.set([a.x, a.y, a.z], i * 3); pb.set([b.x, b.y, b.z], i * 3); side[i] = s ? 1 : -1; wid[i] = w * 0.9;
+ }
+ for (let s = 0; s < 2; s++) {
+ const i = v + 2 + s;
+ pa.set([b.x, b.y, b.z], i * 3); pb.set([b.x + (b.x - a.x), b.y + (b.y - a.y), b.z + (b.z - a.z)], i * 3); side[i] = s ? 1 : -1; wid[i] = w * 0.9;
+ }
+ idx.push(v, v + 2, v + 1, v + 1, v + 2, v + 3);
+ v += 4;
+ if (v >= MAXP * 2 - 4) break;
+ }
+ geo.setIndex(idx);
+ for (const k of ['position', 'aNext', 'aSide', 'aW']) geo.attributes[k].needsUpdate = true;
+ }
+ return { mesh, uniforms, build };
+}
+
+/** A flare: a hot sprite with a smoke trail, rising and hanging on the wind. */
+export function createFlare(color) {
+ const mat = new THREE.SpriteMaterial({ color: new THREE.Color(color).multiplyScalar(0), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false });
+ const c = document.createElement('canvas'); c.width = c.height = 64;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
+ grd.addColorStop(0, '#fff'); grd.addColorStop(0.15, 'rgba(255,255,255,.9)'); grd.addColorStop(0.4, 'rgba(255,255,255,.18)'); grd.addColorStop(1, 'rgba(255,255,255,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, 64, 64);
+ mat.map = new THREE.CanvasTexture(c);
+ const sprite = new THREE.Sprite(mat);
+ sprite.scale.setScalar(1.6);
+ sprite.visible = false;
+ const col = new THREE.Color(color);
+ const state = { t: -1, p: new THREE.Vector3(), v: new THREE.Vector3(), power: 0 };
+ return {
+ sprite, color: col, state,
+ fire(from, wind) {
+ state.t = 0; state.p.copy(from); state.v.set(wind.x * 1.5 + (Math.random() - 0.5), 11 + Math.random() * 2, wind.y * 1.5 + (Math.random() - 0.5));
+ sprite.visible = true;
+ },
+ update(dt, wind) {
+ if (state.t < 0) { state.power = 0; sprite.visible = false; return; }
+ state.t += dt;
+ const t = state.t;
+ if (t < 1.7) state.v.y -= 6 * dt; else state.v.y = lerp(state.v.y, -0.9, dt * 2); // parachute
+ state.v.x = lerp(state.v.x, wind.x * 3, dt * 0.5); state.v.z = lerp(state.v.z, wind.y * 3, dt * 0.5);
+ state.p.addScaledVector(state.v, dt);
+ const flick = 0.85 + Math.sin(t * 37) * 0.08 + Math.sin(t * 91) * 0.07;
+ state.power = Math.min(1, t * 6) * (1 - Math.min(1, Math.max(0, (t - 7) / 1.5))) * flick;
+ sprite.position.copy(state.p);
+ mat.color.copy(col).multiplyScalar(state.power * 16);
+ sprite.scale.setScalar(0.55 + state.power * 0.35);
+ if (t > 8.5 || state.p.y < -0.5) { state.t = -1; sprite.visible = false; state.power = 0; }
+ },
+ };
+}
diff --git a/examples/keeper/index.html b/examples/keeper/index.html
new file mode 100644
index 0000000..7b2ca63
--- /dev/null
+++ b/examples/keeper/index.html
@@ -0,0 +1,221 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>The Keeper — A four-room lighthouse on Sgeir Dubh</title>
+ <meta name="description" content="Four rooms. One light. No one else for nine miles. A working lighthouse hotel on a black rock in the North Atlantic.">
+ <meta name="theme-color" content="#05080c">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect width=%2232%22 height=%2232%22 rx=%226%22 fill=%22%2305080c%22/%3E%3Cpath d=%22M16 9 L30 6 L30 12 Z M16 9 L2 6 L2 12 Z%22 fill=%22%23ffd27a%22/%3E%3Cpath d=%22M13.5 12h5l1.3 14h-7.6z%22 fill=%22%23ece7dc%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Libre+Caslon+Display&family=Libre+Caslon+Text:ital,wght@0,400;1,400&family=Karla:ital,wght@0,300;0,400;0,500;0,600;1,400&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="flash" aria-hidden="true"></div>
+ <div class="grade" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-lamp" aria-hidden="true"><i class="loader-beam"></i><i class="loader-beam b2"></i><b></b></div>
+ <p class="loader-name">The Keeper</p>
+ <p class="loader-line"><span>Lighting the lamp</span> <span class="loader-pct">0</span></p>
+ <p class="loader-char">Sgeir Dubh · Fl W 7s · 36 m · 18 M</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="The Keeper — home">
+ <svg viewBox="0 0 32 32" aria-hidden="true">
+ <path class="brand-beam" d="M16 8 L31 4.5 L31 11.5 Z M16 8 L1 4.5 L1 11.5 Z" />
+ <path d="M13.2 11h5.6l1.4 15h-8.4z M12 26h8 M14.6 6.5h2.8v4.5h-2.8z M13.8 6.5 16 4.6l2.2 1.9" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linejoin="round"/>
+ <path d="M13 16.5h6 M12.6 21h6.8" stroke="currentColor" stroke-width="1.2"/>
+ </svg>
+ <span>The Keeper</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#storm">The storm</a>
+ <a href="#rooms">Rooms</a>
+ <a href="#crossing">The crossing</a>
+ <a href="#dawn">Rates</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" data-cursor="link"><span class="sound-bars" aria-hidden="true"><i></i><i></i><i></i><i></i></span><span class="sound-label">Sound off</span></button>
+ <a class="btn btn-lamp" href="#reserve" data-magnetic><span class="cta-long">Reserve a night</span><span class="cta-short">Reserve</span></a>
+ </div>
+ </header>
+
+ <!-- live conditions, updated as the night passes -->
+ <aside class="log" aria-label="Conditions at the light">
+ <div><span class="k">Time</span><span class="v" data-log="time">02:47</span></div>
+ <div><span class="k">Wind</span><span class="v" data-log="wind">SW 9, severe gale</span></div>
+ <div><span class="k">Sea</span><span class="v" data-log="sea">Very high</span></div>
+ <div><span class="k">Visibility</span><span class="v" data-log="vis">0.4 NM, rain</span></div>
+ </aside>
+
+ <main id="top">
+ <section class="hero" data-kf="0">
+ <div class="hero-inner">
+ <div class="hero-top">
+ <p class="eyebrow">Sgeir Dubh Light <i>·</i> 57°41′N 8°19′W <i>·</i> Fl W 7s</p>
+ <h1 class="title">
+ <span class="l1">Four rooms.</span>
+ <span class="l2">One light.</span>
+ <span class="l3">No one else for nine miles.</span>
+ </h1>
+ </div>
+ <div class="hero-foot">
+ <p class="sub">A working lighthouse on a black rock in the North Atlantic, with one keeper, four rooms, and the weather as the main event.</p>
+ <div class="ctas">
+ <a class="btn btn-lamp" href="#reserve" data-magnetic>Reserve a night</a>
+ <a class="btn btn-ghost" href="#storm" data-magnetic>Take the light <span aria-hidden="true">↓</span></a>
+ </div>
+ </div>
+ </div>
+ <p class="hero-hint"><span class="dot"></span><span class="hint-desktop">Move your cursor — the light is yours</span><span class="hint-touch">Touch the sea — the light is yours</span></p>
+ </section>
+
+ <section class="storm" id="storm">
+ <div class="storm-sticky" data-kf="1">
+ <div class="storm-copy">
+ <p class="eyebrow"><span class="num">01</span> The storm</p>
+ <h2>Take the light.</h2>
+ <p class="lede">Somewhere out there a boat has lost the coast. The lamp is yours now: aim the beam, find her, and hold it on her for two seconds. She'll find her way in.</p>
+ <ul class="how">
+ <li><kbd class="k-desk">Move</kbd><kbd class="k-touch">Touch</kbd> aim the beam</li>
+ <li><kbd>Hold 2s</kbd> on the boat — guide her home</li>
+ </ul>
+ <p class="storm-foot">Since 1861 the lamp on Sgeir Dubh has been lit every night of the year. It has never once been late.</p>
+ </div>
+ <div class="tally" aria-live="polite">
+ <p class="tally-k">Boats guided home</p>
+ <p class="tally-v"><span class="tally-n">0</span></p>
+ <ol class="tally-log"></ol>
+ </div>
+ </div>
+ </section>
+
+ <section class="rooms" id="rooms">
+ <div class="rooms-sticky">
+ <header class="rooms-head">
+ <p class="eyebrow"><span class="num">02</span> The rooms</p>
+ <h2>Four rooms, <em>stacked up a tower.</em></h2>
+ </header>
+ <div class="room-stage">
+ <article class="room" data-room="0">
+ <figure><img src="/img/keeper/room-quarters.webp" alt="The keeper's quarters: a peat stove, a box bed and a small window onto the sea" loading="lazy" width="900" height="1125"></figure>
+ <div class="room-text">
+ <p class="room-meta"><span>I</span> Ground floor · Sleeps 2 · 24 m²</p>
+ <h3>Keeper’s Quarters</h3>
+ <p>The cottage the keepers lived in for a hundred and forty years. A peat stove, a bed built into the wall, and a window the sea comes right up to on a spring tide. The original log books are on the shelf. Read them.</p>
+ <ul><li>Peat stove</li><li>Box bed</li><li>Log books, 1861–2002</li></ul>
+ </div>
+ </article>
+ <article class="room" data-room="1">
+ <figure><img src="/img/keeper/room-fog.webp" alt="The fog signal room: a brass horn through the wall above a copper bath" loading="lazy" width="900" height="1125"></figure>
+ <div class="room-text">
+ <p class="room-meta"><span>II</span> Seaward end · Sleeps 2 · 30 m²</p>
+ <h3>The Fog Signal</h3>
+ <p>The old engine house for the horn, which still sounds at noon on the first Monday of the month. A copper bath under the horn’s brass mouth, walls a metre thick, and a window at the height of the surf.</p>
+ <ul><li>Copper bath</li><li>The horn still works</li><li>Surf-level window</li></ul>
+ </div>
+ </article>
+ <article class="room" data-room="2">
+ <figure><img src="/img/keeper/room-watch.webp" alt="The watch room: a curved window seat, a brass telescope and old sea charts" loading="lazy" width="900" height="1125"></figure>
+ <div class="room-text">
+ <p class="room-meta"><span>III</span> Level five · Sleeps 2 · 19 m²</p>
+ <h3>The Watch</h3>
+ <p>The room where the keeper stayed awake. Six small windows all the way round, a brass telescope, and a chart of every wreck on this reef. It is the first room on the rock to catch the dawn.</p>
+ <ul><li>Windows all round</li><li>Brass telescope</li><li>Wreck charts</li></ul>
+ </div>
+ </article>
+ <article class="room" data-room="3">
+ <figure><img src="/img/keeper/room-lamp.webp" alt="The lamp room: a bed beside the great glass lens, with the sea on every side" loading="lazy" width="900" height="1125"></figure>
+ <div class="room-text">
+ <p class="room-meta"><span>IV</span> The top · Sleeps 2 · 16 m² · 118 steps</p>
+ <h3>The Lamp Room</h3>
+ <p>You sleep beside the lens. It turns all night, because it’s a working light, and a blackout curtain rings the bed. Almost everyone leaves it open.</p>
+ <ul><li>Beside a working lens</li><li>Glass on every side</li><li>No signal, anywhere</li></ul>
+ </div>
+ </article>
+ </div>
+ <div class="room-pins" aria-hidden="true">
+ <div class="pin" data-pin="0"><i></i><span>Keeper’s Quarters</span></div>
+ <div class="pin" data-pin="1"><i></i><span>The Fog Signal</span></div>
+ <div class="pin" data-pin="2"><i></i><span>The Watch</span></div>
+ <div class="pin" data-pin="3"><i></i><span>The Lamp Room</span></div>
+ </div>
+ <ol class="room-index" aria-hidden="true"><li>I</li><li>II</li><li>III</li><li>IV</li></ol>
+ </div>
+ </section>
+
+ <section class="crossing" id="crossing">
+ <div class="crossing-sticky">
+ <div class="crossing-copy">
+ <p class="eyebrow"><span class="num">03</span> The crossing</p>
+ <h2>Nine miles, <em>weather permitting.</em></h2>
+ <p class="lede">The <i>Morag Ann</i> leaves Ardcarra Quay at ten on Tuesdays and Fridays. It is fifty-eight minutes across if the sea agrees. The keeper makes the call at seven each morning, and the keeper’s call is final.</p>
+ </div>
+ <div class="route" aria-hidden="true">
+ <span class="route-a">Ardcarra Quay</span>
+ <div class="route-line"><i class="route-boat"></i><span class="route-nm">9 NM · 58 min</span></div>
+ <span class="route-b">Sgeir Dubh</span>
+ </div>
+ <dl class="facts">
+ <div><dt>Tue &amp; Fri</dt><dd>Out at 10:00 from Ardcarra Quay, back from the rock at 15:00.</dd></div>
+ <div><dt>Two bags</dt><dd>Soft ones. They are passed up the landing ladder by hand.</dd></div>
+ <div><dt>If the sea says no</dt><dd>We pay for your night at the Harbour Inn and try again in the morning.</dd></div>
+ </dl>
+ </div>
+ </section>
+
+ <section class="dawn" id="dawn">
+ <div class="dawn-sticky">
+ <div class="dawn-copy">
+ <p class="eyebrow"><span class="num">04</span> Dawn</p>
+ <h2>And then, <em>the morning.</em></h2>
+ <p class="lede">At sunrise the keeper puts out the light. The sea goes flat and pink, the gannets come back, and you realise how far away everything is.</p>
+ </div>
+ <div class="rates" id="reserve">
+ <p class="rates-from">Rates from <b>£420</b> a night</p>
+ <table id="rates-table">
+ <caption class="sr">Nightly rates for two guests</caption>
+ <tbody>
+ <tr><th scope="row">Keeper’s Quarters</th><td>£420</td></tr>
+ <tr><th scope="row">The Fog Signal</th><td>£460</td></tr>
+ <tr><th scope="row">The Watch</th><td>£540</td></tr>
+ <tr><th scope="row">The Lamp Room</th><td>£680</td></tr>
+ </tbody>
+ </table>
+ <p class="rates-note">Per night for two. Every meal, the crossing and the keeper’s tour of the lamp included. Two nights minimum; the sea sometimes makes it three.</p>
+ <div class="ctas">
+ <a class="btn btn-lamp" href="#reserve" data-magnetic>Reserve a night</a>
+ <a class="btn btn-ghost rates-write" href="#footer" data-magnetic>Write to the keeper</a>
+ <button class="btn btn-ghost rates-toggle" type="button" aria-expanded="false" aria-controls="rates-table">All rooms <span aria-hidden="true">+</span></button>
+ </div>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot" id="footer">
+ <h2 class="foot-title">Hold the <em>light.</em></h2>
+ <div class="foot-cols">
+ <p><b>The Keeper</b><br>Sgeir Dubh Light<br>Nine miles west of Ardcarra</p>
+ <p><b>Season</b><br>March to November<br>Crossings Tuesday &amp; Friday</p>
+ <p><b>The light</b><br>Lit at sunset, out at sunrise<br>A working aid to navigation</p>
+ <a class="btn btn-lamp" href="#reserve" data-magnetic>Reserve a night</a>
+ </div>
+ <p class="foot-small"><span>© The Keeper, Sgeir Dubh</span><span>Four rooms · One light</span></p>
+ </footer>
+ </main>
+
+ <!-- 3D-anchored UI -->
+ <div class="boat-mark" aria-hidden="true">
+ <svg viewBox="0 0 80 80"><circle class="bm-track" cx="40" cy="40" r="30"/><circle class="bm-fill" cx="40" cy="40" r="30"/></svg>
+ <span class="bm-label">Boat in distress</span>
+ </div>
+ <div class="toast" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/keeper/main.js b/examples/keeper/main.js
new file mode 100644
index 0000000..e679f96
--- /dev/null
+++ b/examples/keeper/main.js
@@ -0,0 +1,952 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal, ScrollTrigger } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { Waves, oceanGeometry, oceanMaterial } from './ocean.js';
+import { createSky } from './sky.js';
+import { BeamEffect } from './beams.js';
+import { createRain, createSpray, createBolt, createFlare, lightUniforms } from './fx.js';
+import { StormAudio } from './audio.js';
+
+const DBG = new URLSearchParams(location.search);
+const D2R = Math.PI / 180;
+const MOBILE = matchMedia('(max-width: 900px)').matches;
+const TOUCH = matchMedia('(pointer: coarse)').matches;
+
+// ─── The rock and its light (model-space facts measured from the GLB) ─────────────
+const LH_H = 14; // lighthouse model height in scene units (1 u ≈ 1.8 m)
+const WATER_F = 0.12; // sea level as a fraction of model height (hides the diorama base)
+const K = LH_H / 1.91;
+const AXIS = new THREE.Vector2(-0.161 * K, -0.1905 * K); // tower axis
+const Y = f => f * LH_H - WATER_F * LH_H; // model height fraction → world y
+const LAMP = new THREE.Vector3(AXIS.x, Y(0.887), AXIS.y);
+const GLASS = { y0: Y(0.858), y1: Y(0.918), r: 0.083 * K };
+const BEAM = { outer: 0.072, inner: 0.05, period: 14 };
+const LAMP_COL = new THREE.Color('#ffd27a');
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let beams;
+const engine = new Engine({
+ canvas, fov: 32, near: 0.3, far: 3600, dpr: MOBILE ? 1.5 : 1.5, background: 0x05080c,
+ post: {
+ ao: { aoRadius: 1.6, intensity: 2.2, distanceFalloff: 1.2 },
+ bloom: { intensity: 1.05, luminanceThreshold: 0.42, luminanceSmoothing: 0.4, radius: 0.82 },
+ pre: cam => [(beams = new BeamEffect(cam, { density: 0.05, range: 0.012, cone: [BEAM.outer, BEAM.inner] }))],
+ tone: DBG.get('tone') ?? 'aces',
+ vignette: { offset: 0.2, darkness: 0.72 },
+ noise: 0.075,
+ ca: 0.0012,
+ },
+});
+const { scene, camera, renderer } = engine;
+if (DBG.has('noao') && engine.post.ao) engine.post.ao.enabled = false;
+scene.fog = new THREE.FogExp2(0x0a0e14, 0.008);
+scene.environment = studioEnvironment(renderer, {
+ top: 0x1c2230, bottom: 0x040506,
+ panels: [
+ { pos: [0, 7, -6], size: [10, 3], intensity: 1.4, color: 0x9fb2d8 },
+ { pos: [-8, 2, 4], size: [3, 5], intensity: 1.0, color: 0xffd6a0 },
+ { pos: [8, 2, 3], size: [3, 6], intensity: 0.8, color: 0xb8c6e8 },
+ ],
+});
+scene.environmentIntensity = 0.18;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 8 });
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100) + '%';
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ },
+});
+
+// ─── Lights ────────────────────────────────────────────────────────────────────
+const hemi = new THREE.HemisphereLight(0x2a3548, 0x05070a, 0.35);
+scene.add(hemi);
+// moon (storm) → sun (dawn): the only shadow-casting light
+const key = new THREE.DirectionalLight(0x8aa0d0, 0.3);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+Object.assign(key.shadow.camera, { left: -13, right: 13, top: 14, bottom: -8, near: 1, far: 90 });
+key.shadow.bias = -0.0004; key.shadow.normalBias = 0.03;
+key.target.position.set(AXIS.x, 4, AXIS.y);
+scene.add(key, key.target);
+// lightning
+const bolt = new THREE.DirectionalLight(0xcad6ff, 0);
+bolt.target.position.set(0, 0, 0);
+scene.add(bolt, bolt.target);
+// the lamp's own spill onto gallery and dome
+const lampGlow = new THREE.PointLight(0xffc774, 0, 9, 1.4);
+lampGlow.position.copy(LAMP);
+scene.add(lampGlow);
+// twin beam spots (light the boat, spray and rock when they pass)
+const spots = [0, 1].map(() => {
+ const s = new THREE.SpotLight(LAMP_COL, 0, 0, BEAM.outer * 1.1, 0.55, 0.6);
+ s.position.copy(LAMP);
+ scene.add(s, s.target);
+ return s;
+});
+// flares
+const flareLight = new THREE.PointLight(0xff3a24, 0, 70, 1.4);
+scene.add(flareLight);
+// the keeper's window
+const hearth = new THREE.PointLight(0xffa04a, 0, 9, 1.6);
+hearth.position.set(0.9, 3.4, 0.9);
+scene.add(hearth);
+
+// ─── Procedural textures ───────────────────────────────────────────────────────
+const foamTex = bakeTexture(renderer, 1024, `
+ void main(){
+ float r = ridge(vUv * 6.0, 6.0, 6);
+ float lace = smoothstep(0.64, 0.94, r);
+ float blot = fbm(vUv * 5.0 + 3.1, 5.0, 5, 0.55) * 0.5 + 0.5;
+ float streak = fbm(vec2(vUv.x * 3.0, vUv.y * 22.0), 22.0, 5, 0.5) * 0.5 + 0.5;
+ float g = fbm(vUv * 9.0 + 7.3, 9.0, 4, 0.5) * 0.5 + 0.5;
+ gl_FragColor = vec4(lace * smoothstep(0.35, 0.7, blot), streak, g, 1.0);
+ }`);
+const detailN = fbmNormal(renderer, { size: 1024, scale: 9, octaves: 6, strength: 2.4, ridged: true });
+
+// ─── Ocean ─────────────────────────────────────────────────────────────────────
+const waves = new Waves();
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+const oceanMat = oceanMaterial({ waves, refl: reflection, foamTex, detailN });
+const ocean = new THREE.Mesh(oceanGeometry(MOBILE ? { segs: 480, dr0: 0.18, grow: 0.02 } : {}), oceanMat);
+ocean.frustumCulled = false;
+scene.add(ocean);
+reflection.hidden.push(ocean);
+const OU = oceanMat.uniforms;
+OU.uDebug.value = DBG.has('foam') ? +DBG.get('foam') || 1 : 0;
+OU.uLamp.value.copy(LAMP);
+OU.uBeamCos.value.set(Math.cos(BEAM.outer), Math.cos(BEAM.inner));
+
+// ─── Sky ───────────────────────────────────────────────────────────────────────
+const sky = createSky();
+scene.add(sky.mesh);
+const SU = sky.uniforms;
+
+// ─── Weather ───────────────────────────────────────────────────────────────────
+const LU = lightUniforms();
+LU.uLamp.value.copy(LAMP);
+LU.uBeamCos.value.set(Math.cos(BEAM.outer * 1.05), Math.cos(BEAM.inner));
+const rain = createRain(LU, { count: MOBILE ? 22000 : 42000 });
+scene.add(rain.mesh);
+const spray = createSpray(LU);
+scene.add(spray.points);
+engine.onResize((w, h, dpr) => { spray.uniforms.uDpr.value = dpr; spray.uniforms.uH.value = h * dpr; });
+const lightning = createBolt();
+scene.add(lightning.mesh);
+const redFlare = createFlare(0xff3322);
+const greenFlare = createFlare(0x3dff8a);
+scene.add(redFlare.sprite, greenFlare.sprite);
+reflection.hidden.push(rain.mesh, spray.points);
+
+// Harbour lights: Ardcarra, nine miles off, a smudge of sodium on the horizon.
+const harbour = (() => {
+ const g = new THREE.Group();
+ const c = document.createElement('canvas'); c.width = c.height = 32;
+ const x = c.getContext('2d'); const gr = x.createRadialGradient(16, 16, 0, 16, 16, 16);
+ gr.addColorStop(0, '#fff'); gr.addColorStop(0.3, 'rgba(255,255,255,.5)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
+ x.fillStyle = gr; x.fillRect(0, 0, 32, 32);
+ const tex = new THREE.CanvasTexture(c);
+ const lights = [];
+ for (let i = 0; i < 11; i++) {
+ const m = new THREE.SpriteMaterial({ map: tex, color: new THREE.Color(1, 0.62, 0.3).multiplyScalar(2.2), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false });
+ const s = new THREE.Sprite(m);
+ s.position.set((i - 5) * 6 + Math.sin(i * 7.1) * 3, 0.5 + Math.abs(Math.sin(i * 3.3)) * 1.1, Math.cos(i * 2.7) * 4);
+ s.scale.setScalar(1.1 + Math.random() * 0.8);
+ s.userData.seed = Math.random() * 10;
+ g.add(s); lights.push(s);
+ }
+ scene.add(g);
+ return { group: g, lights };
+})();
+
+// ─── Lighthouse ────────────────────────────────────────────────────────────────
+const lhU = {
+ uLampPow: { value: 0 }, uLampCol: { value: LAMP_COL.clone().multiplyScalar(1) },
+ uAxis: { value: AXIS }, uGlass: { value: new THREE.Vector3(GLASS.y0, GLASS.y1, GLASS.r) },
+ uB0: { value: new THREE.Vector2(1, 0) }, uB1: { value: new THREE.Vector2(-1, 0) }, uWet: { value: 1 },
+};
+function patchLighthouse(mat) {
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, lhU);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWp;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvWp = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vWp; uniform float uLampPow, uWet; uniform vec3 uLampCol, uGlass; uniform vec2 uAxis, uB0, uB1;`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ float wet = (1.0 - smoothstep(0.1, 2.9, vWp.y)) * uWet;
+ diffuseColor.rgb *= mix(1.0, 0.62, wet);`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(roughnessFactor, roughnessFactor * 0.32 + 0.04, wet);`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ float band = smoothstep(uGlass.x, uGlass.x + 0.1, vWp.y) * (1.0 - smoothstep(uGlass.y - 0.1, uGlass.y, vWp.y));
+ vec2 rel = vWp.xz - uAxis; float rad = length(rel);
+ float inside = 1.0 - smoothstep(uGlass.z, uGlass.z + 0.14, rad);
+ vec2 az = rel / max(rad, 1e-3);
+ float face = pow(max(max(dot(az, uB0), dot(az, uB1)), 0.0), 10.0);
+ float lum = dot(diffuseColor.rgb, vec3(0.3, 0.59, 0.11));
+ totalEmissiveRadiance += uLampCol * band * inside * (0.5 + 9.0 * face) * (0.25 + smoothstep(0.03, 0.3, lum)) * uLampPow;
+ }`);
+ };
+ mat.customProgramCacheKey = () => 'keeper-lh';
+ mat.needsUpdate = true;
+}
+const lighthouse = new THREE.Group();
+scene.add(lighthouse);
+
+// Boulders around the waterline break the diorama's square footprint.
+{
+ const rockN = fbmNormal(renderer, { size: 512, scale: 5, octaves: 6, strength: 2.2, ridged: true });
+ const mat = new THREE.MeshStandardMaterial({ color: 0x1b1917, roughness: 0.42, metalness: 0, normalMap: rockN, normalScale: new THREE.Vector2(1.4, 1.4), envMapIntensity: 0.8 });
+ const base = new THREE.IcosahedronGeometry(1, 3);
+ const p = base.attributes.position, v = new THREE.Vector3();
+ const rnd = (i, k) => { const s = Math.sin(i * 127.1 + k * 311.7) * 43758.5453; return s - Math.floor(s); };
+ const geos = [0, 1, 2, 3].map(g => {
+ const geo = base.clone(); const q = geo.attributes.position;
+ for (let i = 0; i < q.count; i++) {
+ v.fromBufferAttribute(q, i);
+ const n = Math.sin(v.x * 3.1 + g) * Math.sin(v.y * 2.7 + g * 2) * Math.sin(v.z * 3.7 - g) * 0.22 + Math.sin(v.x * 7 + v.z * 5 + g) * 0.05;
+ v.multiplyScalar(1 + n); v.y *= 0.62; if (v.y < -0.1) v.y *= 0.4;
+ q.setXYZ(i, v.x, v.y, v.z);
+ }
+ geo.computeVertexNormals();
+ return geo;
+ });
+ const hx = 3.25, hz = 2.95, cx = 0.1, cz = -0.45;
+ let i = 0;
+ for (let side = 0; side < 4; side++) for (let k = 0; k < 6; k++, i++) {
+ const u = (k + 0.5) / 6 * 2 - 1 + (rnd(i, 1) - 0.5) * 0.2;
+ const out = 0.15 + rnd(i, 2) * 0.9;
+ const [x, z] = side === 0 ? [cx + hx + out, cz + u * hz] : side === 1 ? [cx - hx - out, cz + u * hz] : side === 2 ? [cx + u * hx, cz + hz + out] : [cx + u * hx, cz - hz - out];
+ const b = new THREE.Mesh(geos[i % 4], mat);
+ const s = 0.45 + rnd(i, 3) * 0.95;
+ b.scale.set(s * (1 + rnd(i, 4) * 0.6), s * (0.7 + rnd(i, 5) * 0.7), s * (1 + rnd(i, 6) * 0.5));
+ b.position.set(x, -0.25 + rnd(i, 7) * 0.35 - s * 0.2, z);
+ b.rotation.set(rnd(i, 8) * 0.5, rnd(i, 9) * 6.28, rnd(i, 10) * 0.4);
+ b.castShadow = b.receiveShadow = true;
+ lighthouse.add(b);
+ }
+}
+const lhLoad = assets.gltf('models/keeper/lighthouse.glb').then(g => {
+ const m = g.scene;
+ normalize(m, LH_H, { axis: 'y' });
+ m.position.y -= WATER_F * LH_H;
+ prepModel(m, renderer, { env: 0.6, onMat: patchLighthouse });
+ lighthouse.add(m);
+});
+
+// ─── The boat ──────────────────────────────────────────────────────────────────
+const boat = {
+ group: new THREE.Group(), inner: new THREE.Group(), ready: false,
+ state: 'hidden', pos: new THREE.Vector2(30, 20), heading: 0, speed: 0, hold: 0, t: 0, fade: 0,
+ pitch: 0, roll: 0, y: 0, wake: 0, lightsOn: 0, name: '', flareT: 0, saved: 0, found: false,
+};
+boat.group.rotation.order = 'YXZ';
+boat.group.add(boat.inner);
+scene.add(boat.group);
+const navDot = (color, size) => {
+ const m = new THREE.SpriteMaterial({ map: harbour.lights[0].material.map, color: new THREE.Color(color), transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });
+ const s = new THREE.Sprite(m); s.scale.setScalar(size); s.userData.base = new THREE.Color(color); return s;
+};
+const boatLights = {
+ mast: navDot(0xffffff, 0.2), port: navDot(0xff2a20, 0.17), star: navDot(0x20ff60, 0.17), cabin: navDot(0xffb050, 0.55),
+};
+boatLights.mast.position.set(0, 3.55, -0.35);
+boatLights.port.position.set(0.62, 2.05, 0.9);
+boatLights.star.position.set(-0.62, 2.05, 0.9);
+boatLights.cabin.position.set(0, 1.9, 1.1);
+for (const s of Object.values(boatLights)) boat.group.add(s);
+const deckLight = new THREE.PointLight(0xffb866, 0, 9, 1.5);
+deckLight.position.set(0, 3.2, -0.6);
+boat.group.add(deckLight);
+const boatLoad = assets.gltf('models/keeper/boat.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 5.4, { axis: 'x' });
+ prepModel(m, renderer, { env: 0.7 });
+ m.rotation.y = Math.PI / 2; // model bow is −X; the boat group sails along +Z
+ boat.inner.add(m);
+ boat.inner.position.y = -0.62;
+ boat.ready = true;
+});
+boat.group.visible = false;
+const NAMES = ['Kittiwake', 'Morven Lass', 'Silver Darling', 'Brothers’ Pride', 'Grace of Ness', 'Mary Tait', 'Northern Star', 'Endeavour II', 'Sula', 'Good Intent'];
+
+// ─── Camera choreography ──────────────────────────────────────────────────────
+// Positions are cylindrical around the tower (az° from +Z toward +X, radius, height); moves orbit, never cut.
+const A = (x, y, z) => new THREE.Vector3(x, y, z);
+const KF = [
+ { id: 'hero', az: 30, r: 33, y: 3.1, look: A(AXIS.x, 5.2, AXIS.y), shift: [0.2, 0.035], fov: 32, storm: 1, dawn: 0, lamp: 1 },
+ { id: 'storm', az: 62, r: 37, y: 5.2, look: A(-11, 3.4, 5), shift: [-0.02, 0.1], fov: 36, storm: 1, dawn: 0, lamp: 1 },
+ { id: 'quarters', az: 16, r: 13.5, y: 4.3, look: A(0.8, 4.1, -0.6), shift: [0.2, 0.02], fov: 34, storm: 0.86, dawn: 0.04, lamp: 1 },
+ { id: 'fog', az: 66, r: 13, y: 5.2, look: A(2.3, 4.4, -1.2), shift: [0.2, 0.02], fov: 34, storm: 0.76, dawn: 0.08, lamp: 1 },
+ { id: 'watch', az: 30, r: 10.5, y: 9.7, look: A(AXIS.x, 9.6, AXIS.y), shift: [0.2, 0.0], fov: 34, storm: 0.64, dawn: 0.13, lamp: 1 },
+ { id: 'lamp', az: 4, r: 10, y: 12.2, look: A(AXIS.x, 10.7, AXIS.y), shift: [0.2, -0.02], fov: 34, storm: 0.52, dawn: 0.2, lamp: 1 },
+ { id: 'crossing', az: -38, r: 40, y: 1.9, look: A(AXIS.x - 2, 4.4, AXIS.y), shift: [0.12, 0.08], fov: 34, storm: 0.22, dawn: 0.5, lamp: 0.85 },
+ { id: 'dawn', az: 122, r: 58, y: 3.6, look: A(AXIS.x, 5.2, AXIS.y), shift: [-0.02, -0.06], fov: 32, storm: 0.02, dawn: 1, lamp: 0 },
+ { id: 'foot', az: 128, r: 78, y: 7, look: A(AXIS.x, 7, AXIS.y), shift: [0.26, 0.2], fov: 30, storm: 0, dawn: 1, lamp: 0 },
+];
+if (MOBILE) {
+ // portrait framings: [radius, height, shift, look?]
+ const portrait = {
+ hero: [50, 2.8, [0, -0.13]], storm: [50, 8, [0, 0.03], A(AXIS.x - 4, 3, AXIS.y + 3)], quarters: [22, 5, [0, 0.2]], fog: [22, 5.5, [0, 0.2]],
+ watch: [19, 10, [0, 0.18]], lamp: [18, 12, [0, 0.16]], crossing: [52, 2.2, [0, 0.08]], dawn: [60, 3.6, [0, -0.1]], foot: [100, 22, [0, 0.12]],
+ };
+ for (const k of KF) { const p = portrait[k.id]; k.r = p[0]; k.y = p[1]; k.shift = p[2]; if (p[3]) k.look = p[3]; k.fov = 42; }
+}
+const sectionEls = {
+ hero: document.querySelector('.hero'), storm: document.querySelector('.storm'), rooms: document.querySelector('.rooms'),
+ crossing: document.querySelector('.crossing'), dawn: document.querySelector('.dawn'), foot: document.querySelector('.foot'),
+};
+let stops = [];
+function layoutStops() {
+ const vh = innerHeight, top = el => el.getBoundingClientRect().top + scrollY;
+ const st = top(sectionEls.storm), ro = top(sectionEls.rooms), cr = top(sectionEls.crossing), da = top(sectionEls.dawn), fo = top(sectionEls.foot);
+ const maxY = document.documentElement.scrollHeight - vh;
+ stops = [
+ [0, 0], [vh * 0.1, 0],
+ [st, 1], [st + sectionEls.storm.offsetHeight - vh * 1.2, 1],
+ [ro + vh * 0.6, 2], [ro + vh * 1.15, 2],
+ [ro + vh * 1.75, 3], [ro + vh * 2.3, 3],
+ [ro + vh * 2.9, 4], [ro + vh * 3.45, 4],
+ [ro + vh * 4.05, 5], [ro + vh * 4.6, 5],
+ [cr + vh * 0.25, 6], [cr + vh * 1.2, 6],
+ [da + vh * 0.35, 7], [da + sectionEls.dawn.offsetHeight - vh * 0.9, 7],
+ [maxY, 8],
+ ];
+}
+function storyAt(y) {
+ if (y <= stops[0][0]) return 0;
+ for (let i = 0; i < stops.length - 1; i++) {
+ const [y0, k0] = stops[i], [y1, k1] = stops[i + 1];
+ if (y <= y1) return k0 === k1 ? k0 : lerp(k0, k1, smooth(0, 1, (y - y0) / Math.max(1, y1 - y0)));
+ }
+ return stops[stops.length - 1][1];
+}
+const camState = { az: 0, r: 0, y: 0, look: new THREE.Vector3(), sx: 0, sy: 0, fov: 32, storm: 1, dawn: 0, lamp: 1 };
+function sampleKF(s, out) {
+ const i = Math.min(KF.length - 2, Math.floor(s)), f = s - i;
+ const a = KF[i], b = KF[i + 1];
+ let daz = b.az - a.az;
+ out.az = a.az + daz * f;
+ out.r = lerp(a.r, b.r, f);
+ out.y = lerp(a.y, b.y, f) + Math.sin(f * Math.PI) * (Math.abs(b.y - a.y) < 3 ? Math.min(a.r, b.r) * 0.06 : 0);
+ out.look.lerpVectors(a.look, b.look, f);
+ out.sx = lerp(a.shift[0], b.shift[0], f); out.sy = lerp(a.shift[1], b.shift[1], f);
+ out.fov = lerp(a.fov, b.fov, f);
+ out.storm = lerp(a.storm, b.storm, f); out.dawn = lerp(a.dawn, b.dawn, f); out.lamp = lerp(a.lamp, b.lamp, f);
+ return out;
+}
+function camPosFrom(st, out) {
+ return out.set(AXIS.x + Math.sin(st.az * D2R) * st.r, st.y, AXIS.y + Math.cos(st.az * D2R) * st.r);
+}
+
+// ─── Atmosphere: storm night → pink dawn ───────────────────────────────────────
+const C = (r, g, b) => new THREE.Color(r, g, b);
+const PAL = {
+ zen: [C(0.0011, 0.0017, 0.0032), C(0.012, 0.017, 0.04), C(0.03, 0.036, 0.1)],
+ hor: [C(0.0085, 0.012, 0.018), C(0.08, 0.065, 0.11), C(0.44, 0.19, 0.22)],
+ cDark: [C(0.0009, 0.0013, 0.0021), C(0.022, 0.022, 0.04), C(0.06, 0.04, 0.075)],
+ cLit: [C(0.017, 0.023, 0.035), C(0.1, 0.08, 0.13), C(0.62, 0.25, 0.26)],
+ deep: [C(0.0006, 0.0018, 0.003), C(0.007, 0.01, 0.02), C(0.012, 0.014, 0.034)],
+ sss: [C(0.02, 0.15, 0.11), C(0.04, 0.14, 0.13), C(0.1, 0.2, 0.19)],
+ amb: [C(0.0035, 0.0055, 0.009), C(0.03, 0.03, 0.05), C(0.16, 0.11, 0.15)],
+ hemiSky: [C(0.16, 0.2, 0.3), C(0.26, 0.26, 0.38), C(0.7, 0.55, 0.66)],
+ hemiGround: [C(0.02, 0.025, 0.035), C(0.05, 0.05, 0.07), C(0.2, 0.12, 0.14)],
+};
+const ramp = (arr, t, out) => t < 0.5 ? out.copy(arr[0]).lerp(arr[1], t * 2) : out.copy(arr[1]).lerp(arr[2], (t - 0.5) * 2);
+const tmpC = new THREE.Color();
+const sunDir = new THREE.Vector3(), moonDir = new THREE.Vector3();
+function kfCamera(i, cam = new THREE.PerspectiveCamera()) {
+ // the camera a keyframe describes, independent of where we are now
+ const st = sampleKF(i, { look: new THREE.Vector3() });
+ cam.fov = st.fov; cam.aspect = innerWidth / innerHeight; cam.near = 0.3; cam.far = 3000;
+ camPosFrom(st, cam.position); cam.lookAt(st.look);
+ cam.setViewOffset(innerWidth, innerHeight, -st.sx * innerWidth, st.sy * innerHeight, innerWidth, innerHeight);
+ cam.updateMatrixWorld(); cam.updateProjectionMatrix();
+ return cam;
+}
+function placeSky() {
+ // the moon glows just right of the tower in the hero; the sun rises beside it at dawn
+ const r = new THREE.Raycaster();
+ r.setFromCamera(new THREE.Vector2(MOBILE ? 0.5 : 0.78, 0.62), kfCamera(0));
+ moonDir.copy(r.ray.direction).setY(Math.max(r.ray.direction.y, 0.2)).normalize();
+ r.setFromCamera(new THREE.Vector2(MOBILE ? -0.3 : -0.24, 0), kfCamera(7));
+ sunDir.copy(r.ray.direction).setY(0).normalize().setY(0.014).normalize();
+ SU.uMoonDir.value.copy(moonDir); OU.uMoonDir.value.copy(moonDir);
+ SU.uSunDir.value.copy(sunDir); OU.uSunDir.value.copy(sunDir);
+}
+const sunColor = new THREE.Color(1.0, 0.52, 0.34);
+
+function applyAtmosphere(storm, dawn, lampPow, t) {
+ ramp(PAL.zen, dawn, SU.uZen.value); ramp(PAL.hor, dawn, SU.uHor.value);
+ ramp(PAL.cDark, dawn, SU.uCloudDark.value); ramp(PAL.cLit, dawn, SU.uCloudLit.value);
+ SU.uCover.value = lerp(0.56, 0.97, smooth(0, 1, storm * 0.9 + (1 - dawn) * 0.1));
+ SU.uStorm.value = storm; SU.uDawn.value = dawn; SU.uTime.value = t;
+ OU.uMoonCol.value.copy(SU.uMoonCol.value).multiplyScalar(1 - dawn);
+ const sunI = smooth(0.35, 1, dawn);
+ SU.uSunCol.value.copy(sunColor).multiplyScalar(1.6 * sunI * sunI);
+ OU.uSunCol.value.copy(sunColor).multiplyScalar(1.8 * sunI * sunI);
+ // sea
+ OU.uSkyZen.value.copy(SU.uZen.value); OU.uSkyHor.value.copy(SU.uHor.value).lerp(SU.uCloudLit.value, 0.3);
+ ramp(PAL.deep, dawn, OU.uDeep.value); ramp(PAL.sss, dawn, OU.uSSS.value); ramp(PAL.amb, dawn, OU.uAmb.value);
+ OU.uStorm.value = storm; OU.uDawn.value = dawn; OU.uTime.value = t;
+ OU.uReflAmt.value = lerp(0.9, 0.35, storm);
+ waves.setStorm(DBG.has('calm') ? 0 : storm);
+ // fog = horizon haze; rain thickens it
+ const fogDen = lerp(0.0013, 0.0105, storm);
+ scene.fog.density = fogDen;
+ scene.fog.color.copy(SU.uHor.value).multiplyScalar(0.92);
+ OU.uFogCol.value.copy(scene.fog.color); OU.uFogDen.value = fogDen;
+ // lights
+ ramp(PAL.hemiSky, dawn, hemi.color); ramp(PAL.hemiGround, dawn, hemi.groundColor);
+ hemi.intensity = lerp(0.14, 0.6, dawn);
+ scene.environmentIntensity = lerp(0.09, 0.32, dawn);
+ const moonW = 1 - smooth(0.2, 0.7, dawn);
+ key.color.set(0x8aa0d0).lerp(tmpC.copy(sunColor), 1 - moonW);
+ key.intensity = lerp(0.75, 2.3, 1 - moonW) * (moonW > 0.5 ? 1 : smooth(0.2, 1, dawn) + 0.05);
+ const kd = tmpV.copy(moonDir).lerp(sunDir, 1 - moonW).normalize();
+ key.position.copy(key.target.position).addScaledVector(kd, 50);
+ lhU.uWet.value = lerp(0.35, 1, storm);
+ // rain
+ const rainAmt = smooth(0.32, 0.8, storm);
+ rain.uniforms.uAmount.value = rainAmt;
+ rain.uniforms.uTime.value = t;
+ LU.uAmb.value = lerp(0.075, 0.2, dawn) * (0.4 + rainAmt * 0.6);
+ beams.uniforms.get('uRain').value = rainAmt;
+ beams.uniforms.get('uDensity').value = lerp(0.006, 0.052, smooth(0.05, 0.85, storm));
+ // harbour
+ harbour.group.visible = camState.story < 2.4;
+ for (const s of harbour.lights) s.material.opacity = (1 - smooth(0.3, 0.8, dawn)) * (0.55 + 0.25 * Math.sin(t * 2.1 + s.userData.seed * 3));
+}
+const tmpV = new THREE.Vector3(), tmpV2 = new THREE.Vector3(), tmpV3 = new THREE.Vector3();
+
+// ─── Beam control: the cursor takes the light ──────────────────────────────────
+const beam = { yaw: 0.6, pitch: -0.03, vel: (Math.PI * 2) / BEAM.period, control: 0, spin: 1, tYaw: 0, tPitch: -0.03, lastInput: -99, aimed: 0 };
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const beamDir = [new THREE.Vector3(), new THREE.Vector3()];
+let interactive = true;
+const angDiff = (a, b) => Math.atan2(Math.sin(b - a), Math.cos(b - a));
+function aimAt(nx, ny) {
+ ndc.set(nx, ny);
+ ray.setFromCamera(ndc, camera);
+ const o = ray.ray.origin, d = ray.ray.direction;
+ let target;
+ if (d.y < -0.004) {
+ const t = -o.y / d.y;
+ target = tmpV.copy(o).addScaledVector(d, t);
+ // keep the aim point off the rock itself
+ const hx = target.x - LAMP.x, hz = target.z - LAMP.z, hd = Math.hypot(hx, hz);
+ if (hd < 9) { target.x = LAMP.x + hx / (hd || 1) * 9; target.z = LAMP.z + hz / (hd || 1) * 9; }
+ target.y = 0.4;
+ } else target = tmpV.copy(o).addScaledVector(d, 600);
+ const dx = target.x - LAMP.x, dz = target.z - LAMP.z, dy = target.y - LAMP.y;
+ beam.tYaw = Math.atan2(dx, dz);
+ beam.tPitch = clamp(Math.atan2(dy, Math.hypot(dx, dz)), -0.85, 0.14);
+}
+pointer.on('move', e => {
+ if (!interactive || (e.pointerType === 'touch' && !pointer.down)) return;
+ beam.lastInput = engine.time;
+});
+pointer.on('down', e => {
+ if (!interactive || e.target.closest?.('a,button,.rates')) return;
+ beam.lastInput = engine.time + (e.pointerType === 'touch' ? 2.0 : 0);
+});
+addEventListener('pointerleave', () => { beam.lastInput = -99; });
+document.documentElement.addEventListener('mouseleave', () => { beam.lastInput = -99; });
+
+function updateBeam(dt, t) {
+ const hold = TOUCH ? 3.6 : 2.6;
+ const want = interactive && t - beam.lastInput < hold ? 1 : 0;
+ beam.control = damp(beam.control, want, want ? 7 : 1.6, dt);
+ if (want) {
+ aimAt(pointer.x, pointer.y);
+ // magnetic aim: near the boat, the beam settles on her
+ if (boat.state === 'lost' && boat.fade > 0.6 && boat.screen) {
+ const d = Math.hypot(boat.screen[0] - pointer.px, boat.screen[1] - pointer.py);
+ if (d < (TOUCH ? 90 : 70)) {
+ const dx = boat.pos.x - LAMP.x, dz = boat.pos.y - LAMP.z, dy = boat.y + 1.2 - LAMP.y;
+ beam.tYaw = Math.atan2(dx, dz);
+ beam.tPitch = Math.atan2(dy, Math.hypot(dx, dz));
+ }
+ }
+ // take whichever of the twin beams is nearer the cursor
+ const d0 = angDiff(beam.yaw, beam.tYaw), d1 = angDiff(beam.yaw + Math.PI, beam.tYaw);
+ const d = Math.abs(d0) < Math.abs(d1) ? d0 : d1;
+ const step = d * (1 - Math.exp(-7 * dt));
+ beam.yaw += step;
+ beam.vel = step / Math.max(dt, 1e-4);
+ beam.pitch = damp(beam.pitch, Math.abs(d0) < Math.abs(d1) ? beam.tPitch : beam.tPitch, 6, dt);
+ beam.aimed += dt;
+ if (beam.aimed > 1.2) document.body.classList.add('has-aimed');
+ } else {
+ // hand the lamp back to its clockwork: ease back up to the rotation period
+ beam.vel = damp(beam.vel, (Math.PI * 2) / BEAM.period, 1.1, dt);
+ beam.yaw += beam.vel * dt;
+ beam.pitch = damp(beam.pitch, -0.028, 1.2, dt);
+ }
+ if (beam.freeze != null) { beam.yaw = beam.freeze; beam.vel = 0; }
+ for (let i = 0; i < 2; i++) {
+ const y = beam.yaw + i * Math.PI;
+ beamDir[i].set(Math.sin(y) * Math.cos(beam.pitch), Math.sin(beam.pitch), Math.cos(y) * Math.cos(beam.pitch)).normalize();
+ spots[i].target.position.copy(LAMP).addScaledVector(beamDir[i], 50);
+ }
+}
+
+// ─── The boat game ─────────────────────────────────────────────────────────────
+const markEl = document.querySelector('.boat-mark');
+const markFill = markEl.querySelector('.bm-fill');
+const markLabel = markEl.querySelector('.bm-label');
+const tallyEl = document.querySelector('.tally');
+const tallyN = document.querySelector('.tally-n');
+const tallyLog = document.querySelector('.tally-log');
+const toastEl = document.querySelector('.toast');
+let toastTimer;
+function toast(html, ms = 3200) {
+ toastEl.innerHTML = html; toastEl.classList.add('on');
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+const harbourPos = new THREE.Vector3();
+const stormCam = new THREE.PerspectiveCamera();
+// boats always spawn inside the storm keyframe's frame
+const stormCamera = () => kfCamera(1, stormCam);
+function placeHarbour() {
+ const cam = stormCamera();
+ ray.setFromCamera(ndc.set(MOBILE ? -0.7 : -0.86, 0), cam);
+ const d = ray.ray.direction.clone().setY(0).normalize();
+ harbourPos.copy(cam.position).addScaledVector(d, 520).setY(0);
+ harbour.group.position.copy(harbourPos);
+ harbour.group.lookAt(cam.position.x, 0, cam.position.z);
+}
+let spawnIdx = 0;
+const SPAWNS = MOBILE ? [[-0.25, -0.3], [0.3, -0.25], [-0.1, -0.4], [0.2, -0.18]] : [[-0.2, -0.42], [0.08, -0.5], [-0.34, -0.3], [0.2, -0.34], [-0.05, -0.32]];
+function spawnBoat() {
+ const cam = stormCamera();
+ for (let tries = 0; tries < 8; tries++) {
+ const s = SPAWNS[(spawnIdx + tries) % SPAWNS.length];
+ ray.setFromCamera(ndc.set(s[0] + (Math.random() - 0.5) * 0.1, s[1] + (Math.random() - 0.5) * 0.06), cam);
+ const o = ray.ray.origin, d = ray.ray.direction;
+ if (d.y > -0.01) continue;
+ const p = o.clone().addScaledVector(d, -o.y / d.y);
+ const r = Math.hypot(p.x - AXIS.x, p.z - AXIS.y);
+ if (r < 18 || r > 70) continue;
+ boat.pos.set(p.x, p.z);
+ break;
+ }
+ spawnIdx++;
+ boat.heading = Math.random() * Math.PI * 2;
+ boat.state = 'lost'; boat.hold = 0; boat.t = 0; boat.fade = 0; boat.speed = 0.12; boat.wake = 0; boat.lightsOn = 0;
+ boat.flareT = 1.4; boat.name = NAMES[boat.saved % NAMES.length];
+ boat.group.visible = true;
+ boat.pending = false;
+}
+function guideBoat() {
+ boat.state = 'guided'; boat.t = 0;
+ boat.saved++;
+ const now = logTime();
+ tallyN.textContent = boat.saved;
+ tallyEl.classList.remove('bump'); void tallyEl.offsetWidth; tallyEl.classList.add('bump');
+ const li = document.createElement('li');
+ li.innerHTML = `<b>${now}</b>${boat.name} — guided home`;
+ tallyLog.prepend(li);
+ while (tallyLog.children.length > 4) tallyLog.lastElementChild.remove();
+ toast(`<b>Boats guided home: ${boat.saved}</b>The <i>${boat.name}</i> has seen the light and is making for Ardcarra.`);
+ greenFlare.fire(tmpV.set(boat.pos.x, 2.5, boat.pos.y), wind2);
+ audio.horn();
+ gsap.fromTo(beamFlash, { v: 1 }, { v: 0, duration: 1.4, ease: 'power2.out' });
+}
+const beamFlash = { v: 0 };
+const wind2 = new THREE.Vector2(0.94, 0.34);
+const boatCentre = new THREE.Vector3();
+let _ferry = null;
+function ferryPath() {
+ if (_ferry) return _ferry;
+ const st = sampleKF(6, { look: new THREE.Vector3() });
+ const cam = camPosFrom(st, new THREE.Vector3());
+ const fwd = st.look.clone().sub(cam).setY(0).normalize();
+ const right = new THREE.Vector3(-fwd.z, 0, fwd.x);
+ const start = cam.clone().addScaledVector(fwd, 15).addScaledVector(right, MOBILE ? 1.2 : 4.2).setY(0);
+ const end = cam.clone().addScaledVector(fwd, 34).addScaledVector(right, MOBILE ? 0 : 0.8).setY(0);
+ return (_ferry = { start, end });
+}
+addEventListener('resize', () => { _ferry = null; });
+function updateBoat(dt, t, story) {
+ if (!boat.ready) return;
+ const gameOn = story < 1.9;
+ const ferry = story >= 5.4;
+ if (ferry) {
+ // The Morag Ann on her scheduled crossing: scroll drives her in toward the landing.
+ const f = clamp((story - 5.4) / 1.4);
+ boat.state = 'ferry';
+ const { start, end } = ferryPath();
+ const p = tmpV.lerpVectors(start, end, f);
+ boat.pos.set(p.x, p.z);
+ boat.heading = Math.atan2(end.x - start.x, end.z - start.z);
+ boat.speed = 3; boat.wake = damp(boat.wake, 1, 2, dt); boat.lightsOn = damp(boat.lightsOn, 1 - smooth(0.6, 1, camState.dawn), 2, dt);
+ boat.fade = damp(boat.fade, story < 7.6 ? 1 : 0, 2, dt);
+ boat.group.visible = boat.fade > 0.01;
+ } else if (gameOn) {
+ if (boat.state === 'ferry' || (boat.state === 'hidden' && !boat.pending)) spawnBoat();
+ boat.t += dt;
+ if (boat.state === 'lost') {
+ boat.fade = damp(boat.fade, story > 0.45 ? 1 : 0, 1.5, dt);
+ boat.heading += Math.sin(t * 0.3 + boat.saved) * dt * 0.12;
+ const drift = story > 0.4 ? 1 : 0; // she only drifts once you can see her
+ boat.pos.x += (wind2.x * 0.1 + Math.sin(boat.heading) * boat.speed) * dt * drift;
+ boat.pos.y += (wind2.y * 0.1 + Math.cos(boat.heading) * boat.speed) * dt * drift;
+ // is a beam on her?
+ boatCentre.set(boat.pos.x, 1.4, boat.pos.y);
+ const dir = tmpV2.copy(boatCentre).sub(LAMP).normalize();
+ const on = Math.max(dir.dot(beamDir[0]), dir.dot(beamDir[1])) > Math.cos(BEAM.outer * 1.25) && story < 1.7 && boat.fade > 0.6;
+ boat.hold = clamp(boat.hold + (on ? dt : -dt * 0.8), 0, 2);
+ boat.found ||= on;
+ if (boat.hold >= 2) guideBoat();
+ boat.flareT -= dt;
+ if (boat.flareT <= 0 && story > 0.55 && story < 1.75) { redFlare.fire(tmpV.set(boat.pos.x, 2.4, boat.pos.y), wind2); boat.flareT = 9 + Math.random() * 3; }
+ } else if (boat.state === 'guided') {
+ const want = Math.atan2(harbourPos.x - boat.pos.x, harbourPos.z - boat.pos.y);
+ boat.heading += angDiff(boat.heading, want) * (1 - Math.exp(-2.2 * dt));
+ boat.speed = damp(boat.speed, boat.t < 1.2 ? 0.6 : 5.2, 0.5, dt);
+ boat.wake = damp(boat.wake, 1, 1.2, dt);
+ boat.lightsOn = damp(boat.lightsOn, 1, 3, dt);
+ boat.pos.x += Math.sin(boat.heading) * boat.speed * dt;
+ boat.pos.y += Math.cos(boat.heading) * boat.speed * dt;
+ if (boat.t > 9) boat.fade = damp(boat.fade, 0, 1.2, dt);
+ if (boat.t > 12.5) { boat.state = 'hidden'; boat.pending = true; boat.group.visible = false; setTimeout(() => { boat.pending = false; }, 1800); }
+ }
+ } else if (boat.state !== 'hidden') {
+ boat.state = 'hidden'; boat.group.visible = false;
+ }
+ if (!boat.group.visible) { OU.uBoat.value.w = 0; return; }
+ // ride the swell: sample bow, stern and both beams
+ const h = boat.heading, fx = Math.sin(h), fz = Math.cos(h), px = Math.cos(h), pz = -Math.sin(h);
+ const x = boat.pos.x, z = boat.pos.y;
+ const hb = waves.height(x + fx * 2.3, z + fz * 2.3), hs = waves.height(x - fx * 2.3, z - fz * 2.3);
+ const hp = waves.height(x + px * 0.95, z + pz * 0.95), hst = waves.height(x - px * 0.95, z - pz * 0.95);
+ boat.y = damp(boat.y, (hb + hs + hp + hst) * 0.25, 6, dt);
+ boat.pitch = damp(boat.pitch, Math.atan2(hb - hs, 4.6) * 0.9, 5, dt);
+ boat.roll = damp(boat.roll, Math.atan2(hp - hst, 1.9) * 0.55 + Math.sin(t * 1.3) * 0.03 * waves.storm, 4, dt);
+ const sink = (1 - boat.fade) * 4.5;
+ boat.inner.visible = boat.fade > 0.03;
+ boat.group.position.set(x, boat.y - sink, z);
+ boat.group.rotation.set(-boat.pitch, h, boat.roll);
+ OU.uBoat.value.set(x, z, h, boat.fade);
+ OU.uWake.value = boat.wake;
+ const lost = boat.state === 'lost';
+ const blink = lost ? (Math.sin(t * 6) > 0 ? 1 : 0.25) : 1;
+ boatLights.mast.material.color.copy(boatLights.mast.userData.base).multiplyScalar(2.2 * boat.fade * blink);
+ boatLights.port.material.color.copy(boatLights.port.userData.base).multiplyScalar(2.6 * boat.fade);
+ boatLights.star.material.color.copy(boatLights.star.userData.base).multiplyScalar(2.6 * boat.fade);
+ const cab = lost ? 0.35 * (0.7 + 0.3 * Math.sin(t * 13) * Math.sin(t * 5.3)) : boat.lightsOn;
+ boatLights.cabin.material.color.copy(boatLights.cabin.userData.base).multiplyScalar(1.6 * boat.fade * cab);
+ deckLight.intensity = (14 * boat.lightsOn + (lost ? 2.5 : 0)) * boat.fade;
+}
+
+// ─── Lightning ─────────────────────────────────────────────────────────────────
+const flashEl = document.querySelector('.flash');
+const flash = { v: 0 };
+let nextStrike = 3.5;
+const boltTop = new THREE.Vector3(), boltBot = new THREE.Vector3();
+function strike(power = 1) {
+ // pick a spot the camera can see, far out over the sea
+ const nx = (Math.random() * 2 - 1) * 0.85;
+ ray.setFromCamera(ndc.set(nx, 0.05), camera);
+ const d = ray.ray.direction.clone().setY(0).normalize();
+ const dist = 260 + Math.random() * 260;
+ boltBot.copy(camera.position).addScaledVector(d, dist).setY(0);
+ boltTop.copy(boltBot).add(tmpV.set((Math.random() - 0.5) * 80, 150 + Math.random() * 40, (Math.random() - 0.5) * 80));
+ lightning.build(boltTop, boltBot);
+ SU.uFlashDir.value.copy(boltTop).lerp(boltBot, 0.35).sub(camera.position).normalize();
+ const toBolt = tmpV.copy(boltTop).sub(tmpV2.set(0, 0, 0)).normalize();
+ OU.uFlashDir.value.copy(toBolt);
+ bolt.position.copy(toBolt).multiplyScalar(60);
+ flashEl.style.setProperty('--fx', ((nx + 1) * 50).toFixed(0) + '%');
+ const p = Math.min(1, power * (0.75 + Math.random() * 0.5));
+ // short strobes: the frame is only hot for a frame or two, then an afterglow that stays well below white
+ gsap.killTweensOf(flash);
+ gsap.timeline()
+ .set(flash, { v: p })
+ .to(flash, { v: 0.08 * p, duration: 0.035, ease: 'power2.in' })
+ .to(flash, { v: 0.55 * p, duration: 0.025 })
+ .to(flash, { v: 0.12 * p, duration: 0.09 })
+ .to(flash, { v: 0.42 * p, duration: 0.03, delay: 0.06 })
+ .to(flash, { v: 0, duration: 0.42, ease: 'power3.out' });
+ audio.thunder(dist / 180, p);
+}
+
+// ─── HUD: conditions log, rooms, route ─────────────────────────────────────────
+const logEls = Object.fromEntries([...document.querySelectorAll('[data-log]')].map(e => [e.dataset.log, e]));
+let lastLog = '';
+function logTime() {
+ const s = camState.story ?? 0;
+ const mins = 2 * 60 + 47 + s * 26 + (engine.time / 60);
+ const hh = Math.floor(mins / 60) % 24, mm = Math.floor(mins % 60);
+ return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
+}
+function updateLog(storm) {
+ const i = storm > 0.88 ? 0 : storm > 0.7 ? 1 : storm > 0.5 ? 2 : storm > 0.25 ? 3 : 4;
+ const wind = ['SW 9, severe gale', 'SW 8, gale', 'W 6, strong breeze', 'W 4, moderate', 'W 2, light air'][i];
+ const sea = ['Very high', 'High', 'Rough', 'Moderate', 'Smooth'][i];
+ const vis = ['0.4 NM, heavy rain', '1 NM, rain', '4 NM, showers', '10 NM, clearing', 'Excellent'][i];
+ const time = logTime();
+ const key = time + i;
+ if (key === lastLog) return;
+ lastLog = key;
+ logEls.time.textContent = time; logEls.wind.textContent = wind; logEls.sea.textContent = sea; logEls.vis.textContent = vis;
+}
+const rooms = [...document.querySelectorAll('.room')];
+const pins = [...document.querySelectorAll('.pin')];
+const roomIdx = [...document.querySelectorAll('.room-index li')];
+const PIN_AT = [A(0.7, 3.9, -0.02), A(2.35, 4.6, -1.3), A(AXIS.x, 9.62, AXIS.y + 1.08), A(AXIS.x, 10.72, AXIS.y + 0.66)];
+let activeRoom = -1;
+function setRoom(i) {
+ if (i === activeRoom) return;
+ const prev = rooms[activeRoom];
+ activeRoom = i;
+ rooms.forEach(r => { if (r !== prev) { gsap.killTweensOf(r); gsap.set(r, { autoAlpha: 0 }); } });
+ if (prev) { gsap.killTweensOf(prev); gsap.to(prev, { autoAlpha: 0, y: -18, duration: 0.4, ease: 'power2.in' }); }
+ const cur = rooms[i];
+ if (cur) {
+ gsap.fromTo(cur, { autoAlpha: 0, y: 26 }, { autoAlpha: 1, y: 0, duration: 0.9, ease: 'expo.out', delay: prev ? 0.28 : 0 });
+ gsap.fromTo(cur.querySelector('img'), { scale: 1.12 }, { scale: 1, duration: 1.6, ease: 'expo.out', delay: prev ? 0.28 : 0 });
+ }
+ roomIdx.forEach((li, k) => li.classList.toggle('on', k === i));
+}
+const routeEl = document.querySelector('.route');
+const navLinks = [...document.querySelectorAll('.links a')];
+
+const ratesEl = document.querySelector('.rates');
+document.querySelector('.rates-toggle').addEventListener('click', e => {
+ const open = ratesEl.classList.toggle('open');
+ e.currentTarget.setAttribute('aria-expanded', open);
+ e.currentTarget.firstChild.textContent = open ? 'Close ' : 'All rooms ';
+});
+
+// ─── Audio ─────────────────────────────────────────────────────────────────────
+const audio = new StormAudio();
+const soundBtn = document.querySelector('.sound');
+soundBtn.addEventListener('click', () => {
+ const on = audio.toggle();
+ soundBtn.setAttribute('aria-pressed', on);
+ soundBtn.querySelector('.sound-label').textContent = on ? 'Sound on' : 'Sound off';
+});
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+let story = 0, storySm = 0;
+const camPos = new THREE.Vector3();
+const glareV = new THREE.Vector3();
+let sprayT = 0;
+const rockEdge = new THREE.Vector3();
+const cursorApi = cursor({ color: '#ffe2a6', blend: 'normal', size: 30 });
+let cursorLabel = '';
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ story = storyAt(scrollY);
+ storySm = damp(storySm, story, 4.5, dt);
+ sampleKF(storySm, camState);
+ camState.story = storySm;
+ interactive = storySm < 1.75;
+ document.body.classList.toggle('is-past-hero', storySm > 0.5);
+ document.body.classList.toggle('is-foot', storySm > 7.7);
+
+ // camera: orbit + slow sea-swell drift + a little parallax from the pointer
+ camPosFrom(camState, camPos);
+ const sway = camState.storm;
+ camPos.x += Math.sin(t * 0.21) * 0.25 * sway + pointer.sx * 0.5;
+ camPos.y += Math.sin(t * 0.33) * 0.18 * sway + pointer.sy * 0.25;
+ camera.position.copy(camPos);
+ camera.lookAt(tmpV.copy(camState.look).add(tmpV2.set(pointer.sx * 0.35, pointer.sy * 0.2, 0)));
+ camera.rotateZ(Math.sin(t * 0.27) * 0.004 * sway);
+ camera.fov = camState.fov;
+ const W = innerWidth, H = innerHeight;
+ camera.setViewOffset(W, H, -camState.sx * W, camState.sy * H, W, H);
+ camera.updateMatrixWorld();
+ sky.mesh.position.copy(camera.position);
+
+ // weather and light
+ const storm = camState.storm, dawn = camState.dawn;
+ waves.time = t;
+ applyAtmosphere(storm, dawn, camState.lamp, t);
+ updateBeam(dt, t);
+ const lampPow = camState.lamp * intro.lamp;
+ const bcol = tmpC.copy(LAMP_COL);
+ const glareDot = Math.max(beamDir[0].dot(glareV.copy(camera.position).sub(LAMP).normalize()), beamDir[1].dot(glareV));
+ const glare = smooth(Math.cos(0.17), Math.cos(0.015), glareDot) * lampPow;
+ const bu = beams.uniforms;
+ bu.get('uLamp').value.copy(LAMP);
+ bu.get('uDir0').value.copy(beamDir[0]); bu.get('uDir1').value.copy(beamDir[1]);
+ const lock = boat.state === 'lost' ? boat.hold / 2 : 0; // the beam gathers itself as you hold it on her
+ bu.get('uCol').value.copy(bcol).multiplyScalar(lampPow * (26 + beamFlash.v * 30 + lock * 12));
+ bu.get('uHalo').value.copy(bcol).multiplyScalar(lampPow * (0.018 + glare * 0.1) * (0.4 + storm * 0.6));
+ bu.get('uGlare').value.copy(bcol).multiplyScalar(glare * glare * 1.1);
+ bu.get('uWind').value.set(wind2.x * 1.4, -0.9, wind2.y * 1.4);
+ OU.uBeamDir.value[0].copy(beamDir[0]); OU.uBeamDir.value[1].copy(beamDir[1]);
+ OU.uBeamCol.value.copy(bcol).multiplyScalar(lampPow * 26 * (1 + beamFlash.v));
+ OU.uGlintCol.value.copy(bcol).multiplyScalar(lampPow * (0.009 + glare * 0.3));
+ LU.uBeamDir.value[0].copy(beamDir[0]); LU.uBeamDir.value[1].copy(beamDir[1]);
+ LU.uBeamI.value = lampPow * 1.3;
+ SU.uBeamDir.value[0].copy(beamDir[0]); SU.uBeamDir.value[1].copy(beamDir[1]);
+ SU.uBeamGlow.value.copy(bcol).multiplyScalar(lampPow * 0.05 * storm);
+ lhU.uLampPow.value = lampPow * (1 + glare * 2);
+ lhU.uB0.value.set(beamDir[0].x, beamDir[0].z).normalize(); lhU.uB1.value.set(beamDir[1].x, beamDir[1].z).normalize();
+ for (const s of spots) s.intensity = lampPow * 70;
+ lampGlow.intensity = lampPow * 9;
+ hearth.intensity = 5 * (1 - smooth(0.4, 1, dawn)) * intro.lamp;
+ engine.post.bloom.luminanceMaterial.threshold = lerp(0.42, 0.75, dawn);
+
+ // lightning
+ if (storm > 0.62 && t > nextStrike && intro.done && !DBG.has('nolit')) { strike(storm); nextStrike = t + 5 + Math.random() * 8; }
+ const f = flash.v;
+ // soft exposure cap for everything the flash floods; only the bolt itself uses the raw value
+ const fg = f / (1 + f * 1.1);
+ SU.uFlash.value = fg * 1.1; OU.uFlash.value = fg * 1.1; LU.uFlash.value = fg * 0.45;
+ bolt.intensity = fg * fg * 9;
+ lightning.mesh.visible = f > 0.06;
+ lightning.uniforms.uI.value = f;
+ flashEl.style.opacity = (fg * 0.1).toFixed(3);
+ engine.post.bloom.intensity = lerp(1.0, 0.45, dawn) + glare * 0.35 + fg * 0.1;
+
+ // flares
+ if (storySm > 2.2) { redFlare.state.t = -1; greenFlare.state.t = -1; }
+ redFlare.update(dt, wind2); greenFlare.update(dt, wind2);
+ const fl = redFlare.state.power > greenFlare.state.power ? redFlare : greenFlare;
+ flareLight.color.copy(fl.color);
+ flareLight.position.copy(fl.state.p);
+ flareLight.intensity = fl.state.power * 18;
+ const flareCol = tmpC.copy(fl.color).multiplyScalar(fl.state.power * 2.2);
+ OU.uFlarePos.value.copy(fl.state.p); OU.uFlareCol.value.copy(flareCol);
+ LU.uFlarePos.value.copy(fl.state.p); LU.uFlareCol.value.copy(flareCol).multiplyScalar(0.4);
+
+ // rain follows the camera; wind gusts
+ const gust = 1 + Math.sin(t * 0.7) * 0.25 + Math.sin(t * 1.9) * 0.1;
+ rain.uniforms.uCam.value.copy(camera.position);
+ rain.uniforms.uVel.value.set(wind2.x * 13 * gust * storm + 1, -30, wind2.y * 13 * gust * storm);
+
+ // surf bursting on the rock
+ sprayT -= dt;
+ if (sprayT <= 0 && storm > 0.15) {
+ sprayT = lerp(1.6, 0.35, storm) * (0.5 + Math.random());
+ const side = Math.floor(Math.random() * 4);
+ const u = Math.random() * 2 - 1;
+ const hx = 3.3, hz = 3.0, cx = 0.1, cz = -0.45;
+ const [x, z, nx, nz] = side === 0 ? [cx + hx, cz + u * hz, 1, 0] : side === 1 ? [cx - hx, cz + u * hz, -1, 0] : side === 2 ? [cx + u * hx, cz + hz, 0, 1] : [cx + u * hx, cz - hz, 0, -1];
+ rockEdge.set(x + nx * 0.6, waves.height(x + nx, z + nz) - 0.2, z + nz * 0.6);
+ spray.burst(rockEdge, nx, nz, Math.round(lerp(40, 280, storm)), lerp(0.4, 1.15, storm));
+ }
+ spray.update(dt, wind2);
+
+ // the boat
+ updateBoat(dt, t, storySm);
+
+ // boat marker
+ if (boat.group.visible && (boat.state === 'lost' || (boat.state === 'guided' && boat.t < 3.2)) && storySm < 1.7) {
+ tmpV.set(boat.pos.x, boat.y + 1.6, boat.pos.y).project(camera);
+ const on = tmpV.z < 1 && Math.abs(tmpV.x) < 1.05 && Math.abs(tmpV.y) < 1.05;
+ boat.screen = on ? [(tmpV.x * 0.5 + 0.5) * W, (-tmpV.y * 0.5 + 0.5) * H] : null;
+ markEl.classList.toggle('on', on && boat.fade > 0.5 && (storySm > 0.35 || boat.found));
+ const sx = (tmpV.x * 0.5 + 0.5) * W, sy = (-tmpV.y * 0.5 + 0.5) * H;
+ markEl.style.transform = `translate3d(${sx.toFixed(1)}px, ${sy.toFixed(1)}px, 0)`;
+ const p = boat.state === 'guided' ? 1 : boat.hold / 2;
+ markFill.style.strokeDashoffset = (188.5 * (1 - p)).toFixed(1);
+ markEl.classList.toggle('hold', boat.state === 'lost' && boat.hold > 0.02);
+ markEl.classList.toggle('home', boat.state === 'guided');
+ const label = boat.state === 'guided' ? `${boat.name} — heading home` : boat.hold > 0.02 ? `Hold the light · ${(2 - boat.hold).toFixed(1)}s` : 'Boat in distress';
+ if (label !== markLabel.textContent) markLabel.textContent = label;
+ const over = on && Math.hypot(sx - pointer.px, sy - pointer.py) < 60;
+ const cl = over && boat.state === 'lost' ? 'hold' : '';
+ if (cursorApi && cl !== cursorLabel) { cursorLabel = cl; cursorApi.set(cl ? 'drag' : '', cl ? 'Hold' : ''); }
+ } else markEl.classList.remove('on');
+
+ // rooms: cards + pins
+ const ri = storySm > 1.62 && storySm < 5.45 ? clamp(Math.round(storySm - 2), 0, 3) : -1;
+ setRoom(ri);
+ pins.forEach((pin, k) => {
+ const on = k === ri && Math.abs(storySm - (k + 2)) < 0.3;
+ pin.classList.toggle('on', on);
+ if (Math.abs(storySm - (k + 2)) < 0.8) {
+ tmpV.copy(PIN_AT[k]).project(camera);
+ pin.style.transform = `translate3d(${((tmpV.x * 0.5 + 0.5) * W).toFixed(1)}px, ${((-tmpV.y * 0.5 + 0.5) * H).toFixed(1)}px, 0)`;
+ }
+ });
+ routeEl.style.setProperty('--rp', clamp((storySm - 5.4) / 1.3).toFixed(3));
+ const sec = storySm < 0.5 ? -1 : storySm < 1.6 ? 0 : storySm < 5.5 ? 1 : storySm < 6.5 ? 2 : 3;
+ navLinks.forEach((a, k) => a.classList.toggle('on', k === sec));
+ updateLog(storm);
+ audio.setStorm(storm);
+
+ // planar reflection only matters once the sea has calmed enough to hold an image
+ reflection.enabled = !DBG.has('norefl');
+ if (reflection.enabled) reflection.update(scene, camera);
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+const intro = { lamp: 0, done: false };
+worldNav('keeper', { theme: 'dark', corner: 'bl' });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? 0 : document.querySelector(id);
+ if (el === null) return;
+ e.preventDefault();
+ let y = el === 0 ? 0 : el.getBoundingClientRect().top + scrollY;
+ if (id === '#reserve' || id === '#dawn') y = stops.find(s => s[1] === 7)?.[0] ?? y;
+ if (id === '#storm') y = stops.find(s => s[1] === 1)?.[0] ?? y;
+ lenis.scrollTo(y, { duration: 2.2 });
+}));
+layoutStops();
+addEventListener('resize', () => { layoutStops(); placeHarbour(); placeSky(); });
+reveal('.storm h2, .crossing h2, .dawn h2, .rooms-head h2, .foot-title', { type: 'lines', stagger: 0.1 });
+// each chapter's copy lifts away as the next scene takes the frame
+for (const [sec, inner] of [['.hero', '.hero-inner'], ['.storm', '.storm-sticky'], ['.rooms', '.rooms-sticky'], ['.crossing', '.crossing-sticky'], ['.dawn', '.dawn-sticky']]) {
+ gsap.fromTo(inner, { opacity: 1, y: 0 }, { opacity: 0, y: -50, ease: 'none', immediateRender: false,
+ scrollTrigger: { trigger: sec, start: 'bottom 98%', end: 'bottom 45%', scrub: true } });
+}
+reveal('.storm .lede, .crossing .lede, .dawn .lede', { type: 'lines', stagger: 0.05, y: '100%' });
+
+await Promise.all([lhLoad, boatLoad]);
+placeHarbour();
+placeSky();
+spawnBoat();
+// Compile every program up front with every light on, so nothing hitches later.
+intro.lamp = 1; flash.v = 1; boat.group.visible = true;
+sampleKF(0, camState);
+camPosFrom(camState, camera.position); camera.lookAt(camState.look);
+applyAtmosphere(1, 0, 1, 0);
+renderer.compile(scene, camera);
+flash.v = 0; intro.lamp = 0;
+engine.start();
+await loader.finish();
+
+// Intro: darkness, the lamp stutters on, then the storm shows itself.
+gsap.timeline({ delay: 0.15 })
+ .to(intro, { lamp: 0.6, duration: 0.05 })
+ .to(intro, { lamp: 0.05, duration: 0.08, delay: 0.06 })
+ .to(intro, { lamp: 0.85, duration: 0.05, delay: 0.16 })
+ .to(intro, { lamp: 0.25, duration: 0.07, delay: 0.05 })
+ .to(intro, { lamp: 1, duration: 0.9, ease: 'power2.out', delay: 0.1 })
+ .add(() => { intro.done = true; if (!DBG.has('nolit')) strike(1.1); nextStrike = engine.time + 6; }, '-=0.3');
+gsap.from('.title span', { yPercent: 60, opacity: 0, duration: 2, ease: 'expo.out', stagger: 0.14, delay: 0.5 });
+gsap.from('.hero .eyebrow, .hero-foot, .nav', { opacity: 0, y: 16, duration: 1.4, ease: 'power3.out', stagger: 0.08, delay: 1.1 });
+setTimeout(() => document.body.classList.add('is-ready'), 1700);
+
+if (DBG.has('s')) { const s = +DBG.get('s'); const y = (() => { for (const [yy, k] of stops) if (k >= s) return yy; return 0; })(); lenis.scrollTo(y, { immediate: true }); }
+window.__keeperReady = true;
+window.__keeper = {
+ scene, camera, THREE,
+ boatScreen() {
+ const v = new THREE.Vector3(boat.pos.x, boat.y + 1.2, boat.pos.y).project(camera);
+ return [v.x * 0.5 + 0.5, -v.y * 0.5 + 0.5];
+ }, boat, beam, strike, guideBoat, spawnBoat, camState, stops, waves, ocean, OU, SU, engine, flash };
diff --git a/examples/keeper/ocean.js b/examples/keeper/ocean.js
new file mode 100644
index 0000000..3b27814
--- /dev/null
+++ b/examples/keeper/ocean.js
@@ -0,0 +1,338 @@
+// Gerstner-wave ocean: one wave set evaluated identically on the GPU (surface) and the CPU (boat buoyancy).
+// Shading is custom: fresnel sky + planar reflection, green subsurface in wave backs, crest/rock/wake foam,
+// and the lighthouse beams, lamp glint, lightning, flares and the dawn sun all light the water directly.
+import { THREE } from '../../src/core/engine.js';
+
+// [direction (deg), wavelength, steepness at full storm, steepness at dawn]
+const WAVES = [
+ [18, 52, 0.16, 0.06],
+ [-14, 34, 0.15, 0.035],
+ [40, 21, 0.14, 0.012],
+ [-40, 13.5, 0.13, 0.008],
+ [72, 8.4, 0.11, 0.006],
+ [4, 5.1, 0.09, 0.004],
+];
+const N = WAVES.length;
+const G = 7.2; // gravity in scene units (1 unit ≈ 1.8 m) — slightly slowed for weight
+export const ROCK = { c: new THREE.Vector2(0.1, -0.45), half: new THREE.Vector2(3.35, 3.05), r: 0.9 };
+
+export class Waves {
+ constructor() {
+ this.dir = WAVES.map(w => new THREE.Vector2(Math.cos(w[0] * Math.PI / 180), Math.sin(w[0] * Math.PI / 180)));
+ this.k = WAVES.map(w => 2 * Math.PI / w[1]);
+ this.w = this.k.map(k => Math.sqrt(G * k));
+ this.steep = WAVES.map(w => w[2]);
+ this.u = {
+ uWA: { value: WAVES.map(() => new THREE.Vector4()) }, // dir.x, dir.y, k, amplitude
+ uWS: { value: new Array(N).fill(0) }, // steepness (a*k)
+ uWO: { value: this.w.slice() }, // omega
+ uWTime: { value: 0 },
+ uRock: { value: ROCK.c },
+ };
+ this.setStorm(1);
+ }
+
+ setStorm(s) {
+ this.storm = s;
+ for (let i = 0; i < N; i++) {
+ const st = WAVES[i][3] + (WAVES[i][2] - WAVES[i][3]) * s;
+ this.steep[i] = st;
+ const d = this.dir[i];
+ this.u.uWA.value[i].set(d.x, d.y, this.k[i], st / this.k[i]);
+ this.u.uWS.value[i] = st;
+ }
+ }
+
+ set time(t) { this.u.uWTime.value = t; }
+ get time() { return this.u.uWTime.value; }
+
+ rockAtt(x, z) {
+ const dx = x - ROCK.c.x, dz = z - ROCK.c.y;
+ const d = Math.hypot(dx, dz);
+ const t = Math.min(1, Math.max(0, (d - 4.5) / (15 - 4.5)));
+ return 0.28 + 0.72 * t * t * (3 - 2 * t);
+ }
+
+ /** Displacement of the base point (x,z) → out {x,y,z} (absolute world position). */
+ displace(x, z, out) {
+ const t = this.time, att = this.rockAtt(x, z);
+ let dx = 0, dy = 0, dz = 0;
+ for (let i = 0; i < N; i++) {
+ const d = this.dir[i], k = this.k[i], a = this.steep[i] / k * att;
+ const f = k * (d.x * x + d.y * z) - this.w[i] * t;
+ const c = Math.cos(f);
+ dx += d.x * a * c; dz += d.y * a * c; dy += a * Math.sin(f);
+ }
+ out.x = x + dx; out.y = dy; out.z = z + dz;
+ return out;
+ }
+
+ /** Surface height at world (x,z): invert the horizontal displacement with a few fixed-point steps. */
+ height(x, z) {
+ const o = this._o ??= { x: 0, y: 0, z: 0 };
+ let bx = x, bz = z;
+ for (let i = 0; i < 3; i++) { this.displace(bx, bz, o); bx += x - o.x; bz += z - o.z; }
+ return this.displace(bx, bz, o).y;
+ }
+}
+
+export const WAVE_GLSL = /* glsl */`
+ uniform vec4 uWA[${N}];
+ uniform float uWS[${N}];
+ uniform float uWO[${N}];
+ uniform float uWTime;
+ uniform vec2 uRock;
+ float rockAtt(vec2 p){ float d = length(p - uRock); return 0.28 + 0.72 * smoothstep(4.5, 15.0, d); }
+ // Short waves fade with distance so the horizon never aliases.
+ float waveLod(int i, float dist){ return uWA[i].z > 0.4 ? 1.0 - smoothstep(110.0, 320.0, dist) : 1.0; }
+ vec3 gerstner(vec2 p, float dist){
+ float att = rockAtt(p);
+ vec3 d = vec3(0.0);
+ for (int i = 0; i < ${N}; i++) {
+ vec4 w = uWA[i];
+ float f = w.z * dot(w.xy, p) - uWO[i] * uWTime;
+ float a = w.w * att * waveLod(i, dist);
+ float c = cos(f);
+ d += vec3(w.x * a * c, a * sin(f), w.y * a * c);
+ }
+ return d;
+ }
+ // Analytic normal + Jacobian (foam where the surface folds).
+ vec3 gerstnerNormal(vec2 p, float dist, out float jac){
+ float att = rockAtt(p);
+ float sxx = 0.0, szz = 0.0, sxz = 0.0, nx = 0.0, nz = 0.0;
+ for (int i = 0; i < ${N}; i++) {
+ vec4 w = uWA[i];
+ float f = w.z * dot(w.xy, p) - uWO[i] * uWTime;
+ float s = uWS[i] * att * waveLod(i, dist);
+ float sn = sin(f), cs = cos(f);
+ sxx += w.x * w.x * s * sn; szz += w.y * w.y * s * sn; sxz += w.x * w.y * s * sn;
+ nx += w.x * s * cs; nz += w.y * s * cs;
+ }
+ vec3 tx = vec3(1.0 - sxx, nx, -sxz);
+ vec3 tz = vec3(-sxz, nz, 1.0 - szz);
+ jac = (1.0 - sxx) * (1.0 - szz) - sxz * sxz;
+ return normalize(cross(tz, tx));
+ }
+`;
+
+/** Polar grid centred on the rock: dense around it, stretching to the horizon. */
+export function oceanGeometry({ segs = 640, r0 = 1.2, rMax = 1400, dr0 = 0.14, grow = 0.017 } = {}) {
+ const radii = [];
+ for (let r = r0; r < rMax; r += Math.max(dr0, r * grow)) radii.push(r);
+ radii.push(rMax);
+ const R = radii.length;
+ const pos = new Float32Array(R * segs * 3);
+ for (let i = 0; i < R; i++) for (let j = 0; j < segs; j++) {
+ const a = j / segs * Math.PI * 2, k = (i * segs + j) * 3;
+ pos[k] = ROCK.c.x + Math.cos(a) * radii[i]; pos[k + 1] = 0; pos[k + 2] = ROCK.c.y + Math.sin(a) * radii[i];
+ }
+ const idx = new Uint32Array((R - 1) * segs * 6);
+ let n = 0;
+ for (let i = 0; i < R - 1; i++) for (let j = 0; j < segs; j++) {
+ const a = i * segs + j, b = i * segs + (j + 1) % segs, c = (i + 1) * segs + j, d = (i + 1) * segs + (j + 1) % segs;
+ idx[n++] = a; idx[n++] = b; idx[n++] = c; idx[n++] = b; idx[n++] = d; idx[n++] = c;
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setIndex(new THREE.BufferAttribute(idx, 1));
+ g.boundingSphere = new THREE.Sphere(new THREE.Vector3(), rMax + 10);
+ return g;
+}
+
+export function oceanMaterial({ waves, refl, foamTex, detailN, env }) {
+ const uniforms = {
+ ...waves.u,
+ ...refl.uniforms,
+ uTime: { value: 0 },
+ uFoamTex: { value: foamTex },
+ uDetailN: { value: detailN },
+ uStorm: { value: 1 },
+ uDawn: { value: 0 },
+ uWind: { value: new THREE.Vector2(0.94, 0.34) },
+ // palette (animated from JS)
+ uDeep: { value: new THREE.Color() },
+ uSSS: { value: new THREE.Color() },
+ uSkyZen: { value: new THREE.Color() },
+ uSkyHor: { value: new THREE.Color() },
+ uAmb: { value: new THREE.Color() },
+ uFogCol: { value: new THREE.Color() },
+ uFogDen: { value: 0.006 },
+ // lighthouse
+ uLamp: { value: new THREE.Vector3() },
+ uBeamDir: { value: [new THREE.Vector3(1, 0, 0), new THREE.Vector3(-1, 0, 0)] },
+ uBeamCos: { value: new THREE.Vector2(0.99, 0.997) },
+ uBeamCol: { value: new THREE.Color() },
+ uGlintCol: { value: new THREE.Color() },
+ // lightning, flare, sun
+ uFlash: { value: 0 },
+ uFlashDir: { value: new THREE.Vector3(0, 1, 0) },
+ uFlashCol: { value: new THREE.Color(0.75, 0.82, 1.0) },
+ uFlarePos: { value: new THREE.Vector3(0, -100, 0) },
+ uFlareCol: { value: new THREE.Color(0, 0, 0) },
+ uSunDir: { value: new THREE.Vector3(0, 0.05, -1).normalize() },
+ uSunCol: { value: new THREE.Color(0, 0, 0) },
+ uMoonDir: { value: new THREE.Vector3(0, 0.3, -1).normalize() },
+ uMoonCol: { value: new THREE.Color(0, 0, 0) },
+ // boat (for hull foam + wake)
+ uBoat: { value: new THREE.Vector4(0, 0, 0, 1) }, // x, z, heading, visible
+ uWake: { value: 0 },
+ uReflAmt: { value: 0.5 },
+ uDebug: { value: 0 },
+ };
+ const mat = new THREE.ShaderMaterial({
+ uniforms,
+ vertexShader: /* glsl */`
+ ${WAVE_GLSL}
+ varying vec2 vBase;
+ varying vec3 vWorld;
+ varying float vDist;
+ void main(){
+ vec3 wp = (modelMatrix * vec4(position, 1.0)).xyz;
+ float dist = length(wp.xz - cameraPosition.xz);
+ vec3 d = gerstner(wp.xz, dist);
+ vBase = wp.xz; vDist = dist;
+ wp += d;
+ vWorld = wp;
+ gl_Position = projectionMatrix * viewMatrix * vec4(wp, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ ${WAVE_GLSL}
+ uniform float uTime, uStorm, uDawn, uFogDen, uFlash, uWake, uReflAmt, uDebug;
+ uniform vec2 uWind;
+ uniform sampler2D uFoamTex, uDetailN, uRefl;
+ uniform mat4 uReflMat;
+ uniform vec3 uDeep, uSSS, uSkyZen, uSkyHor, uAmb, uFogCol;
+ uniform vec3 uLamp, uBeamDir[2], uBeamCol, uGlintCol;
+ uniform vec2 uBeamCos;
+ uniform vec3 uFlashDir, uFlashCol, uFlarePos, uFlareCol, uSunDir, uSunCol, uMoonDir, uMoonCol;
+ uniform vec4 uBoat;
+ varying vec2 vBase;
+ varying vec3 vWorld;
+ varying float vDist;
+
+ float sdRock(vec2 p){
+ vec2 q = abs(p - uRock) - vec2(${ROCK.half.x.toFixed(2)}, ${ROCK.half.y.toFixed(2)}) + ${ROCK.r.toFixed(2)};
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - ${ROCK.r.toFixed(2)};
+ }
+ float ggx(vec3 N, vec3 V, vec3 L, float r){
+ vec3 H = normalize(V + L);
+ float nh = max(dot(N, H), 0.0), a2 = r * r * r * r;
+ float d = nh * nh * (a2 - 1.0) + 1.0;
+ return a2 / (3.14159 * d * d) * max(dot(N, L), 0.0);
+ }
+ vec3 skyCol(vec3 R){
+ float y = max(R.y, 0.0);
+ vec3 c = mix(uSkyHor, uSkyZen, pow(smoothstep(0.0, 0.7, y), 0.7));
+ float sd = max(dot(R, uSunDir), 0.0);
+ c += uSunCol * (pow(sd, 6.0) * 0.12 + pow(sd, 60.0) * 0.8);
+ c += uFlashCol * uFlash * uFlash * (0.12 + 1.3 * pow(max(dot(R, uFlashDir), 0.0), 4.0));
+ return c;
+ }
+ void main(){
+ float jac;
+ vec3 N = gerstnerNormal(vBase, vDist, jac);
+ vec3 P = vWorld;
+ vec3 V = normalize(cameraPosition - P);
+ float dist = length(cameraPosition - P);
+
+ // Wind chop: two scrolling detail normal layers, fading with distance.
+ float chop = mix(0.18, 1.0, uStorm) * (1.0 - smoothstep(40.0, 260.0, dist));
+ vec2 w = uWind * uTime;
+ vec3 n1 = texture2D(uDetailN, vBase * 0.045 + w * 0.012).xyz * 2.0 - 1.0;
+ vec3 n2 = texture2D(uDetailN, vBase * 0.11 - w.yx * 0.02).xyz * 2.0 - 1.0;
+ vec3 n3 = texture2D(uDetailN, vBase * 0.31 + w * 0.05).xyz * 2.0 - 1.0;
+ vec2 dn = (n1.xy * 0.55 + n2.xy * 0.35 + n3.xy * 0.22 * (1.0 - smoothstep(10.0, 60.0, dist))) * chop;
+ N = normalize(N + vec3(dn.x, 0.0, dn.y) * 0.9);
+
+ // ── Foam: folding crests, wind streaks, the rock, the boat.
+ float h = P.y;
+ vec2 fuv = vBase * 0.07 + w * 0.006;
+ vec4 ft = texture2D(uFoamTex, fuv);
+ vec4 ft2 = texture2D(uFoamTex, vBase * 0.19 - w * 0.011);
+ float lace = ft.r * 0.6 + ft2.r * 0.55;
+ float crest = smoothstep(0.98, 0.42, jac) * smoothstep(-0.2, 1.4, h) + smoothstep(1.1, 2.6, h) * 0.6;
+ float streak = texture2D(uFoamTex, vec2(dot(vBase, uWind) * 0.012 + uTime * 0.01, dot(vBase, vec2(-uWind.y, uWind.x)) * 0.09)).g;
+ float foam = crest * (0.35 + lace) * uStorm;
+ foam += smoothstep(0.52, 0.86, streak) * 0.36 * uStorm * smoothstep(0.1, 0.8, lace + ft.g * 0.4);
+ // churning surf around the rock, with pulses rolling outward
+ float rd = sdRock(vBase + (ft2.gb - 0.5) * 1.6);
+ float surf = exp(-max(rd, 0.0) * mix(0.42, 1.6, 1.0 - uStorm));
+ float pulse = 0.55 + 0.45 * sin(rd * 2.4 - uTime * 1.7 + ft.g * 4.0);
+ foam += surf * (0.5 + lace * 0.9) * mix(0.35, 1.0, uStorm) * mix(1.0, pulse, smoothstep(0.3, 3.5, rd));
+ // the boat: hull wash + Kelvin wake
+ if (uBoat.w > 0.0) {
+ vec2 bf = vec2(sin(uBoat.z), cos(uBoat.z));
+ vec2 rel = vBase - uBoat.xy;
+ float u = dot(rel, bf), v = dot(rel, vec2(bf.y, -bf.x));
+ float hull = length(vec2(u / 2.9, v / 0.95));
+ foam += smoothstep(1.18, 0.92, hull) * (0.25 + lace * 0.9) * uBoat.w;
+ float back = max(-u, 0.0);
+ float arm = abs(abs(v) - back * 0.36);
+ float wake = smoothstep(1.2, 0.0, arm) * smoothstep(0.0, 2.0, back) * exp(-back * 0.045);
+ float wash = smoothstep(1.4, 0.0, abs(v) - back * 0.06) * smoothstep(0.0, 1.5, -u + 0.5) * exp(-back * 0.07);
+ foam += (wake * 0.7 + wash * 0.9) * (0.35 + lace) * uWake * uBoat.w;
+ }
+ foam = clamp(foam, 0.0, 1.0);
+ foam *= 1.0 - smoothstep(180.0, 420.0, dist);
+
+ // ── Lighting
+ float ndv = max(dot(N, V), 0.0);
+ float F = 0.02 + 0.98 * pow(1.0 - ndv, 5.0);
+ vec3 R = reflect(-V, N);
+ vec3 refl = skyCol(vec3(R.x, abs(R.y), R.z));
+ // planar reflection of the lighthouse, boat and sky (rough sea blurs it)
+ {
+ vec4 rp = uReflMat * vec4(vBase.x, 0.0, vBase.y, 1.0);
+ vec2 ruv = rp.xy / rp.w + N.xz * mix(0.035, 0.09, uStorm);
+ float lod = mix(1.0, 3.5, uStorm);
+ vec3 pr = textureLod(uRefl, ruv, lod).rgb;
+ float edge = smoothstep(0.0, 0.05, ruv.x) * smoothstep(1.0, 0.95, ruv.x) * smoothstep(0.0, 0.05, ruv.y) * smoothstep(1.0, 0.95, ruv.y);
+ refl = mix(refl, pr, edge * uReflAmt);
+ }
+
+ // lighthouse beams hitting the sea
+ vec3 Lv = P - uLamp;
+ float Ld = length(Lv);
+ vec3 T = Lv / Ld; // travel direction of lamp light
+ vec3 L = -T;
+ float cone = 0.0;
+ for (int i = 0; i < 2; i++) cone += smoothstep(uBeamCos.x, uBeamCos.y, dot(T, uBeamDir[i]));
+ vec3 E = uBeamCol * cone / (1.0 + Ld * Ld * 0.0009);
+ float thick = smoothstep(-0.6, 2.2, h);
+ vec3 lit = vec3(0.0);
+ lit += E * ggx(N, V, L, 0.22) * 0.9;
+ lit += E * (uSSS * (0.015 + 0.5 * pow(max(dot(T, V), 0.0), 3.0) * thick) + vec3(0.012, 0.009, 0.005) * max(dot(N, L), 0.0));
+ // the lantern itself glints on every wave between it and you
+ lit += uGlintCol * ggx(N, V, L, 0.3) / (1.0 + Ld * Ld * 0.0006);
+ // moon sheen behind the storm
+ lit += uMoonCol * ggx(N, V, uMoonDir, 0.32) * 0.9;
+
+ // lightning
+ lit += uFlashCol * uFlash * uFlash * (ggx(N, V, uFlashDir, 0.3) * 0.6 + uSSS * 2.0 * thick * 0.3 + 0.012);
+ // flare
+ vec3 fv = uFlarePos - P; float fd = length(fv); vec3 fl = fv / fd;
+ vec3 FE = uFlareCol / (1.0 + fd * fd * 0.01);
+ lit += FE * (0.006 + 0.02 * max(dot(N, fl), 0.0) + uSSS * 0.12 * thick);
+ // dawn sun: glitter path + light through the swell
+ lit += uSunCol * (ggx(N, V, uSunDir, mix(0.07, 0.25, uStorm)) * 1.2 + uSSS * 1.1 * pow(max(dot(-uSunDir, V), 0.0), 4.0) * thick);
+
+ vec3 body = uDeep * (0.6 + 0.4 * N.y) + uAmb * 0.35 + uSSS * uAmb * 2.0 * thick;
+ vec3 col = mix(body, refl, F) + lit;
+
+ // foam is lit, not glowing
+ vec3 foamLight = uAmb * 3.0 + uSkyHor * 3.5 + vec3(0.03, 0.036, 0.046) * uStorm + uMoonCol * 0.3 + uGlintCol * 7.0 / (1.0 + Ld * Ld * 0.012) + E * max(dot(N, L), 0.0) * 1.1 + uFlashCol * uFlash * uFlash * 0.6 + FE * 0.03 + uSunCol * 0.35 * max(uSunDir.y + 0.3, 0.0) + uGlintCol * 0.004;
+ col = mix(col, vec3(0.9, 0.93, 0.95) * foamLight, foam * 0.92);
+
+ // fog (rain haze thickens it)
+ float fog = 1.0 - exp(-pow(dist * uFogDen, 2.0));
+ vec3 fogc = uFogCol + uFlashCol * uFlash * uFlash * 0.05;
+ col = mix(col, fogc, fog);
+ if (uDebug > 0.5) col = vec3(foam, jac * 0.5, max(h, 0.0) * 0.3);
+ if (uDebug > 1.5) col = vec3(surf, clamp(rd * 0.05, 0.0, 1.0), lace);
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+ });
+ mat.extensions = { derivatives: true };
+ return mat;
+}
diff --git a/examples/keeper/sky.js b/examples/keeper/sky.js
new file mode 100644
index 0000000..f2bf39b
--- /dev/null
+++ b/examples/keeper/sky.js
@@ -0,0 +1,100 @@
+// Sky dome: storm gradient → dawn, two racing cloud layers projected onto planes (perspective-correct),
+// a moon smothered by cloud, lightning that lights the cloud interiors, and a low sun at dawn.
+import { THREE } from '../../src/core/engine.js';
+
+export function createSky() {
+ const uniforms = {
+ uTime: { value: 0 },
+ uZen: { value: new THREE.Color() },
+ uHor: { value: new THREE.Color() },
+ uCloudDark: { value: new THREE.Color() },
+ uCloudLit: { value: new THREE.Color() },
+ uCover: { value: 0.95 },
+ uStorm: { value: 1 },
+ uDawn: { value: 0 },
+ uSunDir: { value: new THREE.Vector3(0, 0.05, -1).normalize() },
+ uSunCol: { value: new THREE.Color(0, 0, 0) },
+ uMoonDir: { value: new THREE.Vector3(-0.4, 0.35, -0.8).normalize() },
+ uMoonCol: { value: new THREE.Color(0.16, 0.2, 0.28) },
+ uFlash: { value: 0 },
+ uFlashDir: { value: new THREE.Vector3(0, 0.3, -1).normalize() },
+ uFlashCol: { value: new THREE.Color(0.75, 0.82, 1.0) },
+ uWind: { value: new THREE.Vector2(0.94, 0.34) },
+ uBeamDir: { value: [new THREE.Vector3(1, 0, 0), new THREE.Vector3(-1, 0, 0)] },
+ uBeamGlow: { value: new THREE.Color(0, 0, 0) },
+ uLampDir: { value: new THREE.Vector3(0, 0, 1) },
+ };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, side: THREE.BackSide, depthWrite: false, fog: false,
+ vertexShader: /* glsl */`
+ varying vec3 vDir;
+ void main(){
+ vec4 wp = modelMatrix * vec4(position, 1.0);
+ vDir = wp.xyz - cameraPosition;
+ gl_Position = projectionMatrix * viewMatrix * wp;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform float uTime, uCover, uStorm, uDawn, uFlash;
+ uniform vec3 uZen, uHor, uCloudDark, uCloudLit, uSunDir, uSunCol, uMoonDir, uMoonCol, uFlashDir, uFlashCol, uBeamGlow, uLampDir;
+ uniform vec3 uBeamDir[2];
+ uniform vec2 uWind;
+ varying vec3 vDir;
+ float hash(vec2 p){ p = fract(p * vec2(123.34, 456.21)); p += dot(p, p + 45.32); return fract(p.x * p.y); }
+ float noise(vec2 p){
+ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hash(i), hash(i + vec2(1, 0)), f.x), mix(hash(i + vec2(0, 1)), hash(i + vec2(1, 1)), f.x), f.y);
+ }
+ float fbm(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 6; i++) { s += a * noise(p); p = p * 2.03 + vec2(1.7, 9.2); a *= 0.5; } return s; }
+ float fbm3(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 4; i++) { s += a * noise(p); p = p * 2.07 + vec2(5.1, 1.3); a *= 0.5; } return s; }
+ void main(){
+ vec3 d = normalize(vDir);
+ float y = d.y;
+ float yy = max(y, 0.0);
+ vec3 col = mix(uHor, uZen, pow(smoothstep(-0.02, mix(0.62, 0.4, uDawn), yy), mix(0.62, 0.8, uDawn)));
+ // sun & its wide dawn glow
+ float sd = max(dot(d, uSunDir), 0.0);
+ col += uSunCol * (pow(sd, 4.0) * 0.08 + pow(sd, 40.0) * 0.45 + smoothstep(0.99985, 0.99992, sd) * 9.0 * smoothstep(-0.004, 0.004, y));
+ // moon behind the storm
+ float md = max(dot(d, uMoonDir), 0.0);
+ col += uMoonCol * (pow(md, 40.0) * 2.0 + pow(md, 6.0) * 0.35) * (1.0 - uDawn);
+
+ float dens = 0.0;
+ if (y > -0.05) {
+ float yc = max(y, 0.0) + 0.05;
+ vec2 wind = uWind * uTime;
+ // high overcast, lit from above by a moon we never see
+ vec2 uv = d.xz / yc * 0.5;
+ float warp = fbm3(uv * 0.55 + wind * 0.006);
+ float hi = fbm(uv * 0.8 + vec2(warp * 1.6, warp) + wind * 0.022);
+ float cov = uCover;
+ float deck = smoothstep(1.0 - cov - 0.05, 1.0 - cov + 0.4, hi);
+ float bright = smoothstep(0.38, 0.78, hi);
+ vec3 hiCol = mix(uCloudDark, uCloudLit, bright);
+ hiCol += uMoonCol * pow(md, 8.0) * bright * 1.8 * (1.0 - uDawn);
+ hiCol += uSunCol * (pow(sd, 5.0) * 0.7 + 0.06) * mix(1.0, bright, 0.6) * uDawn;
+ float hz = smoothstep(-0.03, 0.14, y);
+ col = mix(col, hiCol, deck * mix(0.7, 1.0, hz));
+ // low racing scud: ragged, dark, fast
+ vec2 uv2 = d.xz / yc * 1.35;
+ float lo = fbm3(uv2 * 1.05 + wind * 0.2 + warp * 1.3);
+ float loM = smoothstep(0.5, 0.72, lo) * (0.2 + 0.8 * uStorm);
+ vec3 loCol = mix(uCloudDark * 0.55, uCloudDark * 1.4 + uSunCol * 0.05 * uDawn, smoothstep(0.72, 0.9, lo));
+ col = mix(col, loCol, loM * 0.92 * hz);
+ dens = max(deck, loM);
+ }
+ // lightning floods the cloud interiors around the strike
+ float fl = pow(max(dot(d, uFlashDir), 0.0), 5.0);
+ col += uFlashCol * (uFlash * (0.02 + pow(max(dot(d, uFlashDir), 0.0), 40.0) * 2.6) + uFlash * uFlash * (0.05 + fl * 2.2)) * (0.3 + dens);
+ // the beams light the rain haze low over the sea when they swing past this direction
+ vec2 dh = normalize(d.xz + 1e-5);
+ float bg = 0.0;
+ for (int i = 0; i < 2; i++) { vec2 bd = normalize(uBeamDir[i].xz + 1e-5); bg += pow(max(dot(dh, bd), 0.0), 60.0); }
+ col += uBeamGlow * bg * exp(-yy * 9.0);
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+ });
+ const mesh = new THREE.Mesh(new THREE.SphereGeometry(1500, 64, 32), mat);
+ mesh.frustumCulled = false;
+ mesh.renderOrder = -10;
+ return { mesh, uniforms };
+}
diff --git a/examples/keeper/style.css b/examples/keeper/style.css
new file mode 100644
index 0000000..6362efb
--- /dev/null
+++ b/examples/keeper/style.css
@@ -0,0 +1,293 @@
+:root {
+ --bg: #05080c;
+ --ink: #ece7dc;
+ --muted: #8d979f;
+ --dim: #5d6770;
+ --lamp: #ffd27a;
+ --lamp-hot: #ffe7b0;
+ --dawn: #f6ada2;
+ --rule: rgba(236, 231, 220, .14);
+ --display: 'Libre Caslon Display', 'Libre Caslon Text', Georgia, serif;
+ --text: 'Libre Caslon Text', Georgia, serif;
+ --sans: 'Karla', system-ui, sans-serif;
+ --gut: clamp(18px, 4.2vw, 64px);
+ --accent: var(--lamp);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; overflow-x: clip; }
+.cta-short { display: none; }
+body { font: 400 16px/1.6 var(--sans); background: var(--bg); overflow-x: clip; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+.flash { position: fixed; inset: 0; z-index: 1; pointer-events: none; opacity: 0; background: radial-gradient(120% 90% at var(--fx, 30%) 0%, rgba(210, 222, 255, .55), rgba(170, 190, 240, .12) 60%, transparent); mix-blend-mode: screen; }
+.grade { position: fixed; inset: 0 0 auto 0; height: 190px; z-index: 1; pointer-events: none; background: linear-gradient(rgba(4, 6, 10, .55), transparent); }
+
+.eyebrow { font: 600 11px/1.2 var(--sans); letter-spacing: .24em; text-transform: uppercase; color: var(--lamp); display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }
+.eyebrow i { font-style: normal; color: var(--dim); }
+.eyebrow .num { font: 400 15px/1 var(--display); letter-spacing: 0; color: var(--ink); padding-right: 12px; border-right: 1px solid var(--rule); }
+h2 { font: 400 clamp(44px, 5.6vw, 92px)/.98 var(--display); letter-spacing: -.012em; margin-top: 22px; text-wrap: balance; }
+h2 em { font: italic 400 .86em/1 var(--text); color: var(--lamp); letter-spacing: -.02em; }
+.lede { margin-top: 24px; max-width: 31em; font: 400 clamp(16px, 1.22vw, 19px)/1.62 var(--sans); color: #c3c6c4; }
+.lede i { font-family: var(--text); color: var(--ink); }
+
+/* ── loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: radial-gradient(90% 70% at 50% 42%, #0b1118, var(--bg) 70%); display: grid; place-content: center; justify-items: center; gap: 14px; overflow: hidden; }
+.loader-lamp { position: relative; width: 14px; height: 14px; margin-bottom: 34px; }
+.loader-lamp b { position: absolute; inset: 0; border-radius: 50%; background: radial-gradient(circle, #fff6de, var(--lamp) 45%, rgba(255, 210, 122, 0) 72%);
+ opacity: calc(.25 + var(--p, 0) * .75); box-shadow: 0 0 calc(10px + var(--p, 0) * 40px) rgba(255, 210, 122, .7); }
+.loader-beam { position: absolute; left: 50%; top: 50%; width: 140vmax; height: 140vmax; transform: translate(-50%, -50%) rotate(0deg);
+ background: conic-gradient(from 84deg, transparent 0deg, rgba(255, 210, 122, .0) 2deg, rgba(255, 214, 140, .22) 5deg, rgba(255, 210, 122, 0) 9deg, transparent 12deg);
+ -webkit-mask: radial-gradient(circle, #000 0%, rgba(0,0,0,.5) 18%, transparent 46%); mask: radial-gradient(circle, #000 0%, rgba(0,0,0,.5) 18%, transparent 46%);
+ animation: lspin 7s linear infinite; opacity: calc(.2 + var(--p, 0) * .8); pointer-events: none; }
+.loader-beam.b2 { animation-delay: -3.5s; }
+@keyframes lspin { to { transform: translate(-50%, -50%) rotate(360deg); } }
+.loader-name { font: 400 clamp(34px, 4vw, 54px)/1 var(--display); letter-spacing: -.01em; position: relative; }
+.loader-line { font: italic 400 16px/1 var(--text); color: var(--muted); position: relative; }
+.loader-pct { display: inline-block; min-width: 2.2em; font-variant-numeric: tabular-nums; color: var(--lamp); font-style: normal; font-family: var(--sans); font-weight: 500; }
+.loader-char { font: 600 10px/1 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: var(--dim); margin-top: 26px; position: relative; }
+
+/* ── nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; padding: 24px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 400 21px/1 var(--display); letter-spacing: .005em; }
+.brand svg { width: 30px; height: 30px; color: var(--ink); overflow: visible; }
+.brand-beam { fill: var(--lamp); opacity: .8; transform-origin: 16px 8px; animation: bbeam 7s ease-in-out infinite; }
+@keyframes bbeam { 0%, 100% { transform: scaleX(1); opacity: .85; } 50% { transform: scaleX(-1); opacity: .85; } 24%, 76% { transform: scaleX(0); opacity: .2; } }
+.links { display: flex; gap: clamp(20px, 2.6vw, 40px); }
+.links a { text-decoration: none; font: 500 14px/1 var(--sans); color: #b9bec1; transition: color .3s; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: -7px; height: 1px; background: var(--lamp); transform: scaleX(0); transform-origin: left; transition: transform .45s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after, .links a.on::after { transform: scaleX(1); }
+.links a.on { color: var(--ink); }
+.nav-right { display: flex; align-items: center; gap: 18px; }
+.sound { display: flex; align-items: center; gap: 10px; font: 600 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); padding: 8px 4px; }
+.sound-bars { display: flex; align-items: flex-end; gap: 2px; height: 12px; }
+.sound-bars i { width: 2px; height: 3px; background: currentColor; transition: height .3s; }
+.sound[aria-pressed="true"] { color: var(--lamp); }
+.sound[aria-pressed="true"] .sound-bars i { animation: sbar 1.1s ease-in-out infinite; }
+.sound-bars i:nth-child(2) { animation-delay: -.3s !important; } .sound-bars i:nth-child(3) { animation-delay: -.7s !important; } .sound-bars i:nth-child(4) { animation-delay: -.5s !important; }
+@keyframes sbar { 0%, 100% { height: 3px; } 50% { height: 12px; } }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 2px; text-decoration: none;
+ font: 600 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; white-space: nowrap; transition: background .35s, color .35s, box-shadow .35s; }
+.btn-lamp { background: var(--lamp); color: #1a1206; box-shadow: 0 0 0 rgba(255, 210, 122, 0); }
+.btn-lamp:hover { background: var(--lamp-hot); box-shadow: 0 0 44px rgba(255, 210, 122, .45); }
+.btn-ghost { color: var(--ink); box-shadow: inset 0 0 0 1px rgba(236, 231, 220, .3); background: rgba(5, 8, 12, .28); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--lamp); color: #fff; }
+.nav .btn { height: 40px; padding: 0 18px; font-size: 11px; }
+
+/* ── conditions log ─────────────────────────────────────── */
+.log { position: fixed; right: var(--gut); bottom: 30px; z-index: 12; display: grid; gap: 7px; pointer-events: none; transition: opacity .6s; min-width: 270px; padding: 12px 16px 14px;
+ background: rgba(5, 8, 12, .42); backdrop-filter: blur(12px) saturate(1.2); -webkit-backdrop-filter: blur(12px) saturate(1.2); box-shadow: inset 0 0 0 1px rgba(236, 231, 220, .08); border-radius: 2px; }
+.log div:first-child { border-top: 0; padding-top: 0; }
+.log div { display: grid; grid-template-columns: 84px 1fr; gap: 14px; font: 500 11px/1.25 var(--sans); letter-spacing: .14em; text-transform: uppercase; border-top: 1px solid var(--rule); padding-top: 7px; }
+.log .k { color: #7f8a93; }
+.log .v { color: #cfd2cf; font-variant-numeric: tabular-nums; }
+.log, .hero-hint { opacity: 0; }
+.is-ready .log, .is-ready .hero-hint { opacity: 1; }
+.is-ready.is-foot .log { opacity: 0; }
+
+/* ── hero ───────────────────────────────────────────────── */
+.hero { position: relative; height: 128vh; z-index: 3; pointer-events: none; }
+.hero-inner { position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; justify-content: space-between; padding: 21vh var(--gut) 100px; }
+.hero .eyebrow { margin-bottom: 26px; }
+.title { font: 400 clamp(56px, 7.2vw, 128px)/.9 var(--display); letter-spacing: -.02em; display: grid; justify-items: start; align-content: start; text-shadow: 0 2px 40px rgba(0, 0, 0, .45); }
+.title span { display: block; }
+.title .l2 { margin-left: .9em; }
+.title .l3 { font: italic 400 clamp(26px, 2.75vw, 48px)/1.1 var(--text); color: var(--lamp); letter-spacing: -.01em; margin: .55em 0 0 2.05em; }
+.hero-foot { display: flex; align-items: flex-end; gap: 48px; flex-wrap: wrap; }
+.sub { max-width: 25em; font: 400 clamp(15px, 1.12vw, 18px)/1.6 var(--sans); color: #c3c7c6; }
+.ctas { display: flex; gap: 12px; flex-wrap: wrap; pointer-events: auto; }
+.hero-hint { position: fixed; left: 50%; bottom: 30px; transform: translateX(-50%); z-index: 12; display: flex; align-items: center; gap: 12px; font: 600 11px/1 var(--sans);
+ letter-spacing: .22em; text-transform: uppercase; color: #d9d6cc; padding: 12px 18px; border-radius: 99px; background: rgba(5, 8, 12, .42); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px);
+ box-shadow: inset 0 0 0 1px rgba(255, 210, 122, .22); transition: opacity .6s, transform .6s; pointer-events: none; white-space: nowrap; }
+.hero-hint .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--lamp); box-shadow: 0 0 12px var(--lamp); animation: pulse 1.8s ease-in-out infinite; }
+@keyframes pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(.55); opacity: .5; } }
+.hint-touch { display: none; }
+.is-ready.is-past-hero .hero-hint, .is-ready.has-aimed .hero-hint { opacity: 0; transform: translate(-50%, 10px); }
+
+/* ── storm ──────────────────────────────────────────────── */
+.storm { position: relative; height: 290vh; z-index: 3; pointer-events: none; }
+.storm-sticky { position: sticky; top: 0; height: 100vh; padding: 17vh var(--gut) 0; }
+.storm-copy { max-width: 440px; }
+.storm-copy h2 { font-size: clamp(46px, 5vw, 84px); }
+.how { list-style: none; margin-top: 30px; display: grid; gap: 10px; }
+.how li { font: 500 13px/1.3 var(--sans); color: #b6bbbd; display: flex; align-items: center; gap: 12px; }
+.how kbd { font: 600 10px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--lamp); padding: 7px 9px; border-radius: 2px; box-shadow: inset 0 0 0 1px rgba(255, 210, 122, .35); min-width: 64px; text-align: center; }
+.k-touch { display: none; }
+.tally { position: absolute; top: 17vh; right: var(--gut); text-align: right; display: grid; justify-items: end; }
+.tally-k { font: 600 11px/1.2 var(--sans); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); }
+.tally-v { font: 400 clamp(72px, 8vw, 132px)/.9 var(--display); color: var(--ink); font-variant-numeric: tabular-nums; margin-top: 10px; }
+.tally-n { display: inline-block; }
+.tally.bump .tally-n { animation: bump .9s cubic-bezier(.2,.9,.2,1); color: var(--lamp); }
+@keyframes bump { 0% { transform: translateY(40%) scale(.8); opacity: 0; } 100% { transform: none; opacity: 1; } }
+.tally-log { list-style: none; margin-top: 14px; display: grid; gap: 6px; }
+.tally-log li { font: italic 400 14px/1.3 var(--text); color: #b9bdbc; animation: fadeIn .8s ease both; }
+.tally-log li b { font: 600 10px/1 var(--sans); letter-spacing: .18em; color: var(--lamp); font-style: normal; margin-right: 8px; }
+@keyframes fadeIn { from { opacity: 0; transform: translateY(6px); } }
+.storm-foot { margin-top: 30px; padding-top: 18px; border-top: 1px solid var(--rule); max-width: 24em; font: italic 400 14.5px/1.5 var(--text); color: #9aa2a6; }
+
+/* boat marker (projected from 3D) */
+.boat-mark { position: fixed; left: 0; top: 0; z-index: 8; width: 80px; height: 80px; margin: -40px 0 0 -40px; pointer-events: none; opacity: 0; transition: opacity .5s; will-change: transform; }
+.boat-mark.on { opacity: 1; }
+.boat-mark svg { width: 100%; height: 100%; transform: rotate(-90deg); overflow: visible; }
+.bm-track { fill: none; stroke: rgba(255, 90, 70, .5); stroke-width: 1; stroke-dasharray: 3 5; animation: spin 14s linear infinite; transform-origin: 40px 40px; }
+.bm-fill { fill: none; stroke: var(--lamp); stroke-width: 2; stroke-dasharray: 188.5; stroke-dashoffset: 188.5; filter: drop-shadow(0 0 6px rgba(255, 210, 122, .8)); }
+@keyframes spin { to { transform: rotate(360deg); } }
+.boat-mark .bm-label { position: absolute; left: 50%; top: calc(100% + 6px); transform: translateX(-50%); white-space: nowrap; font: 600 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase;
+ color: #ffb3a6; text-shadow: 0 1px 12px rgba(0, 0, 0, .9); }
+.boat-mark.hold .bm-track { stroke: rgba(255, 210, 122, .45); }
+.boat-mark.hold .bm-label { color: var(--lamp); }
+.boat-mark.home .bm-track { stroke: rgba(160, 240, 190, .6); }
+.boat-mark.home .bm-label { color: #b6f2c9; }
+
+.toast { position: fixed; left: 50%; bottom: 84px; transform: translate(-50%, 16px); z-index: 40; padding: 15px 24px; border-radius: 2px; background: rgba(8, 12, 17, .72);
+ backdrop-filter: blur(12px); -webkit-backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px rgba(255, 210, 122, .3); font: italic 400 16px/1.3 var(--text); color: var(--ink);
+ opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; text-align: center; white-space: nowrap; }
+.toast b { font: 600 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--lamp); font-style: normal; margin-right: 10px; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+/* ── rooms ──────────────────────────────────────────────── */
+.rooms { position: relative; height: 560vh; z-index: 3; pointer-events: none; }
+.rooms-sticky { position: sticky; top: 0; height: 100vh; padding: 16vh var(--gut) 0; }
+.rooms-head h2 { font-size: clamp(40px, 4.4vw, 72px); max-width: 9em; }
+.room-stage { position: absolute; left: var(--gut); bottom: 108px; width: min(640px, 48vw); height: 330px; }
+.room { position: absolute; inset: 0; display: grid; grid-template-columns: 250px 1fr; gap: 30px; opacity: 0; visibility: hidden; }
+.room figure { position: relative; overflow: hidden; border-radius: 2px; box-shadow: 0 30px 60px -24px rgba(0, 0, 0, .8), inset 0 0 0 1px rgba(255,255,255,.08); }
+.room img { display: block; width: 100%; height: 100%; object-fit: cover; }
+.room-meta { font: 600 10.5px/1.4 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--muted); }
+.room-meta span { font: 400 15px/1 var(--display); color: var(--lamp); letter-spacing: 0; margin-right: 8px; }
+.room h3 { font: 400 clamp(32px, 2.8vw, 46px)/1 var(--display); margin: 14px 0 14px; }
+.room p:not(.room-meta) { font-size: 15px; line-height: 1.6; color: #c1c5c4; }
+.room ul { list-style: none; display: flex; flex-wrap: wrap; gap: 6px 16px; margin-top: 16px; }
+.room li { font: 600 10px/1.4 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: #d5cfbf; }
+.room li::before { content: ''; display: inline-block; width: 5px; height: 5px; border-radius: 50%; background: var(--lamp); margin-right: 8px; vertical-align: 1px; }
+.room-pins { position: fixed; inset: 0; z-index: 6; pointer-events: none; }
+.pin { position: absolute; left: 0; top: 0; opacity: 0; transition: opacity .6s; will-change: transform; }
+.pin.on { opacity: 1; }
+.pin i { position: absolute; left: -6px; top: -6px; width: 12px; height: 12px; border-radius: 50%; box-shadow: 0 0 0 1px var(--lamp), 0 0 18px rgba(255, 210, 122, .6); }
+.pin i::after { content: ''; position: absolute; inset: 3px; border-radius: 50%; background: var(--lamp); }
+.pin span { position: absolute; left: 22px; top: -8px; white-space: nowrap; font: 600 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink);
+ padding-left: 46px; background: linear-gradient(var(--lamp), var(--lamp)) left 50% / 36px 1px no-repeat; text-shadow: 0 1px 10px rgba(0,0,0,.9); }
+.room-index { position: absolute; right: var(--gut); top: 50%; transform: translateY(-50%); list-style: none; display: grid; gap: 14px; justify-items: end; }
+.room-index li { font: 400 15px/1 var(--display); color: var(--dim); transition: color .4s, transform .4s; }
+.room-index li.on { color: var(--lamp); transform: translateX(-8px); }
+
+/* ── crossing ───────────────────────────────────────────── */
+.crossing { position: relative; height: 240vh; z-index: 3; pointer-events: none; }
+.crossing-sticky { position: sticky; top: 0; height: 100vh; padding: 16vh var(--gut) 0; }
+.crossing-copy { max-width: 500px; }
+.route { position: absolute; left: var(--gut); right: calc(var(--gut) + 340px); bottom: 250px; display: flex; align-items: center; gap: 18px; font: 600 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: #cfd0cb; }
+.route-line { position: relative; flex: 1; height: 1px; background: repeating-linear-gradient(90deg, rgba(236,231,220,.5) 0 6px, transparent 6px 12px); }
+.route-boat { position: absolute; top: -4px; left: calc(var(--rp, 0) * 100%); width: 9px; height: 9px; margin-left: -4px; border-radius: 50%; background: var(--lamp); box-shadow: 0 0 14px var(--lamp); }
+.route-nm { position: absolute; left: 50%; top: 14px; transform: translateX(-50%); color: var(--muted); }
+.facts { position: absolute; left: var(--gut); right: calc(var(--gut) + 340px); bottom: 104px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 34px; }
+.facts div { border-top: 1px solid var(--rule); padding-top: 16px; }
+.facts dt { font: 400 26px/1 var(--display); }
+.facts dd { margin-top: 10px; font-size: 14px; line-height: 1.55; color: #b8bdbd; max-width: 19em; }
+
+/* ── dawn ───────────────────────────────────────────────── */
+.dawn { position: relative; height: 230vh; z-index: 3; pointer-events: none; --accent: var(--dawn); }
+.dawn-sticky { position: sticky; top: 0; height: 100vh; padding: 16vh var(--gut) 0; }
+.dawn-copy { max-width: 470px; }
+.dawn h2 { color: #fff4ee; text-shadow: 0 2px 50px rgba(60, 20, 40, .35); }
+.dawn h2 em, .dawn .eyebrow { color: #ffd9c9; }
+.dawn .eyebrow .num { color: #fff4ee; border-color: rgba(255,255,255,.3); }
+.dawn .lede { color: #fff0ea; text-shadow: 0 1px 16px rgba(50, 14, 32, .55); }
+.rates { position: absolute; right: var(--gut); top: 16vh; width: min(400px, 36vw); padding: 30px 32px 32px; pointer-events: auto; border-radius: 2px;
+ background: linear-gradient(180deg, rgba(40, 22, 36, .42), rgba(24, 14, 26, .5)); backdrop-filter: blur(16px) saturate(1.2); -webkit-backdrop-filter: blur(16px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(255, 220, 205, .2), 0 40px 80px -40px rgba(30, 10, 25, .7); color: #fff4ee; }
+.rates-from { font: 600 11px/1.2 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: #ffd9c9; }
+.rates-from b { display: block; font: 400 clamp(62px, 5.4vw, 88px)/1 var(--display); letter-spacing: -.02em; color: #fff; margin: 10px 0 4px; text-transform: none; }
+.rates table { width: 100%; border-collapse: collapse; margin-top: 18px; }
+.rates th, .rates td { padding: 11px 0; border-top: 1px solid rgba(255, 230, 220, .18); font-weight: 400; text-align: left; }
+.rates th { font: 400 17px/1.2 var(--text); }
+.rates td { text-align: right; font: 500 15px/1 var(--sans); font-variant-numeric: tabular-nums; }
+.rates-note { margin: 16px 0 22px; font-size: 13px; line-height: 1.55; color: #ecd8d2; }
+.dawn .btn-lamp { background: #fff1e6; color: #3a1c24; }
+.dawn .btn-lamp:hover { background: #fff; box-shadow: 0 0 44px rgba(255, 200, 180, .6); }
+.dawn .btn-ghost { background: rgba(255, 255, 255, .08); box-shadow: inset 0 0 0 1px rgba(255, 235, 225, .35); }
+.rates-toggle { display: none; }
+
+/* ── footer ─────────────────────────────────────────────── */
+.foot { position: relative; z-index: 3; padding: 30vh var(--gut) 40px; background: linear-gradient(180deg, rgba(10, 8, 16, 0), rgba(10, 9, 16, .82) 32%, #0a0910 64%); }
+.foot-title { font: 400 clamp(80px, 12vw, 220px)/.86 var(--display); letter-spacing: -.03em; }
+.foot-title em { font: italic 400 .88em/1 var(--text); color: var(--dawn); }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr) auto; gap: 40px; align-items: end; margin-top: 80px; padding-top: 28px; border-top: 1px solid var(--rule); font-size: 14px; line-height: 1.8; color: #a7abae; }
+.foot-cols b { font: 600 10.5px/2 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink); }
+.foot-small { display: flex; justify-content: space-between; margin-top: 70px; padding-left: 170px; font: 600 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--dim); }
+
+/* ── small screens ─────────────────────────────────────── */
+@media (max-width: 900px) {
+ .links, .sound-label { display: none; }
+ .nav { padding: 16px 18px; }
+ .brand { font-size: 18px; }
+ .brand svg { width: 26px; height: 26px; }
+ .nav .btn { height: 36px; padding: 0 14px; font-size: 10px; letter-spacing: .12em; }
+ .cta-long { display: none; } .cta-short { display: inline; }
+ .nav-right { gap: 8px; }
+ .hero .ctas .btn { height: 42px; padding: 0 16px; font-size: 10.5px; }
+ .hero-inner { padding: 13vh 18px 132px; }
+ .title { font-size: clamp(44px, 12.5vw, 76px); }
+ .title .l2 { margin-left: .5em; }
+ .title .l3 { font-size: clamp(21px, 5.6vw, 30px); margin-left: 0; }
+ .hero-foot { gap: 18px; }
+ .sub { font-size: 14.5px; max-width: 21em; }
+ .hero-hint { bottom: 76px; font-size: 9.5px; letter-spacing: .16em; }
+ .hint-desktop, .k-desk { display: none; }
+ .hint-touch { display: inline; }
+ .k-touch { display: inline-block; }
+ .log { display: none; }
+ .storm-sticky { padding-top: 12vh; }
+ .storm-copy h2 { font-size: 44px; }
+ .storm-copy .lede { font-size: 14.5px; }
+ .how { margin-top: 16px; }
+ .tally { top: auto; bottom: 82px; right: 18px; }
+ .tally-v { font-size: 64px; }
+ .tally-log { display: none; }
+ .storm-foot { display: none; }
+ .rooms-sticky { padding-top: 12vh; }
+ .room-stage { left: 18px; right: 18px; width: auto; bottom: 76px; height: 238px; }
+ .room { grid-template-columns: 116px 1fr; gap: 16px; }
+ .room h3 { font-size: 26px; margin: 8px 0; }
+ .room p:not(.room-meta) { font-size: 13px; line-height: 1.5; }
+ .room ul { display: none; }
+ .room figure { height: 150px; }
+ .room-index { display: none; }
+ .pin span { display: none; }
+ .crossing-sticky, .dawn-sticky { padding-top: 12vh; }
+ .route { display: none; }
+ .facts div:nth-child(2) { display: none; }
+ .facts { right: 18px; grid-template-columns: 1fr; gap: 12px; bottom: 80px; }
+ .facts dt { font-size: 19px; }
+ .facts dd { font-size: 12.5px; margin-top: 4px; }
+ .facts div { padding-top: 10px; }
+ /* collapsed by default so the lighthouse keeps the frame; the full table opens on demand */
+ .rates { position: absolute; top: auto; bottom: 76px; left: 18px; right: 18px; width: auto; padding: 16px 18px 18px; }
+ .rates-from { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }
+ .rates-from b { display: inline; font-size: 44px; margin: 0 2px; }
+ .rates table, .rates-note { display: none; }
+ .rates.open table { display: table; margin-top: 8px; }
+ .rates th, .rates td { padding: 7px 0; }
+ .rates th { font-size: 15px; }
+ .rates .ctas { margin-top: 12px; flex-wrap: nowrap; gap: 10px; }
+ .rates .ctas .btn { height: 42px; padding: 0 16px; font-size: 10.5px; flex: 1; }
+ .rates-write { display: none !important; }
+ .rates-toggle { display: inline-flex; }
+ .rates-toggle span { display: inline-block; transition: transform .3s; }
+ .rates.open .rates-toggle span { transform: rotate(45deg); }
+ .dawn .lede { font-size: 14.5px; }
+ .foot-cols { grid-template-columns: 1fr; gap: 20px; }
+ .foot-small { padding-left: 0; flex-direction: column; gap: 10px; margin-bottom: 60px; }
+ .toast { white-space: normal; width: calc(100vw - 36px); font-size: 14px; bottom: 130px; }
+}
+@media (max-width: 900px) and (max-height: 760px) { .rates-from b { font-size: 38px; } }
+
+/* scrims keep copy legible over the storm */
+.room-stage::before, .storm-copy::before, .crossing-copy::before, .dawn-copy::before, .hero-top::before {
+ content: ''; position: absolute; z-index: -1; pointer-events: none; inset: -90px -120px -90px -110px;
+ background: radial-gradient(closest-side, rgba(3, 5, 9, .62), rgba(3, 5, 9, .28) 60%, transparent); }
+.storm-copy, .crossing-copy, .dawn-copy, .hero-top { position: relative; }
+.dawn-copy::before { background: radial-gradient(closest-side, rgba(46, 16, 34, .42), rgba(46, 16, 34, .16) 65%, transparent); }
+.room-text { text-shadow: 0 1px 14px rgba(0, 0, 0, .7); }
diff --git a/examples/koen/dial.js b/examples/koen/dial.js
new file mode 100644
index 0000000..7ae4138
--- /dev/null
+++ b/examples/koen/dial.js
@@ -0,0 +1,104 @@
+// The season dial: a year drawn as a brushed ring with twenty-four solar-term ticks.
+// Drag the ink bead around the ring (or anywhere on the dial) to turn the year.
+import { wrap, sekkiAt, SEASON_NAMES, seasonIndex } from './seasons.js';
+
+const R = 62, C = 80;
+export class Dial {
+ constructor(el, { onInput, onStart, onEnd } = {}) {
+ this.el = el;
+ this.onInput = onInput; this.onStart = onStart; this.onEnd = onEnd;
+ const ticks = Array.from({ length: 24 }, (_, i) => {
+ const a = (i / 24) * Math.PI * 2 - Math.PI / 2;
+ const major = i % 6 === 0;
+ const r0 = R - (major ? 9 : 5), r1 = R - 1;
+ return `<line x1="${C + Math.cos(a) * r0}" y1="${C + Math.sin(a) * r0}" x2="${C + Math.cos(a) * r1}" y2="${C + Math.sin(a) * r1}" class="${major ? 'maj' : ''}"/>`;
+ }).join('');
+ const labels = SEASON_NAMES.map(([k], i) => {
+ const a = (i / 4) * Math.PI * 2 - Math.PI / 2;
+ return `<text x="${C + Math.cos(a) * (R + 13)}" y="${C + Math.sin(a) * (R + 13) + 4}" data-i="${i}">${k}</text>`;
+ }).join('');
+ el.innerHTML = `
+ <svg viewBox="0 0 160 160" aria-hidden="true">
+ <defs>
+ <filter id="dial-brush" x="-10%" y="-10%" width="120%" height="120%">
+ <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" seed="4" result="n"/>
+ <feDisplacementMap in="SourceGraphic" in2="n" scale="2.2"/>
+ </filter>
+ </defs>
+ <circle class="ring" cx="${C}" cy="${C}" r="${R}" filter="url(#dial-brush)"/>
+ <path class="arc" d="" filter="url(#dial-brush)"/>
+ <g class="ticks">${ticks}</g>
+ <g class="labels">${labels}</g>
+ <g class="bead"><circle class="bead-halo" r="11"/><circle class="bead-dot" r="5.2"/></g>
+ </svg>
+ <div class="dial-core"><span class="dial-kanji">秋</span></div>`;
+ this.bead = el.querySelector('.bead');
+ this.arc = el.querySelector('.arc');
+ this.kanji = el.querySelector('.dial-kanji');
+ this.labels = [...el.querySelectorAll('.labels text')];
+ this.cap = document.querySelector('.dial-caption');
+ this.dragging = false;
+ this.value = 2;
+ const angleOf = e => {
+ const r = el.getBoundingClientRect();
+ const x = e.clientX - (r.left + r.width / 2), y = e.clientY - (r.top + r.height / 2);
+ let a = Math.atan2(y, x) + Math.PI / 2; // 0 at top, clockwise
+ if (a < 0) a += Math.PI * 2;
+ return a / (Math.PI * 2) * 4;
+ };
+ el.addEventListener('pointerdown', e => {
+ e.preventDefault();
+ this.dragging = true;
+ el.setPointerCapture(e.pointerId);
+ el.classList.add('is-drag', 'was-used');
+ this.onStart?.();
+ this.onInput?.(angleOf(e));
+ });
+ el.addEventListener('pointermove', e => { if (this.dragging) this.onInput?.(angleOf(e)); });
+ const end = e => {
+ if (!this.dragging) return;
+ this.dragging = false;
+ el.classList.remove('is-drag');
+ try { el.releasePointerCapture(e.pointerId); } catch { /* already released */ }
+ this.onEnd?.();
+ };
+ el.addEventListener('pointerup', end);
+ el.addEventListener('pointercancel', end);
+ // keyboard: arrows step one solar term
+ el.tabIndex = 0;
+ el.addEventListener('keydown', e => {
+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { this.onStart?.(); this.onInput?.(wrap(this.value + 1 / 6)); this.onEnd?.(); e.preventDefault(); }
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { this.onStart?.(); this.onInput?.(wrap(this.value - 1 / 6)); this.onEnd?.(); e.preventDefault(); }
+ });
+ this._last = '';
+ }
+
+ /** s: unwrapped season; age: how many autumns the tree has seen. */
+ set(s, age) {
+ this.value = wrap(s);
+ const f = this.value;
+ const a = f / 4 * Math.PI * 2 - Math.PI / 2;
+ this.bead.setAttribute('transform', `translate(${(C + Math.cos(a) * R).toFixed(2)} ${(C + Math.sin(a) * R).toFixed(2)})`);
+ // ink arc from the start of the current season to the bead
+ const si = Math.floor(f + 0.5) % 4;
+ const a0 = ((si - 0.5 + 4) % 4) / 4 * Math.PI * 2 - Math.PI / 2;
+ let da = a - a0; if (da < 0) da += Math.PI * 2;
+ const x0 = C + Math.cos(a0) * R, y0 = C + Math.sin(a0) * R, x1 = C + Math.cos(a) * R, y1 = C + Math.sin(a) * R;
+ this.arc.setAttribute('d', `M${x0.toFixed(2)} ${y0.toFixed(2)} A${R} ${R} 0 ${da > Math.PI ? 1 : 0} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}`);
+ const idx = seasonIndex(s);
+ const [kj, en] = SEASON_NAMES[idx];
+ const [sk, ro, mean] = sekkiAt(s);
+ const key = kj + sk + age;
+ if (key !== this._last) {
+ this._last = key;
+ this.kanji.textContent = kj;
+ this.labels.forEach((l, i) => l.classList.toggle('on', i === idx));
+ if (this.cap) this.cap.innerHTML = `<b>${sk}</b> <span>${ro} — ${mean}</span><em>${en} · the tree's ${ordinal(age)} ${en.toLowerCase()}</em>`;
+ this.el.setAttribute('aria-label', `Season dial: ${en}, ${ro} (${mean}). Use arrow keys to turn the year.`);
+ }
+ }
+}
+export function ordinal(n) {
+ const s = ['th', 'st', 'nd', 'rd'], v = n % 100;
+ return n + (s[(v - 20) % 10] || s[v] || s[0]);
+}
diff --git a/examples/koen/index.html b/examples/koen/index.html
new file mode 100644
index 0000000..e76724d
--- /dev/null
+++ b/examples/koen/index.html
@@ -0,0 +1,239 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Kōen 紅園 — One tree, four seasons</title>
+ <meta name="description" content="A bonsai nursery in Ōmiya, Saitama. Our oldest maple has seen 180 autumns. Scroll to turn its year.">
+ <meta name="theme-color" content="#f1ece2">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Crect x=%224%22 y=%223%22 width=%2224%22 height=%2226%22 rx=%223%22 fill=%22%23c8452f%22/%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%227%22 fill=%22none%22 stroke=%22%23f8efe4%22 stroke-width=%222.2%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;0,600;1,300;1,400&family=Noto+Serif+JP:wght@300;400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <svg width="0" height="0" style="position:absolute" aria-hidden="true">
+ <defs>
+ <filter id="brush" x="-5%" y="-40%" width="110%" height="180%">
+ <feTurbulence type="fractalNoise" baseFrequency="0.035 0.9" numOctaves="3" seed="7" result="n"/>
+ <feDisplacementMap in="SourceGraphic" in2="n" scale="7" xChannelSelector="R" yChannelSelector="G"/>
+ </filter>
+ <filter id="brush-soft" x="-5%" y="-40%" width="110%" height="180%">
+ <feTurbulence type="fractalNoise" baseFrequency="0.02 0.6" numOctaves="2" seed="3" result="n"/>
+ <feDisplacementMap in="SourceGraphic" in2="n" scale="4"/>
+ </filter>
+ </defs>
+ </svg>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-enso"><img data-src="img/koen/enso.webp" alt=""><p class="loader-seal" aria-hidden="true"><span>紅</span><span>園</span></p></div>
+ <p class="loader-line">Preparing the garden <span class="loader-pct">0</span></p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Kōen, home">
+ <span class="seal" aria-hidden="true"><i>紅</i><i>園</i></span>
+ <span class="brand-name">Kōen<small>Bonsai · Ōmiya</small></span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#seasons">Seasons</a>
+ <a href="#nursery">Nursery</a>
+ <a href="#craft">Craft</a>
+ <a href="#visit">Visit</a>
+ </nav>
+ <a class="btn btn-line" href="#visit" data-magnetic>Reserve a morning</a>
+ </header>
+
+ <main id="top">
+ <!-- ── Hero ─────────────────────────────────────────── -->
+ <section class="hero" aria-labelledby="hero-title">
+ <div class="hero-inner">
+ <p class="eyebrow">Bonsai nursery <i></i> Ōmiya, Saitama <i></i> Since 1846</p>
+ <h1 id="hero-title" class="hero-title">
+ <span class="ln">This tree</span>
+ <span class="ln">has seen</span>
+ <span class="ln"><em>180 autumns.</em></span>
+ </h1>
+ <p class="hero-sub">A Japanese maple grown from seed in an Edo rice bowl, the year Emperor Kōmei took the throne. It is older than Japan's railways, its constitution and its yen — and every year it becomes four different trees.</p>
+ <div class="hero-cta">
+ <a class="btn btn-ink" href="#nursery" data-magnetic>Adopt a tree</a>
+ <a class="btn btn-line" href="#seasons" data-magnetic>Turn the year</a>
+ </div>
+ </div>
+ <p class="hero-vert" aria-hidden="true">一本の木、四つの季節</p>
+ <ul class="hint" aria-label="How to explore">
+ <li><b>Scroll</b> to turn the year</li>
+ <li><b>Drag</b> the dial</li>
+ <li><b class="hint-touch">Touch</b> the tree</li>
+ </ul>
+ </section>
+
+ <!-- ── Four seasons (pinned) ─────────────────────────── -->
+ <section class="seasons" id="seasons" aria-label="Four seasons">
+ <div class="seasons-pin">
+ <p class="kicker">The year, in four trees <span class="kicker-jp">四季</span></p>
+ <ol class="rail" aria-hidden="true">
+ <li data-i="0"><b>春</b><span>haru</span><em>三月—五月</em></li>
+ <li data-i="1"><b>夏</b><span>natsu</span><em>六月—八月</em></li>
+ <li data-i="2"><b>秋</b><span>aki</span><em>九月—十一月</em></li>
+ <li data-i="3"><b>冬</b><span>fuyu</span><em>十二月—二月</em></li>
+ </ol>
+ <div class="season-copy">
+ <article data-i="2">
+ <p class="s-num">01 <i></i> Autumn · 紅葉 kōyō</p>
+ <h2>Nine days <em>of red.</em></h2>
+ <p>When the nights fall below eight degrees, the maple stops making green. The sugar trapped in each leaf turns to anthocyanin, and for nine days in November the canopy is the colour of our seal. Then it lets go — all of it, onto the moss.</p>
+ <p class="s-note"><b>In the garden</b> We don't rake. The leaves feed the moss until the first frost.</p>
+ </article>
+ <article data-i="3">
+ <p class="s-num">02 <i></i> Winter · 寒樹 kanju</p>
+ <h2>The tree, <em>undressed.</em></h2>
+ <p>Bare, it finally shows you the work: every branch placed, every line argued over by five generations of the Kōno family. Winter is when a bonsai is judged — and when it is wired.</p>
+ <p class="s-note"><b>In the garden</b> Frost cloth below −5 °C. Water at noon, never at dusk.</p>
+ </article>
+ <article data-i="0">
+ <p class="s-num">03 <i></i> Spring · 芽吹き mebuki</p>
+ <h2>Lighter <em>than air.</em></h2>
+ <p>The buds split in the second week of April and the first leaves come out folded, the green of a lime peel and almost translucent. For a fortnight the tree weighs nothing. Somewhere upwind, the cherries are letting go.</p>
+ <p class="s-note"><b>In the garden</b> Water twice a day. No feeding until the new leaves harden.</p>
+ </article>
+ <article data-i="1">
+ <p class="s-num">04 <i></i> Summer · 深緑 shinryoku</p>
+ <h2>Storing <em>the light.</em></h2>
+ <p>By June the canopy closes and darkens. This is the working season: the tree banks sugar for an autumn it cannot see coming, and we pinch every new shoot back to two leaves so it grows finer, never bigger.</p>
+ <p class="s-note"><b>In the garden</b> Shade cloth after eleven. Three waterings on the hottest days.</p>
+ </article>
+ </div>
+ <div class="season-progress" aria-hidden="true"><i></i></div>
+ <p class="season-glyph" aria-hidden="true"><span data-i="0">春</span><span data-i="1">夏</span><span data-i="2">秋</span><span data-i="3">冬</span></p>
+ </div>
+ </section>
+
+ <div class="brush-divider bd-right" aria-hidden="true">
+ <svg viewBox="0 0 1200 40" preserveAspectRatio="none"><path d="M8 24 C 180 12, 420 30, 640 19 S 1020 14, 1192 22 L1190 26 C 1010 22, 820 28, 640 25 S 240 30, 10 28 Z" filter="url(#brush)"/></svg>
+ </div>
+
+ <!-- ── The nursery ───────────────────────────────────── -->
+ <section class="nursery panel" id="nursery" aria-labelledby="nursery-title">
+ <div class="panel-col">
+ <p class="kicker">The nursery <span class="kicker-jp">預かり</span></p>
+ <h2 id="nursery-title">Trees looking for their next <em>hundred years.</em></h2>
+ <p class="lede">We don't sell bonsai. We place them — with people who will keep them longer than we will. Every adoption includes two house visits a year, a care calendar written for your light, and a winter room at the nursery whenever your tree needs one.</p>
+ <ol class="catalogue">
+ <li data-img="img/koen/pine.webp">
+ <span class="c-no">No. 031</span>
+ <span class="c-name"><b>黒松</b> Kuromatsu <small>Japanese black pine · formal upright</small></span>
+ <span class="c-age">120 yrs<small>74 cm</small></span>
+ <span class="c-price">¥2,800,000</span>
+ </li>
+ <li data-img="img/koen/juniper.webp">
+ <span class="c-no">No. 044</span>
+ <span class="c-name"><b>真柏</b> Shimpaku <small>Chinese juniper · driftwood style</small></span>
+ <span class="c-age">95 yrs<small>52 cm</small></span>
+ <span class="c-price">¥1,650,000</span>
+ </li>
+ <li data-img="img/koen/azalea.webp">
+ <span class="c-no">No. 052</span>
+ <span class="c-name"><b>皐月</b> Satsuki <small>Satsuki azalea · informal upright</small></span>
+ <span class="c-age">60 yrs<small>41 cm</small></span>
+ <span class="c-price">¥680,000</span>
+ </li>
+ <li data-img="img/koen/quince.webp">
+ <span class="c-no">No. 068</span>
+ <span class="c-name"><b>長寿梅</b> Chōjubai <small>Dwarf flowering quince · shōhin</small></span>
+ <span class="c-age">45 yrs<small>19 cm</small></span>
+ <span class="c-price">¥380,000</span>
+ </li>
+ <li class="c-ours">
+ <span class="c-no">No. 001</span>
+ <span class="c-name"><b>紅葉</b> Momiji <small>Japanese maple · the tree on this page</small></span>
+ <span class="c-age">180 yrs<small>68 cm</small></span>
+ <span class="c-price">Never</span>
+ </li>
+ </ol>
+ <p class="fine">Viewings by appointment. An adoption takes three visits: we need to meet you, and the tree needs to meet your balcony.</p>
+ <a class="btn btn-ink" href="#visit" data-magnetic>Arrange a viewing</a>
+ </div>
+ </section>
+
+ <!-- ── The craft (pinned) ────────────────────────────── -->
+ <section class="craft" id="craft" aria-label="The craft">
+ <div class="craft-pin">
+ <p class="kicker">The craft <span class="kicker-jp">手入れ</span></p>
+ <h2 class="craft-title">Three tools. <em>One century at a time.</em></h2>
+ <div class="craft-steps">
+ <article data-i="0">
+ <p class="s-num">I <i></i> June</p>
+ <h3><b>剪定</b> Pruning <small>sentei</small></h3>
+ <p>After the first flush hardens, every shoot is cut back to its first pair of leaves. The tree answers with smaller leaves, shorter nodes and finer twigs. Repeat for a hundred and eighty summers and you get a canopy like lace.</p>
+ </article>
+ <article data-i="1">
+ <p class="s-num">II <i></i> November</p>
+ <h3><b>針金</b> Wiring <small>harigane</small></h3>
+ <p>Annealed copper, wound at forty-five degrees, tells a branch where to grow. The wire stays for one season — long enough to set the line, never long enough to bite the bark.</p>
+ </article>
+ <article data-i="2">
+ <p class="s-num">III <i></i> March</p>
+ <h3><b>植替え</b> Repotting <small>uekae</small></h3>
+ <p>Every third spring, as the buds swell, we lift the tree, comb out a third of its roots and seat it in fresh akadama clay. This maple has been repotted sixty times. The pot is its fourth.</p>
+ </article>
+ </div>
+ <ol class="craft-index" aria-hidden="true"><li>剪定</li><li>針金</li><li>植替え</li></ol>
+ </div>
+ </section>
+
+ <div class="brush-divider bd-left" aria-hidden="true">
+ <svg viewBox="0 0 1200 40" preserveAspectRatio="none"><path d="M10 20 C 260 26, 480 12, 700 21 S 1030 26, 1190 18 L1192 23 C 1020 30, 860 24, 700 26 S 300 31, 12 25 Z" filter="url(#brush)"/></svg>
+ </div>
+
+ <!-- ── Visit ──────────────────────────────────────────── -->
+ <section class="visit panel" id="visit" aria-labelledby="visit-title">
+ <div class="panel-col">
+ <p class="kicker">Visit <span class="kicker-jp">訪問</span></p>
+ <h2 id="visit-title">Come in any season. <em>Come back in all four.</em></h2>
+ <dl class="facts">
+ <div><dt>Garden</dt><dd>2-24 Bonsai-chō, Kita-ku<br>Saitama 331-0805</dd></div>
+ <div><dt>Getting here</dt><dd>Eight minutes on foot from Ōmiya-kōen Station. Forty minutes from Ueno.</dd></div>
+ <div><dt>Hours</dt><dd>09:00 – 16:30<br>Closed Thursdays and 29 Dec – 3 Jan</dd></div>
+ <div><dt>Momiji mornings</dt><dd>3 – 21 November. Twelve guests a morning, tea on the engawa at eight.</dd></div>
+ </dl>
+ <div class="visit-cta">
+ <a class="btn btn-ink" href="#top" data-magnetic>Reserve a morning</a>
+ <a class="btn btn-line" href="#top" data-magnetic>Write to the garden</a>
+ </div>
+ </div>
+ </section>
+ </main>
+
+ <footer class="foot">
+ <div class="foot-inner">
+ <div class="foot-mark">
+ <span class="seal seal-lg" aria-hidden="true"><i>紅</i><i>園</i></span>
+ <p class="foot-line">Five generations, one maple.<br><em>Ōmiya since 1925, Dangozaka before that.</em></p>
+ </div>
+ <nav class="foot-cols" aria-label="Footer">
+ <div><h4>Nursery</h4><a href="#nursery">Trees for adoption</a><a href="#craft">Care &amp; craft</a><a href="#seasons">The four seasons</a></div>
+ <div><h4>Garden</h4><a href="#visit">Visit &amp; hours</a><a href="#visit">Momiji mornings</a><a href="#visit">Winter rooms</a></div>
+ <div><h4>Letters</h4><p>One postcard at each solstice, written by hand in the potting shed.</p><a href="#top">Ask for a postcard →</a></div>
+ </nav>
+ </div>
+ <div class="foot-base">
+ <p>© 2026 Kōen Bonsai 紅園 · In the garden, please don't touch the trees. Here, go ahead.</p>
+ <p class="foot-sekki"></p>
+ </div>
+ </footer>
+
+ <!-- fixed UI -->
+ <div class="dial-wrap">
+ <div class="dial" role="slider" aria-valuemin="0" aria-valuemax="4" aria-label="Season dial"></div>
+ <p class="dial-caption"></p>
+ </div>
+ <div class="callout" aria-hidden="true"><svg><line x1="0" y1="0" x2="0" y2="0"/><circle r="3.5"/></svg><p></p></div>
+ <div class="preview" aria-hidden="true"><img alt=""></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/koen/main.js b/examples/koen/main.js
new file mode 100644
index 0000000..0f0fee2
--- /dev/null
+++ b/examples/koen/main.js
@@ -0,0 +1,649 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, range, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh, url } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { Effect } from 'postprocessing';
+import { U, patchTreeMaterial, treeDepthMaterial, patchBarkMaterial, barkDepthMaterial, analyze, growBranches, wireGeometry } from './tree.js';
+import { Fall, Drift } from './particles.js';
+import { treeState, worldState, wrap, seasonIndex } from './seasons.js';
+import { Dial } from './dial.js';
+
+const DBG = new URLSearchParams(location.search);
+const MOBILE = matchMedia('(max-width: 900px)').matches;
+const TREE_H = 1.75;
+const SLAB_TOP = 0.085;
+const D = Math.PI / 180;
+
+document.querySelectorAll('[data-src]').forEach(img => { img.src = url(img.dataset.src); });
+
+// ─── Paper: the frame is printed on washi ─────────────────────────────────────
+class PaperEffect extends Effect {
+ constructor() {
+ super('KoenPaper', /* glsl */`
+ uniform sampler2D tPaper; uniform vec2 uScale; uniform float uAmt;
+ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor){
+ float p = texture2D(tPaper, uv * uScale).r;
+ vec3 c = inputColor.rgb;
+ float lum = dot(c, vec3(0.299, 0.587, 0.114));
+ c *= 1.0 + (p - 0.5) * uAmt * mix(0.3, 1.0, lum);
+ outputColor = vec4(c, inputColor.a);
+ }`, { uniforms: new Map([['tPaper', new THREE.Uniform(null)], ['uScale', new THREE.Uniform(new THREE.Vector2(1, 1))], ['uAmt', new THREE.Uniform(0.06)]]) });
+ }
+}
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let paper;
+const engine = new Engine({
+ canvas, fov: 26, near: 0.05, far: 60, dpr: 1.75, background: 0xf1ece2,
+ post: {
+ ao: { aoRadius: 0.3, intensity: 2.2, distanceFalloff: 0.45 },
+ bloom: { intensity: 0.3, luminanceThreshold: 1.25, luminanceSmoothing: 0.3, radius: 0.5 },
+ tone: 'neutral',
+ extra: () => [(paper = new PaperEffect())],
+ vignette: { offset: 0.5, darkness: 0.34 },
+ noise: 0.028,
+ },
+});
+const { scene, camera, renderer } = engine;
+scene.fog = new THREE.FogExp2(0xf1ece2, 0.02);
+scene.environment = studioEnvironment(renderer, {
+ top: 0x8a8378, bottom: 0x2a2621,
+ panels: [
+ { pos: [-6, 4, 5], size: [5, 4], intensity: 3, color: 0xfff2e2 },
+ { pos: [6, 5, 3], size: [4, 5], intensity: 1.6, color: 0xf2f4ff },
+ { pos: [0, 8, 0], size: [8, 3], intensity: 2, color: 0xffffff },
+ ],
+});
+scene.environmentIntensity = 0.42;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 6 });
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = String(Math.round(v * 100)).padStart(2, '0');
+ loaderEl.style.setProperty('--p', (0.04 + v * 0.96).toFixed(3));
+ },
+ exit: async () => {
+ await gsap.to('.loader-line, .loader-seal', { opacity: 0, duration: 0.5, ease: 'power2.in' });
+ await gsap.to(loaderEl, { opacity: 0, duration: 1.1, ease: 'power2.inOut' });
+ },
+});
+
+// ─── Studio: a washi cyclorama, a walnut slab ─────────────────────────────────
+const washi = new THREE.TextureLoader().load(url('img/koen/washi.webp'), t => { paper.uniforms.get('tPaper').value = t; });
+washi.wrapS = washi.wrapT = THREE.RepeatWrapping;
+washi.colorSpace = THREE.NoColorSpace;
+engine.onResize((w, h) => { paper?.uniforms.get('uScale').value.set(w / 1024, h / 1024); });
+
+function cycGeometry() {
+ const W = 40, wallZ = -3.9, cove = 2.0, front = 18, top = 16;
+ const prof = [[front, 0], [wallZ + cove, 0]];
+ for (let i = 1; i <= 24; i++) { const a = i / 24 * Math.PI / 2; prof.push([wallZ + cove - Math.sin(a) * cove, cove - Math.cos(a) * cove]); }
+ prof.push([wallZ, top]);
+ const pos = [], uv = [], idx = [];
+ let acc = 0;
+ prof.forEach(([z, y], i) => {
+ if (i) acc += Math.hypot(z - prof[i - 1][0], y - prof[i - 1][1]);
+ for (const x of [-W / 2, W / 2]) { pos.push(x, y, z); uv.push(x / 2.6, acc / 2.6); }
+ });
+ for (let i = 0; i < prof.length - 1; i++) { const a = i * 2; idx.push(a, a + 1, a + 2, a + 1, a + 3, a + 2); }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setIndex(idx);
+ g.computeVertexNormals();
+ return g;
+}
+// An ensō brushed on the wall behind the tree (projected along z, so it follows the cove and takes the tree's shadow).
+const ensoTex = new THREE.TextureLoader().load(url('img/koen/enso.webp'));
+ensoTex.colorSpace = THREE.SRGBColorSpace;
+ensoTex.anisotropy = 8;
+const cycU = { uWallC: { value: new THREE.Color() }, uFloorC: { value: new THREE.Color() }, uEnso: { value: ensoTex },
+ uEnsoC: { value: new THREE.Vector2(1.1, 1.24) }, uEnsoS: { value: 2.45 }, uEnsoA: { value: 0.9 } };
+const cycMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.94, metalness: 0, map: washi, envMapIntensity: 0.3 });
+cycMat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, cycU);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vKw;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvKw = (modelMatrix * vec4(position, 1.)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nvarying vec3 vKw; uniform vec3 uWallC, uFloorC; uniform sampler2D uEnso; uniform vec2 uEnsoC; uniform float uEnsoS, uEnsoA;')
+ .replace('#include <map_fragment>', `
+ float kp = texture2D(map, vMapUv).r;
+ diffuseColor.rgb *= mix(uFloorC, uWallC, smoothstep(0.1, 2.4, vKw.y)) * (0.965 + 0.05 * kp);
+ vec2 eu = (vKw.xy - uEnsoC) / uEnsoS + 0.5;
+ if (uEnsoA > 0.01 && vKw.z < -1.6 && eu.x > 0. && eu.x < 1. && eu.y > 0. && eu.y < 1.) {
+ float ink = clamp(texture2D(uEnso, eu).a * uEnsoA * 1.15, 0., 1.) * (0.93 + 0.07 * kp);
+ vec3 cs = pow(diffuseColor.rgb, vec3(1. / 2.2));
+ diffuseColor.rgb = pow(mix(cs, vec3(0.1, 0.09, 0.085), ink), vec3(2.2));
+ }`);
+};
+const cyc = new THREE.Mesh(cycGeometry(), cycMat);
+cyc.receiveShadow = true;
+scene.add(cyc);
+
+// Walnut slab (jita) under the pot.
+const woodAlbedo = bakeTexture(renderer, 1024, `
+ void main(){
+ float n = fbm(vUv * 3.0, 3.0, 5, 0.55);
+ float w = fbm(vec2(vUv.x * 2.0, vUv.y * 12.0), 2.0, 4, 0.5);
+ float rings = sin((vUv.y * 30.0 + n * 5.0 + w * 2.0) * 6.2831853);
+ float fine = fbm(vec2(vUv.x * 64.0, vUv.y * 2.0), 64.0, 3, 0.5);
+ vec3 dark = vec3(0.036, 0.022, 0.014), mid = vec3(0.085, 0.052, 0.032), light = vec3(0.13, 0.082, 0.05);
+ vec3 col = mix(dark, mid, 0.5 + 0.5 * rings);
+ col = mix(col, light, smoothstep(0.55, 0.95, rings) * 0.5 + fine * 0.25);
+ col *= 0.85 + n * 0.4;
+ gl_FragColor = vec4(col, 1.0);
+ }`);
+const woodRough = bakeTexture(renderer, 512, `void main(){ float r = 0.36 + fbm(vec2(vUv.x * 40.0, vUv.y * 3.0), 40.0, 3, 0.5) * 0.18 + fbm(vUv * 4.0, 4.0, 4, 0.5) * 0.12; gl_FragColor = vec4(1., clamp(r, .1, 1.), 0., 1.); }`);
+woodAlbedo.colorSpace = THREE.SRGBColorSpace;
+const slab = new THREE.Mesh(new RoundedBoxGeometry(1.62, SLAB_TOP, 0.98, 5, 0.03),
+ new THREE.MeshStandardMaterial({ map: woodAlbedo, roughnessMap: woodRough, roughness: 1, metalness: 0, envMapIntensity: 0.45, color: 0xffffff }));
+patchBarkMaterial(slab.material, 'koen-slab');
+slab.position.y = SLAB_TOP / 2;
+slab.castShadow = slab.receiveShadow = true;
+scene.add(slab);
+const SLAB = { x: 0.81, z: 0.49 };
+
+// ─── Light ─────────────────────────────────────────────────────────────────────
+const hemi = new THREE.HemisphereLight(0xffffff, 0x888888, 1);
+scene.add(hemi);
+const key = new THREE.DirectionalLight(0xffffff, 3);
+key.castShadow = true;
+key.shadow.mapSize.set(4096, 4096);
+Object.assign(key.shadow.camera, { left: -3.6, right: 3.6, top: 3.6, bottom: -3.6, near: 1, far: 24 });
+key.shadow.bias = -0.00022;
+key.shadow.normalBias = 0.018;
+const keyTarget = new THREE.Object3D();
+keyTarget.position.set(0, 0.9, -1.1);
+key.target = keyTarget;
+scene.add(key, keyTarget);
+const fill = new THREE.DirectionalLight(0xffffff, 0.4);
+scene.add(fill, fill.target);
+const rim = new THREE.DirectionalLight(0xffffff, 0.9);
+rim.position.set(1.5, 4, -5);
+scene.add(rim);
+
+// ─── Tree ─────────────────────────────────────────────────────────────────────
+const treeRoot = new THREE.Group();
+scene.add(treeRoot);
+let A = null, treeMesh = null, twigs = null, wire = null, wireInfo = null;
+const barkN = fbmNormal(renderer, { size: 512, scale: 6, octaves: 5, strength: 2.2 });
+barkN.repeat.set(1, 8);
+
+const modelUrl = DBG.get('m') ?? 'models/koen/maple2.glb';
+const treeLoad = assets.gltf(modelUrl).then(g => {
+ const m = g.scene;
+ m.rotation.y = +(DBG.get('rot') ?? 0) * D;
+ normalize(m, TREE_H, { axis: 'y' });
+ m.position.y += SLAB_TOP;
+ prepModel(m, renderer, { env: 0.8, metal: 0 });
+ treeRoot.add(m);
+ m.updateMatrixWorld(true);
+ treeMesh = firstMesh(m);
+ A = analyze(treeMesh);
+ treeMesh.geometry.setAttribute('aFol', new THREE.BufferAttribute(A.vertexFoliage, 1));
+ U.uFolY0.value = A.folY0; U.uFolY1.value = A.folY1;
+ U.uSwayY0.value = A.potTop + 0.03 * A.H; U.uSwayY1.value = A.box.max.y;
+ U.uInvModel.value.setFromMatrix4(treeMesh.matrixWorld).invert();
+ A.trunk.slice(0, 24).forEach((p, i) => U.uTrunk.value[i].copy(p));
+ U.uTrunkN.value = Math.min(24, A.trunk.length);
+ U.uTrunkR.value.set(0.105 * A.H / 1.75, 0.05 * A.H / 1.75, A.potTop, A.trunk[A.trunk.length - 1].y);
+ const map = treeMesh.material.map;
+ patchTreeMaterial(treeMesh.material);
+ treeMesh.customDepthMaterial = treeDepthMaterial(map);
+
+ // Winter structure: branches grown into each foliage pad.
+ const br = growBranches(A);
+ const barkMat = patchBarkMaterial(new THREE.MeshStandardMaterial({ color: 0x5a3f2d, roughness: 0.86, normalMap: barkN, normalScale: new THREE.Vector2(0.6, 0.6), envMapIntensity: 0.6 }));
+ twigs = new THREE.Mesh(br.geometry, barkMat);
+ twigs.castShadow = true; twigs.receiveShadow = true;
+ twigs.customDepthMaterial = barkDepthMaterial();
+ scene.add(twigs);
+ // Copper wire on the branch that faces the camera best.
+ const score = m => { const a = m.curve.getPointAt(0), b = m.curve.getPointAt(1); return Math.abs(b.x - a.x) * 2 - Math.abs(b.z - a.z) + (m.pad.center.z > -0.15 ? 0.3 : -1) + Math.min(m.len, 14) * 0.02 + (m.pad.center.x > 0 ? 0.25 : 0); };
+ const pick = [...br.mains].filter(m => m.len >= 6).sort((a, b) => score(b) - score(a))[0];
+ if (pick) {
+ wireInfo = wireGeometry(pick.curve, pick.radiusAt, { wire: 0.0042 * A.H / 1.75, from: 0.06, to: 0.74 });
+ wireInfo.anchor = pick.curve.getPointAt(0.42);
+ const w0 = pick.curve.getPointAt(0), w1 = pick.curve.getPointAt(1);
+ wireInfo.view = w0.clone().lerp(w1, MOBILE ? 0.3 : 0.62);
+ wireInfo.len = w0.distanceTo(w1);
+ const dx = w1.x - w0.x, dz = w1.z - w0.z;
+ let az = Math.atan2(dx, dz) + Math.PI / 2; // perpendicular to the branch
+ if (Math.cos(az) * dx - Math.sin(az) * dz < 0) az += Math.PI; // trunk end on the left
+ wireInfo.az = Math.atan2(Math.sin(az), Math.cos(az));
+ const copper = patchBarkMaterial(new THREE.MeshStandardMaterial({ color: 0xd7895a, metalness: 0.85, roughness: 0.32, envMapIntensity: 2.2, emissive: 0x3a1a0a, emissiveIntensity: 0.5 }), 'koen-copper', { snow: 0.15 });
+ wire = new THREE.Mesh(wireInfo.geometry, copper);
+ wire.castShadow = true;
+ wire.customDepthMaterial = barkDepthMaterial();
+ wire.geometry.setDrawRange(0, 0);
+ scene.add(wire);
+ }
+ if (DBG.has('noleafmesh')) treeMesh.visible = false;
+ if (DBG.has('mask')) U.uDbg.value = 1;
+ if (DBG.has('notwigs')) twigs.visible = false;
+}).catch(e => { console.warn('maple missing', e?.message ?? e); });
+
+// ─── Falling things ───────────────────────────────────────────────────────────
+const groundAt = (x, z) => {
+ const g = A ? A.groundAt(x, z) : -1;
+ if (g > 0) return g;
+ if (Math.abs(x) < SLAB.x - 0.02 && Math.abs(z) < SLAB.z - 0.02) return SLAB_TOP;
+ return 0;
+};
+const fall = new Fall(scene, { count: 2200, groundAt });
+const snow = new Drift(scene, { count: 7000, color: 0xffffff, size: 6.5, speed: 0.34, swirl: 0.11, box: [-3.2, 0, -3.2, 3.2, 3.4, 3.8] });
+const motes = new Drift(scene, { count: 1100, color: 0xfff1cf, size: 3.2, speed: -0.015, swirl: 0.3, bright: 1.25, box: [-2.6, 0.1, -2.2, 2.6, 2.6, 2.6] });
+engine.onResize((w, h, dpr) => { snow.uniforms.uDpr.value = dpr * h / 900; motes.uniforms.uDpr.value = dpr * h / 900; });
+
+const PAL_AUTUMN = ['#b3261e', '#c8321f', '#d2553b', '#a61e1a', '#e06a2c', '#8e1b17', '#d9442a', '#e89a34'].map(h => new THREE.Color(h));
+const PAL_SPRING = ['#f7d9dd', '#f3c5cc', '#fbe7e8', '#eeb8c1'].map(h => new THREE.Color(h));
+const PAL_GREEN = ['#5d8a2c', '#6f9a35', '#4f7a26'].map(h => new THREE.Color(h));
+const pickC = p => p[Math.floor(Math.random() * p.length)];
+const tmpC = new THREE.Color();
+const tmpV = new THREE.Vector3(), tmpW = new THREE.Vector3(), tmpQ = new THREE.Vector3();
+const wind = new THREE.Vector3(-0.08, 0, 0.03);
+function spawnLeaf(ts, { burst = false, near = null, landed = 0 } = {}) {
+ if (!A || !A.spawn.count) return;
+ let i = Math.floor(Math.random() * A.spawn.count);
+ if (near) { // pick the spawn point closest to a random handful near the pointer ray
+ let bd = Infinity;
+ for (let k = 0; k < 24; k++) {
+ const j = Math.floor(Math.random() * A.spawn.count);
+ tmpV.fromArray(A.spawn.position, j * 3);
+ const d = tmpV.distanceToSquared(near);
+ if (d < bd) { bd = d; i = j; }
+ }
+ }
+ tmpV.fromArray(A.spawn.position, i * 3);
+ tmpW.fromArray(A.spawn.normal, i * 3);
+ tmpV.addScaledVector(tmpW, 0.02);
+ const aut = ts.autumn > 0.45;
+ if (aut) tmpC.copy(pickC(PAL_AUTUMN)).lerp(new THREE.Color('#6b3a1c'), ts.cover < 0.4 ? Math.random() * 0.5 : Math.random() * 0.15);
+ else tmpC.copy(pickC(PAL_GREEN)).lerp(new THREE.Color('#b6c94a'), ts.fresh * 0.6);
+ tmpC;
+ fall.spawn({
+ p0: tmpV, drift: tmpQ.set(wind.x + (Math.random() - 0.5) * 0.12, 0, wind.z + (Math.random() - 0.5) * 0.12),
+ speed: (burst ? 0.34 : 0.26) + Math.random() * 0.16, kind: Math.random() < 0.72 ? 0 : 1, color: tmpC,
+ size: (0.052 + Math.random() * 0.03) * TREE_H / 1.75, life: 70 + Math.random() * 60 + landed, spin: 1.2 + Math.random() * 2.6, flutter: 0.05 + Math.random() * 0.09, landed,
+ });
+}
+function spawnSamara() {
+ if (!A) return;
+ const i = Math.floor(Math.random() * A.spawn.count);
+ tmpV.fromArray(A.spawn.position, i * 3);
+ tmpC.set(Math.random() < 0.5 ? '#b56a3c' : '#c58e5a');
+ fall.spawn({ p0: tmpV, drift: tmpQ.set(wind.x * 1.6 + (Math.random() - 0.5) * 0.1, 0, wind.z), speed: 0.42 + Math.random() * 0.12, kind: 3, color: tmpC,
+ size: 0.05, life: 40, spin: 3 + Math.random() * 2, flutter: 0.02 });
+}
+function spawnPetal() {
+ tmpV.set(-2.6 + Math.random() * 3.0, 1.9 + Math.random() * 1.0, -1.2 + Math.random() * 3.0);
+ tmpC.copy(pickC(PAL_SPRING));
+ fall.spawn({ p0: tmpV, drift: tmpQ.set(0.26 + Math.random() * 0.2, 0, 0.04 + (Math.random() - 0.5) * 0.1), speed: 0.15 + Math.random() * 0.09, kind: 2, color: tmpC,
+ size: 0.032 + Math.random() * 0.014, life: 16, spin: 1 + Math.random() * 1.5, flutter: 0.1 + Math.random() * 0.1 });
+}
+function spawnSnowClump(near) {
+ if (!A) return;
+ const i = Math.floor(Math.random() * A.spawn.count);
+ tmpV.fromArray(A.spawn.position, i * 3);
+ if (near) tmpV.lerp(near, 0.35);
+ tmpC.setRGB(0.92, 0.94, 0.97);
+ fall.spawn({ p0: tmpV, drift: tmpQ.set((Math.random() - 0.5) * 0.08, 0, (Math.random() - 0.5) * 0.08), speed: 0.7 + Math.random() * 0.4, kind: 2, color: tmpC,
+ size: 0.012 + Math.random() * 0.012, life: 5, spin: 4, flutter: 0.01 });
+}
+
+// ─── Scroll keys: camera + season per scroll position ─────────────────────────
+const $ = s => document.querySelector(s);
+const secs = { seasons: $('.seasons'), nursery: $('.nursery'), craft: $('.craft'), visit: $('.visit'), foot: $('.foot') };
+let KEYS = [];
+const cam = { az: -0.3, el: 0.1, dist: 5.3, tx: 0, ty: 0.92, tz: 0, ox: 0.2, oy: 0, en: 0.9 };
+function prunePad() { return A?.pads?.length ? [...A.pads].filter(p => p.center.y < A.box.max.y - 0.35 * A.H).sort((a, b) => (b.center.z - b.center.x * 0.3) - (a.center.z - a.center.x * 0.3))[0] : null; }
+function topOf(el) { let y = 0; while (el) { y += el.offsetTop; el = el.offsetParent; } return y; }
+function layout() {
+ const vh = innerHeight;
+ const sT = topOf(secs.seasons), sL = secs.seasons.offsetHeight - vh, c = sL / 4;
+ const nT = topOf(secs.nursery), nH = secs.nursery.offsetHeight;
+ const cT = topOf(secs.craft), cL = secs.craft.offsetHeight - vh, k = cL / 3;
+ const vT = topOf(secs.visit), fT = topOf(secs.foot);
+ const m = MOBILE;
+ const ox = v => (m ? 0 : v);
+ const pad = prunePad()?.center ?? new THREE.Vector3(-0.3, 0.8, 0.3);
+ const paz = Math.atan2(pad.x, pad.z) * 0.8;
+ const wa = wireInfo?.view ?? new THREE.Vector3(0.3, 1.0, 0.2);
+ const waz = wireInfo?.az ?? 0.2, wd = clamp((wireInfo?.len ?? 0.5) * 2.9, 1.5, 2.6);
+ const potTop = A?.potTop ?? 0.4;
+ const base = { tx: 0, tz: 0, oy: m ? -0.075 : 0, en: 0 };
+ const K = (y, o) => ({ y, ...base, ...o });
+ const asp = innerWidth / innerHeight;
+ const d = asp < 1 ? 1 + (1 / asp - 1) * 0.6 : 1; // pull back on narrow screens
+ KEYS = [
+ K(0, { az: -0.34, el: 0.1, dist: 5.85 * d, ty: 0.9, ox: ox(0.2), s: 2.0, oy: m ? 0.2 : -0.035, en: 0.9 }),
+ K(sT, { az: -0.2, el: 0.12, dist: 4.8 * d, ty: 0.92, ox: ox(0.17), s: 2.02, en: 0.55 }),
+ K(sT + c * 0.55, { az: -0.08, el: 0.2, dist: 4.7 * d, ty: 0.78, ox: ox(0.17), s: 2.42 }),
+ K(sT + c * 1.2, { az: 0.08, el: 0.17, dist: 4.4 * d, ty: 0.95, ox: ox(0.17), s: 3.08 }),
+ K(sT + c * 1.6, { az: 0.14, el: 0.16, dist: 4.3 * d, ty: 0.95, ox: ox(0.17), s: 3.14 }),
+ K(sT + c * 2.25, { az: 0.28, el: 0.09, dist: 4.55 * d, ty: 0.92, ox: ox(0.17), s: 4.0 }),
+ K(sT + c * 2.6, { az: 0.32, el: 0.09, dist: 4.55 * d, ty: 0.92, ox: ox(0.17), s: 4.04 }),
+ K(sT + c * 3.3, { az: 0.44, el: 0.05, dist: 4.7 * d, ty: 0.95, ox: ox(0.17), s: 5.0 }),
+ K(sT + c * 4, { az: 0.48, el: 0.06, dist: 4.8 * d, ty: 0.95, ox: ox(0.17), s: 5.02 }),
+ K(nT - vh * 0.45, { az: 0.6, el: 0.16, dist: 5.9 * d, ty: 0.85, ox: ox(-0.22), s: 5.14, oy: m ? -0.22 : 0 }),
+ K(nT + nH - vh, { az: 0.74, el: 0.22, dist: 6.0 * d, ty: 0.8, ox: ox(-0.23), s: 5.28, oy: m ? -0.22 : 0 }),
+ K(cT, { az: paz * 0.75, el: 0.24, dist: 3.3 * d, tx: pad.x, ty: pad.y + 0.05, tz: pad.z, ox: ox(0.25), s: 5.2, oy: m ? -0.12 : 0 }),
+ K(cT + k * 0.6, { az: paz * 0.75 + 0.1, el: 0.22, dist: 3.15 * d, tx: pad.x, ty: pad.y + 0.05, tz: pad.z, ox: ox(0.25), s: 5.26, oy: m ? -0.12 : 0 }),
+ K(cT + k * 1.05, { az: waz + 0.1, el: 0.2, dist: wd * 1.08 * d, tx: wa.x, ty: wa.y, tz: wa.z, ox: ox(0.31), s: 6.9, oy: m ? -0.12 : 0 }),
+ K(cT + k * 1.6, { az: waz - 0.02, el: 0.16, dist: wd * 1.02 * d, tx: wa.x, ty: wa.y, tz: wa.z, ox: ox(0.31), s: 6.92, oy: m ? -0.12 : 0 }),
+ K(cT + k * 2.1, { az: 0.5, el: 0.2, dist: 3.1 * d, tx: 0.05, ty: potTop + 0.02, tz: 0.05, ox: ox(0.28), s: 7.74, oy: m ? -0.12 : -0.08 }),
+ K(cT + k * 3, { az: 0.4, el: 0.22, dist: 3.2 * d, tx: 0.05, ty: potTop + 0.02, tz: 0.05, ox: ox(0.28), s: 7.78, oy: m ? -0.12 : -0.08 }),
+ K(vT - vh * 0.45, { az: -0.4, el: 0.1, dist: 5.7 * d, ty: 0.95, ox: ox(0.24), s: 10.0, oy: m ? -0.24 : 0, en: 0.85 }),
+ K(fT, { az: -0.46, el: 0.14, dist: 6.0 * d, ty: 1.0, ox: ox(0.24), s: 10.02, oy: m ? -0.24 : 0, en: 0.85 }),
+ ];
+ secs._s = { sT, sL, cT, cL, nT, vT, fT };
+}
+const CAMK = ['az', 'el', 'dist', 'tx', 'ty', 'tz', 'ox', 'oy', 's', 'en'];
+const keyOut = {};
+function sample(y) {
+ const K = KEYS;
+ if (y <= K[0].y) { for (const k of CAMK) keyOut[k] = K[0][k]; return keyOut; }
+ for (let i = 0; i < K.length - 1; i++) {
+ const a = K[i], b = K[i + 1];
+ if (y <= b.y) {
+ const t = smooth(0, 1, (y - a.y) / Math.max(1, b.y - a.y));
+ for (const k of CAMK) keyOut[k] = lerp(a[k], b[k], t);
+ return keyOut;
+ }
+ }
+ const L = K[K.length - 1];
+ for (const k of CAMK) keyOut[k] = L[k];
+ return keyOut;
+}
+
+// ─── UI ────────────────────────────────────────────────────────────────────────
+const root = document.documentElement;
+const body = document.body;
+let manual = null;
+let season = 1.55;
+let intro = 0;
+const dial = new Dial($('.dial'), {
+ onStart: () => { manual = { s: season, y: scrollY }; },
+ onInput: f => {
+ if (!manual) manual = { s: season, y: scrollY };
+ const cur = manual.s;
+ let d = f - wrap(cur); if (d > 2) d -= 4; if (d < -2) d += 4;
+ manual.s = cur + d;
+ manual.y = scrollY;
+ },
+ onEnd: () => { if (manual) manual.y = scrollY; },
+});
+const railLis = [...document.querySelectorAll('.rail li')];
+const seasonArts = [...document.querySelectorAll('.season-copy article'), ...document.querySelectorAll('.season-glyph span')];
+const craftArts = [...document.querySelectorAll('.craft-steps article')];
+const craftIdx = [...document.querySelectorAll('.craft-index li')];
+const progEl = $('.season-progress');
+const craftPin = $('.craft-pin');
+const callout = $('.callout'), calloutLine = callout.querySelector('line'), calloutDot = callout.querySelector('circle'), calloutP = callout.querySelector('p');
+const CALLOUTS = [
+ { label: 'Sentei · June', text: 'Cut above the second pair of leaves.' },
+ { label: 'Harigane · 3.5 mm copper', text: 'Wound at forty-five degrees, a third the thickness of the branch.' },
+ { label: 'Nebari', text: 'The root flare — 180 years in the making.' },
+];
+let lastY = 0, lastSI = -1, lastCI = -1, lastAccent = '';
+const dividers = [...document.querySelectorAll('.brush-divider')];
+
+// Nursery hover preview.
+const preview = $('.preview'), previewImg = preview.querySelector('img');
+document.querySelectorAll('.catalogue li[data-img]').forEach(li => {
+ li.addEventListener('pointerenter', () => { previewImg.src = url(li.dataset.img); preview.classList.add('on'); });
+ li.addEventListener('pointerleave', () => preview.classList.remove('on'));
+});
+const catEl = $('.catalogue');
+let overCanvas = true;
+addEventListener('pointermove', e => {
+ overCanvas = e.target === canvas;
+ const r = catEl.getBoundingClientRect();
+ preview.style.transform = `translate3d(${(r.left - 250).toFixed(0)}px, ${(e.clientY - 160).toFixed(0)}px, 0) rotate(-2.5deg)`;
+}, { passive: true });
+
+// ─── Interaction: breeze on hover, shake on touch ─────────────────────────────
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+let hover = 0, hovering = false, shakeT = -10, shakeA = 0;
+const hitPoint = new THREE.Vector3();
+function treeHit() {
+ if (!A) return false;
+ ndc.set(pointer.x, pointer.y);
+ ray.setFromCamera(ndc, camera);
+ let best = Infinity;
+ const sph = new THREE.Sphere();
+ for (const p of A.pads) {
+ sph.set(p.center, p.radius * 0.85);
+ const hit = ray.ray.intersectSphere(sph, tmpW);
+ if (hit) { const d = hit.distanceTo(ray.ray.origin); if (d < best) { best = d; hitPoint.copy(hit); } }
+ }
+ if (best === Infinity) {
+ sph.set(new THREE.Vector3(0, A.potTop + 0.12, 0), 0.32);
+ if (ray.ray.intersectSphere(sph, tmpW)) { hitPoint.copy(tmpW); return true; }
+ }
+ return best < Infinity;
+}
+let cur = null;
+function shake() {
+ const ts = treeState(season);
+ shakeT = engine.time;
+ shakeA = 1;
+ U.uShakeDir.value.set(Math.random() - 0.5, 0, Math.random() - 0.5).normalize();
+ if (ts.cover > 0.2 && ts.autumn > 0.5) for (let i = 0; i < 110 * ts.cover; i++) spawnLeaf(ts, { burst: true, near: i % 5 < 3 ? hitPoint : null });
+ else if (ts.cover > 0.2) { for (let i = 0; i < 9; i++) spawnLeaf(ts, { burst: true, near: hitPoint }); if (wrap(season) > 1.3) for (let i = 0; i < 6; i++) spawnSamara(); }
+ if (ts.snow > 0.3) for (let i = 0; i < 90; i++) spawnSnowClump(hitPoint);
+ if (ts.cover < 0.2 && ts.snow < 0.3) for (let i = 0; i < 4; i++) spawnSamara();
+}
+// Pruning: a few shoots are cut and drift down when the step opens.
+function snip() {
+ const pad = prunePad(); if (!pad) return;
+ const ts = treeState(season);
+ for (let i = 0; i < 14; i++) spawnLeaf(ts, { burst: true, near: tmpQ.copy(pad.center).add(tmpW.set((Math.random() - 0.5) * 0.3, pad.std.y, (Math.random() - 0.5) * 0.3)) });
+ shakeT = engine.time; shakeA = 0.35;
+}
+canvas.addEventListener('pointerdown', e => {
+ if (e.button !== 0 || !intro) return;
+ if (treeHit()) shake();
+});
+
+const NZ = new THREE.Vector3(0, 0, 1), NY = new THREE.Vector3(0, 1, 0);
+const _L = new THREE.Vector3(), _E = new THREE.Color(), _c = new THREE.Color();
+const PAPER_GAIN = +(DBG.get('pg') ?? 1.1);
+function paperAlbedo(out, target, n) {
+ _E.setRGB(0.06, 0.06, 0.06); // environment, roughly
+ for (const l of [key, fill, rim]) {
+ _L.copy(l.position).sub(l.target ? l.target.position : keyTarget.position).normalize();
+ const d = Math.max(0, n.dot(_L));
+ _E.r += l.color.r * l.intensity * d / Math.PI; _E.g += l.color.g * l.intensity * d / Math.PI; _E.b += l.color.b * l.intensity * d / Math.PI;
+ }
+ const hw = 0.5 + 0.5 * n.y;
+ _c.copy(hemi.groundColor).lerp(hemi.color, hw).multiplyScalar(hemi.intensity / Math.PI);
+ _E.add(_c);
+ out.setRGB(target.r / _E.r, target.g / _E.g, target.b / _E.b).multiplyScalar(PAPER_GAIN);
+}
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+let leafAcc = 0, petalAcc = 0, samaraAcc = 0, cleared = true, frameN = 0;
+const tgt = new THREE.Vector3();
+const forced = DBG.has('s') ? +DBG.get('s') : null;
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ const y = scrollY;
+ const k = sample(y);
+ for (const n of ['az', 'el', 'dist', 'tx', 'ty', 'tz', 'ox', 'oy', 'en']) cam[n] = damp(cam[n], k[n], 4.2, dt);
+ cycU.uEnsoA.value = cam.en;
+
+ // Season: scroll by default; the dial overrides until you scroll on.
+ if (manual && !dial.dragging && Math.abs(y - manual.y) > innerHeight * 0.4) {
+ season += 4 * Math.round((k.s - season) / 4);
+ manual = null;
+ }
+ let target = manual ? manual.s : k.s - (1 - intro) * 0.5;
+ if (forced !== null) target = forced;
+ season = damp(season, target, manual ? 5 : 2.6, dt);
+ const ts = treeState(season);
+ const ws = worldState(season);
+
+ // Camera.
+ const introPush = (1 - intro) * 1.4;
+ const dist = cam.dist + introPush;
+ const ce = Math.cos(cam.el);
+ const az = cam.az + pointer.sx * 0.035 + (1 - intro) * -0.12;
+ tgt.set(cam.tx, cam.ty, cam.tz);
+ camera.position.set(tgt.x + Math.sin(az) * ce * dist, tgt.y + Math.sin(cam.el) * dist + pointer.sy * 0.04 + Math.sin(t * 0.3) * 0.008, tgt.z + Math.cos(az) * ce * dist);
+ camera.lookAt(tgt);
+ const w = innerWidth, h = innerHeight;
+ camera.setViewOffset(w, h, -cam.ox * w, -cam.oy * h, w, h);
+
+ // World.
+ scene.fog.color.copy(ws.fog); scene.fog.density = ws.fogD;
+ renderer.setClearColor(ws.fog);
+ hemi.color.copy(ws.sky); hemi.groundColor.copy(ws.ground); hemi.intensity = ws.hemiI * 1.3;
+ key.color.copy(ws.key); key.intensity = ws.keyI;
+ const kaz = ws.az * D, kel = ws.el * D;
+ key.position.set(Math.sin(kaz) * Math.cos(kel), Math.sin(kel), Math.cos(kaz) * Math.cos(kel)).multiplyScalar(11).add(keyTarget.position);
+ key.shadow.radius = ws.soft;
+ fill.position.set(-Math.sin(kaz) * 5, 2.5, 4); fill.color.copy(ws.wall); fill.intensity = 0.55;
+ rim.color.copy(ws.key).lerp(_c.set(0xffc996), ts.snow * 0.8); rim.intensity = 0.7 + ts.autumn * 0.5 + ts.snow * 2.4;
+ U.uWarm.value.setRGB(1 + 0.2 * ts.snow, 1 + 0.03 * ts.snow, 1 - 0.14 * ts.snow);
+ // Calibrate the paper so its lit tone lands on the season's colour; only the key's share falls into shadow.
+ paperAlbedo(cycU.uWallC.value, ws.wall, NZ);
+ paperAlbedo(cycU.uFloorC.value, ws.floor, NY);
+
+ // Tree uniforms.
+ U.uTime.value = t;
+ U.uCover.value = ts.cover; U.uAutumn.value = ts.autumn; U.uFresh.value = ts.fresh; U.uDeep.value = ts.deep; U.uSnow.value = ts.snow;
+ U.uGlow.value = ws.glow;
+ // Breeze: hovering the canopy wakes the wind; pointer speed gusts it.
+ if ((frameN++ & 3) === 0) overCanvas = pointer.active && document.elementFromPoint(pointer.px, pointer.py) === canvas;
+ hovering = intro > 0.5 && pointer.active && !MOBILE && overCanvas && !engine.paused && treeHit();
+ hover = damp(hover, hovering ? 1 : 0, 3, dt);
+ const gust = clamp(Math.hypot(pointer.vx, pointer.vy) * 0.25 * hover);
+ U.uBreeze.value = damp(U.uBreeze.value, 0.16 + hover * 0.7 + gust * 0.8, 2.5, dt);
+ if (Math.abs(pointer.vx) > 0.02) U.uWind.value.x = damp(U.uWind.value.x, Math.sign(pointer.vx), 2 * hover, dt);
+ U.uWind.value.normalize();
+ const st = t - shakeT;
+ U.uShake.value = shakeA * Math.exp(-st * 3.4) * Math.sin(st * 19);
+ if (cur) cur.set(hovering ? 'label' : '', hovering ? (ts.snow > 0.3 ? 'shake snow' : 'shake') : '');
+ if (hovering && Math.random() < dt * 0.6 * hover && ts.cover > 0.4 && ts.autumn > 0.5) spawnLeaf(ts, { near: hitPoint });
+
+ // Particles.
+ wind.set(-0.08 + Math.sin(t * 0.13) * 0.03 - hover * 0.04, 0, 0.03);
+ leafAcc += ws.leafRate * (ts.cover > 0.04 ? 1 : 0) * dt * intro;
+ while (leafAcc > 1) { spawnLeaf(ts); leafAcc -= 1; }
+ petalAcc += ws.petals * 6 * dt * intro;
+ while (petalAcc > 1) { spawnPetal(); petalAcc -= 1; }
+ const f = wrap(season);
+ samaraAcc += (f > 1.45 && f < 2.2 ? 0.25 : 0) * dt * intro;
+ while (samaraAcc > 1) { spawnSamara(); samaraAcc -= 1; }
+ if (!cleared && (f > 3.5 || f < 1.5)) { fall.clearLanded(3); cleared = true; }
+ if (f > 1.8 && f < 3.4) cleared = false;
+ fall.uniforms.uSnow.value = ts.snow;
+ fall.update(dt, wind);
+ snow.uniforms.uFogCol.value.copy(ws.fog); snow.uniforms.uFogD.value = ws.fogD;
+ snow.update(dt, t, ws.snowfall, tmpQ.set(wind.x * 0.8, 0, wind.z));
+ motes.uniforms.uFogCol.value.copy(ws.fog); motes.uniforms.uFogD.value = ws.fogD;
+ motes.update(dt, t, ws.motes * 0.9, tmpQ.set(0.02, 0.01, 0));
+ if (wire && wireInfo) {
+ const { cT, cL } = secs._s;
+ const p = range(y, cT + cL / 3 * 0.45, cT + cL / 3 * 1.3);
+ wire.geometry.setDrawRange(0, Math.floor(p * wireInfo.segs) * wireInfo.radial * 6);
+ wire.visible = p > 0.001;
+ }
+
+ // Page chrome.
+ const accent = '#' + ws.accent.getHexString();
+ if (accent !== lastAccent) {
+ root.style.setProperty('--accent', accent); lastAccent = accent;
+ _c.copy(ws.fog).convertLinearToSRGB();
+ root.style.setProperty('--scene-rgb', `${Math.round(_c.r * 255)}, ${Math.round(_c.g * 255)}, ${Math.round(_c.b * 255)}`);
+ }
+ dial.set(season, 180 + Math.floor((season - 2 + 0.5) / 4));
+ body.classList.toggle('is-scrolled', y > 60);
+ if (Math.abs(y - lastY) > 4) { body.classList.toggle('nav-hide', y > lastY && y > innerHeight * 0.7); lastY = y; }
+ const { sT, sL, cT, cL, fT } = secs._s;
+ const inSeasons = y > sT - innerHeight * 0.3 && y < sT + sL + innerHeight * 0.2;
+ const si = seasonIndex(season);
+ if (si !== lastSI) {
+ lastSI = si;
+ railLis.forEach(li => li.classList.toggle('on', +li.dataset.i === si));
+ seasonArts.forEach(a => a.classList.toggle('on', +a.dataset.i === si));
+ }
+ if (inSeasons) progEl.style.setProperty('--sp', clamp((y - sT) / sL).toFixed(4));
+ craftPin.classList.toggle('is-on', y > cT - h * 0.2 && y < cT + cL + h * 0.25);
+ const cp = (y - cT) / cL;
+ const ci = cp < -0.08 || cp > 1.02 ? -1 : clamp(Math.floor(cp * 3), 0, 2);
+ if (ci !== lastCI) {
+ lastCI = ci;
+ craftArts.forEach((a, i) => a.classList.toggle('on', i === ci));
+ craftIdx.forEach((a, i) => a.classList.toggle('on', i === ci));
+ if (ci >= 0) calloutP.innerHTML = `<b>${CALLOUTS[ci].label}</b>${CALLOUTS[ci].text}`;
+ if (ci === 0 && intro > 0.9) setTimeout(snip, 700);
+ }
+ // Callout anchored to the 3D subject of each craft step.
+ let anchor = null;
+ if (ci === 0 && A?.pads?.length) {
+ const pad = prunePad();
+ anchor = tmpV.copy(pad.center).add(tmpW.set(pad.center.x > 0 ? 0.1 : -0.1, pad.std.y * 1.2, 0.08));
+ } else if (ci === 1 && wireInfo) anchor = tmpV.copy(wireInfo.anchor);
+ else if (ci === 2 && A) anchor = tmpV.set(A.trunk[0].x + 0.12, A.potTop + 0.015, A.trunk[0].z + 0.1);
+ const within = ci >= 0 && Math.abs(cp * 3 - (ci + 0.5)) < 0.42;
+ callout.classList.toggle('on', !!anchor && within);
+ if (anchor) {
+ anchor.project(camera);
+ const ax = (anchor.x + 1) / 2 * w, ay = (1 - anchor.y) / 2 * h;
+ const flip = ax > w * 0.84;
+ const lx = MOBILE ? clamp(ax - 60, 16, w - 190) : flip ? ax - 300 : Math.min(ax + 90, w - 300), ly = Math.max(90, ay - (MOBILE ? 90 : 130));
+ calloutLine.setAttribute('x1', ax.toFixed(1)); calloutLine.setAttribute('y1', ay.toFixed(1));
+ calloutLine.setAttribute('x2', lx.toFixed(1)); calloutLine.setAttribute('y2', (ly + 34).toFixed(1));
+ calloutDot.setAttribute('cx', ax.toFixed(1)); calloutDot.setAttribute('cy', ay.toFixed(1));
+ calloutP.style.transform = `translate3d(${lx.toFixed(1)}px, ${(ly - 10).toFixed(1)}px, 0)`;
+ }
+ for (const dv of dividers) {
+ const r = dv.getBoundingClientRect();
+ dv.style.setProperty('--draw', clamp((h - r.top) / (h * 0.6)).toFixed(3));
+ }
+ body.classList.toggle('in-foot', y + h > fT + h * 0.35);
+ body.classList.toggle('dial-off', y > secs._s.nT + h * 0.1 && y < secs._s.cT - h * 0.35);
+ engine.paused = y > fT + 2;
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('koen', { theme: 'light', corner: 'bl' });
+cur = cursor({ color: '#1d1a17', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.07 });
+reveal('.panel h2', { type: 'lines', stagger: 0.1 });
+reveal('.lede', { type: 'lines', stagger: 0.05, y: '100%' });
+gsap.from('.catalogue li', { opacity: 0, y: 26, duration: 1.1, ease: 'expo.out', stagger: 0.07, scrollTrigger: { trigger: '.catalogue', start: 'top 80%', once: true } });
+gsap.from('.facts > div', { opacity: 0, y: 22, duration: 1.1, ease: 'expo.out', stagger: 0.08, scrollTrigger: { trigger: '.facts', start: 'top 85%', once: true } });
+document.querySelectorAll('.hero-title .ln').forEach(l => { l.innerHTML = `<span>${l.innerHTML}</span>`; });
+gsap.set('.hero-title .ln > span', { yPercent: 110 });
+gsap.set('.eyebrow, .hero-sub, .hero-cta, .hint, .nav, .hero-vert, .dial-wrap', { opacity: 0 });
+
+await treeLoad;
+// The page opens in late autumn: some leaves are already down on the moss and the slab.
+if (A) { const ts0 = treeState(2); for (let i = 0; i < 90; i++) spawnLeaf(ts0, { landed: 1 + Math.random() * 30 }); }
+await document.fonts.ready;
+layout();
+addEventListener('resize', () => { layout(); });
+new ResizeObserver(() => layout()).observe(document.body);
+{ const s0 = sample(scrollY); for (const n of ['az', 'el', 'dist', 'tx', 'ty', 'tz', 'ox', 'oy', 'en']) cam[n] = s0[n]; }
+if (DBG.has('s')) season = +DBG.get('s');
+// Warm every program: summer, autumn and winter states, leaves and snow visible.
+U.uSnow.value = 1; snow.points.visible = true; motes.points.visible = true;
+renderer.compile(scene, camera);
+engine.start();
+await loader.finish();
+gsap.to({ v: 0 }, { v: 1, duration: 3.6, ease: 'power2.inOut', onUpdate() { intro = this.targets()[0].v; } });
+gsap.to('.hero-title .ln > span', { yPercent: 0, duration: 1.8, ease: 'expo.out', stagger: 0.12, delay: 0.35 });
+gsap.to('.eyebrow, .hero-sub, .hero-cta, .nav, .hero-vert', { opacity: 1, duration: 1.4, ease: 'power2.out', stagger: 0.08, delay: 0.9 });
+gsap.to('.hint, .dial-wrap', { opacity: 1, duration: 1.4, ease: 'power2.out', delay: 1.8 });
+window.__koen = { get season() { return season; }, set season(v) { season = v; }, shake, lenis, A: () => A, keys: () => KEYS, cam: () => ({ ...cam }), info: () => ({ ...renderer.info.render, twigTris: twigs?.geometry.index.count / 3 }), wire: () => wireInfo, camera };
diff --git a/examples/koen/particles.js b/examples/koen/particles.js
new file mode 100644
index 0000000..e5e524a
--- /dev/null
+++ b/examples/koen/particles.js
@@ -0,0 +1,308 @@
+// Falling things: maple leaves, samaras and petals as GPU-animated instanced cards that tumble,
+// land and pile up; snow and summer motes as points.
+import { THREE, clamp, lerp } from '../../src/core/engine.js';
+
+// ─── Atlas (2×2): 7-lobed maple leaf, 5-lobed leaf, cherry petal, samara ──────
+function drawAtlas() {
+ const S = 512, cv = document.createElement('canvas');
+ cv.width = cv.height = S * 2;
+ const g = cv.getContext('2d');
+ const leaf = (ox, oy, lobes, spread, lens, width) => {
+ g.save(); g.translate(ox + S / 2, oy + S * 0.6);
+ const path = new Path2D();
+ const L = S * 0.4;
+ const angs = [];
+ for (let i = 0; i < lobes; i++) angs.push(-spread / 2 + spread * i / (lobes - 1));
+ // outline through each lobe tip with serrated flanks and notches between lobes
+ const pt = (a, r) => [Math.sin(a) * r, -Math.cos(a) * r];
+ const first = pt(angs[0] - 0.22, L * 0.12);
+ path.moveTo(first[0], first[1]);
+ angs.forEach((a, i) => {
+ const len = L * lens[i];
+ const w = width;
+ const notchL = pt(a - w, len * 0.32), tip = pt(a, len), notchR = pt(a + w, len * 0.32);
+ // left flank, serrated
+ const teeth = 7;
+ for (let k = 1; k <= teeth; k++) {
+ const t = k / teeth;
+ const aa = lerp(a - w, a, t), rr = lerp(len * 0.32, len, t);
+ const [x, y] = pt(aa - 0.05 * (1 - t), rr * (k % 2 ? 1.035 : 0.985));
+ path.lineTo(x, y);
+ }
+ path.lineTo(tip[0], tip[1]);
+ for (let k = teeth; k >= 1; k--) {
+ const t = k / teeth;
+ const aa = lerp(a + w, a, t), rr = lerp(len * 0.32, len, t);
+ const [x, y] = pt(aa + 0.05 * (1 - t), rr * (k % 2 ? 1.035 : 0.985));
+ path.lineTo(x, y);
+ }
+ path.lineTo(notchR[0], notchR[1]);
+ if (i < angs.length - 1) { const nn = pt((a + angs[i + 1]) / 2, len * 0.22); path.lineTo(nn[0], nn[1]); }
+ void notchL;
+ });
+ const last = pt(angs[angs.length - 1] + 0.22, L * 0.12);
+ path.lineTo(last[0], last[1]);
+ path.lineTo(0, L * 0.06);
+ path.closePath();
+ const grd = g.createRadialGradient(0, 0, 0, 0, 0, L);
+ grd.addColorStop(0, '#f4f0ea'); grd.addColorStop(0.6, '#e2dbd2'); grd.addColorStop(1, '#c9c0b5');
+ g.fillStyle = grd; g.fill(path);
+ // veins
+ g.strokeStyle = 'rgba(90,70,60,0.35)'; g.lineWidth = 3;
+ angs.forEach((a, i) => { const tip = pt(a, L * lens[i] * 0.92); g.beginPath(); g.moveTo(0, 0); g.lineTo(tip[0], tip[1]); g.stroke(); });
+ g.lineWidth = 1.2; g.strokeStyle = 'rgba(90,70,60,0.18)';
+ angs.forEach((a, i) => {
+ for (let k = 1; k < 5; k++) {
+ const r = L * lens[i] * k / 5.5; const [x, y] = pt(a, r);
+ for (const sd of [-1, 1]) { const [x2, y2] = pt(a + sd * width * 0.7, r + L * 0.06); g.beginPath(); g.moveTo(x, y); g.lineTo(x2, y2); g.stroke(); }
+ }
+ });
+ // petiole
+ g.strokeStyle = '#b9ab9c'; g.lineWidth = 5; g.lineCap = 'round';
+ g.beginPath(); g.moveTo(0, 0); g.quadraticCurveTo(6, L * 0.3, -4, L * 0.52); g.stroke();
+ g.restore();
+ };
+ leaf(0, 0, 7, 4.3, [0.62, 0.84, 0.96, 1, 0.96, 0.84, 0.62], 0.2);
+ leaf(S, 0, 5, 3.3, [0.7, 0.94, 1, 0.94, 0.7], 0.3);
+ // petal
+ {
+ g.save(); g.translate(S / 2, S * 1.5 + 20);
+ const p = new Path2D();
+ p.moveTo(0, S * 0.3);
+ p.bezierCurveTo(S * 0.34, S * 0.14, S * 0.3, -S * 0.26, S * 0.07, -S * 0.3);
+ p.lineTo(0, -S * 0.22);
+ p.lineTo(-S * 0.07, -S * 0.3);
+ p.bezierCurveTo(-S * 0.3, -S * 0.26, -S * 0.34, S * 0.14, 0, S * 0.3);
+ const grd = g.createLinearGradient(0, S * 0.3, 0, -S * 0.3);
+ grd.addColorStop(0, '#e6d6d6'); grd.addColorStop(0.35, '#fbf6f5'); grd.addColorStop(1, '#fffafa');
+ g.fillStyle = grd; g.fill(p);
+ g.strokeStyle = 'rgba(160,110,120,0.15)'; g.lineWidth = 2;
+ for (let k = -2; k <= 2; k++) { g.beginPath(); g.moveTo(0, S * 0.28); g.quadraticCurveTo(k * S * 0.06, 0, k * S * 0.08, -S * 0.24); g.stroke(); }
+ g.restore();
+ }
+ // samara (maple seed wing)
+ {
+ g.save(); g.translate(S * 1.5, S * 1.5);
+ g.rotate(-0.5);
+ const p = new Path2D();
+ p.ellipse(0, S * 0.26, S * 0.07, S * 0.06, 0, 0, Math.PI * 2);
+ g.fillStyle = '#b8a48c'; g.fill(p);
+ const w = new Path2D();
+ w.moveTo(-S * 0.05, S * 0.24);
+ w.bezierCurveTo(-S * 0.2, 0, -S * 0.16, -S * 0.3, 0, -S * 0.36);
+ w.bezierCurveTo(S * 0.14, -S * 0.3, S * 0.14, 0, S * 0.05, S * 0.22);
+ w.closePath();
+ const grd = g.createLinearGradient(0, S * 0.24, 0, -S * 0.36);
+ grd.addColorStop(0, '#d8cbbb'); grd.addColorStop(1, '#f2ebe2');
+ g.fillStyle = grd; g.fill(w);
+ g.strokeStyle = 'rgba(110,90,70,0.25)'; g.lineWidth = 1.5;
+ for (let k = 0; k < 9; k++) { g.beginPath(); g.moveTo(-S * 0.03, S * 0.22); g.quadraticCurveTo(-S * 0.1 + k * 0.02 * S, -S * 0.1, -S * 0.08 + k * S * 0.025, -S * 0.33); g.stroke(); }
+ g.restore();
+ }
+ const t = new THREE.CanvasTexture(cv);
+ t.colorSpace = THREE.SRGBColorSpace;
+ t.anisotropy = 8;
+ t.generateMipmaps = true;
+ return t;
+}
+
+const LEAF_HEAD = /* glsl */`
+attribute vec3 aP0; attribute vec3 aP1; attribute vec4 aT; attribute vec4 aK; attribute vec3 aCol;
+uniform float uTime; uniform vec3 uWind;
+varying vec3 vCol; varying float vLanded;
+vec4 qAx(vec3 a, float t){ return vec4(normalize(a) * sin(t * .5), cos(t * .5)); }
+vec4 qMul(vec4 a, vec4 b){ return vec4(a.w * b.xyz + b.w * a.xyz + cross(a.xyz, b.xyz), a.w * b.w - dot(a.xyz, b.xyz)); }
+vec3 qRot(vec4 q, vec3 v){ return v + 2. * cross(q.xyz, cross(q.xyz, v) + q.w * v); }
+vec4 qSlerp(vec4 a, vec4 b, float t){ if (dot(a, b) < 0.) b = -b; return normalize(mix(a, b, t)); }
+void kLeaf(out vec3 p, out vec4 q, out float s, out float land){
+ float age = uTime - aT.x;
+ float k = clamp(age / aT.y, 0., 1.);
+ float seed = aT.w;
+ float alive = step(0., age) * step(uTime, aT.z);
+ s = aK.y * alive * smoothstep(aT.z, aT.z - 1.4, uTime) * smoothstep(0., 0.35, age);
+ land = smoothstep(0.93, 1.0, k);
+ p = mix(aP0, aP1, k);
+ float fr = 1.3 + fract(seed * 7.3) * 1.1;
+ float sw = sin(age * fr + seed * 40.);
+ vec3 side = normalize(vec3(cos(seed * 50.), 0., sin(seed * 50.)));
+ float fl = aK.w * (1. - land) * smoothstep(0., 0.12, k);
+ p += side * sw * fl;
+ p.y += (1. - abs(sw)) * fl * -0.3;
+ vec3 ax = normalize(vec3(sin(seed * 12.), cos(seed * 7.) * 0.4, cos(seed * 12.)));
+ vec4 fly;
+ if (aK.x > 2.5) fly = qMul(qAx(vec3(0., 1., 0.), age * aK.z * 4.), qAx(vec3(1., 0., 0.), 1.1)); // samara: helicopter
+ else fly = qMul(qAx(ax, age * aK.z), qAx(side, sw * 0.9));
+ vec4 flat_ = qMul(qAx(vec3(0., 1., 0.), seed * 6.2831), qAx(vec3(1., 0., 0.), -1.5708 + (fract(seed * 9.1) - 0.5) * 0.45));
+ q = qSlerp(fly, flat_, land);
+}
+`;
+
+export class Fall {
+ constructor(scene, { count = 1800, groundAt = () => 0, receiveShadow = true } = {}) {
+ this.count = count;
+ this.groundAt = groundAt;
+ this.cursor = 0;
+ this.time = 0;
+ this.uniforms = { uTime: { value: 0 }, uWind: { value: new THREE.Vector3() }, uSnow: { value: 0 }, uSnowCol: { value: new THREE.Color(0.9, 0.92, 0.96) } };
+ const base = new THREE.PlaneGeometry(1, 1, 3, 3);
+ // cup the card slightly so leaves read as leaves, not stickers
+ const bp = base.attributes.position;
+ for (let i = 0; i < bp.count; i++) bp.setZ(i, (bp.getX(i) ** 2 + bp.getY(i) ** 2 * 0.4) * 0.28);
+ base.computeVertexNormals();
+ const g = new THREE.InstancedBufferGeometry();
+ g.index = base.index;
+ g.setAttribute('position', base.attributes.position);
+ g.setAttribute('normal', base.attributes.normal);
+ g.setAttribute('uv', base.attributes.uv);
+ const mk = n => new THREE.InstancedBufferAttribute(new Float32Array(count * n), n).setUsage(THREE.DynamicDrawUsage);
+ this.aP0 = mk(3); this.aP1 = mk(3); this.aT = mk(4); this.aK = mk(4); this.aCol = mk(3);
+ for (let i = 0; i < count; i++) this.aT.setXYZW(i, -100, 1, -99, Math.random());
+ g.setAttribute('aP0', this.aP0); g.setAttribute('aP1', this.aP1); g.setAttribute('aT', this.aT); g.setAttribute('aK', this.aK); g.setAttribute('aCol', this.aCol);
+ g.instanceCount = count;
+ this.geometry = g;
+ const atlas = drawAtlas();
+ const U = this.uniforms;
+ const vtx = shader => {
+ Object.assign(shader.uniforms, U);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', `#include <common>\n${LEAF_HEAD}`)
+ .replace('#include <uv_vertex>', `#include <uv_vertex>
+ #ifdef USE_MAP
+ { float kd = floor(aK.x + 0.5); vMapUv = uv * 0.5 + vec2(mod(kd, 2.) * 0.5, kd < 1.5 ? 0.5 : 0.); }
+ #endif`)
+ .replace('#include <begin_vertex>', `vec3 kp; vec4 kq; float ks; float kl; kLeaf(kp, kq, ks, kl);
+ vec3 transformed = qRot(kq, position * ks) + kp; vCol = aCol; vLanded = kl;`);
+ };
+ this.material = new THREE.MeshStandardMaterial({ map: atlas, alphaTest: 0.5, side: THREE.DoubleSide, roughness: 0.62, metalness: 0, envMapIntensity: 0.7 });
+ this.material.onBeforeCompile = shader => {
+ vtx(shader);
+ shader.vertexShader = shader.vertexShader.replace('#include <beginnormal_vertex>', `vec3 objectNormal;
+ { vec3 kp; vec4 kq; float ks; float kl; kLeaf(kp, kq, ks, kl); objectNormal = qRot(kq, normal); }`);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vCol; varying float vLanded; uniform float uSnow; uniform vec3 uSnowCol;')
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ diffuseColor.rgb *= vCol;
+ diffuseColor.rgb = mix(diffuseColor.rgb, uSnowCol, uSnow * vLanded * 0.82);`)
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\ntotalEmissiveRadiance += diffuseColor.rgb * 0.16;');
+ };
+ this.material.customProgramCacheKey = () => 'koen-fall';
+ const depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: atlas, alphaTest: 0.5, side: THREE.DoubleSide });
+ depth.onBeforeCompile = vtx;
+ depth.customProgramCacheKey = () => 'koen-fall-depth';
+ this.mesh = new THREE.Mesh(g, this.material);
+ this.mesh.customDepthMaterial = depth;
+ this.mesh.castShadow = true;
+ this.mesh.receiveShadow = receiveShadow;
+ this.mesh.frustumCulled = false;
+ this.mesh.renderOrder = 2;
+ scene.add(this.mesh);
+ this._dirty = false;
+ this.pile = new Map();
+ }
+
+ /** p0: start, drift: horizontal velocity, speed: fall speed (units/s). */
+ spawn({ p0, drift, speed = 0.3, kind = 0, color, size = 0.065, life = 60, spin = 2, flutter = 0.08, landed = 0 }) {
+ const i = this.cursor; this.cursor = (this.cursor + 1) % this.count;
+ let t0 = this.time;
+ // two passes to find where it lands
+ let gy = 0, dur = 1, lx = p0.x, lz = p0.z;
+ for (let it = 0; it < 3; it++) {
+ dur = Math.max(0.3, (p0.y - gy) / speed);
+ lx = p0.x + drift.x * dur; lz = p0.z + drift.z * dur;
+ gy = this.groundAt(lx, lz);
+ }
+ // leaves pile: each landing lifts the next a little
+ if (landed) t0 -= dur + landed; // already on the ground when the page opens
+ const key = `${Math.round(lx * 30)},${Math.round(lz * 30)}`;
+ const stack = this.pile.get(key) ?? 0;
+ this.pile.set(key, stack + 1);
+ const lift = Math.min(stack, 6) * 0.0035 + 0.003;
+ this.aP0.setXYZ(i, p0.x, p0.y, p0.z);
+ this.aP1.setXYZ(i, lx, gy + lift, lz);
+ this.aT.setXYZW(i, t0, dur, t0 + dur + life, Math.random());
+ this.aK.setXYZW(i, kind, size, spin, flutter);
+ this.aCol.setXYZ(i, color.r, color.g, color.b);
+ this._dirty = true;
+ }
+
+ /** Remove everything that has landed (spring clean) over a few seconds. */
+ clearLanded(within = 2.5) {
+ const now = this.time;
+ for (let i = 0; i < this.count; i++) {
+ const t0 = this.aT.getX(i), dur = this.aT.getY(i), death = this.aT.getZ(i);
+ if (death > now && this.aK.getX(i) < 1.5) this.aT.setZ(i, now + 0.4 + Math.random() * within);
+ }
+ this.pile.clear();
+ this._dirty = true;
+ }
+
+ update(dt, wind) {
+ this.time += dt;
+ this.uniforms.uTime.value = this.time;
+ this.uniforms.uWind.value.copy(wind);
+ if (this._dirty) {
+ for (const a of [this.aP0, this.aP1, this.aT, this.aK, this.aCol]) a.needsUpdate = true;
+ this._dirty = false;
+ }
+ }
+}
+
+// ─── Points: snow and motes ───────────────────────────────────────────────────
+export class Drift {
+ constructor(scene, { count = 5000, box = [-3.5, 0, -3, 3.5, 3.6, 3.4], color = 0xffffff, size = 5, speed = 0.4, swirl = 0.1, bright = 1, glow = false } = {}) {
+ const pos = new Float32Array(count * 3), seed = new Float32Array(count);
+ const [x0, y0, z0, x1, y1, z1] = box;
+ for (let i = 0; i < count; i++) {
+ pos[i * 3] = lerp(x0, x1, Math.random()); pos[i * 3 + 1] = lerp(y0, y1, Math.random()); pos[i * 3 + 2] = lerp(z0, z1, Math.random());
+ seed[i] = Math.random();
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ this.uniforms = {
+ uTime: { value: 0 }, uAmt: { value: 0 }, uDpr: { value: 1 }, uSize: { value: size }, uSpeed: { value: speed }, uSwirl: { value: swirl },
+ uBox0: { value: new THREE.Vector3(x0, y0, z0) }, uBox1: { value: new THREE.Vector3(x1, y1, z1) }, uWind: { value: new THREE.Vector3() },
+ uCol: { value: new THREE.Color(color).multiplyScalar(bright) }, uFogCol: { value: new THREE.Color() }, uFogD: { value: 0.02 },
+ };
+ this.material = new THREE.ShaderMaterial({
+ uniforms: this.uniforms, transparent: true, depthWrite: false,
+ blending: glow ? THREE.AdditiveBlending : THREE.NormalBlending,
+ vertexShader: /* glsl */`
+ attribute float seed; uniform float uTime, uAmt, uDpr, uSize, uSpeed, uSwirl, uFogD; uniform vec3 uBox0, uBox1, uWind;
+ varying float vA; varying float vFog;
+ void main(){
+ vec3 span = uBox1 - uBox0;
+ vec3 p = position;
+ float t = uTime;
+ p.y -= t * uSpeed * (0.6 + seed * 0.8);
+ p += uWind * t * (0.7 + seed * 0.6);
+ p.x += sin(t * (0.5 + seed) + seed * 30.) * uSwirl;
+ p.z += cos(t * (0.4 + seed * 0.7) + seed * 17.) * uSwirl;
+ p = uBox0 + mod(p - uBox0, span);
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ float edge = smoothstep(0., 0.3, p.y - uBox0.y) * smoothstep(0., 0.4, uBox1.y - p.y);
+ vA = uAmt * edge * smoothstep(0.25, 0.9, -mv.z) * step(fract(seed * 13.7), uAmt * 1.2 + 0.05);
+ vFog = 1. - exp(-uFogD * uFogD * mv.z * mv.z);
+ gl_PointSize = uSize * (0.45 + fract(seed * 31.) * 0.9) * uDpr * (2.2 / -mv.z);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uCol, uFogCol; varying float vA; varying float vFog;
+ void main(){
+ float d = length(gl_PointCoord - .5);
+ float a = smoothstep(.5, .12, d);
+ gl_FragColor = vec4(mix(uCol, uFogCol, vFog * 0.7), a * vA);
+ }`,
+ });
+ this.points = new THREE.Points(g, this.material);
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 3;
+ scene.add(this.points);
+ }
+ update(dt, t, amt, wind) {
+ this.uniforms.uTime.value = t;
+ this.uniforms.uAmt.value = amt;
+ this.uniforms.uWind.value.copy(wind);
+ this.points.visible = amt > 0.002;
+ }
+}
diff --git a/examples/koen/seasons.js b/examples/koen/seasons.js
new file mode 100644
index 0000000..869fcc5
--- /dev/null
+++ b/examples/koen/seasons.js
@@ -0,0 +1,94 @@
+// The year as a number. s is unwrapped (it keeps counting up as the page turns years);
+// f = s mod 4 with 0 = mid-spring, 1 = mid-summer, 2 = peak autumn, 3 = deep winter.
+import { THREE, clamp, smooth } from '../../src/core/engine.js';
+
+export const wrap = s => ((s % 4) + 4) % 4;
+
+// Twenty-four solar terms (nijūshi sekki). Index 0 = Risshun; mid-spring (f = 0) sits on Shunbun (index 3).
+export const SEKKI = [
+ ['立春', 'Risshun', 'Spring begins'], ['雨水', 'Usui', 'Snow turns to rain'], ['啓蟄', 'Keichitsu', 'Insects wake'],
+ ['春分', 'Shunbun', 'Spring equinox'], ['清明', 'Seimei', 'Clear and bright'], ['穀雨', 'Kokuu', 'Rain for the grain'],
+ ['立夏', 'Rikka', 'Summer begins'], ['小満', 'Shōman', 'Small ripening'], ['芒種', 'Bōshu', 'Seeds in the ear'],
+ ['夏至', 'Geshi', 'Summer solstice'], ['小暑', 'Shōsho', 'Small heat'], ['大暑', 'Taisho', 'Great heat'],
+ ['立秋', 'Risshū', 'Autumn begins'], ['処暑', 'Shosho', 'Heat withdraws'], ['白露', 'Hakuro', 'White dew'],
+ ['秋分', 'Shūbun', 'Autumn equinox'], ['寒露', 'Kanro', 'Cold dew'], ['霜降', 'Sōkō', 'Frost descends'],
+ ['立冬', 'Rittō', 'Winter begins'], ['小雪', 'Shōsetsu', 'Small snow'], ['大雪', 'Taisetsu', 'Great snow'],
+ ['冬至', 'Tōji', 'Winter solstice'], ['小寒', 'Shōkan', 'Small cold'], ['大寒', 'Daikan', 'Great cold'],
+];
+// Peak colour for a Saitama maple is Sōkō / Rittō, so autumn (f = 2) is pinned to Sōkō rather than the equinox.
+export function sekkiAt(s) {
+ const f = wrap(s);
+ // piecewise: spring/summer evenly, autumn stretched so f=2 → index 17 (Sōkō), winter compresses.
+ const keys = [[0, 3], [1, 9], [2, 17], [3, 21.5], [4, 27]];
+ let idx = 3;
+ for (let i = 0; i < keys.length - 1; i++) {
+ const [a, ia] = keys[i], [b, ib] = keys[i + 1];
+ if (f >= a && f <= b) { idx = ia + (ib - ia) * (f - a) / (b - a); break; }
+ }
+ return SEKKI[Math.floor(idx + 0.5) % 24];
+}
+export const SEASON_NAMES = [['春', 'Spring'], ['夏', 'Summer'], ['秋', 'Autumn'], ['冬', 'Winter']];
+export const seasonIndex = s => Math.floor(wrap(s + 0.5)) % 4;
+
+// ── What the tree is doing ──────────────────────────────────────────────────────
+export function treeState(s) {
+ const f = wrap(s);
+ // leaves on the tree: full until late autumn, gone in winter, budding back at the end of winter
+ const cover = f < 2.3 ? 1 : f < 2.9 ? 1 - smooth(2.3, 2.9, f) : f < 3.5 ? 0 : smooth(3.5, 3.97, f);
+ const autumn = f < 3.3 ? smooth(1.4, 2.0, f) : 1 - smooth(3.3, 3.5, f);
+ // fresh spring lime: strongest just after budding, fading into summer
+ const fresh = f > 3.4 ? smooth(3.4, 3.9, f) : 1 - smooth(0.15, 0.95, f);
+ const snow = f < 2.84 ? 0 : f < 3.35 ? smooth(2.84, 3.05, f) : 1 - smooth(3.35, 3.72, f);
+ const deep = smooth(0.4, 1.0, f) * (1 - smooth(1.2, 1.8, f)); // high-summer darkening
+ return { f, cover, autumn, fresh, snow, deep };
+}
+
+// ── What the world is doing ─────────────────────────────────────────────────────
+// Four keyframes (spring, summer, autumn, winter); cyclic, eased interpolation.
+const C = h => new THREE.Color(h);
+const KEYS = [
+ { // spring — pale blush paper, a fresh morning from the right
+ wall: C(0xf4ede6), floor: C(0xefe6dc), fog: C(0xf2ebe4), fogD: 0.018,
+ key: C(0xfff1e2), keyI: 3.1, az: 38, el: 46, soft: 5,
+ sky: C(0xfbf3ec), ground: C(0xcdbfae), hemiI: 1.05, glow: 0.07, accent: '#c9788a', ink: '#1d1a17',
+ },
+ { // summer — green-tinted haze, sun high and hard
+ wall: C(0xeeecdc), floor: C(0xe9e5d2), fog: C(0xebe9d8), fogD: 0.055,
+ key: C(0xfff5da), keyI: 3.7, az: 18, el: 64, soft: 2,
+ sky: C(0xf4f3e2), ground: C(0xb7b394), hemiI: 0.95, glow: 0.05, accent: '#4f7a3a', ink: '#1b1c16',
+ },
+ { // autumn — warm paper, low golden side light from the left
+ wall: C(0xf2e5d3), floor: C(0xecdcc6), fog: C(0xf0e2cf), fogD: 0.022,
+ key: C(0xffc58c), keyI: 3.6, az: -48, el: 21, soft: 3.5,
+ sky: C(0xf6e6d0), ground: C(0x8f6b4b), hemiI: 0.8, glow: 0.09, accent: '#d2553b', ink: '#1e1813',
+ },
+ { // winter — cool slate paper so the snow reads, diffuse cold light
+ wall: C(0xd3d7dc), floor: C(0xd8dce0), fog: C(0xd2d7dd), fogD: 0.045,
+ key: C(0xe2ebff), keyI: 1.7, az: -12, el: 52, soft: 16,
+ sky: C(0xeef2f8), ground: C(0x8f98a3), hemiI: 1.45, glow: 0.03, accent: '#4b5d7a', ink: '#171a1f',
+ },
+];
+const ease = t => t * t * (3 - 2 * t);
+const out = {
+ wall: new THREE.Color(), floor: new THREE.Color(), fog: new THREE.Color(), key: new THREE.Color(),
+ sky: new THREE.Color(), ground: new THREE.Color(), accent: new THREE.Color(), ink: new THREE.Color(),
+};
+const ca = new THREE.Color(), cb = new THREE.Color();
+export function worldState(s) {
+ const f = wrap(s);
+ const i = Math.floor(f) % 4, j = (i + 1) % 4;
+ const t = ease(f - Math.floor(f));
+ const a = KEYS[i], b = KEYS[j];
+ for (const k of ['wall', 'floor', 'fog', 'key', 'sky', 'ground']) out[k].copy(a[k]).lerp(b[k], t);
+ out.accent.copy(ca.set(a.accent)).lerp(cb.set(b.accent), t);
+ out.ink.copy(ca.set(a.ink)).lerp(cb.set(b.ink), t);
+ for (const k of ['fogD', 'keyI', 'el', 'soft', 'hemiI', 'glow']) out[k] = a[k] + (b[k] - a[k]) * t;
+ // azimuth goes the short way round
+ let d = b.az - a.az; out.az = a.az + d * t;
+ // particles
+ out.petals = clamp(1 - Math.abs(((f + 2) % 4) - 2) / 0.55); // around f = 0
+ out.motes = clamp(1 - Math.abs(f - 1) / 0.7) + clamp(1 - Math.abs(((f + 2) % 4) - 2) / 0.5) * 0.4;
+ out.snowfall = clamp(1 - Math.abs(f - 3.08) / 0.36);
+ out.leafRate = f > 1.7 && f < 2.95 ? 5.5 + 34 * smooth(2.2, 2.45, f) * (1 - smooth(2.55, 2.9, f)) : f > 0.6 && f < 1.4 ? 0.12 : 0;
+ return out;
+}
diff --git a/examples/koen/style.css b/examples/koen/style.css
new file mode 100644
index 0000000..cd96ae8
--- /dev/null
+++ b/examples/koen/style.css
@@ -0,0 +1,286 @@
+:root {
+ --paper: #f1ece2;
+ --paper-2: #e9e2d5;
+ --ink: #1d1a17;
+ --ink-2: #4b443c;
+ --muted: #7d7468;
+ --faint: rgba(29, 26, 23, .13);
+ --seal: #c8452f;
+ --accent: #d2553b;
+ --serif: 'Cormorant Garamond', 'Times New Roman', serif;
+ --jp: 'Noto Serif JP', 'Hiragino Mincho ProN', 'Yu Mincho', serif;
+ --gut: clamp(18px, 4.2vw, 64px);
+ --scene-rgb: 241, 236, 226;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--paper); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 18px/1.55 var(--serif); background: var(--paper); overflow-x: hidden; }
+a { color: inherit; }
+em { font-style: italic; }
+::selection { background: var(--accent); color: var(--paper); }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+
+/* ── seal / brand ───────────────────────────────────────── */
+.seal { display: inline-grid; grid-auto-flow: row; place-content: center; width: 34px; height: 38px; border-radius: 3px;
+ background: var(--seal); color: #f8efe4; font: 600 13px/1.02 var(--jp); text-align: center; filter: url(#brush-soft);
+ box-shadow: inset 0 0 0 2px rgba(248, 239, 228, .18); }
+.seal i { font-style: normal; display: block; }
+.seal-lg { width: 74px; height: 84px; font-size: 28px; border-radius: 5px; }
+
+/* ── loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--paper); display: grid; place-content: center; justify-items: center; gap: 26px; }
+.loader-enso { width: min(38vmin, 300px); aspect-ratio: 1; position: relative; }
+.loader-enso img { width: 100%; height: 100%; display: block; opacity: .92;
+ -webkit-mask-image: conic-gradient(from 212deg, #000 0deg, #000 calc(var(--p, 0) * 352deg), transparent calc(var(--p, 0) * 352deg + 10deg));
+ mask-image: conic-gradient(from 212deg, #000 0deg, #000 calc(var(--p, 0) * 352deg), transparent calc(var(--p, 0) * 352deg + 10deg)); }
+.loader-enso { display: grid; place-items: center; }
+.loader-enso img { position: absolute; inset: 0; }
+.loader-seal { position: relative; display: grid; gap: 4px; font: 400 21px/1 var(--jp); color: var(--ink); text-align: center; }
+.loader-line { font: 400 italic 19px/1 var(--serif); color: var(--muted); letter-spacing: .02em; }
+.loader-pct { font-variant-numeric: tabular-nums; display: inline-block; min-width: 2ch; font-style: normal; font-family: var(--jp); font-size: 12px; color: var(--ink-2); margin-left: 8px; }
+
+/* ── nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between;
+ padding: 22px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav { transition: transform .8s cubic-bezier(.2,.8,.2,1), opacity .6s; }
+.nav-hide .nav { transform: translateY(-110%); opacity: 0; }
+.brand { display: flex; align-items: center; gap: 14px; text-decoration: none; }
+.brand-name { display: grid; font: 500 24px/1 var(--serif); letter-spacing: .02em; }
+.brand-name small { font: 400 10px/1 var(--jp); letter-spacing: .28em; text-transform: uppercase; color: var(--muted); margin-top: 6px; }
+.links { display: flex; gap: clamp(20px, 3vw, 46px); }
+.links a { text-decoration: none; font: 400 12px/1 var(--jp); letter-spacing: .22em; text-transform: uppercase; color: var(--ink-2); position: relative; padding: 6px 0; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: currentColor; transform: scaleX(0); transform-origin: right; transition: transform .6s cubic-bezier(.2,.8,.2,1); }
+.links a:hover::after { transform: scaleX(1); transform-origin: left; }
+
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 12px; height: 48px; padding: 0 26px; border-radius: 1px;
+ text-decoration: none; font: 500 11.5px/1 var(--jp); letter-spacing: .22em; text-transform: uppercase; white-space: nowrap;
+ transition: background .5s, color .5s, box-shadow .5s; }
+.btn-ink { background: var(--ink); color: var(--paper); }
+.btn-ink:hover { background: var(--accent); }
+.btn-line { box-shadow: inset 0 0 0 1px rgba(29, 26, 23, .42); color: var(--ink); background: rgba(241, 236, 226, .35); backdrop-filter: blur(6px); }
+.btn-line:hover { box-shadow: inset 0 0 0 1px var(--ink); background: rgba(241, 236, 226, .8); }
+
+/* ── shared type ────────────────────────────────────────── */
+.kicker { font: 400 11px/1 var(--jp); letter-spacing: .3em; text-transform: uppercase; color: var(--ink-2); display: flex; align-items: center; gap: 14px; }
+.kicker::before { content: ''; width: 34px; height: 1px; background: var(--accent); transition: background 1s; }
+.kicker-jp { letter-spacing: .2em; color: var(--muted); }
+h2 { font: 300 clamp(40px, 4.6vw, 76px)/1.0 var(--serif); letter-spacing: -.018em; }
+h2 em, .hero-title em { color: var(--accent); transition: color 1.2s; }
+.s-num { font: 400 11px/1 var(--jp); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); display: flex; align-items: center; gap: 12px; }
+.s-num i { width: 22px; height: 1px; background: currentColor; opacity: .5; }
+
+/* ── hero ───────────────────────────────────────────────── */
+.hero { position: relative; height: 100vh; min-height: 640px; z-index: 2; pointer-events: none; }
+.hero-inner { position: absolute; left: var(--gut); bottom: 16vh; width: min(46vw, 700px); }
+.eyebrow { font: 400 11px/1 var(--jp); letter-spacing: .28em; text-transform: uppercase; color: var(--ink-2); display: flex; align-items: center; gap: 12px; margin-bottom: 30px; }
+.eyebrow i { width: 4px; height: 4px; border-radius: 50%; background: var(--accent); transition: background 1s; }
+.hero-title { font: 300 clamp(56px, 7.3vw, 126px)/.9 var(--serif); letter-spacing: -.035em; }
+.hero-title .ln { display: block; overflow: hidden; padding-bottom: .04em; }
+.hero-title .ln > span { display: inline-block; }
+.hero-title em { font-weight: 300; }
+.hero-sub { max-width: 30em; margin-top: 30px; font: 400 clamp(17px, 1.3vw, 20px)/1.5 var(--serif); color: var(--ink-2); }
+.hero-cta { display: flex; gap: 12px; margin-top: 34px; pointer-events: auto; }
+.hero-vert { position: absolute; right: calc(var(--gut) + 4px); top: 19vh; writing-mode: vertical-rl; font: 300 15px/1 var(--jp); letter-spacing: .55em; color: var(--ink-2); }
+.hint { position: fixed; left: var(--gut); bottom: 70px; z-index: 6; list-style: none; display: flex; gap: 18px; font: 400 10px/1 var(--jp); letter-spacing: .16em;
+ text-transform: uppercase; color: var(--muted); pointer-events: none; transition: opacity .8s; }
+.hint b { font-weight: 500; color: var(--ink); margin-right: 6px; }
+.hint li { display: flex; align-items: center; }
+.hint li + li::before { content: ''; width: 3px; height: 3px; border-radius: 50%; background: var(--faint); margin-right: 18px; }
+.is-scrolled .hint { opacity: 0 !important; }
+
+/* ── seasons (pinned) ───────────────────────────────────── */
+.seasons { position: relative; height: 520vh; z-index: 2; pointer-events: none; }
+.seasons-pin { position: sticky; top: 0; height: 100vh; overflow: hidden; }
+.seasons-pin::before { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, rgba(var(--scene-rgb),.55) 0%, rgba(var(--scene-rgb),.35) 28%, rgba(var(--scene-rgb),0) 46%); }
+.seasons .kicker { position: absolute; left: var(--gut); top: 16vh; }
+.rail { position: absolute; left: var(--gut); top: 50%; transform: translateY(-40%); list-style: none; display: grid; gap: 30px; }
+.rail li { display: grid; grid-template-columns: auto auto; align-items: start; gap: 10px; opacity: .22; transition: opacity .9s, transform .9s cubic-bezier(.2,.8,.2,1); position: relative; }
+.rail b { font: 400 40px/1 var(--jp); }
+.rail span, .rail em { writing-mode: vertical-rl; font: 400 10px/1 var(--jp); letter-spacing: .3em; color: var(--ink-2); font-style: normal; }
+.rail em { display: none; }
+.rail li.on { opacity: 1; transform: translateX(6px); }
+.rail li.on::before { content: ''; position: absolute; left: -16px; top: 13px; width: 6px; height: 6px; border-radius: 50%; background: var(--accent); }
+.season-copy { position: absolute; left: calc(var(--gut) + 110px); top: 50%; width: min(34vw, 470px); transform: translateY(-42%); }
+.season-copy article { position: absolute; left: 0; top: 0; width: 100%; opacity: 0; transform: translateY(26px); transition: opacity .9s ease, transform 1.2s cubic-bezier(.2,.8,.2,1); }
+.season-copy article.on { opacity: 1; transform: none; transition-delay: .15s; }
+.season-copy h2 { margin: 22px 0 22px; }
+.season-copy .s-num, .craft-steps .s-num { font-size: 11px; color: var(--muted); }
+.season-copy p { color: var(--ink-2); font-size: clamp(17px, 1.28vw, 20px); }
+.season-copy .s-note { margin-top: 24px; padding-top: 16px; border-top: 1px solid var(--faint); font-size: 16px; font-style: italic; color: var(--muted); }
+.season-copy .s-note b { font: 500 10px/1 var(--jp); letter-spacing: .24em; text-transform: uppercase; font-style: normal; color: var(--ink); display: block; margin-bottom: 8px; }
+.season-glyph { position: absolute; right: calc(var(--gut) - 1vw); top: 50%; transform: translateY(-50%); width: 30vh; height: 30vh; font: 300 30vh/1 var(--jp); color: var(--ink); }
+.season-glyph span { position: absolute; inset: 0; opacity: 0; transition: opacity 1.4s ease, transform 1.8s cubic-bezier(.2,.8,.2,1); transform: translateY(4vh); mix-blend-mode: multiply; }
+.season-glyph span.on { opacity: .075; transform: none; }
+.season-progress { position: absolute; left: var(--gut); bottom: 12vh; width: 150px; height: 1px; background: var(--faint); }
+.season-progress i { position: absolute; inset: 0; background: var(--ink); transform-origin: left; transform: scaleX(var(--sp, 0)); }
+
+/* ── brush divider ──────────────────────────────────────── */
+.brush-divider { position: relative; z-index: 3; width: min(40vw, 600px); height: 26px; pointer-events: none; }
+.bd-right { margin: 0 var(--gut) 0 auto; }
+.bd-left { margin: 0 auto 0 var(--gut); }
+.brush-divider svg { width: 100%; height: 100%; display: block; overflow: visible; }
+.brush-divider path { fill: var(--ink); opacity: .85; clip-path: inset(0 calc(100% - var(--draw, 0) * 100%) 0 0); }
+
+/* ── panels ─────────────────────────────────────────────── */
+.panel { position: relative; z-index: 3; padding: 20vh var(--gut); pointer-events: none; }
+.panel a, .panel .catalogue li { pointer-events: auto; }
+.panel h2 { margin: 26px 0 28px; }
+.lede { font-size: clamp(18px, 1.35vw, 21px); color: var(--ink-2); max-width: 32em; }
+.nursery { min-height: 170vh; }
+.nursery .panel-col { margin-left: auto; width: min(47vw, 700px); }
+.catalogue { list-style: none; margin: 56px 0 30px; border-top: 1px solid var(--faint); }
+.catalogue li { display: grid; grid-template-columns: 82px 1fr 84px 124px; align-items: baseline; gap: 16px; padding: 22px 6px 20px;
+ border-bottom: 1px solid var(--faint); transition: background .5s, padding .6s cubic-bezier(.2,.8,.2,1); cursor: default; }
+.catalogue li:hover { background: rgba(255, 252, 246, .55); padding-left: 16px; }
+.c-no { font: 400 10.5px/1 var(--jp); letter-spacing: .2em; color: var(--muted); }
+.c-name { font: 400 25px/1.1 var(--serif); }
+.c-name b { font: 400 17px/1 var(--jp); margin-right: 10px; }
+.c-name small, .c-age small { display: block; font: 400 italic 15px/1.3 var(--serif); color: var(--muted); margin-top: 6px; }
+.c-age { font: 400 18px/1 var(--serif); }
+.c-price { font: 400 19px/1 var(--serif); text-align: right; font-variant-numeric: tabular-nums; }
+.catalogue li:hover .c-price { color: var(--accent); }
+.c-ours .c-price { font-style: italic; color: var(--accent); }
+.fine { font-size: 16px; font-style: italic; color: var(--muted); max-width: 30em; margin-bottom: 34px; }
+.preview { position: fixed; left: 0; top: 0; z-index: 25; width: 214px; aspect-ratio: 3 / 4; pointer-events: none; opacity: 0; transform: translate3d(-999px, 0, 0);
+ transition: opacity .45s; padding: 9px 9px 30px; background: #f6f1e8; box-shadow: 0 1px 0 rgba(29,26,23,.06), 0 24px 50px -18px rgba(40,30,20,.35); }
+.preview img { width: 100%; height: 100%; object-fit: cover; display: block; mix-blend-mode: multiply; }
+.preview::after { content: 'Kōen · 紅園'; position: absolute; left: 12px; bottom: 9px; font: 400 9px/1 var(--jp); letter-spacing: .24em; color: var(--muted); }
+.preview.on { opacity: 1; }
+
+/* ── craft (pinned) ─────────────────────────────────────── */
+.craft { position: relative; height: 420vh; z-index: 2; pointer-events: none; }
+.craft-pin { position: sticky; top: 0; height: 100vh; overflow: hidden; }
+.craft-pin::before { content: ''; position: absolute; inset: 0; background: linear-gradient(90deg, rgba(var(--scene-rgb),.95) 0%, rgba(var(--scene-rgb),.92) 37%, rgba(var(--scene-rgb),.5) 44%, rgba(var(--scene-rgb),0) 51%); opacity: var(--scrim, 1); }
+.craft .kicker { position: absolute; left: var(--gut); top: 16vh; }
+.craft-pin > * { transition: opacity .9s ease; }
+.craft-pin:not(.is-on) > * { opacity: 0; }
+.craft-pin:not(.is-on)::before { opacity: 0; }
+.craft-pin::before { transition: opacity .9s ease; }
+.craft-title { position: absolute; left: var(--gut); top: calc(16vh + 34px); max-width: 9.5em; font-size: clamp(38px, 4vw, 66px); }
+.craft-steps { position: absolute; left: var(--gut); bottom: 17vh; width: min(34vw, 460px); height: 300px; }
+.craft-steps article { position: absolute; left: 0; bottom: 0; width: 100%; opacity: 0; transform: translateY(24px); transition: opacity .8s, transform 1.1s cubic-bezier(.2,.8,.2,1); }
+.craft-steps article.on { opacity: 1; transform: none; transition-delay: .12s; }
+.craft-steps h3 { font: 300 clamp(30px, 2.6vw, 42px)/1 var(--serif); margin: 18px 0 16px; display: flex; align-items: baseline; gap: 14px; }
+.craft-steps h3 b { font: 400 .72em/1 var(--jp); }
+.craft-steps h3 small { font: italic 400 .5em/1 var(--serif); color: var(--muted); }
+.craft-steps p { color: var(--ink-2); font-size: clamp(17px, 1.25vw, 19.5px); }
+.craft-index { position: absolute; right: var(--gut); top: 16vh; list-style: none; display: flex; gap: 22px; font: 400 13px/1 var(--jp); }
+.craft-index li { writing-mode: vertical-rl; letter-spacing: .3em; opacity: .25; transition: opacity .8s; }
+.craft-index li.on { opacity: 1; }
+
+.callout { position: fixed; inset: 0; z-index: 7; pointer-events: none; opacity: 0; transition: opacity .8s; }
+.callout.on { opacity: 1; }
+.callout svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.callout line { stroke: var(--ink); stroke-width: 1; }
+.callout circle { fill: none; stroke: var(--ink); stroke-width: 1; }
+.callout p { position: absolute; left: 0; top: 0; font: italic 400 16px/1.25 var(--serif); color: var(--ink); max-width: 15em; white-space: normal; padding: 10px 12px 11px; margin: -10px 0 0 -12px; background: rgba(var(--scene-rgb), .78); backdrop-filter: blur(6px); }
+.callout p b { display: block; font: 500 9.5px/1 var(--jp); letter-spacing: .24em; text-transform: uppercase; font-style: normal; color: var(--muted); margin-bottom: 7px; }
+
+/* ── visit ──────────────────────────────────────────────── */
+.visit { min-height: 125vh; display: grid; align-content: center; }
+.visit .panel-col { width: min(46vw, 680px); }
+.visit h2 { max-width: 10em; }
+.facts { display: grid; grid-template-columns: 1fr 1fr; gap: 34px 42px; margin: 54px 0 46px; }
+.facts div { border-top: 1px solid var(--faint); padding-top: 16px; }
+.facts dt { font: 500 10px/1 var(--jp); letter-spacing: .26em; text-transform: uppercase; color: var(--muted); margin-bottom: 12px; }
+.facts dd { font-size: 19px; line-height: 1.4; }
+.visit-cta { display: flex; gap: 12px; flex-wrap: wrap; }
+
+/* ── footer ─────────────────────────────────────────────── */
+.foot { position: relative; z-index: 5; background: var(--paper); padding: 16vh var(--gut) 90px; }
+.foot::before { content: ''; position: absolute; left: 0; right: 0; top: -120px; height: 120px; background: linear-gradient(rgba(var(--scene-rgb),0), var(--paper)); pointer-events: none; }
+.foot-inner { display: grid; grid-template-columns: 1.1fr 1.6fr; gap: 60px; align-items: start; }
+.foot-mark { display: flex; gap: 28px; align-items: flex-start; }
+.foot-line { font: 300 clamp(28px, 2.6vw, 42px)/1.12 var(--serif); }
+.foot-line em { color: var(--muted); font-size: .62em; line-height: 1.5; display: inline-block; margin-top: 10px; }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr); gap: 36px; }
+.foot-cols h4 { font: 500 10px/1 var(--jp); letter-spacing: .26em; text-transform: uppercase; color: var(--muted); margin-bottom: 18px; }
+.foot-cols a { display: block; text-decoration: none; font-size: 19px; line-height: 1.8; }
+.foot-cols a:hover { color: var(--accent); }
+.foot-cols p { color: var(--ink-2); font-size: 17px; margin-bottom: 10px; }
+.foot-base { display: flex; justify-content: space-between; gap: 20px; margin-top: 12vh; padding-top: 22px; border-top: 1px solid var(--faint);
+ font: 400 10.5px/1.6 var(--jp); letter-spacing: .12em; color: var(--muted); padding-left: 150px; }
+
+/* ── dial ───────────────────────────────────────────────── */
+.dial-wrap { position: fixed; right: calc(var(--gut) - 14px); bottom: 20px; z-index: 20; display: flex; flex-direction: column; align-items: flex-end; gap: 14px; transition: opacity .6s, transform .8s cubic-bezier(.2,.8,.2,1); }
+.dial { width: 148px; height: 148px; position: relative; cursor: grab; touch-action: none; outline: none; border-radius: 50%; }
+.dial:focus-visible { box-shadow: 0 0 0 1px var(--ink); }
+.dial.is-drag { cursor: grabbing; }
+.dial svg { width: 100%; height: 100%; overflow: visible; display: block; }
+.dial .ring { fill: rgba(var(--scene-rgb), .82); stroke: rgba(29, 26, 23, .26); stroke-width: 1.4; }
+.dial .arc { fill: none; stroke: var(--accent); stroke-width: 3.2; stroke-linecap: round; transition: stroke 1s; }
+.dial .ticks line { stroke: rgba(29, 26, 23, .32); stroke-width: 1; }
+.dial .ticks line.maj { stroke: var(--ink); stroke-width: 1.3; }
+.dial .labels text { font: 400 11px var(--jp); text-anchor: middle; fill: rgba(29, 26, 23, .42); transition: fill .6s; }
+.dial .labels text.on { fill: var(--ink); font-weight: 600; }
+.dial .bead-halo { fill: var(--accent); opacity: .16; transition: fill 1s; }
+.dial .bead-dot { fill: var(--ink); }
+.dial:hover .bead-halo, .dial.is-drag .bead-halo { opacity: .3; }
+.dial:not(.was-used) .bead-halo { animation: bead 2.4s ease-in-out infinite; transform-box: fill-box; transform-origin: center; }
+@keyframes bead { 0%, 100% { transform: scale(1); opacity: .16; } 50% { transform: scale(1.7); opacity: .34; } }
+.dial-core { position: absolute; inset: 0; display: grid; place-items: center; pointer-events: none; }
+.dial-kanji { font: 400 34px/1 var(--jp); }
+.dial-caption { order: -1; display: grid; justify-items: end; text-align: right; gap: 6px; min-width: 190px; margin-right: 8px; }
+.dial-caption b { font: 500 19px/1 var(--jp); letter-spacing: .12em; }
+.dial-caption span { font: italic 400 16px/1.1 var(--serif); color: var(--ink-2); }
+.dial-caption em { font: 400 9.5px/1.3 var(--jp); font-style: normal; letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.dial-hint { position: absolute; }
+.in-foot .dial-wrap, .dial-off .dial-wrap { opacity: 0 !important; transform: translateY(20px); pointer-events: none; }
+
+/* ── mobile ─────────────────────────────────────────────── */
+@media (max-width: 900px) {
+ body { font-size: 17px; }
+ .links { display: none; }
+ .nav { padding: 16px var(--gut); }
+ .nav .btn { height: 38px; padding: 0 14px; font-size: 10px; letter-spacing: .16em; }
+ .brand-name small { display: none; }
+ .hero-inner { top: 92px; bottom: auto; width: auto; right: var(--gut); }
+ .hero-title { font-size: clamp(42px, 12vw, 64px); }
+ .hero-sub { font-size: 16px; margin-top: 16px; max-width: 24em; }
+ .hero-cta { margin-top: 20px; }
+ .hero-cta .btn { height: 42px; padding: 0 16px; }
+ .eyebrow { font-size: 9px; letter-spacing: .18em; margin-bottom: 18px; }
+ .hero-vert { display: none; }
+ .hint { display: none; }
+ .seasons .kicker, .craft .kicker { top: 84px; }
+ .rail { top: 118px; transform: none; grid-auto-flow: column; gap: 18px; }
+ .rail b { font-size: 24px; }
+ .rail li.on::before { left: 3px; top: -12px; }
+ .season-copy { left: var(--gut); right: var(--gut); width: auto; top: auto; bottom: 186px; transform: none; }
+ .season-copy article { top: auto; bottom: 0; padding: 18px 18px 20px; background: rgba(241, 236, 226, .78); backdrop-filter: blur(8px); }
+ .season-copy h2 { font-size: 34px; margin: 12px 0; }
+ .season-copy p { font-size: 15.5px; }
+ .season-copy .s-note { display: none; }
+ .season-progress { display: none; }
+ .season-glyph { display: none; }
+ .panel { padding: 12vh var(--gut); }
+ .nursery { padding-top: 58vh; }
+ .nursery .panel-col, .visit .panel-col { width: auto; padding: 22px 18px; background: rgba(241, 236, 226, .82); backdrop-filter: blur(10px); }
+ .catalogue li { grid-template-columns: 1fr auto; gap: 8px 12px; }
+ .c-no { grid-column: 1 / -1; }
+ .c-age { grid-column: 1; font-size: 15px; }
+ .c-age small { display: inline; margin-left: 8px; }
+ .c-price { grid-column: 2; grid-row: 2 / 4; align-self: center; }
+ .c-name { font-size: 22px; }
+ .craft-title { font-size: 32px; top: 110px; }
+ .craft-steps { left: var(--gut); right: var(--gut); width: auto; bottom: 186px; height: auto; }
+ .craft-steps article { padding: 16px 18px 18px; background: rgba(241, 236, 226, .8); backdrop-filter: blur(8px); }
+ .craft-steps p { font-size: 15.5px; }
+ .craft-index { display: none; }
+ .craft-pin::before { background: linear-gradient(180deg, rgba(var(--scene-rgb),.92) 0%, rgba(var(--scene-rgb),.78) 20%, rgba(var(--scene-rgb),0) 30%); }
+ .seasons-pin::before { background: linear-gradient(180deg, rgba(var(--scene-rgb),.85) 0%, rgba(var(--scene-rgb),.6) 17%, rgba(var(--scene-rgb),0) 26%); }
+ .callout { display: none; }
+ .visit { padding-top: 60vh; }
+ .facts { grid-template-columns: 1fr; gap: 20px; }
+ .foot-inner, .foot-cols { grid-template-columns: 1fr; }
+ .foot-base { flex-direction: column; padding-left: 0; padding-bottom: 50px; }
+ .dial-wrap { right: 10px; bottom: 12px; gap: 8px; }
+ .dial { width: 112px; height: 112px; }
+ .dial-kanji { font-size: 26px; }
+ .dial-caption { display: none; }
+ .dial-caption b { font-size: 15px; }
+ .dial-caption span { font-size: 13.5px; }
+ .dial-caption em { display: none; }
+ .callout p { font-size: 13px; }
+}
diff --git a/examples/koen/tree.js b/examples/koen/tree.js
new file mode 100644
index 0000000..05cc931
--- /dev/null
+++ b/examples/koen/tree.js
@@ -0,0 +1,545 @@
+// The maple: seasonal material (foliage-only hue remap, noise dissolve, snow on top faces, breeze),
+// mesh analysis (where the leaves, trunk and moss are) and procedural winter twigs grown into the canopy.
+import { THREE, clamp, lerp } from '../../src/core/engine.js';
+import { MeshSurfaceSampler } from 'three/examples/jsm/math/MeshSurfaceSampler.js';
+
+export const NOISE = /* glsl */`
+float kh13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+float kvn(vec3 p){ vec3 i = floor(p), f = fract(p); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(kh13(i), kh13(i + vec3(1,0,0)), f.x), mix(kh13(i + vec3(0,1,0)), kh13(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(kh13(i + vec3(0,0,1)), kh13(i + vec3(1,0,1)), f.x), mix(kh13(i + vec3(0,1,1)), kh13(i + vec3(1,1,1)), f.x), f.y), f.z); }
+vec3 krgb2hsv(vec3 c){ vec4 K = vec4(0., -1./3., 2./3., -1.); vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
+ vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y);
+ return vec3(abs(q.z + (q.w - q.y) / (6. * d + 1e-10)), d / (q.x + 1e-10), q.x); }
+vec3 khsv2rgb(vec3 c){ vec3 p = abs(fract(c.xxx + vec3(0., 2./3., 1./3.)) * 6. - 3.); return c.z * mix(vec3(1.), clamp(p - 1., 0., 1.), c.y); }
+`;
+
+// Shared seasonal uniforms (one object, referenced by every patched material).
+export const U = {
+ uTime: { value: 0 }, uBreeze: { value: 0.2 }, uWind: { value: new THREE.Vector3(-1, 0, 0.3).normalize() },
+ uShake: { value: 0 }, uShakeDir: { value: new THREE.Vector3(1, 0, 0) },
+ uSwayY0: { value: 0.4 }, uSwayY1: { value: 1.8 }, uInvModel: { value: new THREE.Matrix3() },
+ uFolY0: { value: 0.5 }, uFolY1: { value: 0.6 },
+ uCover: { value: 1 }, uAutumn: { value: 0 }, uFresh: { value: 0 }, uDeep: { value: 0 }, uSnow: { value: 0 }, uGlow: { value: 0.1 },
+ uSnowCol: { value: new THREE.Color(0.9, 0.92, 0.96) }, uDbg: { value: 0 },
+ uWarm: { value: new THREE.Color(1, 1, 1) },
+ uTrunk: { value: Array.from({ length: 24 }, () => new THREE.Vector3(0, -10, 0)) }, uTrunkN: { value: 0 }, uTrunkR: { value: new THREE.Vector4(0.1, 0.045, 0, 1) },
+};
+
+const SWAY_HEAD = /* glsl */`
+uniform float uTime, uBreeze, uShake, uSwayY0, uSwayY1; uniform vec3 uWind, uShakeDir; uniform mat3 uInvModel;
+attribute float aFol;
+varying vec3 vWPos; varying vec3 vWNrm;
+vec3 kSway(vec3 wp){
+ float hh = clamp((wp.y - uSwayY0) / (uSwayY1 - uSwayY0), 0., 1.);
+ float bend = hh * hh;
+ float ph = dot(wp, vec3(2.1, 1.3, 1.7));
+ vec3 sway = uWind * (sin(uTime * 1.1 + ph * 0.5) * 0.6 + sin(uTime * 2.3 + ph * 1.3) * 0.4) * bend * (0.004 + 0.026 * uBreeze);
+ vec3 flut = vec3(sin(uTime * 9.0 + ph * 23.), sin(uTime * 11.0 + ph * 17.) * 0.6, cos(uTime * 8.0 + ph * 19.)) * aFol * hh * (0.0008 + 0.0042 * uBreeze + 0.01 * abs(uShake));
+ vec3 shake = uShakeDir * uShake * bend * (0.55 + 0.45 * aFol) * 0.085;
+ return sway + flut + shake;
+}`;
+const SWAY_BODY = /* glsl */`
+ vec3 kwp = (modelMatrix * vec4(transformed, 1.)).xyz;
+ transformed += uInvModel * kSway(kwp);
+ vWPos = (modelMatrix * vec4(transformed, 1.)).xyz;
+`;
+
+const FOL_HEAD = /* glsl */`
+uniform float uFolY0, uFolY1, uCover, uAutumn, uFresh, uDeep, uSnow, uGlow, uDbg; uniform vec3 uSnowCol;
+varying vec3 vWPos; varying vec3 vWNrm;
+${NOISE}
+uniform vec3 uTrunk[24]; uniform int uTrunkN; uniform vec4 uTrunkR; uniform vec3 uWarm;
+// distance to the trunk centreline, so moss on the bark never counts as foliage
+float kTrunkGuard(vec3 p){
+ float d = 1e3;
+ for (int i = 0; i < 23; i++) { if (i >= uTrunkN - 1) break; vec3 a = uTrunk[i], b = uTrunk[i + 1]; vec3 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0., 1.); d = min(d, length(pa - ba * h)); }
+ float r = mix(uTrunkR.x, uTrunkR.y, clamp((p.y - uTrunkR.z) / (uTrunkR.w - uTrunkR.z), 0., 1.));
+ return smoothstep(r, r * 1.35, d);
+}
+float kFoliage(vec3 lin, float wy){
+ vec3 c = pow(max(lin, vec3(0.)), vec3(1. / 2.2));
+ vec3 h = krgb2hsv(c);
+ float hue = smoothstep(0.13, 0.18, h.x) * (1. - smoothstep(0.47, 0.53, h.x));
+ float sat = smoothstep(0.17, 0.33, h.y);
+ float val = smoothstep(0.04, 0.10, h.z);
+ return hue * sat * val * smoothstep(uFolY0, uFolY1, wy);
+}
+// looser test for the leaf geometry itself (dark, shadowed, desaturated leaves) once the tree is bare
+float kLeafGeo(vec3 lin, float wy){
+ vec3 h = krgb2hsv(pow(max(lin, vec3(0.)), vec3(1. / 2.2)));
+ float hue = smoothstep(0.12, 0.16, h.x) * (1. - smoothstep(0.5, 0.56, h.x));
+ return hue * smoothstep(0.04, 0.1, h.y) * smoothstep(uFolY0, uFolY1, wy);
+}
+float kDrop(vec3 p){ return clamp((kvn(p * 13.) * 0.6 + kvn(p * 41. + 3.1) * 0.4 - 0.5) * 2.3 + 0.5, 0., 1.); }
+`;
+
+function patchVertex(shader, { normals = true } = {}) {
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', `#include <common>\n${SWAY_HEAD}`)
+ .replace('#include <begin_vertex>', `#include <begin_vertex>\n${SWAY_BODY}\n${normals ? 'vWNrm = normalize(mat3(modelMatrix) * objectNormal);' : 'vWNrm = vec3(0., 1., 0.);'}`);
+}
+
+/** Patch the maple's own material (foliage recolour, dissolve, snow, glow). */
+export function patchTreeMaterial(mat) {
+ mat.side = THREE.DoubleSide;
+ mat.onBeforeCompile = shader => {
+ Object.assign(shader.uniforms, U);
+ patchVertex(shader);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>\n${FOL_HEAD}`)
+ .replace('#include <map_fragment>', /* glsl */`#include <map_fragment>
+ vec3 kBase = diffuseColor.rgb;
+ float kRaw = kFoliage(kBase, vWPos.y);
+ float kFol = kRaw * kTrunkGuard(vWPos);
+ float kSnowA = 0.;
+ if (kFol > 0.01) {
+ vec3 cs = pow(max(kBase, vec3(0.)), vec3(1. / 2.2));
+ vec3 hsv = krgb2hsv(cs);
+ // Art-directed palettes; the texture only contributes its light and shade (v) and a little hue drift.
+ float v = smoothstep(0.22, 0.92, hsv.z);
+ float dev = clamp(hsv.x - 0.25, -0.06, 0.06);
+ float n1 = kvn(vWPos * 5.5), n2 = kvn(vWPos * 19. + 11.), n3 = kvn(vWPos * 47. + 5.);
+ vec3 late = mix(vec3(0.24, 0.36, 0.13), vec3(0.52, 0.64, 0.3), v);
+ vec3 spring = mix(vec3(0.45, 0.6, 0.19), vec3(0.76, 0.86, 0.42), v) + vec3(dev * 0.5, 0., 0.);
+ vec3 summer = mix(vec3(0.1, 0.2, 0.07), vec3(0.3, 0.46, 0.17), v) * (0.92 + n2 * 0.16);
+ vec3 green = mix(late, spring, uFresh);
+ green = mix(green, summer, uDeep);
+ // autumn: each region turns at its own moment, crowns and outer tips first
+ float turnAt = clamp(n1 * 0.7 + n2 * 0.3 - (vWPos.y - uFolY1) * 0.18, 0., 1.);
+ float turned = smoothstep(turnAt - 0.18, turnAt + 0.18, uAutumn * 1.4 - 0.2);
+ float red = clamp(0.8 + (n1 - 0.5) * 1.6 + (vWPos.y - uFolY1) * 0.22 + (n3 - 0.5) * 0.35, 0., 1.);
+ vec3 wine = vec3(0.42, 0.07, 0.07), crimson = vec3(0.66, 0.12, 0.09), scarlet = vec3(0.79, 0.19, 0.11), orange = vec3(0.88, 0.45, 0.16), amber = vec3(0.9, 0.66, 0.24);
+ vec3 aut = mix(orange, scarlet, smoothstep(0.15, 0.5, red));
+ aut = mix(aut, crimson, smoothstep(0.5, 0.88, red));
+ aut = mix(aut, amber, smoothstep(0.72, 0.92, n3) * 0.6 * (1. - red));
+ aut = mix(wine, aut, smoothstep(0.0, 0.55, v)) * mix(0.72, 1.08, v);
+ vec3 yel = mix(vec3(0.62, 0.52, 0.14), vec3(0.93, 0.78, 0.3), v);
+ float mid = smoothstep(0.0, 0.5, turned) * (1. - smoothstep(0.5, 1.0, turned));
+ vec3 leaf = mix(green, aut, turned);
+ leaf = mix(leaf, yel, mid * 0.5);
+ // drying before the drop
+ float dn = kDrop(vWPos);
+ float dry = smoothstep(uCover - 0.16, uCover + 0.02, dn) * (1. - uCover * 0.9) * uAutumn;
+ leaf = mix(leaf, vec3(0.4, 0.2, 0.09) * (0.6 + v * 0.6), dry * 0.8);
+ diffuseColor.rgb = mix(kBase, pow(leaf, vec3(2.2)), kFol);
+ if (uDbg > 0.5) diffuseColor.rgb = mix(kBase, vec3(1., 0., 1.), kFol);
+ if (kFol > mix(0.08, 0.42, uCover) && (dn > uCover || uCover < 0.01)) discard;
+ }
+ diffuseColor.rgb *= mix(uWarm, vec3(1.), kFol);
+ // leaf texels protected on the trunk: in the bare months they read as dull winter moss, not stray leaves
+ { float lum = dot(kBase, vec3(0.3, 0.55, 0.15)); diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.09, 0.075, 0.05) + lum * vec3(0.35, 0.28, 0.18), clamp(kRaw - kFol, 0., 1.) * clamp(1. - uCover * 1.6, 0., 1.) * 0.85); }
+ // bare tree: everything in the canopy zone except the trunk gives way to the grown branch structure
+ if (uCover < 0.35) { float lg = kTrunkGuard(vWPos) * smoothstep(uFolY0, uFolY1, vWPos.y); if (lg > 0.5 && (kDrop(vWPos) > uCover * 2.8 || uCover < 0.01)) discard; }
+ {
+ vec3 wn = normalize(vWNrm);
+ float up = wn.y * (gl_FrontFacing ? 1. : -1.);
+ float sn = smoothstep(0.45, 0.85, up + (kvn(vWPos * 17.) - 0.5) * 0.45 + (kvn(vWPos * 61.) - 0.5) * 0.2);
+ kSnowA = sn * uSnow * smoothstep(0.02, 0.12, vWPos.y);
+ diffuseColor.rgb = mix(diffuseColor.rgb, uSnowCol, kSnowA);
+ }`)
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(roughnessFactor, max(roughnessFactor, 0.74), kFol);\nroughnessFactor = mix(roughnessFactor, 0.62, kSnowA);')
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\ntotalEmissiveRadiance += diffuseColor.rgb * kFol * uGlow * (1. - kSnowA);');
+ };
+ mat.customProgramCacheKey = () => 'koen-tree';
+ mat.needsUpdate = true;
+ return mat;
+}
+
+/** Shadow-casting depth material that drops the same leaves the colour pass drops. */
+export function treeDepthMaterial(map) {
+ const m = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map, side: THREE.DoubleSide });
+ m.onBeforeCompile = shader => {
+ Object.assign(shader.uniforms, U);
+ patchVertex(shader, { normals: false });
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>\n${FOL_HEAD}`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ { float g = kTrunkGuard(vWPos); float f = kFoliage(diffuseColor.rgb, vWPos.y) * g; bool gone = kDrop(vWPos) > uCover || uCover < 0.01;
+ if (f > mix(0.08, 0.42, uCover) && gone) discard;
+ if (uCover < 0.35 && g * smoothstep(uFolY0, uFolY1, vWPos.y) > 0.5 && (kDrop(vWPos) > uCover * 2.8 || uCover < 0.01)) discard; }
+ diffuseColor = vec4(1.);`);
+ };
+ m.customProgramCacheKey = () => 'koen-tree-depth';
+ return m;
+}
+
+/** Bark material for procedural twigs and wire: sway + snow. */
+export function patchBarkMaterial(mat, key = 'koen-bark', { snow = 1 } = {}) {
+ mat.onBeforeCompile = shader => {
+ Object.assign(shader.uniforms, U);
+ patchVertex(shader);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', `#include <common>\nuniform float uSnow; uniform vec3 uSnowCol; varying vec3 vWPos; varying vec3 vWNrm;\n${NOISE}`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ float kSnowA = smoothstep(0.5, 0.88, normalize(vWNrm).y + (kvn(vWPos * 23.) - 0.5) * 0.35) * uSnow * ${snow.toFixed(2)};
+ diffuseColor.rgb = mix(diffuseColor.rgb, uSnowCol, kSnowA);`)
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(roughnessFactor, 0.62, kSnowA);');
+ };
+ mat.customProgramCacheKey = () => key;
+ mat.needsUpdate = true;
+ return mat;
+}
+export function barkDepthMaterial() {
+ const m = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });
+ m.onBeforeCompile = shader => { Object.assign(shader.uniforms, U); patchVertex(shader, { normals: false }); };
+ m.customProgramCacheKey = () => 'koen-bark-depth';
+ return m;
+}
+
+// ─── Analysis ──────────────────────────────────────────────────────────────────
+function readPixels(map) {
+ const img = map.image;
+ const w = Math.min(img.width, 1024), h = Math.min(img.height, 1024);
+ const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
+ const cx = cv.getContext('2d', { willReadFrequently: true });
+ cx.drawImage(img, 0, 0, w, h);
+ return { data: cx.getImageData(0, 0, w, h).data, w, h, flipY: map.flipY };
+}
+function texel(px, u, v) {
+ u = ((u % 1) + 1) % 1; v = ((v % 1) + 1) % 1;
+ const x = Math.floor(u * (px.w - 1)), y = Math.floor((px.flipY ? 1 - v : v) * (px.h - 1));
+ const k = (y * px.w + x) * 4;
+ return [px.data[k] / 255, px.data[k + 1] / 255, px.data[k + 2] / 255];
+}
+function hsv([r, g, b]) {
+ const mx = Math.max(r, g, b), mn = Math.min(r, g, b), d = mx - mn;
+ let h = 0;
+ if (d > 1e-6) {
+ if (mx === r) h = ((g - b) / d) % 6; else if (mx === g) h = (b - r) / d + 2; else h = (r - g) / d + 4;
+ h /= 6; if (h < 0) h += 1;
+ }
+ return [h, mx > 0 ? d / mx : 0, mx];
+}
+const greenScore = c => {
+ const [h, s, v] = hsv(c);
+ const sm = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
+ return sm(0.13, 0.18, h) * (1 - sm(0.47, 0.53, h)) * sm(0.17, 0.33, s) * sm(0.04, 0.1, v);
+};
+
+// Seeded random so the twigs grow the same way on every load.
+function rng(seed = 7) { let s = seed >>> 0; return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 4294967296); }
+
+/**
+ * Work out the anatomy of the tree from its surface: pot top, foliage pads, trunk line, ground height field.
+ * Everything is in world space (call after the model is placed).
+ */
+export function analyze(mesh) {
+ // MeshSurfaceSampler draws from Math.random: seed it so pads, branches and the wired branch are identical on every load.
+ const mr = Math.random; Math.random = rng(1846);
+ try { return analyzeInner(mesh); } finally { Math.random = mr; }
+}
+function analyzeInner(mesh) {
+ mesh.updateMatrixWorld(true);
+ const px = readPixels(mesh.material.map);
+ const box = new THREE.Box3().setFromObject(mesh);
+ const H = box.max.y - box.min.y, y0 = box.min.y;
+ const cx = (box.min.x + box.max.x) / 2, cz = (box.min.z + box.max.z) / 2;
+
+ // Per-vertex foliage attribute for the breeze.
+ const geo = mesh.geometry;
+ const uv = geo.attributes.uv, pos = geo.attributes.position;
+ const fol = new Float32Array(pos.count);
+ for (let i = 0; i < pos.count; i++) fol[i] = greenScore(texel(px, uv.getX(i), uv.getY(i)));
+
+ // Surface samples.
+ const N = 42000;
+ const sampler = new MeshSurfaceSampler(mesh).build();
+ const P = new Float32Array(N * 3), NR = new Float32Array(N * 3), G = new Float32Array(N);
+ const p = new THREE.Vector3(), n = new THREE.Vector3(), c = new THREE.Color(), u2 = new THREE.Vector2();
+ const nm = new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld);
+ for (let i = 0; i < N; i++) {
+ sampler.sample(p, n, c, u2);
+ p.applyMatrix4(mesh.matrixWorld); n.applyMatrix3(nm).normalize();
+ P.set([p.x, p.y, p.z], i * 3); NR.set([n.x, n.y, n.z], i * 3);
+ G[i] = greenScore(texel(px, u2.x, u2.y));
+ }
+
+ // Radial profile to find the pot rim: wide at the bottom (pot), narrow above it (trunk), wide again (canopy).
+ const BINS = 60;
+ const rad = Array.from({ length: BINS }, () => []);
+ for (let i = 0; i < N; i++) {
+ const t = (P[i * 3 + 1] - y0) / H;
+ if (t >= 0.6) continue;
+ const b = Math.floor(t / 0.6 * BINS);
+ rad[b].push(Math.hypot(P[i * 3] - cx, P[i * 3 + 2] - cz));
+ }
+ const pct = (arr, q) => { if (!arr.length) return 0; const s = [...arr].sort((a, b) => a - b); return s[Math.floor((s.length - 1) * q)]; };
+ const r95 = rad.map(a => pct(a, 0.95));
+ const potR = Math.max(...r95.slice(0, Math.floor(BINS * 0.3)));
+ let potTopBin = 0;
+ for (let b = 0; b < BINS * 0.5; b++) { if (r95[b] > potR * 0.6) potTopBin = b; else if (b > 2) break; }
+ const potTop = y0 + (potTopBin + 1) / BINS * 0.6 * H;
+
+ // Foliage points above the rim.
+ const leafIdx = [];
+ for (let i = 0; i < N; i++) if (G[i] > 0.5 && P[i * 3 + 1] > potTop + 0.05 * H) leafIdx.push(i);
+ let folMin = Infinity;
+ const ys = leafIdx.map(i => P[i * 3 + 1]).sort((a, b) => a - b);
+ folMin = ys.length ? ys[Math.floor(ys.length * 0.01)] : potTop + 0.15 * H;
+ const folY0 = Math.max(potTop + 0.03 * H, Math.min(folMin - 0.03 * H, potTop + 0.12 * H));
+ const folY1 = folY0 + 0.04 * H;
+
+ // Ground height field across the pot (moss, roots, rim) for leaves to land on.
+ const GR = 44;
+ const gMinX = cx - potR * 1.05, gMinZ = cz - potR * 1.05, gSize = potR * 2.1;
+ const ground = new Float32Array(GR * GR).fill(-1);
+ for (let i = 0; i < N; i++) {
+ const y = P[i * 3 + 1];
+ if (y > potTop + 0.06 * H) continue;
+ const gx = Math.floor((P[i * 3] - gMinX) / gSize * GR), gz = Math.floor((P[i * 3 + 2] - gMinZ) / gSize * GR);
+ if (gx < 0 || gz < 0 || gx >= GR || gz >= GR) continue;
+ const k = gz * GR + gx;
+ if (y > ground[k]) ground[k] = y;
+ }
+ // Cells with few samples: fill from neighbours but only inside the rim footprint.
+ for (let pass = 0; pass < 2; pass++) for (let z = 1; z < GR - 1; z++) for (let x = 1; x < GR - 1; x++) {
+ const k = z * GR + x; if (ground[k] >= 0) continue;
+ let s = 0, m = 0; for (const d of [-1, 1, -GR, GR]) if (ground[k + d] >= 0) { s += ground[k + d]; m++; }
+ if (m >= 3) ground[k] = s / m;
+ }
+ const groundAt = (x, z) => {
+ const gx = Math.floor((x - gMinX) / gSize * GR), gz = Math.floor((z - gMinZ) / gSize * GR);
+ if (gx < 0 || gz < 0 || gx >= GR || gz >= GR) return -1;
+ return ground[gz * GR + gx];
+ };
+
+ // Foliage pads: k-means on leaf points (height weighted so tiers separate).
+ const rand = rng(11);
+ const K = 7, WY = 1.6;
+ const pts = leafIdx.map(i => [P[i * 3], P[i * 3 + 1], P[i * 3 + 2]]);
+ const cents = [pts[Math.floor(rand() * pts.length)].slice()];
+ while (cents.length < K) {
+ let best = null, bd = -1;
+ for (let j = 0; j < pts.length; j += 7) {
+ const q = pts[j];
+ let d = Infinity;
+ for (const c0 of cents) d = Math.min(d, (q[0] - c0[0]) ** 2 + ((q[1] - c0[1]) * WY) ** 2 + (q[2] - c0[2]) ** 2);
+ if (d > bd) { bd = d; best = q; }
+ }
+ cents.push(best.slice());
+ }
+ const assign = new Int32Array(pts.length);
+ for (let it = 0; it < 14; it++) {
+ const acc = cents.map(() => [0, 0, 0, 0]);
+ for (let j = 0; j < pts.length; j++) {
+ const q = pts[j]; let bi = 0, bd = Infinity;
+ for (let k = 0; k < K; k++) { const c0 = cents[k]; const d = (q[0] - c0[0]) ** 2 + ((q[1] - c0[1]) * WY) ** 2 + (q[2] - c0[2]) ** 2; if (d < bd) { bd = d; bi = k; } }
+ assign[j] = bi; const a = acc[bi]; a[0] += q[0]; a[1] += q[1]; a[2] += q[2]; a[3]++;
+ }
+ for (let k = 0; k < K; k++) if (acc[k][3]) cents[k] = [acc[k][0] / acc[k][3], acc[k][1] / acc[k][3], acc[k][2] / acc[k][3]];
+ }
+ const pads = cents.map((c0, k) => {
+ const mem = []; for (let j = 0; j < pts.length; j++) if (assign[j] === k) mem.push(pts[j]);
+ let sx = 0, sy = 0, sz = 0;
+ for (const q of mem) { sx += (q[0] - c0[0]) ** 2; sy += (q[1] - c0[1]) ** 2; sz += (q[2] - c0[2]) ** 2; }
+ const m = Math.max(1, mem.length);
+ const std = new THREE.Vector3(Math.sqrt(sx / m), Math.sqrt(sy / m), Math.sqrt(sz / m));
+ return { center: new THREE.Vector3(...c0), std, members: mem, radius: Math.max(std.x, std.y, std.z) * 1.9 };
+ }).filter(pd => pd.members.length > 40);
+
+ // Trunk line: track bark (non-green) points upward from the rim.
+ const bark = [];
+ for (let i = 0; i < N; i++) if (G[i] < 0.15 && P[i * 3 + 1] > potTop) bark.push([P[i * 3], P[i * 3 + 1], P[i * 3 + 2]]);
+ const trunk = [];
+ let tc = [cx, cz], rr = 0.14 * H;
+ const step = 0.035 * H;
+ for (let y = potTop + 0.02 * H; y < box.max.y - 0.1 * H; y += step) {
+ const near = bark.filter(q => q[1] >= y && q[1] < y + step && Math.hypot(q[0] - tc[0], q[2] - tc[1]) < rr);
+ if (near.length < 10) break;
+ let sx = 0, sz = 0; for (const q of near) { sx += q[0]; sz += q[2]; }
+ tc = [sx / near.length, sz / near.length];
+ trunk.push(new THREE.Vector3(tc[0], y + step / 2, tc[1]));
+ rr = 0.08 * H;
+ }
+ if (trunk.length < 3) {
+ trunk.length = 0;
+ for (let t = 0; t <= 1; t += 0.1) trunk.push(new THREE.Vector3(cx, lerp(potTop, y0 + 0.75 * H, t), cz));
+ }
+ // Leaf spawn points (surface + outward normal) for falling leaves.
+ const spawn = { position: new Float32Array(leafIdx.length * 3), normal: new Float32Array(leafIdx.length * 3), count: leafIdx.length };
+ leafIdx.forEach((i, j) => { spawn.position.set(P.subarray(i * 3, i * 3 + 3), j * 3); spawn.normal.set(NR.subarray(i * 3, i * 3 + 3), j * 3); });
+
+ return { H, y0, box, center: new THREE.Vector3(cx, 0, cz), potTop, potR, folY0, folY1, pads, trunk, groundAt, spawn, vertexFoliage: fol };
+}
+
+// ─── Procedural branches ───────────────────────────────────────────────────────
+/** Sweep a tapered tube along points. Returns arrays appended into `acc`. */
+function tube(acc, pts, r0, r1, radial, segs, fol0 = 0, fol1 = 1) {
+ const curve = new THREE.CatmullRomCurve3(pts, false, 'centripetal');
+ const frames = curve.computeFrenetFrames(segs, false);
+ const base = acc.pos.length / 3;
+ const P = new THREE.Vector3(), N = new THREE.Vector3();
+ for (let i = 0; i <= segs; i++) {
+ const t = i / segs;
+ curve.getPointAt(t, P);
+ const r = lerp(r0, r1, Math.pow(t, 0.8));
+ for (let j = 0; j <= radial; j++) {
+ const a = j / radial * Math.PI * 2;
+ N.copy(frames.normals[i]).multiplyScalar(Math.cos(a)).addScaledVector(frames.binormals[i], Math.sin(a)).normalize();
+ acc.pos.push(P.x + N.x * r, P.y + N.y * r, P.z + N.z * r);
+ acc.nor.push(N.x, N.y, N.z);
+ acc.uv.push(j / radial, t);
+ acc.fol.push(lerp(fol0, fol1, t));
+ }
+ }
+ for (let i = 0; i < segs; i++) for (let j = 0; j < radial; j++) {
+ const a = base + i * (radial + 1) + j, b = a + radial + 1;
+ acc.idx.push(a, a + 1, b, b, a + 1, b + 1);
+ }
+ return curve;
+}
+
+/** Tube along points with a radius per point (Catmull-Rom smoothed). */
+function tubeR(acc, pts, radii, radial, segs, folOf) {
+ const curve = new THREE.CatmullRomCurve3(pts, false, 'centripetal');
+ const frames = curve.computeFrenetFrames(segs, false);
+ const base = acc.pos.length / 3;
+ const P = new THREE.Vector3(), N = new THREE.Vector3();
+ const n = radii.length - 1;
+ for (let i = 0; i <= segs; i++) {
+ const t = i / segs;
+ curve.getPointAt(t, P);
+ const f = t * n, k = Math.min(n - 1, Math.floor(f));
+ const r = lerp(radii[k], radii[k + 1], f - k);
+ for (let j = 0; j <= radial; j++) {
+ const a = j / radial * Math.PI * 2;
+ N.copy(frames.normals[i]).multiplyScalar(Math.cos(a)).addScaledVector(frames.binormals[i], Math.sin(a)).normalize();
+ acc.pos.push(P.x + N.x * r, P.y + N.y * r, P.z + N.z * r);
+ acc.nor.push(N.x, N.y, N.z);
+ acc.uv.push(j / radial, t * 4);
+ acc.fol.push(folOf(r));
+ }
+ }
+ for (let i = 0; i < segs; i++) for (let j = 0; j < radial; j++) {
+ const a = base + i * (radial + 1) + j, b = a + radial + 1;
+ acc.idx.push(a, a + 1, b, b, a + 1, b + 1);
+ }
+ return curve;
+}
+
+/**
+ * Winter structure: space colonisation inside each foliage pad. Leaf-surface points are the attractors; growth
+ * starts on the trunk, so each pad gets a main limb that forks into the fine lace a pruned maple shows in winter.
+ * Radii follow the pipe model (r^2.4 of a fork = sum of its children's).
+ */
+export function growBranches(A, { seed = 3, attractors = 150 } = {}) {
+ const rand = rng(seed);
+ const H = A.H;
+ const acc = { pos: [], nor: [], uv: [], fol: [], idx: [] };
+ const trunkTop = A.trunk[A.trunk.length - 1];
+ const nearestTrunk = y => {
+ let best = A.trunk[0];
+ for (const t of A.trunk) if (t.y <= y && t.y > best.y) best = t;
+ return best;
+ };
+ const SEG = 0.02 * H, KILL = 0.034 * H, RTIP = 0.0011 * H, RMAX = 0.0135 * H;
+ const mains = [];
+ const tmp = new THREE.Vector3();
+ for (const pad of A.pads) {
+ const c = pad.center;
+ // attractors: leaf points, pulled a little inside and under the pad surface
+ const att = [];
+ for (let i = 0; i < attractors; i++) {
+ const q = pad.members[Math.floor(rand() * pad.members.length)];
+ const v = new THREE.Vector3(...q).lerp(c, 0.12);
+ v.y -= 0.012 * H + rand() * 0.012 * H;
+ att.push(v);
+ }
+ const isApex = c.y > trunkTop.y - 0.05 * H;
+ const start = (isApex ? trunkTop : nearestTrunk(c.y - pad.std.y * 1.2 - 0.05 * H)).clone();
+ const nodes = [{ p: start, parent: -1, dir: new THREE.Vector3(), n: 0 }];
+ const alive = att.map(() => true);
+ for (let it = 0; it < 90; it++) {
+ for (const nd of nodes) { nd.dir.set(0, 0, 0); nd.n = 0; }
+ let any = false;
+ for (let a = 0; a < att.length; a++) {
+ if (!alive[a]) continue;
+ let bi = -1, bd = Infinity;
+ for (let k = 0; k < nodes.length; k++) { const d = nodes[k].p.distanceToSquared(att[a]); if (d < bd) { bd = d; bi = k; } }
+ if (bd < KILL * KILL) { alive[a] = false; continue; }
+ const nd = nodes[bi];
+ nd.dir.add(tmp.copy(att[a]).sub(nd.p).normalize()); nd.n++;
+ any = true;
+ }
+ if (!any) break;
+ const L = nodes.length;
+ for (let k = 0; k < L; k++) {
+ const nd = nodes[k];
+ if (!nd.n) continue;
+ const d = nd.dir.normalize();
+ d.x += (rand() - 0.5) * 0.5; d.y += (rand() - 0.5) * 0.3; d.z += (rand() - 0.5) * 0.5;
+ d.normalize();
+ const p = nd.p.clone().addScaledVector(d, SEG);
+ // avoid duplicates (two nodes growing into the same spot)
+ let dup = false;
+ for (let m = L; m < nodes.length; m++) if (nodes[m].p.distanceToSquared(p) < (SEG * 0.3) ** 2) { dup = true; break; }
+ if (!dup) nodes.push({ p, parent: k, dir: new THREE.Vector3(), n: 0 });
+ }
+ }
+ if (nodes.length < 3) continue;
+ // pipe-model radii
+ const kids = nodes.map(() => []);
+ nodes.forEach((nd, i) => { if (nd.parent >= 0) kids[nd.parent].push(i); });
+ const r = new Float32Array(nodes.length);
+ const desc = new Int32Array(nodes.length);
+ for (let i = nodes.length - 1; i >= 0; i--) {
+ if (!kids[i].length) { r[i] = RTIP; desc[i] = 1; continue; }
+ let s = 0, dsum = 0;
+ for (const k of kids[i]) { s += Math.pow(r[k], 2.4); dsum += desc[k]; }
+ r[i] = Math.min(RMAX, Math.pow(s, 1 / 2.4) * 1.02 + 0.00005);
+ desc[i] = dsum + 1;
+ }
+ // chains: follow the heaviest child, branch off the others
+ const stack = [0];
+ while (stack.length) {
+ const s0 = stack.pop();
+ const chain = nodes[s0].parent >= 0 ? [nodes[s0].parent, s0] : [s0];
+ let cur = s0;
+ while (kids[cur].length) {
+ const ks = [...kids[cur]].sort((x, y) => desc[y] - desc[x]);
+ for (let q = 1; q < ks.length; q++) stack.push(ks[q]);
+ cur = ks[0];
+ chain.push(cur);
+ }
+ if (chain.length < 2) continue;
+ const pts = chain.map(i => nodes[i].p);
+ const rad = chain.map(i => r[i]);
+ if (pts.length === 2) { pts.splice(1, 0, pts[0].clone().lerp(pts[1], 0.5)); rad.splice(1, 0, (rad[0] + rad[1]) / 2); }
+ const thick = rad[0] > 0.004 * H;
+ const curve = tubeR(acc, pts, rad, thick ? 8 : rad[0] > 0.002 * H ? 5 : 4, Math.min(64, pts.length * (thick ? 3 : 2)), rr => clamp(1 - rr / (0.006 * H)));
+ if (chain[0] === 0 || nodes[chain[0]].parent === -1) mains.push({ pad, curve, rad, len: pts.length, radiusAt: u => { const f = u * (rad.length - 1), k = Math.min(rad.length - 2, Math.floor(f)); return lerp(rad[k], rad[k + 1], f - k); } });
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(acc.pos, 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(acc.nor, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(acc.uv, 2));
+ g.setAttribute('aFol', new THREE.Float32BufferAttribute(acc.fol, 1));
+ g.setIndex(acc.idx);
+ return { geometry: g, mains };
+}
+
+/** A copper wire wound at ~45° along a branch curve; drawRange reveals the winding. */
+export function wireGeometry(curve, radiusAt, { from = 0.06, to = 0.78, wire = 0.0032, turnsPerUnit = 0 } = {}) {
+ const L = curve.getLength() * (to - from);
+ const pts = [];
+ const n = 420;
+ const frames = curve.computeFrenetFrames(n, false);
+ let ang = 0;
+ const P = new THREE.Vector3(), T = new THREE.Vector3();
+ for (let i = 0; i <= n; i++) {
+ const t = from + (to - from) * i / n;
+ curve.getPointAt(t, P);
+ const fi = Math.min(n, Math.round(t * n));
+ const r = radiusAt(t) + wire * 0.9;
+ // 45°: advance one circumference of angle per circumference of length
+ if (i > 0) ang += (L / n) / r * (turnsPerUnit || 1);
+ T.copy(frames.normals[fi]).multiplyScalar(Math.cos(ang)).addScaledVector(frames.binormals[fi], Math.sin(ang));
+ pts.push(P.clone().addScaledVector(T, r));
+ }
+ const path = new THREE.CatmullRomCurve3(pts);
+ const g = new THREE.TubeGeometry(path, 900, wire, 6, false);
+ g.setAttribute('aFol', new THREE.Float32BufferAttribute(new Float32Array(g.attributes.position.count).fill(0.4), 1));
+ return { geometry: g, segs: 900, radial: 6 };
+}
diff --git a/examples/koi/flora.js b/examples/koi/flora.js
new file mode 100644
index 0000000..62ccf81
--- /dev/null
+++ b/examples/koi/flora.js
@@ -0,0 +1,477 @@
+// Things on the water: lotus, lily pads, falling maple leaves and petals, food pellets, splash droplets, snow.
+import * as THREE from 'three';
+import { bakeTexture } from '../../src/core/textures.js';
+import { pondSDF } from './shape.js';
+import { underShared } from './water.js';
+
+// Floating objects sample the ripple surface in the vertex shader: heave with the height, tilt with the slope.
+export const floatShared = { uBob: { value: 5 }, uTilt: { value: 0.9 } };
+export function patchFloat(mat, key) {
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, floatShared, { uSurf: underShared.uSurf, uSimRect: underShared.uSimRect });
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform sampler2D uSurf; uniform vec4 uSimRect; uniform float uBob, uTilt;')
+ .replace('#include <project_vertex>', /* glsl */`
+ vec4 kw = vec4(transformed, 1.0);
+ vec4 kc = vec4(0., 0., 0., 1.);
+ #ifdef USE_INSTANCING
+ kw = instanceMatrix * kw; kc = instanceMatrix * kc;
+ #endif
+ kw = modelMatrix * kw; kc = modelMatrix * kc;
+ vec4 ks = texture2D(uSurf, (kc.xz - uSimRect.xy) / uSimRect.z);
+ float kfl = 1. - smoothstep(0.02, 0.12, kc.y);
+ kw.y += kfl * (ks.x * uBob - dot(kw.xz - kc.xz, ks.yz) * uTilt * 0.12);
+ vec4 mvPosition = viewMatrix * kw;
+ gl_Position = projectionMatrix * mvPosition;`);
+ };
+ mat.customProgramCacheKey = () => 'float' + key;
+ return mat;
+}
+
+// ─── Leaf & petal atlas (canvas-drawn) ─────────────────────────────────────────
+function leafAtlas() {
+ const W = 256, c = document.createElement('canvas'); c.width = W * 3; c.height = W * 2;
+ const g = c.getContext('2d');
+ const pals = [['#f7784a', '#e0503a', '#9e2317'], ['#ec4a33', '#b8261a', '#6d1210'], ['#f9a440', '#e8702a', '#a8401a'],
+ ['#f5cf5a', '#e9a03a', '#b0621c'], ['#a8c455', '#6f9632', '#35561c'], ['#ffe0e6', '#f7b3c3', '#dc7d96']];
+ for (let s = 0; s < 6; s++) {
+ const ox = (s % 3) * W + W / 2, oy = Math.floor(s / 3) * W + W / 2;
+ const [c0, c1, c2] = pals[s];
+ g.save(); g.translate(ox, oy);
+ if (s < 5) {
+ const R = W * 0.46;
+ const lobes = [[0, 1], [0.8, 0.9], [-0.8, 0.9], [1.58, 0.7], [-1.58, 0.7], [2.3, 0.36], [-2.3, 0.36]];
+ g.beginPath();
+ for (let k = 0; k <= 720; k++) {
+ const phi = -Math.PI + k / 720 * Math.PI * 2;
+ let r = 0.2;
+ for (const [a, l] of lobes) { let u = Math.abs(phi - a) / 0.3; r = Math.max(r, l * Math.pow(Math.max(0, 1 - u), 0.85)); }
+ r += 0.018 * Math.abs(Math.sin(phi * 46)) * (r > 0.3 ? 1 : 0);
+ const x = Math.sin(phi) * r * R, y = -Math.cos(phi) * r * R + R * 0.08;
+ k ? g.lineTo(x, y) : g.moveTo(x, y);
+ }
+ g.closePath();
+ const gr = g.createRadialGradient(0, R * 0.1, 0, 0, R * 0.1, R);
+ gr.addColorStop(0, c0); gr.addColorStop(0.55, c1); gr.addColorStop(1, c2);
+ g.fillStyle = gr; g.fill();
+ g.strokeStyle = 'rgba(40,10,5,.35)'; g.lineWidth = 2;
+ for (const [a, l] of lobes) { g.beginPath(); g.moveTo(0, R * 0.12); g.lineTo(Math.sin(a) * l * R * 0.9, -Math.cos(a) * l * R * 0.9 + R * 0.08); g.stroke(); }
+ g.strokeStyle = c2; g.lineWidth = 4; g.beginPath(); g.moveTo(0, R * 0.12); g.quadraticCurveTo(R * 0.05, R * 0.5, -R * 0.02, R * 0.85); g.stroke();
+ } else {
+ const R = W * 0.42;
+ g.beginPath();
+ g.moveTo(0, R);
+ g.bezierCurveTo(R * 0.9, R * 0.5, R * 0.75, -R * 0.75, R * 0.12, -R * 0.9);
+ g.lineTo(0, -R * 0.68);
+ g.lineTo(-R * 0.12, -R * 0.9);
+ g.bezierCurveTo(-R * 0.75, -R * 0.75, -R * 0.9, R * 0.5, 0, R);
+ const gr = g.createLinearGradient(0, R, 0, -R);
+ gr.addColorStop(0, c2); gr.addColorStop(0.35, c1); gr.addColorStop(1, c0);
+ g.fillStyle = gr; g.fill();
+ }
+ g.restore();
+ }
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8;
+ return t;
+}
+
+function padTexture(renderer) {
+ return bakeTexture(renderer, 1024, /* glsl */`
+ void main(){
+ vec2 p = vUv * 2. - 1.;
+ float r = length(p), a = atan(p.y, p.x);
+ float veins = pow(abs(sin(a * 13. + fbm(vUv * 6., 6., 2, .5) * 0.8)), 42.) * smoothstep(0.06, 0.35, r) * (1. - smoothstep(0.85, 0.98, r));
+ float n = fbm(vUv * 7., 7., 5, .55);
+ float n2 = fbm(vUv * 2.5 + 3.1, 2.5, 4, .5);
+ vec3 base = mix(vec3(0.035, 0.085, 0.022), vec3(0.09, 0.17, 0.04), n * .5 + .5);
+ base = mix(base, vec3(0.12, 0.2, 0.05), smoothstep(0.15, 0.0, r) * 0.7);
+ base = mix(base, base * 1.55, veins * 0.6);
+ base = mix(base, vec3(0.16, 0.08, 0.04), smoothstep(0.86, 0.99, r) * 0.75);
+ base = mix(base, vec3(0.2, 0.17, 0.05), smoothstep(0.25, 0.5, n2) * 0.25);
+ gl_FragColor = vec4(base, 1.);
+ }`);
+}
+
+function padGeometry() {
+ const g = new THREE.CircleGeometry(0.5, 64, 0.22, Math.PI * 2 - 0.44);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), z = p.getZ(i), r = Math.hypot(x, z) * 2;
+ p.setY(i, Math.pow(r, 6) * 0.03 + Math.sin(Math.atan2(z, x) * 7) * 0.004 * r);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+function leafGeometry() {
+ const g = new THREE.PlaneGeometry(1, 1, 8, 8);
+ g.rotateX(-Math.PI / 2);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) { const x = p.getX(i), z = p.getZ(i); p.setY(i, (x * x + z * z) * 0.16 + Math.sin(x * 3) * 0.02); }
+ g.computeVertexNormals();
+ return g;
+}
+
+// ─── The floating world ────────────────────────────────────────────────────────
+export class Flora {
+ constructor({ renderer, scene, under, lotusGltf, sim }) {
+ this.scene = scene; this.under = under; this.sim = sim;
+ this.season = { leaves: 50, petals: 0, slots: [0, 1, 2, 2, 3], snow: 0 };
+ // Lotus flowers with their pads
+ const src = lotusGltf.scene;
+ this.lotus = [];
+ const lotusSpots = [[2.45, 1.3, 0.6, 0.4], [3.3, 2.2, 0.52, 2.1], [4.6, -0.3, 0.62, 1.0], [-4.1, 1.7, 0.66, 1.2], [-1.7, 7.2, 0.6, 3.3]];
+ const proxyMat = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false });
+ for (const [x, z, s, r] of lotusSpots) {
+ const m = src.clone(true);
+ m.traverse(o => { if (o.isMesh) { o.castShadow = true; o.receiveShadow = true; } });
+ const holder = new THREE.Group();
+ holder.add(m);
+ holder.position.set(x, 0.0, z); holder.rotation.y = r; holder.scale.setScalar(s);
+ scene.add(holder);
+ const proxy = holder.clone(true);
+ proxy.traverse(o => { if (o.isMesh) { o.material = proxyMat; o.castShadow = true; } });
+ under.add(proxy);
+ this.lotus.push({ holder, proxy, x, z, r, s, bx: x, bz: z, vx: 0, vz: 0 });
+ }
+ // Pads without flowers, clustered around the lotus
+ const padMat = patchFloat(new THREE.MeshStandardMaterial({ map: padTexture(renderer), roughness: 0.48, metalness: 0, envMapIntensity: 1.0, side: THREE.DoubleSide }), 'pad');
+ const padGeo = padGeometry();
+ const padSpots = [];
+ let rs = 5; const rnd = () => ((rs = (rs * 16807) % 2147483647) / 2147483647);
+ for (const [x, z] of lotusSpots) for (let k = 0; k < 7; k++) {
+ const a = rnd() * 6.28, d = 0.38 + rnd() * 0.75;
+ const s = 0.2 + rnd() * 0.22;
+ const px = x + Math.cos(a) * d, pz = z + Math.sin(a) * d;
+ if (pondSDF(px, pz) < -0.4 && Math.hypot(px - x, pz - z) > 0.33 && padSpots.every(p => Math.hypot(p[0] - px, p[1] - pz) > (p[2] + s) * 0.5)) padSpots.push([px, pz, s, rnd() * 6.28]);
+ }
+ this.pads = new THREE.InstancedMesh(padGeo, padMat, padSpots.length);
+ this.pads.castShadow = true; this.pads.receiveShadow = true;
+ this.padState = padSpots.map(([x, z, s, r]) => ({ x, z, s, r, bx: x, bz: z, vx: 0, vz: 0, spin: 0 }));
+ scene.add(this.pads);
+ this.padProxy = new THREE.InstancedMesh(padGeo, proxyMat, padSpots.length);
+ this.padProxy.instanceMatrix = this.pads.instanceMatrix;
+ this.padProxy.castShadow = true;
+ under.add(this.padProxy);
+
+ // Leaves and petals
+ this.leafTex = leafAtlas();
+ const leafMat = new THREE.MeshStandardMaterial({ map: this.leafTex, alphaTest: 0.5, side: THREE.DoubleSide, roughness: 0.55, metalness: 0, envMapIntensity: 0.9 });
+ patchFloat(leafMat, 'leaf');
+ const prevLeaf = leafMat.onBeforeCompile;
+ leafMat.onBeforeCompile = (sh, r) => {
+ prevLeaf(sh, r);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute float aSlot;')
+ .replace('#include <uv_vertex>', '#include <uv_vertex>\nvMapUv = (vMapUv + vec2(mod(aSlot, 3.), 1. - floor(aSlot / 3.))) / vec2(3., 2.);');
+ };
+ this.LEAVES = 420;
+ this.leafGeo = leafGeometry();
+ this.leafSlot = new THREE.InstancedBufferAttribute(new Float32Array(this.LEAVES), 1);
+ this.leafGeo.setAttribute('aSlot', this.leafSlot);
+ this.leaves = new THREE.InstancedMesh(this.leafGeo, leafMat, this.LEAVES);
+ this.leaves.castShadow = true; this.leaves.receiveShadow = true;
+ this.leaves.frustumCulled = false;
+ this.leafDepth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: this.leafTex, alphaTest: 0.5, side: THREE.DoubleSide });
+ this.leafDepth.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nattribute float aSlot;')
+ .replace('#include <uv_vertex>', '#include <uv_vertex>\n#ifdef USE_MAP\nvMapUv = (vMapUv + vec2(mod(aSlot, 3.), 1. - floor(aSlot / 3.))) / vec2(3., 2.);\n#endif');
+ };
+ this.leaves.customDepthMaterial = this.leafDepth;
+ scene.add(this.leaves);
+ this.leafProxy = new THREE.InstancedMesh(this.leafGeo, proxyMat, this.LEAVES);
+ this.leafProxy.instanceMatrix = this.leaves.instanceMatrix;
+ this.leafProxy.castShadow = true; this.leafProxy.frustumCulled = false;
+ this.leafProxy.customDepthMaterial = this.leafDepth;
+ under.add(this.leafProxy);
+ this.leafState = Array.from({ length: this.LEAVES }, () => ({ alive: false }));
+ this.leafAcc = 0;
+
+ // Food pellets
+ this.PELLETS = 48;
+ this.pellets = new THREE.InstancedMesh(new THREE.SphereGeometry(0.017, 12, 8), patchFloat(new THREE.MeshStandardMaterial({ color: 0x6b4526, roughness: 0.62, envMapIntensity: 0.6 }), 'pellet'), this.PELLETS);
+ this.pellets.castShadow = true; this.pellets.frustumCulled = false;
+ this.pelletState = Array.from({ length: this.PELLETS }, () => ({ alive: false }));
+ scene.add(this.pellets);
+
+ // Splash droplets
+ this.DROPS = 260;
+ const dmat = new THREE.MeshBasicMaterial({ color: new THREE.Color(1.6, 1.75, 1.8) });
+ this.droplets = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 8, 6), dmat, this.DROPS);
+ this.droplets.frustumCulled = false;
+ this.dropState = Array.from({ length: this.DROPS }, () => ({ alive: false }));
+ scene.add(this.droplets);
+
+ // Snow
+ const SN = 2400, sp = new Float32Array(SN * 3), sd = new Float32Array(SN);
+ for (let i = 0; i < SN; i++) { sp.set([(Math.random() - 0.5) * 16, Math.random() * 7, (Math.random() - 0.5) * 14 + 2], i * 3); sd[i] = Math.random(); }
+ const sg = new THREE.BufferGeometry();
+ sg.setAttribute('position', new THREE.BufferAttribute(sp, 3));
+ sg.setAttribute('seed', new THREE.BufferAttribute(sd, 1));
+ this.snowMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { uTime: { value: 0 }, uAmt: { value: 0 }, uDpr: { value: 1 }, uCol: { value: new THREE.Color(1.3, 1.35, 1.45) } },
+ vertexShader: /* glsl */`
+ attribute float seed; uniform float uTime, uAmt, uDpr; varying float vA;
+ void main(){
+ vec3 p = position;
+ float fall = 0.32 + seed * 0.3;
+ p.y = mod(p.y - uTime * fall, 7.0);
+ p.x += sin(uTime * 0.7 + seed * 30.) * 0.25; p.z += cos(uTime * 0.5 + seed * 17.) * 0.2;
+ vA = step(seed, uAmt) * smoothstep(0.0, 0.25, p.y) * smoothstep(7.0, 6.0, p.y);
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (3.0 + seed * 4.5) * uDpr * (9.0 / -mv.z);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uCol; varying float vA;
+ void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .15, d) * vA; if (a < .01) discard; gl_FragColor = vec4(uCol, a * .9); }`,
+ });
+ this.snow = new THREE.Points(sg, this.snowMat);
+ this.snow.frustumCulled = false;
+ scene.add(this.snow);
+
+ // Fireflies over the water at dusk
+ const FN = 90, fp = new Float32Array(FN * 3), fs = new Float32Array(FN);
+ for (let i = 0; i < FN; i++) {
+ const a = Math.random() * 6.28, r = Math.random();
+ const cx = i % 3 === 0 ? 3.4 : i % 3 === 1 ? -2.6 : 0.8, cz = i % 3 === 0 ? -2.6 : i % 3 === 1 ? -1.8 : 2.0;
+ fp.set([cx + Math.cos(a) * r * 3.2, 0.25 + Math.random() * 1.4, cz + Math.sin(a) * r * 2.6], i * 3); fs[i] = Math.random();
+ }
+ const fg = new THREE.BufferGeometry();
+ fg.setAttribute('position', new THREE.BufferAttribute(fp, 3));
+ fg.setAttribute('seed', new THREE.BufferAttribute(fs, 1));
+ this.fireMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uAmt: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: /* glsl */`
+ attribute float seed; uniform float uTime, uAmt, uDpr; varying float vA;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.25 + seed * 0.2) + seed * 40.;
+ p += vec3(sin(t * 1.3) * 0.35 + sin(t * 0.37) * 0.6, sin(t * 0.9 + seed * 9.) * 0.18, cos(t * 1.1) * 0.35 + cos(t * 0.29) * 0.6);
+ float blink = pow(max(0., sin(uTime * (0.6 + seed * 0.9) + seed * 31.)), 6.);
+ vA = blink * uAmt;
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (5. + seed * 5.) * uDpr * (3.0 / -mv.z) * (0.4 + blink * 0.6);
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA;
+ void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .0, d); a = a * a; if (vA * a < .002) discard; gl_FragColor = vec4(vec3(2.4, 3.2, 1.1) * a * vA, 1.); }`,
+ });
+ this.fireflies = new THREE.Points(fg, this.fireMat);
+ this.fireflies.frustumCulled = false;
+ scene.add(this.fireflies);
+
+ // Low mist that lies on the water at dawn
+ this.mistMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { uTime: { value: 0 }, uAmt: { value: 0 }, uCol: { value: new THREE.Color(0.8, 0.82, 0.8) }, uNoise: { value: null }, uLayer: { value: 0 } },
+ vertexShader: 'varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }',
+ fragmentShader: /* glsl */`
+ uniform sampler2D uNoise; uniform float uTime, uAmt, uLayer; uniform vec3 uCol; varying vec3 vW;
+ void main(){
+ vec2 q = vW.xz * 0.07 + vec2(uTime * 0.006, uTime * 0.0035) + uLayer * 0.37;
+ float n = texture2D(uNoise, q).r * 0.65 + texture2D(uNoise, q * 2.3 - vec2(uTime * 0.009, 0.)).r * 0.35;
+ float a = smoothstep(0.55, 0.95, n) * smoothstep(0.3, 0.7, texture2D(uNoise, q * 0.37 + 0.2).r) * uAmt * (0.42 - uLayer * 0.1);
+ if (a < 0.003) discard;
+ gl_FragColor = vec4(uCol, a);
+ }`,
+ });
+ this.mist = [];
+ for (let k = 0; k < 3; k++) {
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(34, 34).rotateX(-Math.PI / 2), this.mistMat.clone());
+ m.material.uniforms.uLayer.value = k;
+ m.position.set(0, 0.06 + k * 0.16, 2);
+ m.renderOrder = 2 + k;
+ scene.add(m);
+ this.mist.push(m);
+ }
+
+ this._m = new THREE.Matrix4(); this._q = new THREE.Quaternion(); this._e = new THREE.Euler(); this._s = new THREE.Vector3(); this._p = new THREE.Vector3();
+ this.syncPads();
+ for (let i = 0; i < 24; i++) this.spawnLeaf(true);
+ for (let i = 0; i < 26; i++) this.spawnLeaf(true, { x: 0.4, z: 0.2, w: 5.2, h: 4.4 });
+ }
+
+ syncPads() {
+ const { _m, _q, _e, _s, _p } = this;
+ this.padState.forEach((p, i) => {
+ _e.set(0, p.r, 0); _q.setFromEuler(_e); _s.setScalar(p.s * (this.padScale ?? 1)); _p.set(p.x, 0.004, p.z);
+ this.pads.setMatrixAt(i, _m.compose(_p, _q, _s));
+ });
+ this.pads.instanceMatrix.needsUpdate = true;
+ }
+
+ spawnLeaf(onWater = false, near = null, kind = 'leaf') {
+ const i = this.leafState.findIndex(l => !l.alive);
+ if (i < 0) return;
+ const slots = kind === 'petal' ? [5] : this.season.slots;
+ const slot = slots[Math.floor(Math.random() * slots.length)];
+ let x, z, tries = 0;
+ do {
+ x = near ? near.x + (Math.random() - 0.5) * near.w : (Math.random() - 0.5) * 14 - 0.5;
+ z = near ? near.z + (Math.random() - 0.5) * near.h : (Math.random() - 0.5) * 10 + 2;
+ } while (pondSDF(x, z) > -0.35 && ++tries < 30);
+ const petal = slot === 5;
+ this.leafSlot.setX(i, slot); this.leafSlot.needsUpdate = true;
+ this.leafState[i] = {
+ alive: true, x, z, y: onWater ? 0.012 : 1.2 + Math.random() * 2.8, vx: 0, vz: 0,
+ rot: Math.random() * 6.28, spin: (Math.random() - 0.5) * 3, tilt: Math.random() * 6.28, flutter: 2 + Math.random() * 2,
+ size: petal ? 0.042 + Math.random() * 0.02 : 0.085 + Math.random() * 0.06, landed: onWater, age: onWater ? Math.random() * 40 : 0,
+ life: 60 + Math.random() * 60, sink: 0, petal,
+ };
+ }
+
+ drop(x, z, n = 4, hooks) {
+ for (let k = 0; k < n; k++) {
+ const i = this.pelletState.findIndex(p => !p.alive);
+ if (i < 0) break;
+ const a = Math.random() * 6.28, d = k === 0 ? 0 : 0.05 + Math.random() * 0.16;
+ const px = x + Math.cos(a) * d, pz = z + Math.sin(a) * d;
+ const delay = k * 0.06 + Math.random() * 0.05;
+ this.pelletState[i] = { alive: true, x: px, z: pz, y: 1.2 + delay * 4, vy: -3.2, landed: false, t: 0, food: null, delay };
+ }
+ }
+
+ splash(x, z, n = 10, power = 1) {
+ for (let k = 0; k < n; k++) {
+ const i = this.dropState.findIndex(d => !d.alive);
+ if (i < 0) return;
+ const a = Math.random() * 6.28, h = (0.25 + Math.random() * 0.75) * power;
+ this.dropState[i] = { alive: true, x, z, y: 0.01, vx: Math.cos(a) * h * 0.55, vz: Math.sin(a) * h * 0.55, vy: (0.9 + Math.random() * 1.1) * power, r: 0.004 + Math.random() * 0.006 };
+ }
+ }
+
+ update(dt, t, { school, pointer, hooks, view }) {
+ const { _m, _q, _e, _s, _p } = this;
+ // pads drift back to their anchors, pushed by the visitor's hand
+ for (const p of this.padState) {
+ if (pointer?.on) {
+ const dx = p.x - pointer.x, dz = p.z - pointer.z, d = Math.hypot(dx, dz);
+ if (d < p.s * 0.5 + 0.35) { p.vx += pointer.vx * dt * 0.8; p.vz += pointer.vz * dt * 0.8; p.spin += (pointer.vx * dz - pointer.vz * dx) * dt * 0.8; }
+ }
+ p.vx += (p.bx - p.x) * dt * 0.6; p.vz += (p.bz - p.z) * dt * 0.6;
+ p.vx *= Math.exp(-dt * 1.5); p.vz *= Math.exp(-dt * 1.5); p.spin *= Math.exp(-dt * 1.2);
+ p.x += p.vx * dt; p.z += p.vz * dt; p.r += p.spin * dt + Math.sin(t * 0.1 + p.bx) * 0.0006;
+ }
+ this.syncPads();
+ for (const l of this.lotus) {
+ if (pointer?.on) {
+ const dx = l.x - pointer.x, dz = l.z - pointer.z, d = Math.hypot(dx, dz);
+ if (d < l.s * 0.5 + 0.3) { l.vx += pointer.vx * dt * 0.6; l.vz += pointer.vz * dt * 0.6; }
+ }
+ l.vx += (l.bx - l.x) * dt * 0.5; l.vz += (l.bz - l.z) * dt * 0.5;
+ l.vx *= Math.exp(-dt * 1.4); l.vz *= Math.exp(-dt * 1.4);
+ l.x += l.vx * dt; l.z += l.vz * dt;
+ l.holder.position.set(l.x, 0, l.z);
+ l.holder.rotation.y = l.r + Math.sin(t * 0.13 + l.bx) * 0.08;
+ l.proxy.position.copy(l.holder.position); l.proxy.rotation.copy(l.holder.rotation);
+ }
+
+ // leaves and petals: keep the view stocked to the season's taste, let the out-of-season ones sink
+ let nLeaf = 0, nPetal = 0;
+ const R2 = (view.w * 0.75) ** 2;
+ for (const l of this.leafState) {
+ if (!l.alive || l.sink) continue;
+ const d2 = (l.x - view.x) ** 2 + (l.z - view.z) ** 2;
+ if (d2 > R2) { if (l.landed && l.life - l.age > 12) l.life = l.age + 4 + Math.random() * 8; continue; }
+ l.petal ? nPetal++ : nLeaf++;
+ }
+ const want = [[this.season.leaves, nLeaf, 'leaf'], [this.season.petals, nPetal, 'petal']];
+ for (const [target, n, kind] of want) {
+ const deficit = target - n;
+ if (deficit > 0) {
+ const rate = Math.min(40, 0.25 + deficit * 0.18);
+ this[kind + 'Acc'] = (this[kind + 'Acc'] ?? 0) + dt * rate;
+ while (this[kind + 'Acc'] > 1) { this[kind + 'Acc'] -= 1; this.spawnLeaf(false, view, kind); }
+ } else if (deficit < -8) {
+ // thin the surplus: the oldest on-screen ones slowly sink
+ let k = Math.min(6, -deficit - 8);
+ for (const l of this.leafState) {
+ if (!k) break;
+ if (l.alive && l.landed && !l.sink && (kind === 'petal') === !!l.petal && l.life - l.age > 6) { l.life = l.age + 1 + Math.random() * 5; k--; }
+ }
+ }
+ }
+ let alive = 0;
+ for (let i = 0; i < this.LEAVES; i++) {
+ const l = this.leafState[i];
+ if (!l.alive) { this.leaves.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ alive++;
+ if (!l.landed) {
+ l.y -= dt * (l.petal ? 0.5 : 0.75) * (0.8 + Math.sin(t * l.flutter + i) * 0.4);
+ l.x += Math.sin(t * 0.9 + i) * dt * 0.25 + dt * 0.08; l.z += Math.cos(t * 0.7 + i * 1.3) * dt * 0.2;
+ l.tilt += dt * l.flutter; l.rot += l.spin * dt;
+ if (l.y <= 0.012) {
+ l.y = 0.012; l.landed = true;
+ if (pondSDF(l.x, l.z) < -0.1) { hooks.leafLand?.(l); } else { l.sink = 1; }
+ }
+ } else {
+ l.age += dt;
+ const drift = 0.018;
+ l.vx += (Math.sin(t * 0.05 + l.z * 0.3) * drift - l.vx) * dt * 0.3;
+ l.vz += (Math.cos(t * 0.04 + l.x * 0.3) * drift - l.vz) * dt * 0.3;
+ if (pointer?.on) {
+ const dx = l.x - pointer.x, dz = l.z - pointer.z, d2 = dx * dx + dz * dz;
+ if (d2 < 0.16) { const k = (1 - Math.sqrt(d2) / 0.4); l.vx += pointer.vx * k * dt * 2.2; l.vz += pointer.vz * k * dt * 2.2; l.spin += (Math.random() - 0.5) * k * pointer.speed * dt * 10; }
+ }
+ for (const f of school.fish) { // koi nosing up under a leaf push it aside
+ if (f.y > -0.18) { const dx = l.x - f.x, dz = l.z - f.z, d2 = dx * dx + dz * dz; if (d2 < 0.05) { l.vx += dx * dt * 3; l.vz += dz * dt * 3; } }
+ }
+ const sdf = pondSDF(l.x, l.z);
+ if (sdf > -0.15) { l.vx -= (l.x - 0.2) * dt * 0.02; l.vz -= (l.z - 2.2) * dt * 0.02; }
+ l.vx *= Math.exp(-dt * 0.9); l.vz *= Math.exp(-dt * 0.9);
+ l.x += l.vx * dt; l.z += l.vz * dt;
+ l.spin *= Math.exp(-dt * 0.8); l.rot += l.spin * dt;
+ if (l.age > l.life && !l.sink) l.sink = 0.001;
+ if (l.sink) { l.sink += dt * 0.25; l.y = 0.012 - l.sink * 0.06; if (l.sink > 1) { l.alive = false; continue; } }
+ }
+ const fallTilt = l.landed ? 0 : Math.sin(l.tilt) * 0.9;
+ _e.set(fallTilt, l.rot, l.landed ? 0 : Math.cos(l.tilt * 0.7) * 0.6, 'YXZ');
+ _q.setFromEuler(_e); _s.setScalar(l.size * (l.sink ? 1 - l.sink * 0.4 : 1)); _p.set(l.x, l.y, l.z);
+ this.leaves.setMatrixAt(i, _m.compose(_p, _q, _s));
+ }
+ this.leaves.instanceMatrix.needsUpdate = true;
+
+ // pellets
+ for (let i = 0; i < this.PELLETS; i++) {
+ const p = this.pelletState[i];
+ if (!p.alive) { this.pellets.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ p.t += dt;
+ if (!p.landed) {
+ if (p.t < p.delay) { this.pellets.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ p.y += p.vy * dt; p.vy -= 9.8 * dt;
+ if (p.y <= 0.008) { p.y = 0.008; p.landed = true; p.food = { x: p.x, z: p.z, t, eaten: false, pellet: p }; school.food.push(p.food); hooks.pelletLand?.(p); }
+ } else {
+ p.x += Math.sin(t * 0.3 + i) * dt * 0.01; p.z += Math.cos(t * 0.27 + i) * dt * 0.01;
+ p.food.x = p.x; p.food.z = p.z;
+ if (p.food.eaten) { p.alive = false; school.food.splice(school.food.indexOf(p.food), 1); this.pellets.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ if (p.t > 40) { p.food.eaten = true; }
+ }
+ _p.set(p.x, p.y, p.z); this.pellets.setMatrixAt(i, _m.compose(_p, _q.identity(), _s.setScalar(1)));
+ }
+ this.pellets.instanceMatrix.needsUpdate = true;
+
+ // droplets
+ for (let i = 0; i < this.DROPS; i++) {
+ const d = this.dropState[i];
+ if (!d.alive) { this.droplets.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ d.vy -= 9.8 * dt; d.x += d.vx * dt; d.y += d.vy * dt; d.z += d.vz * dt;
+ if (d.y < 0) { d.alive = false; hooks.dropletLand?.(d); this.droplets.setMatrixAt(i, _m.makeScale(0, 0, 0)); continue; }
+ _p.set(d.x, d.y, d.z); this.droplets.setMatrixAt(i, _m.compose(_p, _q.identity(), _s.setScalar(d.r)));
+ }
+ this.droplets.instanceMatrix.needsUpdate = true;
+
+ for (const m of this.mist) { m.material.uniforms.uTime.value = t; m.visible = m.material.uniforms.uAmt.value > 0.005; }
+ this.fireMat.uniforms.uTime.value = t;
+ this.fireflies.visible = this.fireMat.uniforms.uAmt.value > 0.01;
+ this.snowMat.uniforms.uTime.value = t;
+ this.snowMat.uniforms.uAmt.value = this.season.snow;
+ this.snow.visible = this.season.snow > 0.01;
+ return alive;
+ }
+}
diff --git a/examples/koi/garden.js b/examples/koi/garden.js
new file mode 100644
index 0000000..6561151
--- /dev/null
+++ b/examples/koi/garden.js
@@ -0,0 +1,263 @@
+// The garden around the water: one terrain (pond floor below y=0, moss banks above), shoreline rocks.
+import * as THREE from 'three';
+import { bakeTexture, fbmNormal, fbmTexture } from '../../src/core/textures.js';
+import { patchUnder } from './water.js';
+import { terrainH, pondSDF, noise, fbm, LANTERN } from './shape.js';
+
+export const gardenShared = {
+ uFloorTex: { value: null }, uMossTex: { value: null }, uNoiseTex: { value: null }, uGranite: { value: null },
+ uSnow: { value: 0 }, uMossTint: { value: new THREE.Color(1, 1, 1) }, uSilt: { value: new THREE.Color(0.10, 0.11, 0.06) },
+};
+
+const TERRAIN_HEAD = /* glsl */`
+ uniform sampler2D uFloorTex, uMossTex, uNoiseTex; uniform float uSnow; uniform vec3 uMossTint, uSilt;
+ varying vec3 vWN;
+ vec3 terrainAlbedo(vec3 wp, out float rough){
+ vec2 q = wp.xz;
+ vec2 q2 = mat2(0.8, -0.6, 0.6, 0.8) * q;
+ float h = wp.y;
+ float nb = texture2D(uNoiseTex, q * 0.045).r;
+ float nb2 = texture2D(uNoiseTex, q * 0.13 + 0.5).r;
+ vec3 f1 = texture2D(uFloorTex, q / 3.1, 1.2).rgb;
+ vec3 f2 = texture2D(uFloorTex, q2 / 4.3 + 0.31, 2.0).rgb;
+ vec3 fl = mix(f1, f2, smoothstep(0.42, 0.58, nb));
+ // broad variation: sand fans, darker algae beds
+ float big = texture2D(uNoiseTex, q * 0.021 + 0.3).r;
+ fl *= 0.55 + big * 0.9;
+ fl = mix(fl, vec3(0.34, 0.30, 0.22) * (0.8 + nb2 * 0.4), smoothstep(0.62, 0.8, big) * 0.45 * smoothstep(-1.1, -0.3, h));
+ // fine silt and algae settle in the deep water
+ float silt = smoothstep(-0.2, -0.9, h) * smoothstep(0.15, 0.6, nb2 + 0.25);
+ fl = mix(fl * 0.75, uSilt * (0.6 + nb * 0.7), silt * 0.85);
+ fl *= mix(vec3(1.), vec3(0.62, 0.72, 0.5), smoothstep(-0.1, -0.9, h));
+ vec3 m1 = texture2D(uMossTex, q / 2.1).rgb;
+ vec3 m2 = texture2D(uMossTex, q2 / 2.9 + 0.5).rgb;
+ vec3 moss = mix(m1, m2, smoothstep(0.4, 0.6, nb2)) * uMossTint;
+ moss = mix(moss, moss * vec3(0.72, 0.62, 0.42), smoothstep(0.55, 0.8, nb) * 0.6);
+ float mossW = smoothstep(0.035, 0.13, h + (nb - 0.5) * 0.1);
+ float wet = smoothstep(0.09, 0.0, h);
+ vec3 shore = fl * mix(1.0, 0.55, wet);
+ vec3 col = mix(shore, moss, mossW);
+ float up = smoothstep(0.55, 0.9, vWN.y);
+ col = mix(col, vec3(0.92, 0.94, 0.97), uSnow * mossW * up * smoothstep(0.3, 0.55, nb2 + uSnow * 0.4));
+ rough = mix(mix(0.8, 0.28, wet), 0.96, mossW);
+ return col;
+ }
+`;
+
+export function terrainTextures(renderer, assets) {
+ gardenShared.uNoiseTex.value = fbmTexture(renderer, { size: 512, scale: 4, octaves: 5, contrast: 1.4 });
+ return Promise.all([
+ assets.texture('img/koi/floor.webp', { repeat: [1, 1] }).then(t => { t.anisotropy = 16; gardenShared.uFloorTex.value = t; }),
+ assets.texture('img/koi/moss.webp', { repeat: [1, 1] }).then(t => { t.anisotropy = 16; gardenShared.uMossTex.value = t; }),
+ ]);
+}
+
+export function buildTerrain(renderer) {
+ const S = 38, N = 300;
+ const geo = new THREE.PlaneGeometry(S, S, N, N);
+ geo.rotateX(-Math.PI / 2);
+ geo.translate(0, 0, 2);
+ const p = geo.attributes.position;
+ for (let i = 0; i < p.count; i++) p.setY(i, terrainH(p.getX(i), p.getZ(i)));
+ geo.computeVertexNormals();
+ const nrm = fbmNormal(renderer, { size: 1024, scale: 16, octaves: 6, strength: 2.2 });
+ nrm.repeat.set(S / 1.6, S / 1.6);
+ const mat = new THREE.MeshStandardMaterial({ roughness: 1, metalness: 0, normalMap: nrm, normalScale: new THREE.Vector2(0.9, 0.9), envMapIntensity: 0.7 });
+ patchUnder(mat, {
+ key: 'terrain',
+ extraVertexHead: 'varying vec3 vWN;',
+ extraFragHead: TERRAIN_HEAD,
+ mapFragment: 'float kRough; diffuseColor.rgb *= terrainAlbedo(vWP, kRough);',
+ roughFragment: 'float roughnessFactor = kRough;',
+ custom: {
+ uniforms: gardenShared,
+ patch: sh => { sh.vertexShader = sh.vertexShader.replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvWN = normalize(mat3(modelMatrix) * objectNormal);'); },
+ },
+ });
+ // the patch above inserted vWN after worldpos; make sure it comes after patchUnder's own worldpos replacement
+ const under = new THREE.Mesh(geo, mat);
+ under.receiveShadow = true; under.castShadow = false;
+ const above = new THREE.Mesh(geo, mat);
+ above.receiveShadow = true; above.castShadow = true;
+ return { under, above, geo, mat };
+}
+
+// ─── Rocks ─────────────────────────────────────────────────────────────────────
+function rockGeometry(seed, detail = 5) {
+ const g = new THREE.IcosahedronGeometry(1, detail);
+ const p = g.attributes.position, v = new THREE.Vector3(), d = new THREE.Vector3();
+ const sx = seed * 7.13, sz = seed * 3.71;
+ for (let i = 0; i < p.count; i++) {
+ v.fromBufferAttribute(p, i);
+ d.copy(v);
+ // weathered boulder: broad lumps, a few ridges, a flattened top and a buried base
+ const broad = fbm(d.x * 0.9 + sx, d.y * 0.9 + d.z * 0.7 + sz, 3) * 0.5;
+ const ridg = (1 - Math.abs(noise(d.x * 2.2 + sz, d.z * 2.2 + d.y * 1.6 - sx))) * 0.05;
+ const fine = noise(d.x * 7 - sx, d.y * 7 + d.z * 4) * 0.01;
+ v.multiplyScalar(1 + broad + ridg + fine);
+ if (v.y > 0.6) v.y = 0.6 + (v.y - 0.6) * 0.7;
+ if (v.y < -0.25) v.y = -0.25 + (v.y + 0.25) * 0.3;
+ p.setXYZ(i, v.x, v.y, v.z);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+export function rockMaterial(renderer) {
+ const granite = bakeTexture(renderer, 1024, /* glsl */`
+ void main(){
+ float n = fbm(vUv * 6., 6., 6, .55);
+ float sp = pnoise(vUv * 180., 180.); float sp2 = pnoise(vUv * 90. + 3., 90.);
+ vec3 base = mix(vec3(0.11, 0.105, 0.10), vec3(0.27, 0.26, 0.24), n * .5 + .5);
+ base = mix(base, vec3(0.05, 0.05, 0.045), smoothstep(0.2, 0.45, sp) * 0.75);
+ base = mix(base, vec3(0.42, 0.41, 0.37), smoothstep(0.3, 0.5, sp2) * 0.4);
+ float lich = smoothstep(0.12, 0.32, fbm(vUv * 7. + 2., 7., 5, .55));
+ base = mix(base, vec3(0.52, 0.55, 0.46), lich * 0.45);
+ float dark = smoothstep(0.05, 0.3, fbm(vUv * 4. + 7., 4., 4, .5));
+ base *= 1.0 - dark * 0.35;
+ gl_FragColor = vec4(base, 1.);
+ }`);
+ gardenShared.uGranite.value = granite;
+ const nrm = fbmNormal(renderer, { size: 1024, scale: 10, octaves: 7, strength: 3.2, ridged: true });
+ nrm.repeat.set(3, 3);
+ const mat = new THREE.MeshStandardMaterial({ roughness: 0.88, metalness: 0, normalMap: nrm, normalScale: new THREE.Vector2(0.6, 0.6), envMapIntensity: 0.55 });
+ patchUnder(mat, {
+ key: 'rock',
+ extraVertexHead: 'varying vec3 vWN; varying vec3 vOP;',
+ extraFragHead: /* glsl */`
+ uniform sampler2D uGranite, uMossTex, uNoiseTex; uniform float uSnow; uniform vec3 uMossTint;
+ varying vec3 vWN; varying vec3 vOP;`,
+ mapFragment: /* glsl */`
+ vec3 an = abs(normalize(vWN));
+ vec3 gx = texture2D(uGranite, vWP.zy * 0.8).rgb, gy = texture2D(uGranite, vWP.xz * 0.8).rgb, gz = texture2D(uGranite, vWP.xy * 0.8).rgb;
+ vec3 gr = (gx * an.x + gy * an.y + gz * an.z) / (an.x + an.y + an.z);
+ float nb = texture2D(uNoiseTex, vWP.xz * 0.6).r;
+ float nb2 = texture2D(uNoiseTex, vWP.xz * 1.7 + vWP.y * 0.8 + 0.3).r;
+ float up = smoothstep(0.62, 0.95, vWN.y + (nb - 0.5) * 0.7) * smoothstep(0.42, 0.62, nb2);
+ vec3 moss = texture2D(uMossTex, vWP.xz / 1.4).rgb * uMossTint * 0.85;
+ gr *= (0.8 + nb2 * 0.4) * 0.72;
+ float wet = smoothstep(0.05, -0.01, vWP.y);
+ vec3 col = mix(gr, moss, up * smoothstep(0.02, 0.12, vWP.y));
+ col *= mix(1.0, 0.62, wet);
+ col = mix(col, vec3(0.93, 0.95, 0.98), uSnow * smoothstep(0.6, 0.9, vWN.y) * smoothstep(0.35, 0.6, nb + uSnow * 0.3));
+ diffuseColor.rgb *= col;
+ float kRough = mix(mix(0.9, 0.5, wet), 0.97, up);`,
+ roughFragment: 'float roughnessFactor = kRough;',
+ custom: {
+ uniforms: gardenShared,
+ patch: sh => {
+ sh.vertexShader = sh.vertexShader.replace('#include <worldpos_vertex>', `#include <worldpos_vertex>
+ mat3 kIM = mat3(modelMatrix);
+ #ifdef USE_INSTANCING
+ kIM = kIM * mat3(instanceMatrix);
+ #endif
+ vWN = normalize(kIM * objectNormal); vOP = position;`);
+ },
+ },
+ });
+ return mat;
+}
+
+/** Rocks placed along the shoreline plus hand-placed feature stones. Returns two instanced meshes (under + above). */
+export function buildRocks(mat) {
+ const geos = [1, 2, 3, 4].map(s => rockGeometry(s));
+ const placements = [[], [], [], []];
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), sc = new THREE.Vector3(), po = new THREE.Vector3();
+ let rs = 11;
+ const rnd = () => ((rs = (rs * 16807) % 2147483647) / 2147483647);
+ const add = (x, z, size, squash = 0.55, sink = 0.35, kind = null) => {
+ const k = kind ?? Math.floor(rnd() * 4);
+ e.set((rnd() - 0.5) * 0.3, rnd() * Math.PI * 2, (rnd() - 0.5) * 0.3);
+ q.setFromEuler(e);
+ sc.set(size * (0.85 + rnd() * 0.4), size * squash * (0.8 + rnd() * 0.4), size * (0.85 + rnd() * 0.4));
+ po.set(x, terrainH(x, z) - size * squash * sink + 0.02, z);
+ m.compose(po, q, sc);
+ placements[k].push(m.clone());
+ };
+ // walk the shoreline
+ const pts = [];
+ for (let a = 0; a < Math.PI * 2; a += 0.0025) {
+ // march outward from the pond centre until we cross the shore
+ let lo = 0, hi = 14;
+ const cx = 0.2, cz = 2.2, dx = Math.cos(a), dz = Math.sin(a);
+ for (let it = 0; it < 24; it++) { const mid = (lo + hi) / 2; (pondSDF(cx + dx * mid, cz + dz * mid) < 0 ? (lo = mid) : (hi = mid)); }
+ pts.push([cx + dx * lo, cz + dz * lo]);
+ }
+ let acc = 0;
+ for (let i = 1; i < pts.length; i++) {
+ acc += Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][1] - pts[i - 1][1]);
+ const gap = 0.55 + noise(i * 0.013, 3.3) * 1.4;
+ if (acc < gap) continue;
+ acc = 0;
+ const [x, z] = pts[i];
+ const cluster = noise(x * 0.4, z * 0.4) > -0.05;
+ if (!cluster || Math.hypot(x - LANTERN.x, z - LANTERN.z) < 1.5) continue;
+ const s = 0.22 + rnd() * 0.36;
+ // set rocks straddling the waterline, a little outboard
+ const out = 0.05 + rnd() * 0.25;
+ const nx = x - 0.2, nz = z - 2.2, nl = Math.hypot(nx, nz);
+ add(x + nx / nl * out, z + nz / nl * out, s);
+ if (rnd() < 0.55) add(x + nx / nl * (out + s * 1.2) + (rnd() - 0.5) * 0.3, z + nz / nl * (out + s * 1.2) + (rnd() - 0.5) * 0.3, s * (0.6 + rnd() * 0.6));
+ if (rnd() < 0.5) add(x - nx / nl * 0.08 + (rnd() - 0.5) * 0.4, z - nz / nl * 0.08 + (rnd() - 0.5) * 0.4, 0.07 + rnd() * 0.08, 0.6, 0.3);
+ }
+ // the lantern's rock and a few stepping stones across the south-west lobe
+ add(LANTERN.x + 0.85, LANTERN.z - 0.55, 0.62, 0.55, 0.45, 0);
+ add(LANTERN.x - 0.95, LANTERN.z - 0.35, 0.4, 0.5, 0.45, 2);
+ add(LANTERN.x + 0.55, LANTERN.z + 0.42, 0.2, 0.55, 0.35, 1);
+ const steps = [[-3.1, 4.9], [-3.75, 5.55], [-4.35, 6.25], [-4.85, 7.05]];
+ const avoid = [{ x: LANTERN.x, z: LANTERN.z, r: 0.5 }];
+ for (const [x, z] of steps) {
+ e.set(0, rnd() * 3, 0); q.setFromEuler(e); sc.set(0.34, 0.16, 0.28);
+ po.set(x, 0.035, z); m.compose(po, q, sc); placements[3].push(m.clone());
+ avoid.push({ x, z, r: 0.32 });
+ }
+ const make = () => geos.map((g, k) => {
+ const im = new THREE.InstancedMesh(g, mat, placements[k].length);
+ placements[k].forEach((mm, i) => im.setMatrixAt(i, mm));
+ im.castShadow = true; im.receiveShadow = true;
+ im.computeBoundingSphere();
+ return im;
+ });
+ return { under: make(), above: make(), avoid };
+}
+
+// ─── Enclosure: a clipped hedge around the garden and a sky above it ───────────
+export function buildEnclosure(W) {
+ const hedgeU = { uKeyDir: { value: new THREE.Vector3(0, 1, 0) }, uKeyCol: { value: new THREE.Color(1, 1, 1) }, uAmb: { value: new THREE.Color(0.2, 0.25, 0.2) }, uTime: { value: 0 } };
+ const hedge = new THREE.Mesh(
+ new THREE.CylinderGeometry(11.5, 11.5, 6, 160, 1, true),
+ new THREE.ShaderMaterial({
+ side: THREE.BackSide, uniforms: hedgeU,
+ vertexShader: 'varying vec3 vW; varying vec2 vUv; void main(){ vUv = uv; vec4 w = modelMatrix * vec4(position, 1.); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }',
+ fragmentShader: /* glsl */`
+ uniform vec3 uKeyDir, uKeyCol, uAmb; varying vec3 vW; varying vec2 vUv;
+ float h21(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+ float vn(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3. - 2. * f);
+ return mix(mix(h21(i), h21(i + vec2(1, 0)), f.x), mix(h21(i + vec2(0, 1)), h21(i + vec2(1, 1)), f.x), f.y); }
+ float fb(vec2 p){ float s = 0., a = .5; for (int i = 0; i < 5; i++){ s += a * vn(p); p *= 2.07; a *= .5; } return s; }
+ void main(){
+ float u = vUv.x * 180.;
+ float y = vW.y;
+ float top = 2.3 + fb(vec2(u * 0.08, 1.3)) * 1.6 + pow(fb(vec2(u * 0.025, 7.1)), 3.) * 5.5;
+ if (y > top) discard;
+ float leaf = fb(vec2(u * 0.9, y * 2.2));
+ float clump = fb(vec2(u * 0.22, y * 0.6 + 3.));
+ vec3 c = mix(vec3(0.018, 0.034, 0.016), vec3(0.07, 0.11, 0.04), leaf);
+ c = mix(c, c * vec3(1.5, 1.2, 0.7), smoothstep(0.55, 0.8, clump) * 0.5);
+ vec3 n = normalize(vec3(-vW.x, 0., -(vW.z - 2.)));
+ float lit = max(dot(n, uKeyDir), 0.) * smoothstep(0.35, 0.8, leaf) * smoothstep(0.0, 1.5, y);
+ vec3 col = c * (uAmb * 1.4 + uKeyCol * lit * 1.3);
+ col *= mix(0.35, 1.0, smoothstep(0.0, 1.6, y)) * (0.75 + 0.25 * smoothstep(top - 0.6, top, y));
+ gl_FragColor = vec4(col, 1.);
+ }`,
+ }),
+ );
+ hedge.position.set(0.3, 2.9, 2);
+ const sky = new THREE.Mesh(new THREE.SphereGeometry(45, 48, 24), new THREE.ShaderMaterial({
+ side: THREE.BackSide, depthWrite: false, uniforms: { uZen: W.uZenith, uHor: W.uHorizon },
+ vertexShader: 'varying vec3 vD; void main(){ vD = normalize(position); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }',
+ fragmentShader: 'uniform vec3 uZen, uHor; varying vec3 vD; void main(){ gl_FragColor = vec4(mix(uHor, uZen, pow(clamp(vD.y, 0., 1.), 0.55)) * 0.9, 1.); }',
+ }));
+ sky.renderOrder = -2;
+ return { hedge, sky, uniforms: hedgeU };
+}
diff --git a/examples/koi/index.html b/examples/koi/index.html
new file mode 100644
index 0000000..61ac8f2
--- /dev/null
+++ b/examples/koi/index.html
@@ -0,0 +1,197 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Still Water — A seven-room ryokan around a koi pond, Kyoto</title>
+ <meta name="description" content="Seven rooms. One pond. No clocks. A ryokan in Higashiyama, Kyoto, built around a two-hundred-year-old koi pond.">
+ <meta name="theme-color" content="#0b1511">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Shippori+Mincho:wght@400;500;600;700&family=Zen+Kaku+Gothic+New:wght@300;400;500;700&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <svg class="enso" viewBox="0 0 200 200" aria-hidden="true">
+ <circle class="enso-track" cx="100" cy="100" r="78"/>
+ <circle class="enso-ink" cx="100" cy="100" r="78" pathLength="100"/>
+ </svg>
+ <p class="loader-kanji" aria-hidden="true">静</p>
+ <p class="loader-line">Filling the pond <span class="loader-pct">0</span>%</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Still Water, home">
+ <span class="seal" aria-hidden="true">静水</span>
+ <span class="brand-name">Still Water</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#rooms">Rooms</a>
+ <a href="#kaiseki">Kaiseki &amp; tea</a>
+ <a href="#seasons">Seasons</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="true" aria-label="Water sounds">
+ <span class="sound-bars" aria-hidden="true"><i></i><i></i><i></i></span><span class="sound-label">Sound</span>
+ </button>
+ <a class="btn btn-ink" href="#reserve" data-magnetic>Reserve</a>
+ </div>
+ </header>
+
+ <main id="top">
+ <!-- Hero -->
+ <section class="hero" data-key="hero">
+ <div class="hero-copy">
+ <p class="eyebrow">Ryokan · Higashiyama, Kyoto<span class="hide-m"> · Since 1824</span></p>
+ <h1 class="title">
+ <span class="line">Seven rooms.</span>
+ <span class="line">One pond.</span>
+ <span class="line"><em>No clocks.</em></span>
+ </h1>
+ <p class="sub">A seven-room inn built around a koi pond fed by the same mountain spring for two hundred years. Stay long enough and you stop counting the hours, and start counting the fish.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#reserve" data-magnetic>Reserve a room</a>
+ <a class="btn btn-ghost" href="#rooms" data-magnetic>See the rooms</a>
+ </div>
+ </div>
+ <div class="hint" aria-hidden="true">
+ <span class="hint-ring"><i></i><i></i></span>
+ <ul>
+ <li class="hint-draw"><b>Draw</b> a finger through the water</li>
+ <li class="hint-feed"><b>Click</b> to scatter food for the koi</li>
+ <li class="hint-still"><b>Hold still</b> — they come to you</li>
+ </ul>
+ </div>
+ <div class="scroll-cue" aria-hidden="true"><span>Drift across the pond</span><i></i></div>
+ </section>
+
+ <!-- Rooms -->
+ <section class="rooms" id="rooms">
+ <div class="pin">
+ <div class="paper rooms-paper">
+ <header class="sec-head">
+ <p class="eyebrow">The rooms <span class="jp">部屋</span></p>
+ <h2>Every room opens onto the water.</h2>
+ <p class="lede">Seven rooms in three kinds, each with its own veranda over the pond. No televisions, no clocks. The light tells you the time, and the koi tell you when it is morning.</p>
+ </header>
+ <div class="room-deck">
+ <article class="room is-on" data-room="0">
+ <figure><img src="../../img/koi/room-moss.webp" alt="A tatami room with shoji open onto a moss garden and the edge of the pond" loading="lazy"></figure>
+ <div class="room-body">
+ <p class="room-kind"><span class="jp-big" aria-hidden="true">苔</span><span>Koke · three rooms</span></p>
+ <h3>Moss</h3>
+ <p>Ground floor on the north bank, where the cushion moss runs right up to the cedar boards of the veranda. Tatami for two, a deep hinoki tub, shoji that slide away entirely. The quietest rooms in the house.</p>
+ <p class="room-meta"><span>28 m²</span><span>2 guests</span><span>Garden bath</span></p>
+ <p class="price">from <b>¥68,000</b> / night, dinner &amp; breakfast</p>
+ </div>
+ </article>
+ <article class="room" data-room="1">
+ <figure><img src="../../img/koi/room-maple.webp" alt="A ryokan room with a cedar tub and a red maple framed by the window" loading="lazy"></figure>
+ <div class="room-body">
+ <p class="room-kind"><span class="jp-big" aria-hidden="true">紅葉</span><span>Momiji · two rooms</span></p>
+ <h3>Maple</h3>
+ <p>Under the hundred-and-forty-year-old momiji. In the third week of November its leaves fall onto the water outside your window, and for nine days the pond is more vermilion than green.</p>
+ <p class="room-meta"><span>34 m²</span><span>2–3 guests</span><span>Cedar soaking tub</span></p>
+ <p class="price">from <b>¥84,000</b> / night, dinner &amp; breakfast</p>
+ </div>
+ </article>
+ <article class="room" data-room="2">
+ <figure><img src="../../img/koi/room-moon.webp" alt="An upper room at night opening onto a moon-viewing deck over the pond" loading="lazy"></figure>
+ <div class="room-body">
+ <p class="room-kind"><span class="jp-big" aria-hidden="true">月</span><span>Tsuki · two rooms</span></p>
+ <h3>Moon</h3>
+ <p>The upper floor, with a moon-viewing deck built out over the pond. On clear nights the moon sits in the black water directly beneath you, and the stone lantern is lit at dusk.</p>
+ <p class="room-meta"><span>41 m²</span><span>2 guests</span><span>Private tsukimi deck</span></p>
+ <p class="price">from <b>¥112,000</b> / night, dinner &amp; breakfast</p>
+ </div>
+ </article>
+ </div>
+ <ol class="room-dots" aria-hidden="true"><li class="is-on">Moss</li><li>Maple</li><li>Moon</li></ol>
+ </div>
+ </div>
+ <div class="steps"><div class="step" data-key="moss"></div><div class="step" data-key="maple"></div><div class="step" data-key="moon"></div></div>
+ </section>
+
+ <!-- Kaiseki & tea -->
+ <section class="kaiseki" id="kaiseki" data-key="kaiseki">
+ <p class="vert vert-kaiseki" aria-hidden="true">懐石と茶</p>
+ <div class="paper paper-dark kaiseki-paper">
+ <p class="eyebrow">Kaiseki &amp; tea <span class="jp">懐石</span></p>
+ <h2>Dinner arrives in nine courses, and in no hurry.</h2>
+ <p class="lede">Chef Aoki Ren has cooked in this kitchen for twenty-two years. The old calendar has seventy-two seasons of five days each, and his menu follows every one of them.</p>
+ <ol class="menu">
+ <li><span class="jp">先付</span><b>Sakizuke</b><span>Sesame tofu, fresh wasabi, one chrysanthemum petal</span></li>
+ <li><span class="jp">八寸</span><b>Hassun</b><span>The fortnight on a cedar tray: ginkgo, persimmon, grilled sweetfish</span></li>
+ <li><span class="jp">焼物</span><b>Yakimono</b><span>Spanish mackerel over binchō charcoal, yuzu miso</span></li>
+ <li><span class="jp">止椀</span><b>Tomewan</b><span>Red miso with clams from Lake Biwa, rice from the Tamba hills</span></li>
+ </ol>
+ <div class="tea">
+ <p class="tea-time">06:10</p>
+ <p><b>Tea at first light.</b> Before breakfast the tea master whisks matcha on the flat stone beside the lantern. Guests sit on the moss in borrowed haori. The koi come to the edge to see who is up.</p>
+ </div>
+ <div class="stats">
+ <div><b>9</b><span>courses at dinner</span></div>
+ <div><b>72</b><span>micro-seasons a year</span></div>
+ <div><b>1</b><span>seating, at dusk</span></div>
+ </div>
+ </div>
+ </section>
+
+ <!-- Seasons -->
+ <section class="seasons" id="seasons">
+ <div class="pin">
+ <div class="season-kanji" aria-hidden="true"><span class="is-on">春</span><span>夏</span><span>秋</span><span>冬</span></div>
+ <div class="paper season-paper">
+ <p class="eyebrow">The seasons at Still Water <span class="jp">四季</span></p>
+ <h2>The same pond, four times a year.</h2>
+ <ol class="season-list">
+ <li class="is-on"><p class="s-name"><span>Spring</span><em>March – April</em></p><p>Cherry petals drift over the wall from the temple next door and gather in the corners of the pond. The koi wake up hungry.</p></li>
+ <li><p class="s-name"><span>Summer</span><em>June – August</em></p><p>The lotus open at dawn and close by noon. Fireflies over the water in the first week of July, and the veranda doors stay open all night.</p></li>
+ <li><p class="s-name"><span>Autumn</span><em>October – November</em></p><p>The maple turns. Nine days when the pond is more red than green; most guests book them a year ahead.</p></li>
+ <li><p class="s-name"><span>Winter</span><em>December – February</em></p><p>Snow on the lantern’s roof. The koi rest deep and slow under the ice-cold spring, and the house is at its most silent.</p></li>
+ </ol>
+ </div>
+ </div>
+ <div class="steps"><div class="step" data-key="spring"></div><div class="step" data-key="summer"></div><div class="step" data-key="autumn"></div><div class="step" data-key="winter"></div></div>
+ </section>
+
+ <!-- Reserve -->
+ <section class="reserve" id="reserve" data-key="reserve">
+ <div class="paper reserve-paper">
+ <p class="eyebrow">Reservations <span class="jp">予約</span></p>
+ <h2>The pond keeps its own time. <em>Come and keep it with us.</em></h2>
+ <form class="booking" novalidate>
+ <label><span>Arrival</span><input type="date" name="arrival" value="2026-11-18"></label>
+ <label><span>Nights</span>
+ <select name="nights"><option>1</option><option selected>2</option><option>3</option><option>4</option><option>5</option><option>7</option></select></label>
+ <label><span>Guests</span>
+ <select name="guests"><option>1</option><option selected>2</option><option>3</option></select></label>
+ <label><span>Room</span>
+ <select name="room"><option>Moss</option><option selected>Maple</option><option>Moon</option></select></label>
+ <button class="btn btn-solid" type="submit" data-magnetic>Request a stay</button>
+ </form>
+ <p class="fine">We answer every request by hand within a day. Nothing is charged until we write back to confirm.</p>
+ </div>
+ </section>
+
+ <footer class="foot" data-key="foot">
+ <div class="foot-inner">
+ <p class="foot-mark"><span class="jp">静水</span> Still Water</p>
+ <div class="foot-cols">
+ <p>12 Shimokawara-chō<br>Higashiyama-ku, Kyoto 605-0825<br>Five minutes’ walk from Kōdai-ji</p>
+ <p>+81 75 555 0142<br>[email protected]<br>Check-in 15:00 · Check-out 11:00</p>
+ <p>There are no clocks in the rooms.<br>We will knock when dinner is ready.</p>
+ <nav aria-label="Footer"><a href="#rooms">Rooms</a><a href="#kaiseki">Kaiseki</a><a href="#seasons">Seasons</a><a href="#reserve">Reserve</a></nav>
+ </div>
+ <p class="fine foot-fine">© 2026 Still Water Ryokan · The koi are not for sale; please do not ask.</p>
+ </div>
+ </footer>
+ </main>
+
+ <div class="toast" role="status"></div>
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/koi/koi.js b/examples/koi/koi.js
new file mode 100644
index 0000000..a2810ae
--- /dev/null
+++ b/examples/koi/koi.js
@@ -0,0 +1,363 @@
+// Koi: each Meshy fish is re-parameterised along an automatically extracted spine (arc length s, lateral, vertical,
+// along offsets), so the vertex shader can bend it along a live follow-the-leader chain with a travelling body wave.
+import * as THREE from 'three';
+import { firstMesh } from '../../src/core/assets.js';
+import { patchUnder } from './water.js';
+import { pondSDF } from './shape.js';
+
+export const SEG = 24;
+
+// ─── Spine extraction ──────────────────────────────────────────────────────────
+function extractSpine(P, n, index) {
+ let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity;
+ for (let i = 0; i < n; i++) { const x = P[i * 3], z = P[i * 3 + 2]; x0 = Math.min(x0, x); x1 = Math.max(x1, x); z0 = Math.min(z0, z); z1 = Math.max(z1, z); }
+ const G = 160, cs = Math.max(x1 - x0, z1 - z0) / (G - 8), ox = x0 - 4 * cs, oz = z0 - 4 * cs;
+ const ymin = new Float32Array(G * G).fill(1e9), ymax = new Float32Array(G * G).fill(-1e9), cnt = new Uint32Array(G * G);
+ // Rasterise every triangle's top-down footprint so thin fins stay connected.
+ const tri = index.count / 3;
+ for (let f = 0; f < tri; f++) {
+ const a = index.getX(f * 3) * 3, b = index.getX(f * 3 + 1) * 3, c = index.getX(f * 3 + 2) * 3;
+ const ax = (P[a] - ox) / cs, az = (P[a + 2] - oz) / cs, bx = (P[b] - ox) / cs, bz = (P[b + 2] - oz) / cs, cx = (P[c] - ox) / cs, cz = (P[c + 2] - oz) / cs;
+ const i0 = Math.max(0, Math.floor(Math.min(ax, bx, cx))), i1 = Math.min(G - 1, Math.floor(Math.max(ax, bx, cx)));
+ const j0 = Math.max(0, Math.floor(Math.min(az, bz, cz))), j1 = Math.min(G - 1, Math.floor(Math.max(az, bz, cz)));
+ const ya = P[a + 1], yb = P[b + 1], yc = P[c + 1];
+ const den = (bz - cz) * (ax - cx) + (cx - bx) * (az - cz);
+ for (let j = j0; j <= j1; j++) for (let i = i0; i <= i1; i++) {
+ const px = i + 0.5, pz = j + 0.5;
+ let y;
+ if (i0 === i1 && j0 === j1) y = (ya + yb + yc) / 3;
+ else {
+ if (Math.abs(den) < 1e-12) continue;
+ const w1 = ((bz - cz) * (px - cx) + (cx - bx) * (pz - cz)) / den, w2 = ((cz - az) * (px - cx) + (ax - cx) * (pz - cz)) / den, w3 = 1 - w1 - w2;
+ if (w1 < -0.02 || w2 < -0.02 || w3 < -0.02) continue;
+ y = ya * w1 + yb * w2 + yc * w3;
+ }
+ const k = j * G + i;
+ ymin[k] = Math.min(ymin[k], y); ymax[k] = Math.max(ymax[k], y); cnt[k]++;
+ }
+ // always mark the vertices' own cells too (tiny triangles)
+ for (const [vx, vz, vy] of [[ax, az, ya], [bx, bz, yb], [cx, cz, yc]]) {
+ const k = Math.floor(vz) * G + Math.floor(vx);
+ ymin[k] = Math.min(ymin[k], vy); ymax[k] = Math.max(ymax[k], vy); cnt[k]++;
+ }
+ }
+ const occ = new Uint8Array(G * G), thick = new Float32Array(G * G);
+ for (let j = 1; j < G - 1; j++) for (let i = 1; i < G - 1; i++) {
+ const k = j * G + i;
+ if (cnt[k]) { occ[k] = 1; thick[k] = ymax[k] - ymin[k]; continue; }
+ // one-cell closing so fins and body stay connected
+ let c = 0; for (const d of [-1, 1, -G, G]) if (cnt[k + d]) c++;
+ if (c >= 2) occ[k] = 1;
+ }
+ let maxT = 0; for (let k = 0; k < G * G; k++) maxT = Math.max(maxT, thick[k]);
+ let head = -1;
+ for (let k = G * G - 1; k >= 0; k--) if (thick[k] > maxT * 0.42) { head = k; break; } // highest z row first
+ // Dijkstra over the occupancy grid (8-connected)
+ const dist = new Float64Array(G * G).fill(Infinity);
+ dist[head] = 0;
+ const heap = [[0, head]];
+ const push = (d, k) => { heap.push([d, k]); let i = heap.length - 1; while (i > 0) { const p = (i - 1) >> 1; if (heap[p][0] <= heap[i][0]) break; [heap[p], heap[i]] = [heap[i], heap[p]]; i = p; } };
+ const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2 * i + 1, r = l + 1; let m = i; if (l < heap.length && heap[l][0] < heap[m][0]) m = l; if (r < heap.length && heap[r][0] < heap[m][0]) m = r; if (m === i) break; [heap[m], heap[i]] = [heap[i], heap[m]]; i = m; } } return top; };
+ const nb = [[1, 0, 1], [-1, 0, 1], [0, 1, 1], [0, -1, 1], [1, 1, 1.414], [1, -1, 1.414], [-1, 1, 1.414], [-1, -1, 1.414]];
+ while (heap.length) {
+ const [d, k] = pop();
+ if (d > dist[k]) continue;
+ const i = k % G, j = (k / G) | 0;
+ for (const [di, dj, w] of nb) {
+ const ii = i + di, jj = j + dj; if (ii < 0 || jj < 0 || ii >= G || jj >= G) continue;
+ const kk = jj * G + ii; if (!occ[kk]) continue;
+ const nd = d + w; if (nd < dist[kk]) { dist[kk] = nd; push(nd, kk); }
+ }
+ }
+ let maxD = 0; for (let k = 0; k < G * G; k++) if (occ[k] && dist[k] < Infinity) maxD = Math.max(maxD, dist[k]);
+ const B = 44, sx = new Float64Array(B), sz = new Float64Array(B), sy = new Float64Array(B), sw = new Float64Array(B), syw = new Float64Array(B);
+ for (let k = 0; k < G * G; k++) {
+ if (!occ[k] || dist[k] === Infinity) continue;
+ const b = Math.min(B - 1, Math.floor(dist[k] / maxD * B));
+ const w = thick[k] * thick[k] + 1e-6 * maxT * maxT;
+ const cx = ox + ((k % G) + 0.5) * cs, cz = oz + (((k / G) | 0) + 0.5) * cs;
+ sx[b] += cx * w; sz[b] += cz * w; sw[b] += w;
+ if (cnt[k]) { sy[b] += (ymin[k] + ymax[k]) * 0.5 * w; syw[b] += w; }
+ }
+ let pts = [];
+ const hx = ox + ((head % G) + 0.5) * cs, hz = oz + (((head / G) | 0) + 0.5) * cs;
+ pts.push([hx, 0, hz]);
+ for (let b = 0; b < B; b++) if (sw[b] > 0) pts.push([sx[b] / sw[b], syw[b] ? sy[b] / syw[b] : 0, sz[b] / sw[b]]);
+ pts[0][1] = pts[1][1];
+ for (let it = 0; it < 6; it++) pts = pts.map((p, i) => (i === 0 || i === pts.length - 1) ? p : p.map((v, c) => pts[i - 1][c] * 0.25 + v * 0.5 + pts[i + 1][c] * 0.25));
+ // resample by arc length
+ const cum = [0];
+ for (let i = 1; i < pts.length; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][2] - pts[i - 1][2]));
+ const L = cum[cum.length - 1];
+ const out = [];
+ for (let s = 0; s < SEG; s++) {
+ const t = s / (SEG - 1) * L;
+ let i = 1; while (i < cum.length - 1 && cum[i] < t) i++;
+ const f = (t - cum[i - 1]) / Math.max(cum[i] - cum[i - 1], 1e-9);
+ out.push(pts[i - 1].map((v, c) => v + (pts[i][c] - v) * f));
+ }
+ return { pts: out, length: L };
+}
+
+function tangents(pts) {
+ return pts.map((p, i) => {
+ const a = pts[Math.max(0, i - 1)], b = pts[Math.min(pts.length - 1, i + 1)];
+ const dx = a[0] - b[0], dz = a[2] - b[2], l = Math.hypot(dx, dz) || 1;
+ return [dx / l, dz / l]; // toward the head
+ });
+}
+
+/** Re-express a fish mesh in spine coordinates. Returns a prototype shared by all instances of that variety. */
+export function koiPrototype(gltf) {
+ const src = firstMesh(gltf.scene);
+ gltf.scene.updateMatrixWorld(true);
+ const g = src.geometry;
+ const n = g.attributes.position.count;
+ const P = new Float32Array(n * 3), Nn = new Float32Array(n * 3);
+ const v = new THREE.Vector3(), nm = new THREE.Matrix3().getNormalMatrix(src.matrixWorld);
+ for (let i = 0; i < n; i++) {
+ v.fromBufferAttribute(g.attributes.position, i).applyMatrix4(src.matrixWorld); P.set([v.x, v.y, v.z], i * 3);
+ v.fromBufferAttribute(g.attributes.normal, i).applyMatrix3(nm).normalize(); Nn.set([v.x, v.y, v.z], i * 3);
+ }
+ const { pts, length } = extractSpine(P, n, g.index);
+ const T = tangents(pts);
+ const cum = [0]; for (let i = 1; i < SEG; i++) cum.push(cum[i - 1] + Math.hypot(pts[i][0] - pts[i - 1][0], pts[i][2] - pts[i - 1][2]));
+ const pos = new Float32Array(n * 3), nor = new Float32Array(n * 3), aS = new Float32Array(n);
+ for (let k = 0; k < n; k++) {
+ const x = P[k * 3], y = P[k * 3 + 1], z = P[k * 3 + 2];
+ let best = Infinity, bi = 0, bt = 0;
+ for (let i = 0; i < SEG - 1; i++) {
+ const ax = pts[i][0], az = pts[i][2], bx = pts[i + 1][0] - ax, bz = pts[i + 1][2] - az;
+ const t = Math.min(1, Math.max(0, ((x - ax) * bx + (z - az) * bz) / (bx * bx + bz * bz)));
+ const dx = x - ax - bx * t, dz = z - az - bz * t, d = dx * dx + dz * dz;
+ if (d < best) { best = d; bi = i; bt = t; }
+ }
+ const a = pts[bi], b = pts[bi + 1];
+ const px = a[0] + (b[0] - a[0]) * bt, py = a[1] + (b[1] - a[1]) * bt, pz = a[2] + (b[2] - a[2]) * bt;
+ let tx = T[bi][0] + (T[bi + 1][0] - T[bi][0]) * bt, tz = T[bi][1] + (T[bi + 1][1] - T[bi][1]) * bt;
+ const tl = Math.hypot(tx, tz) || 1; tx /= tl; tz /= tl;
+ const nx = tz, nz = -tx; // lateral axis
+ const ox = x - px, oy = y - py, oz = z - pz;
+ pos.set([(ox * nx + oz * nz) / length, oy / length, (ox * tx + oz * tz) / length], k * 3);
+ const qx = Nn[k * 3], qy = Nn[k * 3 + 1], qz = Nn[k * 3 + 2];
+ nor.set([qx * nx + qz * nz, qy, qx * tx + qz * tz], k * 3);
+ aS[k] = (cum[bi] + (cum[bi + 1] - cum[bi]) * bt) / length;
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('normal', new THREE.BufferAttribute(nor, 3));
+ geo.setAttribute('uv', g.attributes.uv);
+ geo.setAttribute('aS', new THREE.BufferAttribute(aS, 1));
+ geo.setIndex(g.index);
+ geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(), 1e4);
+ return { geometry: geo, material: src.material, restSpine: pts, length };
+}
+
+const FRAME_GLSL = /* glsl */`
+ attribute float aS;
+ uniform vec4 uSp[${SEG}];
+ uniform float uScale;
+ void koiFrame(float s, out vec3 P, out vec3 T, out vec3 N){
+ float f = clamp(s, 0., 1.) * ${(SEG - 1).toFixed(1)};
+ int i = int(min(floor(f), ${(SEG - 2).toFixed(1)}));
+ float t = f - float(i);
+ vec4 a = uSp[i], b = uSp[i + 1];
+ P = mix(a.xyz, b.xyz, t);
+ vec2 d = normalize(mix(vec2(sin(a.w), cos(a.w)), vec2(sin(b.w), cos(b.w)), t));
+ T = vec3(d.x, 0., d.y);
+ N = vec3(T.z, 0., -T.x);
+ }
+`;
+const BEGIN = /* glsl */`
+ vec3 kP, kT, kN; koiFrame(aS, kP, kT, kN);
+ vec3 transformed = kP + (kN * position.x + vec3(0., 1., 0.) * position.y + kT * position.z) * uScale;
+`;
+const BEGIN_NORMAL = /* glsl */`
+ vec3 kP0, kT0, kN0; koiFrame(aS, kP0, kT0, kN0);
+ vec3 objectNormal = kN0 * normal.x + vec3(0., 1., 0.) * normal.y + kT0 * normal.z;
+`;
+
+/** Pond-wide steering for the school. */
+export class School {
+ constructor({ protos, specs, env }) {
+ this.fish = specs.map((s, i) => new Koi(protos[s.kind], s, i, env));
+ this.food = []; // { x, z, eaten, t, owner }
+ this.pointer = null; // { x, z, speed, on }
+ this.time = 0;
+ }
+ update(dt, t, hooks) {
+ this.time = t;
+ for (const f of this.fish) f.think(dt, t, this, hooks);
+ for (const f of this.fish) f.move(dt, t, hooks);
+ }
+}
+
+let seedN = 0;
+export class Koi {
+ constructor(proto, spec, i, env) {
+ this.i = i;
+ this.len = spec.len;
+ const mat = proto.material.clone();
+ if (spec.tint) mat.color = new THREE.Color(spec.tint);
+ mat.envMapIntensity = spec.env ?? 1.0;
+ if (spec.rough != null) mat.roughness = spec.rough;
+ if (spec.metal != null) mat.metalness = spec.metal;
+ this.uniforms = { uSp: { value: Array.from({ length: SEG }, () => new THREE.Vector4()) }, uScale: { value: spec.len } };
+ const u = this.uniforms;
+ patchUnder(mat, {
+ key: 'koi',
+ extraVertexHead: FRAME_GLSL,
+ custom: {
+ uniforms: u,
+ patch: sh => {
+ sh.vertexShader = sh.vertexShader.replace('#include <beginnormal_vertex>', BEGIN_NORMAL).replace('#include <begin_vertex>', BEGIN);
+ },
+ },
+ });
+ const depthMat = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking });
+ depthMat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, u);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\n' + FRAME_GLSL).replace('#include <begin_vertex>', BEGIN);
+ };
+ depthMat.customProgramCacheKey = () => 'koidepth';
+ this.mesh = new THREE.Mesh(proto.geometry, mat);
+ this.mesh.customDepthMaterial = depthMat;
+ this.mesh.frustumCulled = false;
+ this.mesh.castShadow = true;
+ this.mesh.receiveShadow = true;
+ this.env = env;
+ // state
+ this.x = spec.x; this.z = spec.z; this.head = spec.heading ?? Math.random() * 6.28;
+ this.speed = 0.12; this.tSpeed = 0.15;
+ this.cruiseDepth = spec.depth; this.y = spec.depth; this.tY = spec.depth;
+ this.phase = Math.random() * 10;
+ this.seed = ++seedN * 17.13 + Math.random() * 100;
+ this.turn = 0;
+ this.mode = 'cruise';
+ this.target = null;
+ this.gulp = 0;
+ this.startle = 0;
+ this.chain = new Float32Array(SEG * 3);
+ this.render = new Float32Array(SEG * 3);
+ const seg = this.len / (SEG - 1);
+ for (let k = 0; k < SEG; k++) {
+ this.chain[k * 3] = this.x - Math.sin(this.head) * seg * k;
+ this.chain[k * 3 + 1] = this.y;
+ this.chain[k * 3 + 2] = this.z - Math.cos(this.head) * seg * k;
+ }
+ }
+
+ think(dt, t, school, hooks) {
+ const fx = Math.sin(this.head), fz = Math.cos(this.head);
+ let dx = fx, dz = fz; // desired direction
+ // wander: slow smooth noise in the turning rate
+ const w = Math.sin(t * 0.21 + this.seed) * 0.6 + Math.sin(t * 0.53 + this.seed * 1.7) * 0.4;
+ const wa = this.head + w * 0.9;
+ dx += Math.sin(wa) * 0.8; dz += Math.cos(wa) * 0.8;
+ // shoreline: look ahead and steer down the distance gradient
+ const ax = this.x + fx * (0.6 + this.speed * 1.5), az = this.z + fz * (0.6 + this.speed * 1.5);
+ const d = pondSDF(ax, az);
+ if (d > -0.9) {
+ const e = 0.05, gx = pondSDF(ax + e, az) - pondSDF(ax - e, az), gz = pondSDF(ax, az + e) - pondSDF(ax, az - e);
+ const gl = Math.hypot(gx, gz) || 1, k = (d + 0.9) * 4.5;
+ dx -= gx / gl * k; dz -= gz / gl * k;
+ }
+ for (const o of this.env.avoid) { // lantern rock, stepping stones
+ const ox = this.x - o.x, oz = this.z - o.z, od = Math.hypot(ox, oz);
+ if (od < o.r + 0.6) { const k = (o.r + 0.6 - od) * 3; dx += ox / od * k; dz += oz / od * k; }
+ }
+ // koi drift toward wherever people are looking (they expect to be fed)
+ const home = school.home;
+ if (home) {
+ const hx = home.x - this.x, hz = home.z - this.z, hd = Math.hypot(hx, hz) || 1;
+ const k = Math.min(1, Math.max(0, (hd - home.w * 0.28) / 2.5)) * 1.6;
+ dx += hx / hd * k; dz += hz / hd * k;
+ }
+ // separation from the others (mid-body positions)
+ for (const f of school.fish) {
+ if (f === this) continue;
+ const ox = this.x - f.x, oz = this.z - f.z, od = Math.hypot(ox, oz);
+ const r = (this.len + f.len) * 0.55;
+ if (od < r && od > 1e-4) { const k = (r - od) / r * (this.mode === 'seek' ? 1.5 : 2.4) * (Math.abs(this.y - f.y) < 0.14 ? 1 : 0.3); dx += ox / od * k; dz += oz / od * k; }
+ }
+ this.tSpeed = 0.13 + (Math.sin(t * 0.17 + this.seed * 3.1) * 0.5 + 0.5) * 0.14;
+ this.tY = this.cruiseDepth + Math.sin(t * 0.11 + this.seed) * 0.12;
+ // food
+ let best = null, bd = 7.5;
+ for (const p of school.food) {
+ if (p.eaten || t < p.t + 0.25 + Math.hypot(p.x - this.x, p.z - this.z) * 0.18) continue; // ripples reach them after a beat
+ const pd = Math.hypot(p.x - this.x, p.z - this.z);
+ if (pd < bd) { bd = pd; best = p; }
+ }
+ if (best) {
+ this.mode = 'seek';
+ const hx = this.chain[0], hz = this.chain[2];
+ const px = best.x - hx, pz = best.z - hz, pd = Math.hypot(px, pz) || 1;
+ dx = dx * 0.25 + px / pd * 3.2; dz = dz * 0.25 + pz / pd * 3.2;
+ this.tSpeed = pd > 0.6 ? 0.62 + (this.i % 3) * 0.09 : 0.2 + pd * 0.5;
+ this.tY = (pd < 0.9 ? -0.06 - pd * 0.12 : -0.22) - (this.i % 3) * 0.08;
+ if (pd < 0.09 + this.len * 0.05) {
+ best.eaten = true; this.gulp = 1; hooks.eat?.(best, this);
+ }
+ } else if (this.mode === 'seek') this.mode = 'cruise';
+ // the visitor's hand: a slow hand is interesting, a fast one is not
+ const p = school.pointer;
+ if (p?.on) {
+ const ox = this.x - p.x, oz = this.z - p.z, od = Math.hypot(ox, oz);
+ if (p.speed > 1.4 && od < 0.9) { this.startle = 1; const k = 4; dx += ox / od * k; dz += oz / od * k; }
+ else if (p.speed < 0.35 && od < 2.6 && !best) {
+ const k = (od > 0.3 ? 0.9 : -0.4) * (1 - od / 2.6); dx -= ox / od * k; dz -= oz / od * k;
+ this.tY = Math.max(this.tY, od < 0.7 ? -0.07 : -0.28);
+ this.tSpeed = Math.min(this.tSpeed, 0.1 + od * 0.1);
+ // close under a still hand they come up and mouth at the surface
+ const hx = this.chain[0], hz = this.chain[2];
+ if (od < 0.75 && this.y > -0.12 && Math.random() < dt * 1.3) hooks.kiss?.(this, hx, hz);
+ }
+ }
+ if (this.startle > 0.01) { this.tSpeed = Math.max(this.tSpeed, 0.4 + this.startle * 1.1); this.startle *= Math.exp(-dt * 1.6); this.tY = Math.min(this.tY, this.cruiseDepth - 0.15); }
+ if (this.gulp > 0) { this.gulp = Math.max(0, this.gulp - dt * 1.4); this.tY = -0.04; }
+ // turn toward desired heading, rate-limited
+ const want = Math.atan2(dx, dz);
+ let da = want - this.head; da = Math.atan2(Math.sin(da), Math.cos(da));
+ const maxTurn = 0.8 + this.speed * 3.2;
+ const tr = Math.max(-maxTurn, Math.min(maxTurn, da * 2.2));
+ this.turn += (tr - this.turn) * (1 - Math.exp(-dt * 4));
+ this.head += this.turn * dt;
+ }
+
+ move(dt, t, hooks) {
+ const acc = this.tSpeed > this.speed ? 1.6 : 0.9;
+ this.speed += (this.tSpeed - this.speed) * (1 - Math.exp(-dt * acc));
+ this.y += (this.tY - this.y) * (1 - Math.exp(-dt * 1.1));
+ this.x += Math.sin(this.head) * this.speed * dt;
+ this.z += Math.cos(this.head) * this.speed * dt;
+ const c = this.chain, seg = this.len / (SEG - 1);
+ c[0] = this.x; c[1] = this.y; c[2] = this.z;
+ for (let k = 1; k < SEG; k++) {
+ const i = k * 3;
+ let dx = c[i] - c[i - 3], dz = c[i + 2] - c[i - 1];
+ const l = Math.hypot(dx, dz) || 1;
+ c[i] = c[i - 3] + dx / l * seg; c[i + 2] = c[i - 1] + dz / l * seg;
+ c[i + 1] += (c[i - 2] - c[i + 1]) * Math.min(1, dt * 9);
+ }
+ // travelling body wave; amplitude grows toward the tail and with effort
+ const effort = Math.min(1, this.speed / 0.8) + Math.abs(this.turn) * 0.15;
+ const freq = 0.45 + this.speed * 2.6;
+ this.phase += dt * freq * Math.PI * 2;
+ const amp = this.len * (0.03 + effort * 0.075);
+ const r = this.render;
+ for (let k = 0; k < SEG; k++) {
+ const s = k / (SEG - 1), i = k * 3;
+ const a = Math.max(0, k - 1) * 3, b = Math.min(SEG - 1, k + 1) * 3;
+ let tx = c[a] - c[b], tz = c[a + 2] - c[b + 2]; const tl = Math.hypot(tx, tz) || 1; tx /= tl; tz /= tl;
+ const lat = amp * (0.12 + 0.88 * s * s) * Math.sin(this.phase - s * Math.PI * 1.7);
+ r[i] = c[i] + tz * lat; r[i + 1] = c[i + 1]; r[i + 2] = c[i + 2] - tx * lat;
+ }
+ const U = this.uniforms.uSp.value;
+ for (let k = 0; k < SEG; k++) {
+ const a = Math.max(0, k - 1) * 3, b = Math.min(SEG - 1, k + 1) * 3;
+ U[k].set(r[k * 3], r[k * 3 + 1], r[k * 3 + 2], Math.atan2(r[a] - r[b], r[a + 2] - r[b + 2]));
+ }
+ if (this.y > -0.2 && this.speed > 0.25) hooks.wake?.(this, c[0], c[2], c[3], c[5]);
+ }
+}
diff --git a/examples/koi/main.js b/examples/koi/main.js
new file mode 100644
index 0000000..89a4269
--- /dev/null
+++ b/examples/koi/main.js
@@ -0,0 +1,553 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { fbmTexture } from '../../src/core/textures.js';
+import { RippleSim, waterMaterial, causticTexture, microTexture, underShared, patchUnder } from './water.js';
+import { koiPrototype, School } from './koi.js';
+import { Flora, patchFloat } from './flora.js';
+import { MapleBranch } from './maple.js';
+import { buildTerrain, terrainTextures, rockMaterial, buildRocks, gardenShared, buildEnclosure } from './garden.js';
+import { terrainH, pondSDF, LANTERN } from './shape.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+
+const DBG = new URLSearchParams(location.search);
+const D = Math.PI / 180;
+const isTouch = matchMedia('(pointer: coarse)').matches;
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 32, near: 0.05, far: 90, dpr: 1.5, background: 0x0b1511,
+ post: {
+ ao: { aoRadius: 0.5, intensity: 1.6, distanceFalloff: 0.5 },
+ bloom: { intensity: 0.55, luminanceThreshold: 0.92, luminanceSmoothing: 0.25, radius: 0.62 },
+ vignette: { offset: 0.28, darkness: 0.58 },
+ noise: 0.04,
+ ca: 0.0005,
+ tone: 'agx',
+ },
+});
+const { scene, camera, renderer } = engine;
+const under = new THREE.Scene();
+renderer.shadowMap.autoUpdate = true;
+
+const envMain = studioEnvironment(renderer, {
+ top: 0x9fb3bf, bottom: 0x18200f,
+ panels: [{ pos: [2, 8, -5], size: [9, 6], intensity: 3.2, color: 0xfff3e0 }, { pos: [-7, 4, 2], size: [4, 6], intensity: 1.2, color: 0xd8e6ff }],
+});
+const envUnder = studioEnvironment(renderer, {
+ top: 0x7fa090, bottom: 0x040a07,
+ panels: [{ pos: [0, 9, -2], size: [10, 10], intensity: 2.2, color: 0xe4f4ea }],
+});
+scene.environment = envMain; scene.environmentIntensity = 0.55;
+under.environment = envUnder; under.environmentIntensity = 0.5;
+
+// Key light (sun by day, moon by night): one per scene, same parameters.
+function makeKey() {
+ const l = new THREE.DirectionalLight(0xfff3dd, 3.5);
+ l.castShadow = true;
+ l.shadow.mapSize.set(3072, 3072);
+ const c = l.shadow.camera; c.left = -12; c.right = 12; c.top = 12; c.bottom = -12; c.near = 1; c.far = 110;
+ l.shadow.bias = -0.00025; l.shadow.normalBias = 0.02; l.shadow.radius = 2;
+ return l;
+}
+const keyMain = makeKey(), keyUnder = makeKey();
+keyUnder.shadow.bias = -0.0004;
+scene.add(keyMain, keyMain.target); under.add(keyUnder, keyUnder.target);
+const hemiMain = new THREE.HemisphereLight(0xcfe0ea, 0x2a3318, 0.35);
+const hemiUnder = new THREE.HemisphereLight(0x9fc4b0, 0x0a140e, 0.3);
+scene.add(hemiMain); under.add(hemiUnder);
+const lampMain = new THREE.PointLight(0xffa24a, 0, 9, 1.4);
+const lampUnder = new THREE.PointLight(0xffa24a, 0, 7, 1.6);
+scene.add(lampMain); under.add(lampUnder);
+
+// ─── Loading ───────────────────────────────────────────────────────────────────
+const assets = new Assets();
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ },
+ exit: async () => {
+ loaderEl.classList.add('out');
+ await gsap.to(loaderEl, { autoAlpha: 0, duration: 1.4, ease: 'power2.inOut', delay: 0.35 });
+ },
+});
+
+// ─── Water ─────────────────────────────────────────────────────────────────────
+const sim = new RippleSim(renderer, { res: DBG.has('lowsim') ? 512 : 1024, x0: -10.5, z0: -8.5, size: 21 });
+underShared.uSurf.value = sim.texture;
+underShared.uSimRect.value.copy(sim.rect);
+underShared.uCaust.value = causticTexture(renderer);
+underShared.uFocus.value = 0.045;
+
+// The maple canopy lives on a plane 6.5 m above the water; reflections and dapple both look it up.
+const CANOPY = { x0: -12, z0: -9.5, w: 16, h: 14.5 };
+const canopyMat = new THREE.Matrix3().set(1 / CANOPY.w, 0, -CANOPY.x0 / CANOPY.w, 0, -1 / CANOPY.h, 1 + CANOPY.z0 / CANOPY.h, 0, 0, 1);
+underShared.uCanopyMat.value = canopyMat;
+
+const underRT = new THREE.WebGLRenderTarget(4, 4, { type: THREE.HalfFloatType, samples: 4 });
+const W = {
+ uUnder: { value: underRT.texture }, uUnderSize: { value: new THREE.Vector2(4, 4) },
+ uSurf: { value: sim.texture }, uSimRect: { value: sim.rect },
+ uMicro: { value: microTexture(renderer) }, uCanopy: { value: null }, uCookie: { value: null },
+ uCanopyMat: { value: canopyMat }, uCanopyH: underShared.uCanopyH,
+ uSunDir: { value: new THREE.Vector3() }, uSunCol: { value: new THREE.Color() },
+ uZenith: { value: new THREE.Color() }, uHorizon: { value: new THREE.Color() },
+ uAbsorb: { value: new THREE.Vector3(1.55, 0.64, 0.8) }, uScatter: { value: new THREE.Vector3(0.006, 0.028, 0.02) },
+ uMoonDir: { value: new THREE.Vector3(0, 0.5, -1).normalize() }, uMoonCol: { value: new THREE.Color(0, 0, 0) },
+ uLampPos: { value: new THREE.Vector3() }, uLampCol: { value: new THREE.Color(0, 0, 0) },
+ uLeafTint: { value: new THREE.Color(0.95, 0.22, 0.08) },
+ uTime: { value: 0 }, uSlope: { value: 1 }, uRefr: { value: 0.07 }, uWind: { value: 0.06 },
+ uAutumn: { value: 0 }, uBare: { value: 0 }, uGlint: { value: 1 }, uCanopyK: { value: 1 }, uReflK: { value: 0.75 }, uDebug: { value: +(DBG.get('wdbg') ?? 0) }, uMicroK: { value: 1 },
+};
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+W.uRefl = { value: reflection.rt.texture }; W.uReflMat = { value: reflection.texMatrix };
+const water = new THREE.Mesh(new THREE.PlaneGeometry(sim.rect.z, sim.rect.z, 1, 1).rotateX(-Math.PI / 2), waterMaterial(W));
+water.position.set(sim.rect.x + sim.rect.z / 2, 0, sim.rect.y + sim.rect.z / 2);
+water.renderOrder = -1;
+scene.add(water);
+reflection.hidden.push(water);
+engine.onResize((w, h, dpr) => {
+ underRT.setSize(Math.round(w * dpr), Math.round(h * dpr));
+ W.uUnderSize.value.set(Math.round(w * dpr), Math.round(h * dpr));
+});
+
+// ─── Garden ────────────────────────────────────────────────────────────────────
+const texLoads = [
+ terrainTextures(renderer, assets),
+ assets.texture('img/koi/canopy.webp').then(t => { t.anisotropy = 8; W.uCanopy.value = t; }),
+ assets.texture('img/koi/cookie.webp', { srgb: false }).then(t => { W.uCookie.value = t; underShared.uCookie.value = t; }),
+];
+const terrain = buildTerrain(renderer);
+under.add(terrain.under); scene.add(terrain.above);
+const rocks = buildRocks(rockMaterial(renderer));
+const enclosure = buildEnclosure(W);
+scene.add(enclosure.hedge, enclosure.sky);
+enclosure.sky.onBeforeRender = (r, s, cam) => enclosure.sky.position.copy(cam.position);
+rocks.under.forEach(r => under.add(r)); rocks.above.forEach(r => scene.add(r));
+
+// Lantern on its bank; its fire box glows at dusk.
+const lanternGroup = new THREE.Group();
+lanternGroup.position.set(LANTERN.x, terrainH(LANTERN.x, LANTERN.z) - 0.04, LANTERN.z);
+lanternGroup.rotation.y = -28 * D;
+scene.add(lanternGroup);
+const LANTERN_H = 1.7;
+const fire = new THREE.Mesh(new THREE.BoxGeometry(0.17, 0.13, 0.17), new THREE.MeshBasicMaterial({ color: new THREE.Color(0, 0, 0) }));
+fire.position.y = LANTERN_H * 0.625;
+lanternGroup.add(fire);
+lanternGroup.updateMatrixWorld(true);
+const firePos = new THREE.Vector3(); fire.getWorldPosition(firePos);
+lampMain.position.copy(firePos); lampUnder.position.copy(firePos);
+W.uLampPos.value.copy(firePos);
+
+const loads = [
+ assets.gltf('models/koi/kohaku.glb'), assets.gltf('models/koi/showa.glb'),
+ assets.gltf('models/koi/lotus.glb'), assets.gltf('models/koi/lantern.glb'),
+];
+
+// ─── Koi ───────────────────────────────────────────────────────────────────────
+const KOI = [
+ { kind: 'kohaku', len: 0.9, depth: -0.36, x: 0.9, z: 0.5, heading: 2.2 },
+ { kind: 'showa', len: 0.84, depth: -0.5, x: -0.6, z: 1.2, heading: -0.6 },
+ { kind: 'kohaku', len: 0.72, depth: -0.28, x: 1.9, z: -0.6, heading: 3.6 },
+ { kind: 'showa', len: 0.7, depth: -0.62, x: -1.4, z: -0.4, heading: 1.2 },
+ { kind: 'kohaku', len: 0.96, depth: -0.7, x: 0.1, z: -1.3, heading: 0.4, tint: 0xffcf6a },
+ { kind: 'kohaku', len: 0.66, depth: -0.24, x: 2.3, z: 1.4, heading: -2.2 },
+ { kind: 'showa', len: 0.92, depth: -0.44, x: -0.2, z: 2.0, heading: 2.8 },
+ { kind: 'kohaku', len: 0.8, depth: -0.56, x: 1.4, z: 1.9, heading: -1.1, tint: 0xc9a07a },
+ { kind: 'showa', len: 0.74, depth: -0.34, x: -1.8, z: 0.9, heading: 0.9 },
+];
+let school, flora, branch;
+
+// ─── Looks (lighting + season) and scroll stations ────────────────────────────
+const sunDir = (az, el) => [Math.sin(az * D) * Math.cos(el * D), Math.sin(el * D), -Math.cos(az * D) * Math.cos(el * D)];
+const LOOK = {
+ day: {
+ keyDir: sunDir(-135, 55), key: [1.0, 0.95, 0.86], keyI: 4.2, env: 0.5, envU: 0.26, hemi: 0.14,
+ zen: [0.55, 0.7, 0.86], hor: [1.25, 1.35, 1.42], moon: 0, lamp: 0, glint: 1,
+ autumn: 0.3, bare: 0, snow: 0, petals: 0, leaves: 60, wind: 0.06, lotus: 1,
+ scatter: [0.0028, 0.013, 0.0105], moss: [1, 1, 1], mist: 0, caust: 1,
+ },
+};
+LOOK.morning = { ...LOOK.day, keyDir: sunDir(155, 32), key: [1.0, 0.88, 0.72], keyI: 2.6, zen: [0.9, 1.1, 1.35], hor: [1.7, 1.65, 1.55], autumn: 0.15, leaves: 35, wind: 0.02, mist: 0.55 };
+LOOK.afternoon = { ...LOOK.day, keyDir: sunDir(140, 38), key: [1.0, 0.82, 0.6], keyI: 3.2, zen: [1.0, 1.05, 1.15], hor: [1.9, 1.6, 1.2], autumn: 1, leaves: 230, wind: 0.08 };
+LOOK.night = {
+ ...LOOK.day, keyDir: sunDir(4, 30), key: [0.55, 0.68, 1.0], keyI: 0.7, env: 0.08, envU: 0.08, hemi: 0.06,
+ zen: [0.02, 0.035, 0.09], hor: [0.05, 0.075, 0.14], moon: 1, lamp: 1, glint: 0.9, autumn: 0.6, leaves: 70, wind: 0.02,
+ scatter: [0.0006, 0.0018, 0.002],
+};
+LOOK.spring = { ...LOOK.day, caust: 0.55, keyDir: sunDir(-160, 52), autumn: 0, petals: 300, leaves: 6, zen: [1.1, 1.25, 1.45], moss: [1.05, 1.08, 0.95] };
+LOOK.summer = { ...LOOK.day, caust: 0.6, keyDir: sunDir(175, 62), keyI: 3.9, autumn: 0, leaves: 10, wind: 0.04, moss: [0.95, 1.05, 0.9] };
+LOOK.autumn = { ...LOOK.afternoon, caust: 0.55, keyDir: sunDir(-165, 42), autumn: 1, leaves: 340 };
+LOOK.winter = {
+ ...LOOK.day, keyDir: sunDir(190, 26), key: [0.82, 0.9, 1.0], keyI: 2.0, env: 0.7, hemi: 0.45, zen: [1.3, 1.4, 1.55], hor: [2.0, 2.05, 2.1],
+ autumn: 0.5, bare: 1, snow: 1, leaves: 0, lotus: 0, wind: 0.02, scatter: [0.006, 0.02, 0.022], moss: [0.7, 0.75, 0.72],
+};
+LOOK.dawn = { ...LOOK.day, keyDir: sunDir(150, 16), key: [1.0, 0.72, 0.5], keyI: 2.2, env: 0.4, zen: [0.7, 0.8, 1.05], hor: [1.9, 1.3, 0.95], autumn: 0.35, leaves: 40, wind: 0.02, mist: 0.4 };
+
+const V = (...a) => new THREE.Vector3(...a);
+const STATIONS = {
+ hero: { pos: V(0.35, 4.4, 2.75), look: V(0.35, -0.35, 0.35), look_: 'day', subject: V(1.1, 0, 0.3) },
+ moss: { pos: V(2.1, 1.72, 1.5), look: V(2.45, 0.72, -2.3), look_: 'morning', subject: V(3.45, 0.7, -2.6) },
+ maple: { pos: V(1.85, 4.7, 2.35), look: V(1.7, -0.2, -0.35), look_: 'afternoon', subject: V(2.2, 1.2, 0.5) },
+ moon: { pos: V(0.9, 2.7, 5.4), look: V(0.9, -0.1, -0.2), look_: 'night', subject: V(1.4, 0, 0.6) },
+ kaiseki: { pos: V(5.9, 2.0, 1.55), look: V(4.05, 0.75, -2.1), look_: 'night', subject: V(3.45, 0.9, -2.6) },
+ spring: { pos: V(1.3, 6.3, 4.6), look: V(1.7, -0.4, 0.5), look_: 'spring' },
+ summer: { pos: V(1.7, 6.2, 4.5), look: V(1.9, -0.4, 0.45), look_: 'summer' },
+ autumn: { pos: V(2.1, 6.1, 4.4), look: V(2.1, -0.4, 0.4), look_: 'autumn' },
+ winter: { pos: V(2.5, 6.0, 4.3), look: V(2.3, -0.4, 0.35), look_: 'winter' },
+ reserve: { pos: V(0.2, 5.4, 4.2), look: V(0.1, -0.3, 0.6), look_: 'dawn' },
+ foot: { pos: V(0.2, 7.2, 4.8), look: V(0.1, -0.3, 0.8), look_: 'dawn' },
+};
+// Portrait screens: a wider lens, the subject pulled to the centre line and lifted above the paper panels.
+let portrait = false;
+engine.onResize((w, h) => {
+ portrait = w / h < 0.85;
+ camera.fov = portrait ? 54 : 32;
+ camera.updateProjectionMatrix();
+});
+for (const s of Object.values(STATIONS)) {
+ const subj = s.subject ?? s.look;
+ const look = s.look.clone().lerp(subj, 0.85);
+ const pos = look.clone().add(s.pos.clone().sub(s.look).multiplyScalar(1.12));
+ s.m = { pos, look };
+}
+const keyEls = [...document.querySelectorAll('[data-key]')];
+let anchors = [];
+function measure() {
+ anchors = keyEls.map(el => {
+ const r = el.getBoundingClientRect();
+ const top = r.top + scrollY;
+ const k = el.dataset.key;
+ const a = k === 'hero' ? 0 : k === 'foot' ? document.documentElement.scrollHeight - innerHeight : top + r.height / 2 - innerHeight / 2;
+ return { key: k, a };
+ });
+}
+addEventListener('resize', measure);
+addEventListener('load', measure);
+document.fonts?.ready.then(measure);
+setInterval(measure, 2500);
+// in-page links glide with Lenis to the station they name
+document.addEventListener('click', e => {
+ const a = e.target.closest('a[href^="#"]');
+ if (!a) return;
+ const id = a.getAttribute('href').slice(1);
+ const el = id === 'top' ? document.body : document.getElementById(id);
+ if (!el) return;
+ e.preventDefault();
+ const key = el.dataset.key ? el : el.querySelector('[data-key]');
+ const anchor = key && anchors.find(x => x.key === key.dataset.key);
+ window.__lenis?.scrollTo(id === 'top' ? 0 : anchor ? anchor.a : el, { duration: 2.4, easing: t => 1 - Math.pow(1 - t, 3) });
+});
+function scrollU() {
+ const y = scrollY;
+ if (!anchors.length) return 0;
+ if (y <= anchors[0].a) return 0;
+ for (let i = 0; i < anchors.length - 1; i++) {
+ const a = anchors[i].a, b = anchors[i + 1].a;
+ if (y < b) return i + (y - a) / Math.max(1, b - a);
+ }
+ return anchors.length - 1;
+}
+
+const lookKeys = Object.keys(LOOK.day);
+function mixLook(a, b, t) {
+ const o = {};
+ for (const k of lookKeys) {
+ const x = a[k], y = b[k];
+ o[k] = Array.isArray(x) ? x.map((v, i) => lerp(v, y[i], t)) : lerp(x, y, t);
+ }
+ return o;
+}
+let look = { ...LOOK.day };
+
+// ─── Interaction ───────────────────────────────────────────────────────────────
+const pointer = new Pointer({ lambda: 9 });
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const hand = { x: 0, z: 0, px: 0, pz: 0, vx: 0, vz: 0, speed: 0, on: false, valid: false, lastMove: -10, still: 0 };
+let overWater = false;
+addEventListener('pointermove', e => { overWater = e.target === canvas; hand.lastMove = engine.time; }, { passive: true });
+document.addEventListener('pointerleave', () => { overWater = false; });
+function waterHit(nx, ny, out) {
+ ndc.set(nx, ny);
+ ray.setFromCamera(ndc, camera);
+ const d = ray.ray.direction, o = ray.ray.origin;
+ if (d.y > -0.02) return false;
+ const t = -o.y / d.y;
+ out.x = o.x + d.x * t; out.z = o.z + d.z * t;
+ return pondSDF(out.x, out.z) < -0.05;
+}
+
+// Audio: a soft plop, synthesized, only ever in response to a click.
+let audio = null, soundOn = true;
+const soundBtn = document.querySelector('.sound');
+soundBtn.addEventListener('click', () => { soundOn = !soundOn; soundBtn.setAttribute('aria-pressed', soundOn); soundBtn.classList.toggle('off', !soundOn); });
+let gestured = false;
+for (const ev of ['pointerdown', 'keydown']) addEventListener(ev, () => { gestured = true; }, { once: true, capture: true });
+function plop(vol = 1, pitch = 1) {
+ if (!soundOn || !gestured) return;
+ try {
+ audio ??= new AudioContext();
+ const t = audio.currentTime + 0.001;
+ const o = audio.createOscillator(), g = audio.createGain();
+ o.type = 'sine';
+ const f0 = (620 + Math.random() * 240) * pitch;
+ o.frequency.setValueAtTime(f0 * 0.5, t);
+ o.frequency.exponentialRampToValueAtTime(f0, t + 0.035);
+ o.frequency.exponentialRampToValueAtTime(f0 * 0.35, t + 0.16);
+ g.gain.setValueAtTime(0.0001, t);
+ g.gain.exponentialRampToValueAtTime(0.09 * vol, t + 0.01);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + 0.22);
+ o.connect(g).connect(audio.destination);
+ o.start(t); o.stop(t + 0.25);
+ } catch { /* optional */ }
+}
+
+let fedOnce = false;
+function feed(x, z) {
+ flora.drop(x, z, 5);
+ fedOnce = true;
+ document.body.classList.add('has-fed');
+}
+canvas.addEventListener('pointerdown', e => {
+ if (e.button !== 0 || !flora) return;
+ const nx = (e.clientX / innerWidth) * 2 - 1, ny = -(e.clientY / innerHeight) * 2 + 1;
+ const p = {};
+ if (waterHit(nx, ny, p)) feed(p.x, p.z);
+});
+
+const hooks = {
+ pelletLand: p => { sim.drop(p.x, p.z, 0.05, 0.012); flora.splash(p.x, p.z, 7, 0.8); if (p.delay < 0.08) plop(0.9); else if (Math.random() < 0.5) plop(0.4, 1.3); },
+ eat: (food, fish) => {
+ sim.drop(food.x, food.z, 0.08, -0.009);
+ setTimeout(() => { sim.drop(food.x, food.z, 0.05, 0.006); flora.splash(food.x, food.z, 5, 0.55); plop(0.55, 0.7); }, 90);
+ },
+ leafLand: l => sim.drop(l.x, l.z, l.petal ? 0.025 : 0.04, l.petal ? 0.0012 : 0.0026),
+ kiss: (f, x, z) => { sim.drop(x, z, 0.035, -0.004); setTimeout(() => sim.drop(x, z, 0.025, 0.003), 120); },
+ dropletLand: d => sim.drop(d.x, d.z, 0.018, 0.0009),
+ wake: (f, hx, hz, bx, bz) => { if (Math.random() < 0.35) sim.drop(hx, hz, 0.05, 0.0005 * f.speed * (1 + f.y * 3), bx, bz); },
+};
+
+// ─── UI ────────────────────────────────────────────────────────────────────────
+worldNav('koi', { theme: 'dark', corner: 'bl' });
+const cur = cursor({ color: '#f3efe6', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.07 });
+reveal('.sec-head h2, .kaiseki-paper h2, .season-paper h2, .reserve-paper h2', { type: 'lines', stagger: 0.09 });
+reveal('.lede', { type: 'lines', stagger: 0.05, y: '100%' });
+if (isTouch) {
+ document.querySelector('.hint-feed').innerHTML = '<b>Tap</b> the water to feed the koi';
+ document.body.classList.add('touch');
+}
+const toastEl = document.querySelector('.toast');
+let toastT;
+function toast(msg, ms = 3200) { toastEl.textContent = msg; toastEl.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => toastEl.classList.remove('on'), ms); }
+document.querySelector('.booking').addEventListener('submit', e => {
+ e.preventDefault();
+ const f = new FormData(e.target);
+ toast(`Thank you. We will write back by hand about ${f.get('nights')} nights in a ${f.get('room')} room.`, 4200);
+});
+const roomEls = [...document.querySelectorAll('.room')], roomDots = [...document.querySelectorAll('.room-dots li')];
+const seasonEls = [...document.querySelectorAll('.season-list li')], seasonKanji = [...document.querySelectorAll('.season-kanji span')];
+let activeKey = '';
+function setActive(k) {
+ if (k === activeKey) return;
+ activeKey = k;
+ const ri = ['moss', 'maple', 'moon'].indexOf(k);
+ if (ri >= 0) { roomEls.forEach((el, i) => el.classList.toggle('is-on', i === ri)); roomDots.forEach((el, i) => el.classList.toggle('is-on', i === ri)); }
+ const si = ['spring', 'summer', 'autumn', 'winter'].indexOf(k);
+ if (si >= 0) { seasonEls.forEach((el, i) => el.classList.toggle('is-on', i === si)); seasonKanji.forEach((el, i) => el.classList.toggle('is-on', i === si)); }
+ document.body.dataset.station = k;
+}
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const camPos = new THREE.Vector3().copy(STATIONS.hero.pos), camLook = new THREE.Vector3().copy(STATIONS.hero.look);
+const tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), right = new THREE.Vector3();
+const intro = { v: 1 };
+let uS = 0;
+const keyDirV = new THREE.Vector3();
+const bgColor = new THREE.Color(0x0b1511);
+const view = { x: 0, z: 0, w: 6, h: 5 };
+
+function applyLook(L) {
+ keyDirV.set(...L.keyDir).normalize();
+ for (const k of [keyMain, keyUnder]) {
+ k.color.setRGB(...L.key);
+ k.intensity = L.keyI;
+ k.target.position.set(0, 0, 1.5);
+ k.position.copy(k.target.position).addScaledVector(keyDirV, 45);
+ }
+ underShared.uKeyDir.value.copy(keyDirV);
+ // refracted key direction under water (for caustic and dapple offsets)
+ const sinT = Math.sqrt(1 - keyDirV.y * keyDirV.y) / 1.33, cosT = Math.sqrt(1 - sinT * sinT);
+ const hl = Math.hypot(keyDirV.x, keyDirV.z) || 1;
+ underShared.uSunRefr.value.set(keyDirV.x / hl * sinT / cosT, keyDirV.z / hl * sinT / cosT);
+ hemiMain.intensity = L.hemi; hemiUnder.intensity = L.hemi * 0.9;
+ scene.environmentIntensity = L.env; under.environmentIntensity = L.envU;
+ W.uSunDir.value.copy(keyDirV);
+ W.uSunCol.value.setRGB(...L.key).multiplyScalar(L.keyI / 3.4);
+ W.uZenith.value.setRGB(...L.zen); W.uHorizon.value.setRGB(...L.hor);
+ W.uMoonCol.value.setRGB(1.0, 0.97, 0.9).multiplyScalar(L.moon * 1.2);
+ W.uMoonDir.value.copy(keyDirV);
+ W.uLampCol.value.setRGB(1.0, 0.55, 0.2).multiplyScalar(L.lamp * 1.6);
+ W.uAutumn.value = L.autumn; W.uBare.value = L.bare; W.uWind.value = L.wind; W.uGlint.value = L.glint; W.uMicroK.value = 1 - L.moon * 0.75;
+ W.uScatter.value.set(...L.scatter);
+ lampMain.intensity = L.lamp * 9; lampUnder.intensity = L.lamp * 4;
+ fire.material.color.setRGB(9, 4.2, 1.4).multiplyScalar(L.lamp);
+ gardenShared.uSnow.value = L.snow;
+ underShared.uCaustK.value = L.caust;
+ enclosure.uniforms.uKeyDir.value.copy(keyDirV); enclosure.uniforms.uKeyCol.value.setRGB(...L.key).multiplyScalar(L.keyI / 3.4);
+ enclosure.uniforms.uAmb.value.setRGB(0.5, 0.62, 0.5).multiplyScalar(L.hemi * 1.6 + L.env * 0.3);
+ gardenShared.uMossTint.value.setRGB(...L.moss);
+ underShared.uDappleK.value = 1 - L.bare * 0.7;
+ if (flora) {
+ flora.season.leaves = Math.round(L.leaves);
+ flora.season.petals = Math.round(L.petals);
+ flora.season.snow = L.snow;
+ flora.season.slots = L.autumn > 0.55 ? [0, 1, 1, 2, 3] : L.autumn > 0.2 ? [0, 2, 3, 4, 4] : [4, 4, 3];
+ for (const l of flora.lotus) l.holder.scale.setScalar(l.s * Math.max(0.001, L.lotus));
+ flora.padScale = Math.max(0.001, L.lotus);
+ flora.fireMat.uniforms.uAmt.value = L.lamp;
+ for (const m of flora.mist) { m.material.uniforms.uAmt.value = L.mist; m.material.uniforms.uCol.value.setRGB(...L.key).multiplyScalar(0.35 + L.keyI * 0.12).lerp(W.uHorizon.value, 0.35); }
+ }
+}
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ if (!school) return;
+ // scroll → station
+ const u = scrollU();
+ uS = damp(uS, u, 4.5, dt);
+ const i0 = clamp(Math.floor(uS), 0, anchors.length - 1), i1 = Math.min(i0 + 1, anchors.length - 1);
+ const f = smooth(0.12, 0.88, uS - i0);
+ const A = STATIONS[anchors[i0].key], B = STATIONS[anchors[i1].key];
+ setActive(anchors[Math.round(u)]?.key ?? 'hero');
+ const Am = portrait ? A.m : A, Bm = portrait ? B.m : B;
+ tmp.lerpVectors(Am.pos, Bm.pos, f);
+ tmp2.lerpVectors(Am.look, Bm.look, f);
+ // lift the camera a little mid-transition so the drift reads as flight over water
+ tmp.y += Math.sin(f * Math.PI) * 0.5 * (A === B ? 0 : 1);
+ tmp.y += intro.v * 3.2; tmp.z += intro.v * 1.2;
+ camPos.copy(tmp); camLook.copy(tmp2);
+ look = mixLook(LOOK[A.look_], LOOK[B.look_], f);
+ applyLook(look);
+ document.body.classList.toggle('is-night', look.lamp > 0.5);
+ document.body.classList.toggle('scrolled', u > 0.15);
+
+ // camera: slow breath + pointer parallax
+ right.set(1, 0, 0).applyQuaternion(camera.quaternion);
+ camera.position.copy(camPos)
+ .addScaledVector(right, pointer.sx * 0.12 + Math.sin(t * 0.13) * 0.05)
+ .add(tmp.set(0, Math.sin(t * 0.21) * 0.04, pointer.sy * -0.08));
+ if (DBG.has('cam')) { const c = DBG.get('cam').split(',').map(Number); camera.position.set(c[0], c[1], c[2]); camera.lookAt(c[3], c[4], c[5]); if (DBG.has('look')) { look = { ...LOOK[DBG.get('look')] }; applyLook(look); } }
+ else {
+ camera.lookAt(camLook);
+ if (portrait) { // nudge the subject into the upper half, above the panels
+ tmp2.set(0, 1, 0).applyQuaternion(camera.quaternion);
+ camera.lookAt(tmp.copy(camLook).addScaledVector(tmp2, -camera.position.distanceTo(camLook) * 0.2));
+ }
+ }
+ camera.updateMatrixWorld();
+
+ // the visitor's hand on the water
+ const onW = overWater && pointer.active && !isTouch && engine.time - hand.lastMove < 4;
+ const p = {};
+ const hit = onW && waterHit(pointer.x, pointer.y, p);
+ if (hit) {
+ if (hand.valid) {
+ const vx = (p.x - hand.x) / dt, vz = (p.z - hand.z) / dt;
+ hand.vx = damp(hand.vx, vx, 12, dt); hand.vz = damp(hand.vz, vz, 12, dt);
+ hand.speed = Math.hypot(hand.vx, hand.vz);
+ const moved = Math.hypot(p.x - hand.x, p.z - hand.z);
+ if (moved > 0.002) sim.drop(hand.x, hand.z, 0.05, -0.0048 * clamp(hand.speed / 1.4, 0.12, 1.3), p.x, p.z);
+ }
+ hand.x = p.x; hand.z = p.z; hand.valid = true; hand.on = true;
+ } else { hand.valid = false; hand.on = false; hand.speed = 0; }
+ school.pointer = hand;
+ hand.still = hand.on && hand.speed < 0.2 ? hand.still + dt : 0;
+ if (cur) cur.set(hand.on && u < 0.6 ? (hand.still > 0.9 && !fedOnce ? 'label' : '') : '', 'feed');
+
+ // what the camera sees (for spawning leaves where they will be noticed)
+ camera.getWorldDirection(tmp);
+ const tHit = -camera.position.y / Math.min(tmp.y, -0.2);
+ view.x = camera.position.x + tmp.x * tHit; view.z = camera.position.z + tmp.z * tHit;
+ view.w = camera.position.y * 1.2; view.h = camera.position.y * 0.9;
+
+ school.home = view;
+ school.update(dt, t, hooks);
+ flora.update(dt, t, { school, pointer: hand, hooks, view });
+ branch.update(t, look);
+ // a koi occasionally kisses the surface
+ if (Math.random() < dt * 0.35) { const k = school.fish[Math.floor(Math.random() * school.fish.length)]; if (k.y > -0.3) { sim.drop(k.chain[0], k.chain[2], 0.03, 0.002); } }
+ sim.step(dt);
+
+ underShared.uTime.value = t;
+ W.uTime.value = t;
+
+ // mirrored garden for the surface
+ if (!DBG.has('norefl')) {
+ renderer.setClearColor(0x000000, 0);
+ reflection.update(scene, camera);
+ }
+ // under-water pass
+ underShared.uDepthOut.value = 1;
+ const prevT = renderer.getRenderTarget();
+ renderer.setRenderTarget(underRT);
+ renderer.setClearColor(0x000000, 1);
+ renderer.clear();
+ renderer.render(under, camera);
+ renderer.setRenderTarget(prevT);
+ renderer.setClearColor(bgColor, 1);
+ underShared.uDepthOut.value = 0;
+});
+
+// ─── Boot ──────────────────────────────────────────────────────────────────────
+const T0 = performance.now();
+const [kohaku, showa, lotus, lanternG] = await Promise.all(loads);
+await Promise.all(texLoads);
+const T1 = performance.now();
+{
+ const m = lanternG.scene;
+ normalize(m, LANTERN_H, { axis: 'y' });
+ prepModel(m, renderer, { env: 0.8, onMat: mat => patchUnder(mat, { key: 'lantern' }) });
+ lanternGroup.add(m);
+}
+normalize(lotus.scene, 1.0);
+prepModel(lotus.scene, renderer, { env: 1.0, onMat: mat => { patchFloat(mat, 'lotus'); patchUnder(mat, { key: 'lotus' }); } });
+const protos = { kohaku: koiPrototype(kohaku), showa: koiPrototype(showa) };
+const T2 = performance.now();
+school = new School({ protos, specs: KOI, env: { avoid: rocks.avoid } });
+for (const f of school.fish) {
+ f.mesh.material.envMapIntensity = 0.9;
+ under.add(f.mesh);
+}
+flora = new Flora({ renderer, scene, under, lotusGltf: lotus, sim });
+{ const nt = fbmTexture(renderer, { size: 512, scale: 5, octaves: 5, contrast: 1.3 }); for (const m of flora.mist) { m.material.uniforms.uNoise.value = nt; reflection.hidden.push(m); } }
+engine.onResize((w, h, dpr) => { flora.fireMat.uniforms.uDpr.value = dpr; flora.snowMat.uniforms.uDpr.value = dpr; });
+branch = new MapleBranch({ renderer, scene, under, leafTex: flora.leafTex, leafGeo: flora.leafGeo });
+patchUnder(flora.pads.material, { key: 'pad' });
+patchUnder(flora.leaves.material, { key: 'leaf' });
+measure();
+applyLook(LOOK.day);
+// warm up: one sim step + both passes compiled before the loader goes
+sim.step(1 / 60);
+renderer.compile(under, camera);
+renderer.compile(scene, camera);
+const T3 = performance.now();
+if (DBG.has('debug')) console.info('[koi] boot', { sinceNav: Math.round(T0), load: Math.round(T1 - T0), protos: Math.round(T2 - T1), compile: Math.round(T3 - T2) });
+engine.start();
+await loader.finish();
+if (DBG.has('nointro')) intro.v = 0;
+gsap.to(intro, { v: 0, duration: 3.4, ease: 'power3.inOut' });
+setTimeout(() => { sim.drop(0.4, 0.4, 0.16, 0.03); plop(0.6, 0.6); }, 900);
+gsap.from('.title .line', { yPercent: 110, opacity: 0, duration: 2.0, ease: 'expo.out', stagger: 0.14, delay: 1.1 });
+gsap.from('.hero .eyebrow, .hero .sub, .hero-cta, .nav, .scroll-cue', { opacity: 0, y: 16, duration: 1.6, ease: 'power3.out', stagger: 0.07, delay: 1.5 });
+setTimeout(() => document.body.classList.add('ready'), 900);
+window.__koi = { school, flora, sim, look: LOOK, STATIONS, feed, protos, get anchors() { return anchors; }, camera, W, underShared, engine };
diff --git a/examples/koi/maple.js b/examples/koi/maple.js
new file mode 100644
index 0000000..4341506
--- /dev/null
+++ b/examples/koi/maple.js
@@ -0,0 +1,156 @@
+// An old momiji limb reaching over the water: tapered bark tubes and a few hundred instanced leaves
+// that sway, turn with the seasons and throw their shadows onto the pond floor.
+import * as THREE from 'three';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { patchUnder, underShared } from './water.js';
+
+function taperedTube(curve, r0, r1, seg = 40, radial = 9) {
+ const frames = curve.computeFrenetFrames(seg, false);
+ const pos = [], nor = [], uv = [], idx = [];
+ const p = new THREE.Vector3(), n = new THREE.Vector3();
+ for (let i = 0; i <= seg; i++) {
+ const t = i / seg;
+ curve.getPointAt(t, p);
+ const r = r0 + (r1 - r0) * Math.pow(t, 0.8);
+ for (let j = 0; j <= radial; j++) {
+ const a = j / radial * Math.PI * 2;
+ n.copy(frames.normals[i]).multiplyScalar(Math.cos(a)).addScaledVector(frames.binormals[i], Math.sin(a));
+ // knobbly bark
+ const k = 1 + Math.sin(t * 37 + a * 3) * 0.06 + Math.sin(t * 91 + a * 5) * 0.03;
+ pos.push(p.x + n.x * r * k, p.y + n.y * r * k, p.z + n.z * r * k);
+ nor.push(n.x, n.y, n.z);
+ uv.push(j / radial, t * curve.getLength() * 3);
+ }
+ }
+ for (let i = 0; i < seg; i++) for (let j = 0; j < radial; j++) {
+ const a = i * (radial + 1) + j, b = a + radial + 1;
+ idx.push(a, b, a + 1, b, b + 1, a + 1);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setIndex(idx);
+ return g;
+}
+
+export class MapleBranch {
+ constructor({ renderer, scene, under, leafTex, leafGeo }) {
+ let rs = 77;
+ const rnd = () => ((rs = (rs * 16807) % 2147483647) / 2147483647);
+ const V = (x, y, z) => new THREE.Vector3(x, y, z);
+ const limbs = [];
+ const main = new THREE.CatmullRomCurve3([V(4.6, 3.35, -0.2), V(3.4, 3.0, 0.45), V(2.5, 2.72, 0.95), V(1.75, 2.55, 1.2), V(1.05, 2.42, 1.3)]);
+ limbs.push([main, 0.075, 0.018]);
+ const twigs = [];
+ for (let k = 0; k < 26; k++) {
+ const t = 0.28 + rnd() * 0.72;
+ const o = main.getPointAt(t);
+ const side = rnd() < 0.5 ? -1 : 1;
+ const dir = V(-0.6 - rnd() * 0.5, -0.12 - rnd() * 0.2, side * (0.4 + rnd() * 0.8)).normalize();
+ const len = 0.35 + rnd() * 0.55;
+ const mid = o.clone().addScaledVector(dir, len * 0.5).add(V(0, 0.05, 0));
+ const end = o.clone().addScaledVector(dir, len).add(V(0, -0.08 - rnd() * 0.1, 0));
+ const c = new THREE.CatmullRomCurve3([o, mid, end]);
+ limbs.push([c, 0.022 * (1.2 - t * 0.5), 0.005]);
+ twigs.push(c);
+ }
+ twigs.push(new THREE.CatmullRomCurve3([main.getPointAt(0.85), main.getPointAt(0.92), main.getPointAt(1)]));
+
+ const bark = bakeTexture(renderer, 512, /* glsl */`
+ void main(){
+ float n = fbm(vec2(vUv.x * 3., vUv.y * 0.35), 3., 5, .6);
+ float streak = ridge(vec2(vUv.x * 9., vUv.y * 0.6), 9., 4);
+ vec3 c = mix(vec3(0.05, 0.04, 0.035), vec3(0.16, 0.13, 0.11), n * .5 + .5);
+ c = mix(c, vec3(0.22, 0.2, 0.17), smoothstep(0.55, 0.8, streak) * 0.5);
+ c = mix(c, vec3(0.19, 0.22, 0.12), smoothstep(0.3, 0.6, fbm(vUv * vec2(2., .2) + 4., 2., 3, .5)) * 0.35);
+ gl_FragColor = vec4(c, 1.);
+ }`);
+ const barkN = fbmNormal(renderer, { size: 512, scale: 8, octaves: 5, strength: 3, ridged: true });
+ const barkMat = patchUnder(new THREE.MeshStandardMaterial({ map: bark, normalMap: barkN, roughness: 0.92, metalness: 0, envMapIntensity: 0.5 }), { key: 'bark' });
+ this.group = new THREE.Group();
+ for (const [c, r0, r1] of limbs) {
+ const m = new THREE.Mesh(taperedTube(c, r0, r1, c === main ? 60 : 14, c === main ? 12 : 6), barkMat);
+ m.castShadow = true; m.receiveShadow = true;
+ this.group.add(m);
+ }
+ scene.add(this.group);
+ const proxyMat = new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false });
+ this.proxy = this.group.clone(true);
+ this.proxy.traverse(o => { if (o.isMesh) o.material = proxyMat; });
+ under.add(this.proxy);
+
+ // Leaves in loose palmate clusters toward the twig ends.
+ const leaves = [];
+ for (const c of twigs) {
+ const n = 22 + Math.floor(rnd() * 16);
+ for (let i = 0; i < n; i++) {
+ const t = 0.35 + Math.pow(rnd(), 0.6) * 0.65;
+ const p = c.getPointAt(t).add(V((rnd() - 0.5) * 0.18, (rnd() - 0.5) * 0.08 - 0.03, (rnd() - 0.5) * 0.18));
+ leaves.push({ p, s: 0.075 + rnd() * 0.05, yaw: rnd() * 6.28, tx: (rnd() - 0.5) * 0.9, tz: (rnd() - 0.5) * 0.9 });
+ }
+ }
+ this.count = leaves.length;
+ this.slot = new THREE.InstancedBufferAttribute(new Float32Array(this.count), 1);
+ this.phase = new THREE.InstancedBufferAttribute(new Float32Array(this.count).map(() => rnd() * 6.28), 1);
+ const geo = leafGeo.clone();
+ geo.setAttribute('aSlot', this.slot);
+ geo.setAttribute('aPhase', this.phase);
+ this.uTime = { value: 0 };
+ const mat = new THREE.MeshStandardMaterial({ map: leafTex, alphaTest: 0.5, side: THREE.DoubleSide, roughness: 0.62, metalness: 0, envMapIntensity: 0.7 });
+ const sway = sh => {
+ sh.uniforms.uTimeB = this.uTime;
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute float aSlot; attribute float aPhase; uniform float uTimeB;')
+ .replace('#include <uv_vertex>', '#include <uv_vertex>\n#ifdef USE_MAP\nvMapUv = (vMapUv + vec2(mod(aSlot, 3.), 1. - floor(aSlot / 3.))) / vec2(3., 2.);\n#endif')
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ float kr = length(position.xz);
+ transformed.y += (sin(uTimeB * 1.7 + aPhase) * 0.6 + sin(uTimeB * 3.1 + aPhase * 2.3) * 0.4) * 0.09 * kr;
+ transformed.x += sin(uTimeB * 1.3 + aPhase * 1.7) * 0.03 * kr;`);
+ };
+ mat.onBeforeCompile = sway;
+ patchUnder(mat, { key: 'branchleaf' });
+ this.leaves = new THREE.InstancedMesh(geo, mat, this.count);
+ this.leaves.castShadow = true; this.leaves.receiveShadow = true; this.leaves.frustumCulled = false;
+ const depth = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, map: leafTex, alphaTest: 0.5, side: THREE.DoubleSide });
+ depth.onBeforeCompile = sway;
+ this.leaves.customDepthMaterial = depth;
+ this.data = leaves;
+ this.setMatrices(1);
+ scene.add(this.leaves);
+ this.leafProxy = new THREE.InstancedMesh(geo, proxyMat, this.count);
+ this.leafProxy.instanceMatrix = this.leaves.instanceMatrix;
+ this.leafProxy.customDepthMaterial = depth;
+ this.leafProxy.castShadow = true; this.leafProxy.frustumCulled = false;
+ under.add(this.leafProxy);
+ this.season = -1;
+ this.leafScale = 1;
+ }
+
+ setMatrices(k) {
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), s = new THREE.Vector3();
+ this.data.forEach((l, i) => {
+ e.set(l.tx, l.yaw, l.tz, 'YXZ'); q.setFromEuler(e);
+ this.leaves.setMatrixAt(i, m.compose(l.p, q, s.setScalar(l.s * k)));
+ });
+ this.leaves.instanceMatrix.needsUpdate = true;
+ }
+
+ /** autumn 0..1 turns the leaves; bare 0..1 strips them. */
+ update(t, { autumn, bare }) {
+ this.uTime.value = t;
+ const key = Math.round(autumn * 4) * 10 + Math.round(bare * 4);
+ if (key !== this.season) {
+ this.season = key;
+ let rs = 3;
+ const rnd = () => ((rs = (rs * 16807) % 2147483647) / 2147483647);
+ for (let i = 0; i < this.count; i++) {
+ const r = rnd();
+ this.slot.setX(i, r < autumn * 0.95 ? [0, 1, 1, 2, 3, 0][Math.floor(rnd() * 6)] : (r < autumn + 0.15 ? 3 : 4));
+ }
+ this.slot.needsUpdate = true;
+ }
+ const k = 1 - bare;
+ if (Math.abs(k - this.leafScale) > 0.01) { this.leafScale = k; this.setMatrices(Math.max(0.0001, k)); }
+ }
+}
diff --git a/examples/koi/shape.js b/examples/koi/shape.js
new file mode 100644
index 0000000..14eb3f4
--- /dev/null
+++ b/examples/koi/shape.js
@@ -0,0 +1,56 @@
+// The pond's plan: one signed-distance outline shared by the terrain, the ripple mask, the koi and the leaves.
+// World units are metres; the water surface is y = 0, +y up; the far (north) shore is toward -z.
+
+// Seeded 2D gradient noise.
+const P = new Uint8Array(512);
+{
+ let s = 1337;
+ const rnd = () => ((s = (s * 16807) % 2147483647) / 2147483647);
+ const p = Array.from({ length: 256 }, (_, i) => i);
+ for (let i = 255; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [p[i], p[j]] = [p[j], p[i]]; }
+ for (let i = 0; i < 512; i++) P[i] = p[i & 255];
+}
+const G = Array.from({ length: 256 }, (_, i) => [Math.cos(i * 2.39996), Math.sin(i * 2.39996)]);
+const fade = t => t * t * t * (t * (t * 6 - 15) + 10);
+export function noise(x, y) {
+ const xi = Math.floor(x), yi = Math.floor(y);
+ const xf = x - xi, yf = y - yi;
+ const g = (ix, iy) => G[P[(P[ix & 255] + iy) & 255]];
+ const d = (gg, dx, dy) => gg[0] * dx + gg[1] * dy;
+ const u = fade(xf), v = fade(yf);
+ const a = d(g(xi, yi), xf, yf), b = d(g(xi + 1, yi), xf - 1, yf);
+ const c = d(g(xi, yi + 1), xf, yf - 1), e = d(g(xi + 1, yi + 1), xf - 1, yf - 1);
+ return (a + (b - a) * u) + ((c + (e - c) * u) - (a + (b - a) * u)) * v; // ~[-0.7, 0.7]
+}
+export const fbm = (x, y, o = 4) => { let s = 0, a = 0.5, f = 1; for (let i = 0; i < o; i++) { s += a * noise(x * f, y * f); f *= 2.03; a *= 0.5; } return s; };
+
+const smin = (a, b, k) => { const h = Math.max(k - Math.abs(a - b), 0) / k; return Math.min(a, b) - h * h * k * 0.25; };
+const smax = (a, b, k) => -smin(-a, -b, k);
+const ell = (x, z, cx, cz, rx, rz) => { const dx = (x - cx) / rx, dz = (z - cz) / rz; return (Math.hypot(dx, dz) - 1) * Math.min(rx, rz); };
+
+/** Signed distance to the shoreline in metres: negative over water. */
+export function pondSDF(x, z) {
+ let d = ell(x, z, 0.2, 2.2, 7.4, 5.6); // main basin
+ d = smin(d, ell(x, z, -5.2, 5.8, 3.6, 3.0), 1.6); // south-west lobe
+ d = smin(d, ell(x, z, -2.2, -2.6, 3.4, 2.0), 1.4); // north-west bay, under the maple
+ d = smax(d, -ell(x, z, 3.7, -3.35, 1.9, 1.35), 1.2); // the lantern's bank juts in from the north-east
+ d = smax(d, -ell(x, z, 6.9, 3.4, 1.4, 2.2), 1.0); // east bank bulge
+ d += fbm(x * 0.32 + 3.1, z * 0.32 - 1.7, 3) * 1.1;
+ return d;
+}
+
+const ss = (a, b, v) => { const t = Math.min(1, Math.max(0, (v - a) / (b - a))); return t * t * (3 - 2 * t); };
+/** Terrain height: the pond floor under water, moss banks above. */
+export function terrainH(x, z) {
+ const d = pondSDF(x, z);
+ if (d < 0) {
+ const deep = Math.pow(ss(0, 2.8, -d), 0.8);
+ const lumps = fbm(x * 0.9, z * 0.9, 3) * 0.14 * ss(0.3, 1.5, -d);
+ return 0.02 - 0.12 * ss(0, 0.35, -d) - 1.25 * deep + lumps;
+ }
+ const mounds = fbm(x * 0.35 + 7, z * 0.35, 4) * 0.55 * ss(0.4, 3, d);
+ return 0.02 + 0.13 * ss(0, 0.4, d) + 0.32 * ss(0.4, 4, d) + Math.max(mounds, -0.1);
+}
+
+export const LANTERN = { x: 3.45, z: -2.62, rock: 1.25 };
+export const MAPLE = { x: -3.4, z: -3.2 }; // trunk position, canopy spreads south-east over the bay
diff --git a/examples/koi/style.css b/examples/koi/style.css
new file mode 100644
index 0000000..714428d
--- /dev/null
+++ b/examples/koi/style.css
@@ -0,0 +1,231 @@
+:root {
+ --pond: #0b1511;
+ --ink: #16241e;
+ --ink-2: #33443b;
+ --washi: #f3efe6;
+ --washi-2: #e9e3d6;
+ --paper-line: rgba(22, 36, 30, .14);
+ --verm: #e0503a;
+ --verm-2: #c63f2b;
+ --moss: #6d7c4b;
+ --light: #f3efe6;
+ --light-dim: rgba(243, 239, 230, .72);
+ --serif: 'Shippori Mincho', 'Hiragino Mincho ProN', 'Yu Mincho', serif;
+ --sans: 'Zen Kaku Gothic New', 'Hiragino Sans', system-ui, sans-serif;
+ --gutter: clamp(18px, 4vw, 56px);
+ --fibre: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='220' height='220'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 .35 0 0 0 0 .3 0 0 0 0 .22 0 0 0 .09 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--pond); color: var(--light); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 16px/1.7 var(--sans); background: var(--pond); overflow-x: hidden; }
+a { color: inherit; }
+img { display: block; max-width: 100%; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+.jp { font-family: var(--serif); letter-spacing: .12em; }
+
+/* ─── Loader ─── */
+.loader { position: fixed; inset: 0; z-index: 100; background: radial-gradient(120% 90% at 50% 40%, #13231c, #070d0a 70%); display: grid; place-content: center; justify-items: center; gap: 26px; }
+.enso { width: 150px; height: 150px; grid-area: 1 / 1; transform: rotate(-100deg); overflow: visible; }
+.enso circle { fill: none; stroke-linecap: round; }
+.enso-track { stroke: rgba(243, 239, 230, .06); stroke-width: 1; }
+.enso-ink { stroke: var(--washi); stroke-width: 5; stroke-dasharray: 100; stroke-dashoffset: calc(100 - var(--p, 0) * 92); opacity: .92;
+ filter: drop-shadow(0 0 1px rgba(243,239,230,.35)); transition: stroke-dashoffset .2s linear; }
+.loader-kanji { grid-area: 1 / 1; align-self: center; font: 500 44px/1 var(--serif); color: var(--verm); opacity: calc(.25 + var(--p, 0) * .75); }
+.loader-line { font: 400 13px/1 var(--sans); letter-spacing: .28em; text-transform: uppercase; color: rgba(243,239,230,.55); }
+.loader-pct { font-variant-numeric: tabular-nums; color: var(--washi); }
+.loader.out .enso { animation: ripple-out 1.6s cubic-bezier(.2,.7,.2,1) forwards; }
+@keyframes ripple-out { to { transform: rotate(-100deg) scale(5.5); opacity: 0; } }
+
+/* ─── Nav ─── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between;
+ padding: 22px var(--gutter); pointer-events: none; transition: background .6s, backdrop-filter .6s; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 14px; text-decoration: none; }
+.seal { display: grid; place-items: center; width: 34px; height: 44px; background: var(--verm); color: var(--washi); border-radius: 3px;
+ writing-mode: vertical-rl; font: 600 15px/1 var(--serif); letter-spacing: .08em; box-shadow: 0 6px 20px -8px rgba(224, 80, 58, .8); }
+.brand-name { font: 500 19px/1 var(--serif); letter-spacing: .04em; }
+.links { display: flex; gap: 38px; }
+.links a { text-decoration: none; font: 400 14px/1 var(--sans); letter-spacing: .06em; color: var(--light-dim); transition: color .3s; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: -7px; height: 1px; background: var(--verm); transform: scaleX(0); transform-origin: left; transition: transform .5s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--light); }
+.links a:hover::after { transform: scaleX(1); }
+.nav-right { display: flex; align-items: center; gap: 18px; }
+.sound { display: flex; align-items: center; gap: 9px; background: none; border: 0; color: var(--light-dim); font: 400 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; cursor: pointer; padding: 8px 4px; }
+.sound-bars { display: flex; align-items: flex-end; gap: 2px; height: 12px; }
+.sound-bars i { width: 2px; background: currentColor; height: 100%; animation: bars 1.2s ease-in-out infinite; }
+.sound-bars i:nth-child(2) { animation-delay: -.4s; } .sound-bars i:nth-child(3) { animation-delay: -.8s; }
+.sound.off .sound-bars i { animation: none; height: 2px; }
+@keyframes bars { 0%, 100% { height: 25%; } 50% { height: 100%; } }
+.btn { display: inline-flex; align-items: center; justify-content: center; height: 46px; padding: 0 24px; border-radius: 999px; text-decoration: none; border: 0; cursor: pointer;
+ font: 500 14px/1 var(--sans); letter-spacing: .08em; white-space: nowrap; transition: background .35s, color .35s, box-shadow .35s; }
+.btn-solid { background: var(--verm); color: #fff8f0; box-shadow: 0 10px 30px -12px rgba(224, 80, 58, .9); }
+.btn-solid:hover { background: #ec6248; }
+.btn-ghost { color: var(--light); box-shadow: inset 0 0 0 1px rgba(243,239,230,.35); background: rgba(8, 16, 12, .22); backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--light); }
+.btn-ink { height: 42px; padding: 0 22px; color: var(--ink); background: var(--washi); }
+.btn-ink:hover { background: #fff; }
+
+/* ─── Hero ─── */
+main { position: relative; z-index: 2; pointer-events: none; }
+.foot, .hero-cta, .paper, .nav a, .nav button { pointer-events: auto; }
+.hero { position: relative; height: 100vh; min-height: 640px; pointer-events: none; }
+.hero::before { content: ''; position: absolute; inset: 0; background: radial-gradient(90% 70% at 0% 100%, rgba(5, 12, 9, .62), transparent 62%), linear-gradient(0deg, rgba(5,12,9,.35), transparent 30%); pointer-events: none; }
+.hero-copy { position: absolute; left: var(--gutter); bottom: 12vh; max-width: min(760px, 62vw); }
+.eyebrow { font: 500 12px/1.4 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: var(--verm); margin-bottom: 22px; display: flex; align-items: center; gap: 14px; }
+.eyebrow .jp { letter-spacing: .3em; color: currentColor; opacity: .8; text-transform: none; font-size: 13px; }
+.hero .eyebrow { color: #f19a86; }
+.title { font: 500 clamp(52px, 7.4vw, 124px)/.98 var(--serif); letter-spacing: -.02em; color: var(--light); text-shadow: 0 2px 40px rgba(0, 10, 6, .45); }
+.title .line { display: block; overflow: hidden; padding-bottom: .04em; }
+.title em { font-style: normal; color: var(--verm); }
+.sub { max-width: 32em; margin-top: 28px; font: 400 clamp(15px, 1.2vw, 18px)/1.75 var(--sans); color: rgba(243, 239, 230, .86); text-shadow: 0 1px 18px rgba(0,0,0,.4); }
+.hero-cta { display: flex; gap: 14px; margin-top: 34px; pointer-events: auto; }
+.vert { writing-mode: vertical-rl; font: 500 15px/1 var(--serif); letter-spacing: .5em; color: rgba(243,239,230,.7); }
+.vert-hero { position: absolute; right: var(--gutter); bottom: 30vh; }
+.hint { position: absolute; right: var(--gutter); bottom: 9vh; display: flex; gap: 18px; align-items: center; color: var(--light-dim); font: 400 13px/1.9 var(--sans); letter-spacing: .04em; opacity: 0; transform: translateX(18px); transition: opacity 1.2s, transform 1.4s cubic-bezier(.2,.8,.2,1); }
+.ready .hint { opacity: 1; transform: none; }
+.hint ul { list-style: none; }
+.hint b { color: var(--light); font-weight: 500; }
+.hint-ring { position: relative; width: 46px; height: 46px; }
+.hint-ring i { position: absolute; inset: 0; border-radius: 50%; border: 1px solid rgba(243,239,230,.7); animation: ring 2.6s cubic-bezier(.2,.6,.3,1) infinite; }
+.hint-ring i:last-child { animation-delay: -1.3s; }
+.hint-ring::after { content: ''; position: absolute; left: 50%; top: 50%; width: 6px; height: 6px; margin: -3px; border-radius: 50%; background: var(--verm); }
+@keyframes ring { from { transform: scale(.2); opacity: 1; } to { transform: scale(1.35); opacity: 0; } }
+.has-fed .hint .hint-feed { opacity: .45; text-decoration: line-through; text-decoration-color: var(--verm); }
+.scroll-cue { position: absolute; left: 50%; bottom: 3.5vh; transform: translateX(-50%); display: grid; justify-items: center; gap: 10px; font: 400 11px/1 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: rgba(243,239,230,.55); transition: opacity .6s; }
+.scroll-cue i { width: 1px; height: 38px; background: linear-gradient(rgba(243,239,230,.7), transparent); animation: drip 2.4s ease-in-out infinite; transform-origin: top; }
+@keyframes drip { 0% { transform: scaleY(0); } 50% { transform: scaleY(1); } 100% { transform: scaleY(1); opacity: 0; } }
+.scrolled .scroll-cue, .ready.scrolled .hint { opacity: 0; }
+
+/* ─── Paper panels ─── */
+.paper { position: relative; background-color: var(--washi); background-image: var(--fibre), linear-gradient(160deg, #f6f3eb, #ece6d9); color: var(--ink);
+ border-radius: 2px; box-shadow: 0 40px 80px -30px rgba(0, 8, 5, .7), 0 2px 0 rgba(255,255,255,.5) inset; pointer-events: auto; }
+.paper .eyebrow { color: var(--verm-2); }
+.paper h2 { font: 500 clamp(30px, 3.3vw, 52px)/1.12 var(--serif); letter-spacing: -.01em; color: var(--ink); }
+.paper h2 em { font-style: normal; color: var(--verm-2); }
+.lede { margin-top: 20px; font: 400 clamp(15px, 1.05vw, 17px)/1.8 var(--sans); color: var(--ink-2); max-width: 34em; }
+.pin { position: sticky; top: 0; height: 100vh; display: flex; align-items: center; padding: 0 var(--gutter); pointer-events: none; }
+.steps { margin-top: -100vh; pointer-events: none; }
+.step { height: 100vh; }
+
+/* rooms */
+.rooms-paper { width: min(560px, 44vw); padding: 38px 40px 30px; margin-top: 4vh; }
+.room-deck { position: relative; margin-top: 28px; display: grid; }
+.room { grid-area: 1 / 1; display: grid; grid-template-columns: 170px 1fr; gap: 24px; opacity: 0; transform: translateY(14px); transition: opacity .7s, transform .9s cubic-bezier(.2,.8,.2,1); pointer-events: none; }
+.room.is-on { opacity: 1; transform: none; pointer-events: auto; }
+.room figure { aspect-ratio: 4 / 5; overflow: hidden; border-radius: 1px; background: #d9d2c3; }
+.room figure img { width: 100%; height: 100%; object-fit: cover; transform: scale(1.06); transition: transform 1.4s cubic-bezier(.2,.8,.2,1); }
+.room.is-on figure img { transform: scale(1); }
+.room-kind { display: flex; align-items: baseline; gap: 12px; font: 500 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--moss); }
+.jp-big { font: 600 26px/1 var(--serif); letter-spacing: .05em; color: var(--verm-2); text-transform: none; }
+.room h3 { font: 500 34px/1 var(--serif); margin: 12px 0 10px; }
+.room-body > p:not([class]) { font-size: 14px; line-height: 1.75; color: var(--ink-2); }
+.room-meta { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 14px; font: 500 11px/1 var(--sans); letter-spacing: .12em; text-transform: uppercase; color: var(--ink-2); }
+.room-meta span + span::before { content: '·'; margin-right: 14px; color: var(--verm); }
+.price { margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--paper-line); font-size: 13px; color: var(--ink-2); }
+.price b { font: 600 22px/1 var(--serif); color: var(--ink); margin: 0 4px; }
+.room-dots { list-style: none; display: flex; gap: 22px; margin-top: 26px; font: 500 11px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: rgba(22,36,30,.4); }
+.room-dots li { position: relative; padding-top: 12px; transition: color .5s; }
+.room-dots li::before { content: ''; position: absolute; top: 0; left: 0; width: 26px; height: 2px; background: currentColor; transition: width .6s, background .5s; }
+.room-dots li.is-on { color: var(--ink); }
+.room-dots li.is-on::before { background: var(--verm); width: 100%; }
+
+/* kaiseki */
+.kaiseki { position: relative; min-height: 150vh; display: flex; align-items: center; justify-content: flex-end; padding: 20vh var(--gutter); pointer-events: none; }
+.paper-dark { background: rgba(10, 18, 14, .64); background-image: none; color: var(--light); backdrop-filter: blur(16px) saturate(1.1); -webkit-backdrop-filter: blur(16px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px rgba(243,239,230,.1), 0 40px 80px -30px rgba(0,0,0,.8); }
+.paper-dark h2 { color: var(--light); }
+.paper-dark .eyebrow { color: #f0906e; }
+.paper-dark .lede { color: rgba(243,239,230,.74); }
+.kaiseki-paper { width: min(660px, 48vw); padding: 38px 42px 32px; }
+.kaiseki-paper h2 { font-size: clamp(28px, 2.6vw, 42px); }
+.menu { list-style: none; margin-top: 24px; border-top: 1px solid rgba(243,239,230,.12); display: grid; grid-template-columns: 1fr 1fr; column-gap: 28px; }
+.menu li { display: grid; grid-template-columns: 44px 1fr; gap: 2px 12px; align-items: baseline; padding: 12px 0; border-bottom: 1px solid rgba(243,239,230,.12); }
+.menu li > span:last-child { grid-column: 2; }
+.menu .jp { font-size: 17px; color: #f0906e; }
+.menu b { font: 500 16px/1.3 var(--serif); }
+.menu li > span:last-child { font-size: 14px; color: rgba(243,239,230,.7); line-height: 1.55; }
+.tea { display: grid; grid-template-columns: auto 1fr; gap: 22px; margin-top: 22px; align-items: start; }
+.tea-time { font: 500 40px/1 var(--serif); color: #ffc98a; letter-spacing: .02em; text-shadow: 0 0 30px rgba(255, 170, 90, .35); }
+.tea p:last-child { font-size: 14px; color: rgba(243,239,230,.78); }
+.tea b { color: var(--light); font-weight: 500; }
+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin-top: 22px; padding-top: 18px; border-top: 1px solid rgba(243,239,230,.12); }
+.stats b { display: block; font: 500 40px/1 var(--serif); color: var(--light); }
+.stats span { display: block; margin-top: 8px; font: 500 11px/1.4 var(--sans); letter-spacing: .14em; text-transform: uppercase; color: rgba(243,239,230,.55); }
+.vert-kaiseki { position: absolute; left: var(--gutter); top: 50%; transform: translateY(-50%); font-size: 30px; letter-spacing: .6em; color: rgba(255, 214, 170, .8); text-shadow: 0 0 40px rgba(255,160,80,.35); }
+
+/* seasons */
+.season-paper { width: min(470px, 38vw); padding: 38px 38px 30px; }
+.season-list { list-style: none; margin-top: 26px; }
+.season-list li { padding: 14px 0 14px 18px; border-left: 2px solid var(--paper-line); transition: border-color .6s, opacity .6s; opacity: .42; }
+.season-list li.is-on { border-color: var(--verm); opacity: 1; }
+.s-name { display: flex; justify-content: space-between; align-items: baseline; font: 500 20px/1.2 var(--serif); }
+.s-name em { font: 500 11px/1 var(--sans); font-style: normal; letter-spacing: .16em; text-transform: uppercase; color: var(--moss); }
+.season-list li p:last-child { font-size: 14px; color: var(--ink-2); line-height: 1.7; max-height: 0; overflow: hidden; transition: max-height .8s cubic-bezier(.2,.8,.2,1), margin .6s; }
+.season-list li.is-on p:last-child { max-height: 8em; margin-top: 8px; }
+.season-kanji { position: absolute; right: var(--gutter); top: 50%; transform: translateY(-50%); display: grid; }
+.season-kanji span { grid-area: 1 / 1; font: 600 clamp(120px, 16vw, 260px)/1 var(--serif); color: var(--washi); opacity: 0; transform: translateY(30px); transition: opacity 1s, transform 1.2s cubic-bezier(.2,.8,.2,1);
+ text-shadow: 0 10px 60px rgba(0,10,6,.5); mix-blend-mode: normal; }
+.season-kanji span.is-on { opacity: .8; transform: none; }
+
+/* reserve */
+.reserve { min-height: 130vh; display: flex; align-items: center; justify-content: center; padding: 20vh var(--gutter); pointer-events: none; }
+.reserve-paper { width: min(980px, 100%); padding: 48px 52px 38px; text-align: left; }
+.reserve-paper h2 { max-width: 20em; }
+.booking { display: grid; grid-template-columns: 1.4fr .8fr .8fr 1fr auto; gap: 14px; align-items: end; margin-top: 34px; }
+.booking label { display: grid; gap: 8px; font: 500 11px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--ink-2); }
+.booking input, .booking select { height: 48px; border: 0; border-bottom: 1px solid rgba(22,36,30,.3); background: transparent; font: 400 17px/1 var(--serif); color: var(--ink); padding: 0 2px; border-radius: 0; appearance: none; }
+.booking select { background-image: linear-gradient(45deg, transparent 50%, var(--ink-2) 50%), linear-gradient(135deg, var(--ink-2) 50%, transparent 50%); background-position: calc(100% - 12px) 22px, calc(100% - 7px) 22px; background-size: 5px 5px; background-repeat: no-repeat; }
+.booking input:focus, .booking select:focus { outline: none; border-bottom-color: var(--verm); }
+.booking .btn { height: 48px; }
+.fine { margin-top: 22px; font-size: 13px; color: var(--ink-2); }
+
+/* footer */
+.foot { position: relative; background-color: var(--washi); background-image: var(--fibre), linear-gradient(180deg, #f3efe6, #e8e1d2); color: var(--ink); padding: 90px var(--gutter) 46px; }
+.foot-inner { max-width: 1320px; margin: 0 auto; }
+.foot-mark { font: 500 clamp(54px, 9vw, 150px)/1 var(--serif); letter-spacing: -.02em; display: flex; align-items: baseline; gap: .25em; }
+.foot-mark .jp { color: var(--verm); font-size: .62em; letter-spacing: .05em; }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr) auto; gap: 40px; margin-top: 60px; padding-top: 28px; border-top: 1px solid var(--paper-line); font-size: 14px; line-height: 1.9; color: var(--ink-2); }
+.foot-cols nav { display: grid; gap: 4px; }
+.foot-cols nav a { text-decoration: none; color: var(--ink); }
+.foot-cols nav a:hover { color: var(--verm-2); }
+.foot-fine { margin-top: 56px; font-size: 12px; letter-spacing: .04em; color: rgba(22,36,30,.55); }
+
+.toast { position: fixed; left: 50%; bottom: 5vh; transform: translate(-50%, 16px); z-index: 40; max-width: min(92vw, 560px); padding: 14px 24px; border-radius: 999px;
+ background: var(--washi); color: var(--ink); font-size: 14px; box-shadow: 0 20px 40px -12px rgba(0,0,0,.5); opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; text-align: center; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+@media (max-width: 900px) {
+ .links, .sound-label { display: none; }
+ .nav { padding: 16px 18px; }
+ .hero-copy { max-width: none; right: 18px; bottom: 15vh; }
+ .title { font-size: clamp(44px, 12.5vw, 72px); }
+ .hint { left: 18px; right: auto; bottom: 4vh; font-size: 12px; }
+ .hint-ring { display: none; }
+ .touch .hint-draw, .touch .hint-still, .hint-still { display: none; }
+ .hint { bottom: 76px; }
+ .scroll-cue { display: none; }
+ .vert-hero, .hide-m { display: none; }
+ .pin { align-items: flex-end; padding: 0 12px 64px; }
+ .rooms-paper, .season-paper { width: 100%; padding: 22px 20px 18px; margin: 0; }
+ .rooms-paper .lede, .season-paper h2 { display: none; }
+ .paper h2 { font-size: 26px; }
+ .room { grid-template-columns: 96px 1fr; gap: 14px; }
+ .room-body > p:not([class]) { font-size: 13px; line-height: 1.6; display: -webkit-box; -webkit-line-clamp: 4; -webkit-box-orient: vertical; overflow: hidden; }
+ .room h3 { font-size: 26px; margin: 8px 0 6px; }
+ .room-meta { display: none; }
+ .room-dots { margin-top: 14px; }
+ .kaiseki { padding: 60vh 12px 12vh; justify-content: center; }
+ .kaiseki-paper { width: 100%; padding: 26px 22px; }
+ .menu { grid-template-columns: 1fr; }
+ .menu li { grid-template-columns: 40px 1fr; }
+ .menu li > span:last-child { grid-column: 2; }
+ .vert-kaiseki { top: 26vh; font-size: 22px; }
+ .season-kanji { right: 12px; top: 22vh; transform: none; }
+ .season-kanji span { font-size: 110px; }
+ .season-list li { padding: 8px 0 8px 14px; }
+ .reserve-paper { padding: 28px 22px; }
+ .booking { grid-template-columns: 1fr 1fr; }
+ .booking label:first-child, .booking .btn { grid-column: 1 / -1; }
+ .foot-cols { grid-template-columns: 1fr; gap: 20px; }
+ .stats b { font-size: 30px; }
+}
diff --git a/examples/koi/water.js b/examples/koi/water.js
new file mode 100644
index 0000000..450a5dd
--- /dev/null
+++ b/examples/koi/water.js
@@ -0,0 +1,349 @@
+// Still Water — the pond surface.
+// RippleSim: height-field wave equation in ping-pong float targets, plus a derived surface texture (h, dh/dx, dh/dz, laplacian).
+// waterMaterial: the surface shader — screen-space refraction of the under-water pass with depth absorption,
+// fresnel reflection of sky and maple canopy, sun glints, moon and lantern reflections.
+// patchUnder: caustics + depth-in-alpha for every material that is drawn in the under-water pass.
+import * as THREE from 'three';
+import { bakeTexture } from '../../src/core/textures.js';
+import { pondSDF } from './shape.js';
+
+const quadGeo = new THREE.PlaneGeometry(2, 2);
+const orthoCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+const FS_VERT = 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }';
+
+function pass(frag, uniforms) {
+ const mat = new THREE.ShaderMaterial({ vertexShader: FS_VERT, fragmentShader: frag, uniforms, depthTest: false, depthWrite: false });
+ const mesh = new THREE.Mesh(quadGeo, mat);
+ mesh.frustumCulled = false;
+ const scene = new THREE.Scene();
+ scene.add(mesh);
+ return { mat, scene, uniforms };
+}
+
+const MAX_DROPS = 24;
+
+export class RippleSim {
+ constructor(renderer, { res = 1024, x0 = -10, z0 = -8.5, size = 20 } = {}) {
+ this.renderer = renderer;
+ this.res = res;
+ this.rect = new THREE.Vector4(x0, z0, size, size / res); // xmin, zmin, size, texel (m)
+ const gl = renderer.getContext();
+ const floatOK = !!gl.getExtension('EXT_color_buffer_float');
+ const type = floatOK ? THREE.FloatType : THREE.HalfFloatType;
+ const opts = { type, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, depthBuffer: false, stencilBuffer: false, wrapS: THREE.ClampToEdgeWrapping, wrapT: THREE.ClampToEdgeWrapping };
+ this.a = new THREE.WebGLRenderTarget(res, res, opts);
+ this.b = new THREE.WebGLRenderTarget(res, res, opts);
+ this.surf = new THREE.WebGLRenderTarget(res, res, { type: THREE.HalfFloatType, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, depthBuffer: false, stencilBuffer: false });
+ this.texture = this.surf.texture;
+
+ // Land mask: waves reflect off the shore instead of running up the moss.
+ const MR = 256, md = new Uint8Array(MR * MR * 4);
+ for (let j = 0; j < MR; j++) for (let i = 0; i < MR; i++) {
+ const x = x0 + (i + 0.5) / MR * size, z = z0 + (j + 0.5) / MR * size;
+ const d = pondSDF(x, z);
+ const m = Math.min(1, Math.max(0, (-d + 0.02) / 0.18));
+ md.set([m * 255, m * 255, m * 255, 255], (j * MR + i) * 4);
+ }
+ this.mask = new THREE.DataTexture(md, MR, MR, THREE.RGBAFormat);
+ this.mask.magFilter = this.mask.minFilter = THREE.LinearFilter;
+ this.mask.needsUpdate = true;
+
+ this.dropA = Array.from({ length: MAX_DROPS }, () => new THREE.Vector4());
+ this.dropB = Array.from({ length: MAX_DROPS }, () => new THREE.Vector4());
+ this.queue = [];
+ this.stepPass = pass(/* glsl */`
+ precision highp float;
+ uniform sampler2D uPrev, uMask; uniform vec2 uTexel; uniform float uDamp;
+ uniform vec4 uDropA[${MAX_DROPS}]; uniform vec4 uDropB[${MAX_DROPS}]; uniform int uN;
+ varying vec2 vUv;
+ void main(){
+ vec4 info = texture2D(uPrev, vUv);
+ float avg = (texture2D(uPrev, vUv - vec2(uTexel.x, 0.)).r + texture2D(uPrev, vUv + vec2(uTexel.x, 0.)).r +
+ texture2D(uPrev, vUv - vec2(0., uTexel.y)).r + texture2D(uPrev, vUv + vec2(0., uTexel.y)).r) * 0.25;
+ info.g += (avg - info.r) * 2.0;
+ info.g *= uDamp;
+ info.r += info.g;
+ info.r *= 0.99965;
+ for (int i = 0; i < ${MAX_DROPS}; i++) {
+ if (i >= uN) break;
+ vec4 a = uDropA[i]; vec4 b = uDropB[i];
+ vec2 pa = vUv - a.xy, ba = a.zw - a.xy;
+ float t = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-12), 0., 1.);
+ float d = length(pa - ba * t) / b.x;
+ if (d < 1.) info.r += (0.5 + 0.5 * cos(3.14159265 * d)) * b.y;
+ }
+ float m = texture2D(uMask, vUv).r;
+ info.rg *= m;
+ gl_FragColor = info;
+ }`, {
+ uPrev: { value: null }, uMask: { value: this.mask }, uTexel: { value: new THREE.Vector2(1 / res, 1 / res) }, uDamp: { value: 0.9955 },
+ uDropA: { value: this.dropA }, uDropB: { value: this.dropB }, uN: { value: 0 },
+ });
+ this.surfPass = pass(/* glsl */`
+ precision highp float;
+ uniform sampler2D uSim; uniform vec2 uTexel; uniform float uTw;
+ varying vec2 vUv;
+ void main(){
+ float h = texture2D(uSim, vUv).r;
+ float l = texture2D(uSim, vUv - vec2(uTexel.x, 0.)).r, r = texture2D(uSim, vUv + vec2(uTexel.x, 0.)).r;
+ float d = texture2D(uSim, vUv - vec2(0., uTexel.y)).r, u = texture2D(uSim, vUv + vec2(0., uTexel.y)).r;
+ gl_FragColor = vec4(h, (r - l) / (2. * uTw), (u - d) / (2. * uTw), (l + r + u + d - 4. * h) / (uTw * uTw));
+ }`, { uSim: { value: null }, uTexel: { value: new THREE.Vector2(1 / res, 1 / res) }, uTw: { value: size / res } });
+ this.acc = 0;
+ this.clear();
+ }
+
+ clear() {
+ const r = this.renderer, prev = r.getRenderTarget();
+ for (const t of [this.a, this.b, this.surf]) { r.setRenderTarget(t); r.setClearColor(0, 0); r.clear(); }
+ r.setRenderTarget(prev);
+ }
+
+ /** A soft disc (or capsule from a to b) of displaced water, in world metres. strength in metres of height. */
+ drop(x, z, radius = 0.06, strength = 0.01, x2 = x, z2 = z) {
+ if (this.queue.length > 96) return;
+ this.queue.push([x, z, x2, z2, radius, strength]);
+ }
+
+ step(dt) {
+ const r = this.renderer;
+ const prevTarget = r.getRenderTarget();
+ const prevAuto = r.autoClear;
+ r.autoClear = false;
+ this.acc = Math.min(this.acc + dt * 60, 3);
+ const R = this.rect;
+ const toU = (x, z) => [(x - R.x) / R.z, (z - R.y) / R.z];
+ let steps = 0;
+ while (this.acc >= 1 || (steps === 0 && this.queue.length)) {
+ this.acc = Math.max(0, this.acc - 1);
+ const n = Math.min(MAX_DROPS, this.queue.length);
+ for (let i = 0; i < n; i++) {
+ const [x, z, x2, z2, rad, s] = this.queue.shift();
+ const [u1, v1] = toU(x, z), [u2, v2] = toU(x2, z2);
+ this.dropA[i].set(u1, v1, u2, v2);
+ this.dropB[i].set(rad / R.z, s, 0, 0);
+ }
+ const u = this.stepPass.uniforms;
+ u.uN.value = n;
+ u.uPrev.value = this.a.texture;
+ r.setRenderTarget(this.b);
+ r.render(this.stepPass.scene, orthoCam);
+ [this.a, this.b] = [this.b, this.a];
+ steps++;
+ if (steps > 3) break;
+ }
+ this.surfPass.uniforms.uSim.value = this.a.texture;
+ r.setRenderTarget(this.surf);
+ r.render(this.surfPass.scene, orthoCam);
+ r.setRenderTarget(prevTarget);
+ r.autoClear = prevAuto;
+ }
+}
+
+// ─── Procedural textures ───────────────────────────────────────────────────────
+export function causticTexture(renderer) {
+ const t = bakeTexture(renderer, 1024, /* glsl */`
+ vec2 h2(vec2 p){ p = mod(p, 7.0); return fract(sin(vec2(dot(p, vec2(127.1, 311.7)), dot(p, vec2(269.5, 183.3)))) * 43758.5453); }
+ void main(){
+ vec2 p = vUv * 7.0;
+ p += vec2(fbm(vUv * 3., 3., 3, .5), fbm(vUv * 3. + 5.3, 3., 3, .5)) * 1.1;
+ vec2 ip = floor(p), fp = fract(p);
+ float f1 = 9., f2 = 9.;
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
+ vec2 g = vec2(float(i), float(j));
+ vec2 r = g + h2(ip + g) * 0.9 + 0.05 - fp;
+ float d = dot(r, r);
+ if (d < f1) { f2 = f1; f1 = d; } else if (d < f2) f2 = d;
+ }
+ float e = sqrt(f2) - sqrt(f1);
+ float c = pow(1.0 - smoothstep(0.0, 0.2, e), 2.2) + pow(1.0 - smoothstep(0.0, 0.5, e), 3.0) * 0.25;
+ gl_FragColor = vec4(vec3(c), 1.);
+ }`);
+ return t;
+}
+
+/** Small wind ripples: RG = tangent-space slope, B = broad breeze patches. Tileable. */
+export function microTexture(renderer) {
+ return bakeTexture(renderer, 512, /* glsl */`
+ float H(vec2 p){ return fbm(p * 5., 5., 3, .45); }
+ void main(){
+ float e = 1. / 512.;
+ float hx = H(vUv + vec2(e, 0.)) - H(vUv - vec2(e, 0.));
+ float hy = H(vUv + vec2(0., e)) - H(vUv - vec2(0., e));
+ vec2 s = vec2(hx, hy) * 30.;
+ float b = fbm(vUv * 2., 2., 4, .5) * .5 + .5;
+ gl_FragColor = vec4(s * .5 + .5, b, 1.);
+ }`);
+}
+
+// ─── Caustics + depth output for under-water materials ─────────────────────────
+export const underShared = {
+ uSurf: { value: null }, uSimRect: { value: new THREE.Vector4() }, uCaust: { value: null }, uTime: { value: 0 },
+ uSunRefr: { value: new THREE.Vector2(0.2, 0.3) }, uCaustK: { value: 1 }, uDepthOut: { value: 0 }, uFocus: { value: 0.006 },
+ uLightAbs: { value: new THREE.Vector3(0.55, 0.16, 0.3) },
+ uCookie: { value: null }, uCanopyMat: { value: new THREE.Matrix3() }, uCanopyH: { value: 6.5 }, uKeyDir: { value: new THREE.Vector3(0, 1, 0) },
+ uDappleK: { value: 1 }, uLeafLight: { value: 0.16 },
+};
+export const CAUSTIC_GLSL = /* glsl */`
+ uniform sampler2D uSurf, uCaust, uCookie; uniform vec4 uSimRect; uniform float uTime, uCaustK, uDepthOut, uFocus, uCanopyH, uDappleK, uLeafLight;
+ uniform vec2 uSunRefr; uniform vec3 uLightAbs, uKeyDir; uniform mat3 uCanopyMat;
+ varying vec3 vWP;
+ float dappleAt(vec3 wp){
+ float t = (uCanopyH - wp.y) / max(uKeyDir.y, 0.08);
+ vec2 cuv = (uCanopyMat * vec3(wp.xz + uKeyDir.xz * t, 1.)).xy;
+ vec2 e = smoothstep(vec2(0.), vec2(0.08), cuv) * smoothstep(vec2(1.), vec2(0.92), cuv);
+ float c = texture2D(uCookie, cuv, 0.6).r;
+ return mix(1., mix(uLeafLight, 1., smoothstep(0.25, 0.85, c)), e.x * e.y * uDappleK);
+ }
+ vec3 causticsAt(vec3 wp){
+ float depth = max(-wp.y, 0.);
+ vec2 sp = wp.xz + uSunRefr * depth;
+ vec4 s = texture2D(uSurf, (sp - uSimRect.xy) / uSimRect.z);
+ vec2 p = sp * 0.42 + s.yz * depth * 0.08;
+ float c1 = texture2D(uCaust, p + vec2(uTime * 0.013, uTime * 0.008)).r;
+ float c2 = texture2D(uCaust, p * 1.17 + vec2(-uTime * 0.011, uTime * 0.012) + 0.37).r;
+ float c = pow((c1 + c2) * 0.5, 1.2) * 1.45;
+ float focus = clamp(-s.w * uFocus * min(depth, 1.2), -0.85, 2.5);
+ float k = smoothstep(0.0, 0.18, depth) * uCaustK;
+ return max(mix(1.0, (0.3 + c * 2.8) * (1.0 + focus), k), 0.0) * exp(-uLightAbs * depth);
+ }
+`;
+
+/** Patch a standard material so it gets caustics under water and writes view distance to alpha in the under pass. */
+export function patchUnder(mat, { extraVertexHead = '', extraFragHead = '', mapFragment = null, roughFragment = null, custom = null, key = '' } = {}) {
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (shader, r) => {
+ Object.assign(shader.uniforms, underShared);
+ custom?.uniforms && Object.assign(shader.uniforms, custom.uniforms);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWP;\n' + extraVertexHead)
+ .replace('#include <worldpos_vertex>', `#include <worldpos_vertex>
+ vec4 kwp = vec4(transformed, 1.0);
+ #ifdef USE_INSTANCING
+ kwp = instanceMatrix * kwp;
+ #endif
+ vWP = (modelMatrix * kwp).xyz;`);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\n' + CAUSTIC_GLSL + extraFragHead)
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\nfloat kDap = dappleAt(vWP); vec3 kCaust = mix(vec3(1.), causticsAt(vWP), smoothstep(0.25, 0.85, kDap)) * kDap;')
+ .replace('#include <lights_fragment_begin>', THREE.ShaderChunk.lights_fragment_begin
+ .replace('getDirectionalLightInfo( directionalLight, directLight );', 'getDirectionalLightInfo( directionalLight, directLight );\ndirectLight.color *= kCaust;'))
+ .replace('#include <dithering_fragment>', '#include <dithering_fragment>\nif (uDepthOut > 0.5) gl_FragColor.a = length(vViewPosition);');
+ if (mapFragment) shader.fragmentShader = shader.fragmentShader.replace('#include <map_fragment>', mapFragment);
+ if (roughFragment) shader.fragmentShader = shader.fragmentShader.replace('#include <roughnessmap_fragment>', roughFragment);
+ prev?.(shader, r);
+ custom?.patch?.(shader);
+ };
+ const prevKey = mat.customProgramCacheKey?.bind(mat);
+ mat.customProgramCacheKey = () => 'under' + key + (prevKey ? prevKey() : '');
+ return mat;
+}
+
+// ─── The surface ───────────────────────────────────────────────────────────────
+export function waterMaterial(u) {
+ return new THREE.ShaderMaterial({
+ uniforms: u,
+ vertexShader: /* glsl */`
+ varying vec3 vW;
+ void main(){ vec4 w = modelMatrix * vec4(position, 1.); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }`,
+ fragmentShader: /* glsl */`
+ precision highp float;
+ uniform sampler2D uUnder, uSurf, uMicro, uCanopy, uCookie, uRefl; uniform mat4 uReflMat;
+ uniform vec2 uUnderSize; uniform vec4 uSimRect;
+ uniform mat3 uCanopyMat; uniform float uCanopyH;
+ uniform vec3 uSunDir, uSunCol, uZenith, uHorizon, uAbsorb, uScatter, uMoonDir, uMoonCol, uLampPos, uLampCol, uLeafTint;
+ uniform float uTime, uSlope, uRefr, uWind, uAutumn, uBare, uGlint, uCanopyK, uReflK, uDebug, uMicroK;
+ varying vec3 vW;
+
+ vec3 skyAt(vec3 R, vec3 R0, vec3 P, float blur){
+ float up = max(R.y, 0.03);
+ vec3 sky = mix(uHorizon, uZenith, pow(up, 0.55));
+ float t = (uCanopyH - P.y) / up;
+ vec2 q = P.xz + R.xz * t;
+ vec2 cuv = (uCanopyMat * vec3(q, 1.)).xy;
+ vec2 e = smoothstep(vec2(0.), vec2(0.08), cuv) * smoothstep(vec2(1.), vec2(0.92), cuv);
+ float inside = e.x * e.y * uCanopyK;
+ vec3 c = texture2D(uCanopy, cuv, blur).rgb;
+ float lum = dot(c, vec3(0.3, 0.55, 0.15));
+ float leaf = 1. - smoothstep(0.35, 0.9, lum);
+ vec3 autumn = uLeafTint * (0.25 + lum * 1.6);
+ vec3 tr = mix(c, mix(c, autumn, leaf), uAutumn);
+ tr = mix(tr, vec3(1.), uBare * leaf * 0.75);
+ sky *= mix(vec3(1.), tr, inside);
+ float md = dot(R0, uMoonDir);
+ sky += uMoonCol * (smoothstep(0.999969, 0.999982, md) * 70. + pow(max(md, 0.), 9000.) * 0.8 + pow(max(md, 0.), 60.) * 0.015);
+ // a scatter of stars where the canopy opens
+ vec2 sg = R0.xz / max(R0.y, 0.2) * 70.;
+ float sh = fract(sin(dot(floor(sg), vec2(12.9898, 78.233))) * 43758.5453);
+ vec2 sf = fract(sg) - 0.5;
+ float star = smoothstep(0.9965, 1.0, sh) * smoothstep(0.32, 0.0, length(sf));
+ sky += uMoonCol * star * 3.5 * (1. - inside * leaf);
+ vec3 lp = uLampPos - P;
+ float lg = max(dot(R0, normalize(lp)), 0.);
+ sky += uLampCol * (pow(lg, 2600.) * 30. + pow(lg, 160.) * 0.5 + pow(lg, 12.) * 0.03);
+ return sky;
+ }
+
+ void main(){
+ vec2 suv = (vW.xz - uSimRect.xy) / uSimRect.z;
+ vec4 s = texture2D(uSurf, suv);
+ vec3 n = normalize(vec3(-s.y * uSlope, 1., -s.z * uSlope));
+ vec3 m1 = texture2D(uMicro, vW.xz * 0.23 + uTime * vec2(0.011, 0.007)).xyz;
+ vec3 m2 = texture2D(uMicro, vW.xz * 0.61 + uTime * vec2(-0.009, 0.013)).xyz;
+ float breeze = smoothstep(0.52, 0.78, texture2D(uMicro, vW.xz * 0.018 + uTime * vec2(0.0045, 0.003)).b);
+ vec2 mslope = (m1.xy * 2. - 1.) + (m2.xy * 2. - 1.) * 0.6;
+ mslope *= uMicroK;
+ n = normalize(n + vec3(mslope.x, 0., mslope.y) * (0.022 + breeze * uWind));
+
+ vec3 V = normalize(cameraPosition - vW);
+ float NdV = clamp(dot(n, V), 0., 1.);
+ float F = (0.02 + 0.98 * pow(1. - NdV, 5.)) * uReflK;
+
+ vec2 sc = gl_FragCoord.xy / uUnderSize;
+ float dS = length(cameraPosition - vW);
+ vec4 u0 = texture2D(uUnder, sc);
+ float L0 = max(u0.a - dS, 0.);
+ vec3 nv = mat3(viewMatrix) * vec3(n.x, 0., n.z);
+ vec2 off = nv.xy * uRefr * min(L0 + 0.1, 1.4);
+ vec2 ruv = sc - off;
+ ruv = clamp(ruv, vec2(0.002), vec2(0.998));
+ vec4 u1 = texture2D(uUnder, ruv);
+ float L = u1.a - dS;
+ if (L < 0.) { u1 = u0; L = L0; }
+ vec3 Tr = exp(-uAbsorb * L);
+ vec3 scat = uScatter * (1. - exp(-L * 1.3));
+ vec3 refr = u1.rgb * Tr + scat;
+
+ // ripples read in a photograph mostly through what they reflect: exaggerate the reflection normal
+ vec3 nR = normalize(vec3(-s.y * uSlope * 2.6 + mslope.x * (0.03 + breeze * uWind), 1., -s.z * uSlope * 2.6 + mslope.y * (0.03 + breeze * uWind)));
+ vec3 R = reflect(-V, nR);
+ float blur = clamp(length(s.yz) * 1.5 + breeze * 1.5, 0., 5.);
+ vec3 R0 = reflect(-V, n);
+ vec3 refl = skyAt(R, R0, vW, blur);
+ // the garden itself — banks, lantern, lotus, the maple limb — mirrored in the water
+ vec4 rp = uReflMat * vec4(vW, 1.0);
+ vec2 rduv = rp.xy / rp.w + (mat3(viewMatrix) * vec3(nR.x - n.x * 0.0, 0., nR.z)).xy * 0.09;
+ vec4 ro = texture2D(uRefl, rduv, blur * 0.5);
+ refl = mix(refl, ro.rgb, clamp(ro.a, 0., 1.));
+ float slope = length(s.yz);
+ F = max(F, 0.035 * uReflK) + smoothstep(0.03, 0.4, slope) * 0.05 * uReflK;
+ vec3 col = mix(refr, refl, F);
+ // lit and shaded flanks of each ripple, as the eye reads them on a still pond
+ vec2 ld = normalize(uSunDir.xz + vec2(0.0001));
+ col += uHorizon * 0.018 * clamp(dot(-s.yz, ld) * 1.6 + slope * 0.6, -0.6, 1.2);
+
+ float tt = (uCanopyH - vW.y) / max(uSunDir.y, 0.08);
+ vec2 cuv = (uCanopyMat * vec3(vW.xz + uSunDir.xz * tt, 1.)).xy;
+ vec2 ce = smoothstep(vec2(0.), vec2(0.08), cuv) * smoothstep(vec2(1.), vec2(0.92), cuv);
+ float lit = mix(1., smoothstep(0.3, 0.9, texture2D(uCookie, cuv).r), ce.x * ce.y * uCanopyK);
+ float sd = max(dot(R, uSunDir), 0.);
+ col += uSunCol * lit * uGlint * pow(sd, 2400.) * 140.;
+ // shallow shoreline: a soft meniscus sheen
+ col += refl * smoothstep(0.08, 0.0, L) * 0.08;
+ if (uDebug > 0.5 && uDebug < 1.5) col = u0.rgb;
+ if (uDebug > 1.5 && uDebug < 2.5) col = refl;
+ if (uDebug > 2.5 && uDebug < 3.5) col = vec3(fract(u0.a), fract(dS), L * 0.3);
+ gl_FragColor = vec4(col, 1.);
+ }`,
+ });
+}
diff --git a/examples/lithos/geode.js b/examples/lithos/geode.js
new file mode 100644
index 0000000..e8bed04
--- /dev/null
+++ b/examples/lithos/geode.js
@@ -0,0 +1,414 @@
+// The closed geode: two copies of the cut half, the top one mirrored across the measured cut plane so the rims
+// meet exactly. Hold to crack (violet seam glow, falling grit, tremble), release the stone at 100%.
+import { THREE, clamp, lerp, smooth } from '../../src/core/engine.js';
+import { firstMesh } from '../../src/core/assets.js';
+import { gsap } from '../../src/core/scroll.js';
+import { patchGeode } from './materials.js';
+
+// Cut plane of models/lithos/geode.glb, measured once offline (max-coplanar-vertex search): unit normal, offset along it, rim centroid.
+const PLANE_N = new THREE.Vector3(-0.01168, 0.74314, 0.66903).normalize();
+const PLANE_D = 0.2214;
+const RIM_C = new THREE.Vector3(0.00324, 0.59829, -0.34094);
+const WIDTH = 1.9;
+const HOLD_TIME = 1.9;
+const UP = new THREE.Vector3(0, 1, 0);
+
+export class Geode {
+ constructor(gltf, { size = 1, position = new THREE.Vector3(), scene, camera, renderer }) {
+ this.scene = scene; this.camera = camera;
+ this.S = size / WIDTH;
+ const S = this.S;
+ const src = gltf.scene;
+ src.position.set(0, 0, 0); src.updateMatrixWorld(true);
+ const mesh = firstMesh(src);
+ const meshRel = mesh.matrixWorld.clone();
+ const c = RIM_C.clone().addScaledVector(PLANE_N, PLANE_D - 0.0015 - RIM_C.dot(PLANE_N));
+ const q = new THREE.Quaternion().setFromUnitVectors(PLANE_N, UP);
+ this.toHalf = new THREE.Matrix4().compose(new THREE.Vector3(), q, new THREE.Vector3(S, S, S))
+ .multiply(new THREE.Matrix4().makeTranslation(-c.x, -c.y, -c.z)).multiply(meshRel);
+
+ this.u = {
+ uToHalf: { value: this.toHalf }, uSeal: { value: 1 }, uSeamY: { value: 0.02 }, uCrack: { value: 0 }, uGlint: { value: 0 }, uInner: { value: 0 }, uTime: { value: 0 },
+ uGlintScale: { value: 95 }, uCrackColor: { value: new THREE.Color(0x9d6bff).multiplyScalar(1.6) },
+ uL1Pos: { value: new THREE.Vector3() }, uL1Col: { value: new THREE.Vector3() },
+ uL2Pos: { value: new THREE.Vector3() }, uL2Col: { value: new THREE.Vector3() },
+ };
+ patchGeode(mesh.material, { ...this.u, uSide: { value: -1 } });
+ mesh.material.envMapIntensity = 0.55;
+ this.mat = mesh.material;
+ mesh.castShadow = mesh.receiveShadow = true;
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+ for (const k of ['map', 'normalMap', 'roughnessMap']) if (mesh.material[k]) mesh.material[k].anisotropy = aniso;
+
+ // Geometry in half space: rest height, rim ring (dust), cavity points (burst).
+ const pos = mesh.geometry.attributes.position, nor = mesh.geometry.attributes.normal;
+ const nm = new THREE.Matrix3().getNormalMatrix(this.toHalf);
+ const P = new THREE.Vector3(), N = new THREE.Vector3();
+ let minY = 0, maxR = 0;
+ const rim = [], cav = [], cavN = [], all = [];
+ for (let i = 0; i < pos.count; i++) {
+ P.fromBufferAttribute(pos, i).applyMatrix4(this.toHalf);
+ minY = Math.min(minY, P.y);
+ const r = Math.hypot(P.x, P.z);
+ maxR = Math.max(maxR, r);
+ if (i % 3 === 0) all.push(P.x, P.y, P.z);
+ if (Math.abs(P.y) < 0.008) rim.push([P.x, P.z, r]);
+ N.fromBufferAttribute(nor, i).applyMatrix3(nm).normalize();
+ if (P.y < -0.03 && N.dot(P.clone().normalize()) < -0.25 && i % 2 === 0) { cav.push(P.x, P.y, P.z); cavN.push(N.x, N.y, N.z); }
+ }
+ this.depth = -minY;
+ this.all = all;
+ const rimMax = rim.reduce((m, p) => Math.max(m, p[2]), 0);
+ this.rim = rim.filter(p => p[2] > rimMax * 0.93);
+ this.rimR = rimMax;
+ this.cav = cav;
+ this.cavN = cavN;
+ this.radius = maxR;
+
+ // Hierarchy: pair (tremble) -> root (animated) -> flip (mirror) -> align (plane to y=0) -> gltf scene.
+ this.group = new THREE.Group();
+ this.group.position.copy(position);
+ scene.add(this.group);
+ this.pair = new THREE.Group();
+ this.group.add(this.pair);
+ const half = (mirror) => {
+ const root = new THREE.Group();
+ const flip = new THREE.Group(); if (mirror) flip.scale.y = -1;
+ const align = new THREE.Group(); align.quaternion.copy(q); align.scale.setScalar(S);
+ const inner = mirror ? src.clone(true) : src;
+ inner.position.copy(c).negate();
+ if (mirror) {
+ // Same maps and uniforms, different crack pattern, so the lid is not a mirror image of the base.
+ const mm = firstMesh(inner);
+ mm.material = patchGeode(this.mat.clone(), { ...this.u, uSide: { value: 1 } });
+ }
+ align.add(inner); flip.add(align); root.add(flip);
+ root.position.y = this.depth - 0.018;
+ root.userData.flip = flip;
+ this.pair.add(root);
+ return root;
+ };
+ this.bottom = half(false);
+ this.top = half(true);
+ this.seamY = this.depth - 0.018;
+
+ // Where the lid comes to rest: standing behind, leaning back, its cavity turned to the room.
+ this.restN = new THREE.Vector3(-0.3, 0.5, 0.81).normalize();
+ this.restQ = new THREE.Quaternion().setFromUnitVectors(new THREE.Vector3(0, -1, 0), this.restN);
+ let lo = 0;
+ const tmp = new THREE.Vector3();
+ for (let i = 0; i < all.length; i += 3) { tmp.set(all[i], -all[i + 1], all[i + 2]).applyQuaternion(this.restQ); lo = Math.min(lo, tmp.y); }
+ this.restPos = new THREE.Vector3(0.88, -lo - 0.02, -0.36);
+ this.bottomTilt = 0.34;
+ this.closeGap = 0.04;
+
+ this.state = 'closed';
+ this.hold = 0;
+ this.open = 0; // 0 closed .. 1 fully open (camera blend)
+ this.lidT = 0; // lid path parameter
+ this.burstT = -1;
+ this.listeners = [];
+ this.front = new THREE.Vector3(0, this.seamY, 0);
+ let best = -1e9;
+ for (const [x, z] of this.rim) if (z > best) { best = z; this.front.set(x, this.seamY, z); }
+ this.front.add(position);
+
+ this._buildDust();
+ this._buildBurst();
+ this._buildChips();
+ this.flareU = { uL1: { value: new THREE.Vector3() }, uL2: { value: new THREE.Vector3() }, uC1: { value: 0 }, uC2: { value: 0 }, uGlint: this.u.uGlint, uTime: this.u.uTime, uDpr: { value: 1 } };
+ for (const r of [this.bottom, this.top]) r.userData.flip.add(this._buildFlares(r === this.top ? 7.1 : 0));
+ this.burstLight = new THREE.PointLight(0xa47bff, 0, 3.5, 2);
+ this.burstLight.position.set(0, this.seamY - 0.08, 0);
+ this.group.add(this.burstLight);
+ }
+
+ on(f) { this.listeners.push(f); }
+ _emit(e) { for (const f of this.listeners) f(e); }
+
+ // ── falling grit from the seam ─────────────────────────────────────────────
+ _buildDust() {
+ const N = 2200;
+ const p = new Float32Array(N * 3), d = new Float32Array(N * 3), s = new Float32Array(N * 4);
+ for (let i = 0; i < N; i++) {
+ const [x, z] = this.rim[(Math.random() * this.rim.length) | 0];
+ p.set([x, this.seamY, z], i * 3);
+ const l = Math.hypot(x, z) || 1;
+ d.set([x / l, 0, z / l], i * 3);
+ s.set([Math.random(), Math.random(), Math.random(), Math.random()], i * 4);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(p, 3));
+ g.setAttribute('dir', new THREE.BufferAttribute(d, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(s, 4));
+ this.dustMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uEmit: { value: 0 }, uDpr: { value: 1 }, uColor: { value: new THREE.Color(0x9d6bff) } },
+ vertexShader: /* glsl */`
+ attribute vec3 dir; attribute vec4 seed; uniform float uTime, uEmit, uDpr; varying float vA; varying float vHot;
+ float h(float n){ return fract(sin(n) * 43758.5453); }
+ void main(){
+ float period = 0.9 + seed.x * 1.1;
+ float ph = uTime / period + seed.y * 17.0;
+ float age = fract(ph);
+ float alive = step(h(floor(ph) * 7.13 + seed.z * 91.7), uEmit * 0.9);
+ float t = age * period;
+ vec3 p = position + dir * (0.004 + t * (0.03 + seed.w * 0.05)) + vec3(0.0, -2.6 * t * t, 0.0);
+ vec4 wp = modelMatrix * vec4(p, 1.0);
+ wp.y = max(wp.y, 0.006);
+ vHot = 1.0 - smoothstep(0.0, 0.12, t);
+ vA = alive * (1.0 - smoothstep(0.55, 1.0, age)) * smoothstep(0.01, 0.06, wp.y);
+ vec4 mv = viewMatrix * wp;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (0.7 + seed.w * 1.5) * uDpr * (3.0 / -mv.z);
+ if (vA < 0.002) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uColor; varying float vA; varying float vHot;
+ void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .1, d) * vA;
+ if (a < 0.003) discard;
+ vec3 c = mix(vec3(0.34, 0.31, 0.29), uColor * 5.0, vHot);
+ gl_FragColor = vec4(c, a); }`,
+ });
+ const pts = new THREE.Points(g, this.dustMat);
+ pts.frustumCulled = false;
+ this.pair.add(pts);
+ this.dust = pts;
+ }
+
+ // ── violet glitter released when the stone opens ──────────────────────────
+ _buildBurst() {
+ const src = this.cav;
+ const N = 2600;
+ const p = new Float32Array(N * 3), v = new Float32Array(N * 3), s = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const k = ((Math.random() * (src.length / 3)) | 0) * 3;
+ p.set([src[k], src[k + 1] + this.seamY, src[k + 2]], i * 3);
+ const a = Math.random() * Math.PI * 2, sp = 0.15 + Math.random() * 0.9;
+ v.set([Math.cos(a) * sp * 0.55 + src[k] * 1.2, 0.5 + Math.random() * 1.6, Math.sin(a) * sp * 0.55 + src[k + 2] * 1.2], i * 3);
+ s[i] = Math.random();
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(p, 3));
+ g.setAttribute('vel', new THREE.BufferAttribute(v, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(s, 1));
+ this.burstMat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uT: { value: -1 }, uDpr: { value: 1 }, uTime: { value: 0 } },
+ vertexShader: /* glsl */`
+ attribute vec3 vel; attribute float seed; uniform float uT, uDpr, uTime; varying float vA; varying float vS;
+ void main(){
+ float t = max(uT - seed * 0.25, 0.0);
+ vec3 p = position + vel * t * (0.55 + seed * 0.5) + vec3(0.0, -1.1 * t * t, 0.0);
+ vec4 wp = modelMatrix * vec4(p, 1.0);
+ wp.y = max(wp.y, 0.006);
+ vA = step(0.0, uT) * exp(-t * (0.9 + seed * 1.6)) * smoothstep(0.0, 0.05, t);
+ vS = 0.55 + 0.45 * sin(uTime * (9.0 + seed * 14.0) + seed * 60.0);
+ vec4 mv = viewMatrix * wp;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (1.0 + seed * 2.6) * uDpr * (3.4 / -mv.z);
+ if (vA < 0.002) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA; varying float vS;
+ void main(){ vec2 q = gl_PointCoord - .5; float d = length(q);
+ float core = smoothstep(.5, .0, d); float cross = max(smoothstep(.06, .0, abs(q.x)), smoothstep(.06, .0, abs(q.y))) * smoothstep(.5, .1, d);
+ float a = (core + cross * 0.6) * vA * vS;
+ if (a < 0.003) discard;
+ vec3 c = mix(vec3(0.62, 0.42, 1.0), vec3(1.0, 0.95, 1.0), core * core) * 6.0;
+ gl_FragColor = vec4(c, min(a, 1.0)); }`,
+ });
+ const pts = new THREE.Points(g, this.burstMat);
+ pts.frustumCulled = false;
+ this.group.add(pts);
+ }
+
+ // ── stone chips that spit off the seam ────────────────────────────────────
+ _buildChips() {
+ const N = 46;
+ const geo = new THREE.IcosahedronGeometry(1, 0);
+ const mat = new THREE.MeshStandardMaterial({ color: 0x7d746b, roughness: 0.92, metalness: 0 });
+ this.chips = new THREE.InstancedMesh(geo, mat, N);
+ this.chips.castShadow = true;
+ this.chips.count = 0;
+ this.chipState = [];
+ for (let i = 0; i < N; i++) {
+ const [x, z] = this.rim[(Math.random() * this.rim.length) | 0];
+ const l = Math.hypot(x, z) || 1;
+ const sp = 0.4 + Math.random() * 1.1;
+ this.chipState.push({
+ p: new THREE.Vector3(x, this.seamY, z), v: new THREE.Vector3(x / l * sp, 0.4 + Math.random() * 1.2, z / l * sp),
+ r: new THREE.Euler(Math.random() * 6, Math.random() * 6, Math.random() * 6), w: new THREE.Vector3().randomDirection().multiplyScalar(8 + Math.random() * 14),
+ s: 0.006 + Math.random() ** 2 * 0.02, rest: false,
+ });
+ }
+ this.group.add(this.chips);
+ this._m = new THREE.Matrix4(); this._q = new THREE.Quaternion(); this._sv = new THREE.Vector3();
+ }
+
+ // ── star flares: facets that catch the key or the cursor light flash into four-point stars ─────
+ _buildFlares(salt) {
+ const src = this.cav, sn = this.cavN;
+ const N = 1800;
+ const p = new Float32Array(N * 3), n = new Float32Array(N * 3), s = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const k = ((Math.random() * (src.length / 3)) | 0) * 3;
+ p.set([src[k] + sn[k] * 0.004, src[k + 1] + sn[k + 1] * 0.004, src[k + 2] + sn[k + 2] * 0.004], i * 3);
+ n.set([sn[k], sn[k + 1], sn[k + 2]], i * 3);
+ s[i] = Math.random() + salt;
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(p, 3));
+ g.setAttribute('nrm', new THREE.BufferAttribute(n, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(s, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, uniforms: this.flareU,
+ vertexShader: /* glsl */`
+ attribute vec3 nrm; attribute float seed;
+ uniform vec3 uL1, uL2; uniform float uC1, uC2, uGlint, uTime, uDpr;
+ varying float vI; varying float vRot;
+ vec3 h3(float n){ return fract(sin(vec3(n * 91.37, n * 47.13, n * 13.71)) * 43758.5453) - 0.5; }
+ void main(){
+ vec4 wp = modelMatrix * vec4(position, 1.0);
+ vec3 wn = normalize(mat3(modelMatrix) * nrm);
+ vec3 nf = normalize(wn + h3(seed) * 1.1);
+ vec3 V = normalize(cameraPosition - wp.xyz);
+ float s1 = pow(max(dot(nf, normalize(normalize(uL1 - wp.xyz) + V)), 0.0), 160.0);
+ float s2 = pow(max(dot(nf, normalize(normalize(uL2 - wp.xyz) + V)), 0.0), 160.0);
+ float tw = 0.55 + 0.45 * sin(uTime * (1.7 + fract(seed * 7.3) * 4.0) + seed * 50.0);
+ vI = (s1 * uC1 + s2 * uC2) * tw * uGlint;
+ vRot = fract(seed * 13.1) * 0.5;
+ vec4 mv = viewMatrix * wp;
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = clamp(sqrt(vI), 0.0, 1.5) * 56.0 * uDpr * (2.4 / -mv.z);
+ if (vI < 0.015) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vI; varying float vRot;
+ void main(){
+ vec2 q = gl_PointCoord - 0.5;
+ float c = cos(vRot), s = sin(vRot);
+ q = mat2(c, -s, s, c) * q;
+ float d = length(q);
+ float core = exp(-d * d * 180.0);
+ float ray = (exp(-abs(q.x) * 90.0) + exp(-abs(q.y) * 90.0)) * (1.0 - smoothstep(0.0, 0.5, d));
+ float diag = exp(-abs(q.x + q.y) * 120.0) * exp(-abs(q.x - q.y) * 3.0) + exp(-abs(q.x - q.y) * 120.0) * exp(-abs(q.x + q.y) * 3.0);
+ float a = (core * 1.6 + ray * 0.7 + diag * 0.12 * (1.0 - smoothstep(0.0, 0.35, d)));
+ vec3 col = mix(vec3(0.78, 0.62, 1.0), vec3(1.0), core);
+ float i = min(vI, 3.0);
+ if (a * i < 0.004) discard;
+ gl_FragColor = vec4(col * 3.0, min(a * i, 1.0));
+ }`,
+ });
+ const pts = new THREE.Points(g, mat);
+ pts.frustumCulled = false;
+ return pts;
+ }
+
+ setLights(l1, c1, l2, c2) { this.flareU.uL1.value.copy(l1); this.flareU.uC1.value = c1; this.flareU.uL2.value.copy(l2); this.flareU.uC2.value = c2; }
+
+ setDpr(d) { this.dustMat.uniforms.uDpr.value = d; this.burstMat.uniforms.uDpr.value = d; this.flareU.uDpr.value = d; }
+
+ // ── state ─────────────────────────────────────────────────────────────────
+ update(dt, t, holding) {
+ this.u.uTime.value = t;
+ this.dustMat.uniforms.uTime.value = t;
+ this.burstMat.uniforms.uTime.value = t;
+ if (this.state === 'closed') {
+ this.hold = clamp(this.hold + (holding ? dt / HOLD_TIME : -dt * 0.9));
+ const h = this.hold;
+ // A faint breathing hairline hints that something is alive inside before anyone touches it.
+ const idle = 0.05 + 0.035 * Math.sin(t * 1.6);
+ this.u.uCrack.value = Math.max(h * h * (3 - 2 * h) * 0.95, idle);
+ this.dustMat.uniforms.uEmit.value = smooth(0.12, 1, h);
+ // Tremble: a stone under stress, not a phone buzzing.
+ const a = h * h * 0.0065 + (h > 0.85 ? (h - 0.85) * 0.03 : 0);
+ this.pair.position.set(Math.sin(t * 71) * a, Math.abs(Math.sin(t * 53)) * a * 0.6, Math.cos(t * 67) * a);
+ this.pair.rotation.set(Math.sin(t * 43) * a * 0.9, Math.sin(t * 29) * a * 0.5, Math.cos(t * 37) * a * 0.9);
+ if (this.hold >= 1) this.split();
+ } else {
+ this.dustMat.uniforms.uEmit.value = Math.max(0, this.dustMat.uniforms.uEmit.value - dt * 1.5);
+ }
+ if (this.burstT >= 0) {
+ this.burstT += dt;
+ this.burstMat.uniforms.uT.value = this.burstT;
+ this._chips(dt);
+ if (this.burstT > 6) { this.burstT = -1; this.burstMat.uniforms.uT.value = -1; }
+ }
+ this._lid();
+ }
+
+ _chips(dt) {
+ let n = 0;
+ for (const c of this.chipState) {
+ if (!c.rest) {
+ c.v.y -= 3.2 * dt;
+ c.p.addScaledVector(c.v, dt);
+ c.r.x += c.w.x * dt; c.r.y += c.w.y * dt; c.r.z += c.w.z * dt;
+ if (c.p.y < c.s * 0.6) {
+ c.p.y = c.s * 0.6;
+ if (Math.abs(c.v.y) < 0.25) { c.rest = true; c.v.set(0, 0, 0); }
+ else { c.v.y *= -0.32; c.v.x *= 0.5; c.v.z *= 0.5; c.w.multiplyScalar(0.5); }
+ }
+ }
+ this._q.setFromEuler(c.r);
+ this._m.compose(c.p, this._q, this._sv.set(c.s, c.s * 0.7, c.s * 0.85));
+ this.chips.setMatrixAt(n++, this._m);
+ }
+ this.chips.count = n;
+ this.chips.instanceMatrix.needsUpdate = true;
+ }
+
+ _lid() {
+ const k = this.lidT;
+ const lift = this.seamY;
+ const up = new THREE.Vector3(0, lift + 0.5, 0.02);
+ const end = this.restPos;
+ // Rise, hang for a heartbeat, swing back and down onto the velvet.
+ const a = smooth(0, 0.34, k), b = smooth(0.34, 1, k);
+ // Closed, the lid sinks a hair into the base: the sawn rim is not perfectly flat, and a gap would show the crystals.
+ const p = new THREE.Vector3(0, lift - this.closeGap, 0).lerp(up, a);
+ const mid = up.clone().lerp(end, b); mid.y += Math.sin(b * Math.PI) * 0.12;
+ if (k > 0.34) p.copy(mid);
+ this.top.position.copy(p);
+ const qa = new THREE.Quaternion().setFromEuler(new THREE.Euler(-0.18 * a, -0.35 * a, -0.06 * a));
+ this.top.quaternion.copy(qa).slerp(this.restQ, b);
+ this.bottom.rotation.x = this.bottomTilt * smooth(0.25, 1, k);
+ this.bottom.position.z = 0.06 * smooth(0.25, 1, k);
+ }
+
+ split() {
+ if (this.state !== 'closed') return;
+ this.state = 'opening';
+ this.hold = 1;
+ this._emit('split');
+ this.pair.position.set(0, 0, 0); this.pair.rotation.set(0, 0, 0);
+ this.burstT = 0;
+ for (const c of this.chipState) c.rest = false;
+ const tl = gsap.timeline({ onComplete: () => { this.state = 'open'; this._emit('open'); } });
+ tl.to(this.u.uCrack, { value: 1.5, duration: 0.12, ease: 'power2.out' }, 0)
+ .to(this.u.uSeal, { value: 0, duration: 0.6 }, 0.2)
+ .to(this.u.uCrack, { value: 0, duration: 2.4, ease: 'power2.inOut' }, 0.35)
+ .to(this.burstLight, { intensity: 9, duration: 0.18, ease: 'power2.out' }, 0.05)
+ .to(this.burstLight, { intensity: 0.35, duration: 3.2, ease: 'power3.out' }, 0.3)
+ .to(this.u.uInner, { value: 2.4, duration: 0.2 }, 0.1)
+ .to(this.u.uInner, { value: 0.06, duration: 3.2, ease: 'power2.out' }, 0.4)
+ .to(this.u.uGlint, { value: 1, duration: 1.4, ease: 'power2.inOut' }, 0.3)
+ .to(this, { lidT: 1, duration: 3.1, ease: 'power1.inOut' }, 0.05)
+ .to(this, { open: 1, duration: 3.6, ease: 'power2.inOut' }, 0.15);
+ this.tl = tl;
+ }
+
+ reseal() {
+ if (this.state !== 'open') return;
+ this.state = 'closing';
+ this.tl?.kill();
+ gsap.timeline({ onComplete: () => { this.state = 'closed'; this.hold = 0; this.chips.count = 0; this._emit('closed'); } })
+ .to(this, { lidT: 0, duration: 2.2, ease: 'power2.inOut' }, 0)
+ .to(this, { open: 0, duration: 2.4, ease: 'power2.inOut' }, 0)
+ .to(this.u.uGlint, { value: 0, duration: 1.2 }, 1)
+ .to(this.u.uSeal, { value: 1, duration: 0.6 }, 1.6)
+ .to(this.u.uInner, { value: 0, duration: 1 }, 0)
+ .to(this.burstLight, { intensity: 0, duration: 1 }, 0);
+ }
+}
diff --git a/examples/lithos/index.html b/examples/lithos/index.html
new file mode 100644
index 0000000..4a9b038
--- /dev/null
+++ b/examples/lithos/index.html
@@ -0,0 +1,234 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Lithos — Mineral specimens &amp; fine jewellery, Geneva</title>
+ <meta name="description" content="Museum-grade mineral specimens, chosen one at a time, and a jewellery line cut from the stones we could not bear to sell.">
+ <meta name="theme-color" content="#050407">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 24 24%22%3E%3Cpath d=%22M12 2.5 18.5 8 16 20.5H8L5.5 8Z%22 fill=%22%239d6bff%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Cinzel:wght@400;500;600&family=Italiana&family=Jost:wght@300;400;500&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-half loader-top"></div>
+ <div class="loader-half loader-bot"></div>
+ <div class="loader-core">
+ <svg class="loader-stone" viewBox="0 0 120 120" aria-hidden="true">
+ <circle cx="60" cy="60" r="44" fill="none" stroke="currentColor" stroke-width=".6" opacity=".35"/>
+ <path class="loader-crack" pathLength="1" d="M16 60 L27 58 L33 62 L41 57 L49 61 L57 58 L64 62 L71 57 L80 61 L88 58 L95 61 L104 60"/>
+ </svg>
+ <p class="loader-word">Lithos</p>
+ <p class="loader-line">Opening the vault <span class="loader-pct">0</span>%</p>
+ </div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Lithos home">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2.5 18.5 8 16 20.5H8L5.5 8Z M5.5 8h13 M12 2.5 9.5 8 12 20.5 14.5 8Z" fill="none" stroke="currentColor" stroke-width="1" stroke-linejoin="round"/></svg>
+ <span>Lithos</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#collection">Collection</a>
+ <a href="#jewellery">Jewellery</a>
+ <a href="#provenance">Provenance</a>
+ <a href="#visit">Visit</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" data-cursor="link"><i></i><i></i><i></i><span>Sound</span></button>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Private viewing</a>
+ </div>
+ </header>
+
+ <main id="top">
+ <!-- I. Hero ─────────────────────────────────────────── -->
+ <section class="hero" data-station="hero">
+ <p class="eyebrow cz">Mineral specimens &amp; fine jewellery &nbsp;·&nbsp; Geneva, since 1987</p>
+ <h1 class="title" aria-label="Four billion years of patience.">
+ <span class="line"><span>Four billion years</span></span>
+ <span class="line"><span><em>of</em> patience.</span></span>
+ </h1>
+ <div class="hero-foot">
+ <p class="sub">Museum-grade minerals, chosen one stone at a time — and a jewellery line cut from the specimens we could not bear to sell.</p>
+ <p class="label cz"><b>Specimen I</b><br>Amethyst geode · Artigas<br>Still sealed</p>
+ </div>
+ </section>
+
+ <!-- II. The crack ─────────────────────────────────────── -->
+ <section class="crack" id="crack" data-station="crack">
+ <div class="crack-copy">
+ <p class="eyebrow cz">I &nbsp;·&nbsp; The opening</p>
+ <h2 class="h2">Every geode is<br>a sealed room.</h2>
+ <p class="lede">A hundred and thirty million years ago this stone was a gas bubble in cooling lava. Water seeped in, one drop per century, and left its silica behind. Nobody has ever seen the inside.</p>
+ <p class="lede strong">You will be the first.</p>
+ <div class="hold-cta">
+ <span class="hold-ring" aria-hidden="true"><svg viewBox="0 0 40 40"><circle cx="20" cy="20" r="17"/><circle class="p" cx="20" cy="20" r="17" pathLength="1"/></svg></span>
+ <span class="cz">Press &amp; hold the stone</span>
+ </div>
+ <button class="reseal cz" type="button" data-cursor="link">Seal it again</button>
+ </div>
+ </section>
+
+ <!-- III. The collection ───────────────────────────────── -->
+ <div id="collection" class="collection">
+ <header class="col-head">
+ <p class="eyebrow cz">II &nbsp;·&nbsp; The collection</p>
+ <h2 class="h2">Four stones, <em>this season.</em></h2>
+ </header>
+
+ <section class="spec spec-left" data-station="amethyst">
+ <article class="spec-card">
+ <p class="spec-num cz"><span>Specimen I</span><span>SiO₂ · Fe³⁺</span></p>
+ <h3>Amethyst Geode</h3>
+ <p class="spec-desc">Formed in a gas pocket of the Paraná basalt flows. The violet is trace iron, darkened by natural radiation over geological time — never heated, dyed or restored.</p>
+ <dl class="facts">
+ <div><dt>Locality</dt><dd>Artigas, Uruguay</dd></div>
+ <div><dt>Age</dt><dd>132 million years</dd></div>
+ <div><dt>Weight</dt><dd>14.2 kg · pair</dd></div>
+ <div><dt>Price</dt><dd>CHF 18,400</dd></div>
+ </dl>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Reserve for viewing</a>
+ </article>
+ </section>
+
+ <section class="spec spec-right" data-station="quartz">
+ <article class="spec-card">
+ <p class="spec-num cz"><span>Specimen II</span><span>SiO₂</span></p>
+ <h3>Rock Crystal Cluster</h3>
+ <p class="spec-desc">Water-clear points with two phantoms and a rainbow fracture in the tallest terminal. Cleaned with water and a soft brush — no acid bath, no oil to hide the flaws.</p>
+ <dl class="facts">
+ <div><dt>Locality</dt><dd>Mount Ida, Arkansas</dd></div>
+ <div><dt>Age</dt><dd>~ 300 million years</dd></div>
+ <div><dt>Weight</dt><dd>3.8 kg</dd></div>
+ <div><dt>Price</dt><dd>CHF 6,900</dd></div>
+ </dl>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Reserve for viewing</a>
+ </article>
+ </section>
+
+ <section class="spec spec-left" data-station="pyrite">
+ <article class="spec-card">
+ <p class="spec-num cz"><span>Specimen III</span><span>FeS₂</span></p>
+ <h3>Pyrite Cubes</h3>
+ <p class="spec-desc">Cubes so square they were once thought to be carved by hand. The fine striations on every face are the record of the crystal growing, one atomic layer at a time.</p>
+ <dl class="facts">
+ <div><dt>Locality</dt><dd>Navajún, La Rioja, Spain</dd></div>
+ <div><dt>Age</dt><dd>~ 120 million years</dd></div>
+ <div><dt>Weight</dt><dd>2.1 kg</dd></div>
+ <div><dt>Price</dt><dd>CHF 4,250</dd></div>
+ </dl>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Reserve for viewing</a>
+ </article>
+ </section>
+
+ <section class="spec spec-right" data-station="ammonite">
+ <article class="spec-card">
+ <p class="spec-num cz"><span>Specimen IV</span><span>CaCO₃ · aragonite</span></p>
+ <h3>Iridescent Ammonite</h3>
+ <p class="spec-desc"><i>Cleoniceras</i>, with original nacre over four-fifths of the shell. The suture lines — the walls between its chambers — are drawn in agate, like frost on a window.</p>
+ <dl class="facts">
+ <div><dt>Locality</dt><dd>Mahajanga, Madagascar</dd></div>
+ <div><dt>Age</dt><dd>110 million years</dd></div>
+ <div><dt>Weight</dt><dd>1.6 kg</dd></div>
+ <div><dt>Price</dt><dd>CHF 3,600</dd></div>
+ </dl>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Reserve for viewing</a>
+ </article>
+ </section>
+ </div>
+
+ <!-- IV. Jewellery ─────────────────────────────────────── -->
+ <section class="jewel" id="jewellery" data-station="wide">
+ <div class="jewel-head">
+ <p class="eyebrow cz">III &nbsp;·&nbsp; The jewellery</p>
+ <h2 class="h2">Cut from the stones <em>we kept.</em></h2>
+ <p class="lede">When a specimen is too fractured to sell whole, our cutter in Idar-Oberstein takes what is left and sets it in platinum. Each piece is engraved inside with the number of the stone it came from.</p>
+ </div>
+ <div class="pieces">
+ <figure class="piece">
+ <div class="piece-img"><img src="/img/lithos/ring.webp" alt="Platinum signet ring set with a violet amethyst cabochon on black velvet" loading="lazy" width="800" height="1000"></div>
+ <figcaption>
+ <p class="cz piece-from">From specimen I</p>
+ <h3>Artigas Signet</h3>
+ <p>Amethyst cabochon, 6.2 ct, in hand-forged platinum.</p>
+ <p class="piece-price">CHF 4,800</p>
+ </figcaption>
+ </figure>
+ <figure class="piece piece-mid">
+ <div class="piece-img"><img src="/img/lithos/pendant.webp" alt="Raw clear quartz point pendant capped in platinum on a fine chain" loading="lazy" width="800" height="1000"></div>
+ <figcaption>
+ <p class="cz piece-from">From specimen II</p>
+ <h3>Ouachita Drop</h3>
+ <p>A single uncut quartz terminal, capped in brushed platinum.</p>
+ <p class="piece-price">CHF 2,650</p>
+ </figcaption>
+ </figure>
+ <figure class="piece">
+ <div class="piece-img"><img src="/img/lithos/studs.webp" alt="Pair of tiny pyrite cube stud earrings in platinum settings" loading="lazy" width="800" height="1000"></div>
+ <figcaption>
+ <p class="cz piece-from">From specimen III</p>
+ <h3>Navajún Studs</h3>
+ <p>Two natural 5 mm cubes, grown, not cut. Platinum claws.</p>
+ <p class="piece-price">CHF 1,450</p>
+ </figcaption>
+ </figure>
+ </div>
+ </section>
+
+ <!-- V. Provenance ─────────────────────────────────────── -->
+ <section class="prov" id="provenance" data-station="low">
+ <div class="prov-inner">
+ <p class="eyebrow cz">IV &nbsp;·&nbsp; Provenance &amp; ethics</p>
+ <h2 class="h2">Every stone arrives<br><em>with its paperwork.</em></h2>
+ <div class="prov-grid">
+ <figure class="prov-photo"><img src="/img/lithos/miner.webp" alt="A miner's hands holding a freshly opened amethyst geode in a basalt tunnel" loading="lazy" width="1600" height="900"><figcaption class="cz">Artigas, Uruguay — the Pereira family mine, level 3</figcaption></figure>
+ <ol class="principles">
+ <li><span class="cz">01</span><h3>Named, not sourced</h3><p>We buy from thirty-one miners and families we know by name — never at auction. Each label carries the GPS locality, the date it came out of the ground and who found it.</p></li>
+ <li><span class="cz">02</span><h3>Untreated, always</h3><p>No heat, no dye, no resin, no reassembly. If a specimen has ever been repaired, the label says so, in ink, on the front.</p></li>
+ <li><span class="cz">03</span><h3>We publish what we paid</h3><p>On average 41% of a sale price goes back to the mine. The trade norm is under five. The figure for every stone is printed on its certificate.</p></li>
+ </ol>
+ </div>
+ <div class="stats">
+ <div><b>412</b><span class="cz">specimens catalogued</span></div>
+ <div><b>31</b><span class="cz">named miners &amp; families</span></div>
+ <div><b>0</b><span class="cz">treated stones, ever</span></div>
+ </div>
+ </div>
+ </section>
+
+ <!-- VI. Visit ─────────────────────────────────────────── -->
+ <section class="visit" id="visit" data-station="final">
+ <div class="visit-inner">
+ <p class="eyebrow cz">V &nbsp;·&nbsp; By appointment</p>
+ <h2 class="visit-title">Hold something<br><em>older than the Alps.</em></h2>
+ <p class="lede">Private viewings at Rue du Rhône 48, one party at a time, with the stones out of their cases and in your hands. Bring nothing but curiosity; we provide the gloves and the loupe.</p>
+ <div class="visit-cta">
+ <a class="btn btn-solid btn-lg" href="#visit" data-magnetic>Book a private viewing</a>
+ <a class="btn btn-ghost btn-lg" href="#visit" data-magnetic>Request the catalogue</a>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot" data-station="foot" data-hold="1">
+ <div class="foot-grid">
+ <div class="foot-brand"><span class="cz">Lithos</span><p>Mineral specimens &amp; fine jewellery.<br>Geneva, since 1987.</p></div>
+ <p>Rue du Rhône 48<br>1204 Genève<br>Tuesday — Saturday, 11:00 — 19:00</p>
+ <p>[email protected]<br>+41 22 000 48 48</p>
+ <p>Instagram<br>Journal<br>Certificates</p>
+ </div>
+ <p class="fine cz">© Lithos SA · Every specimen sold with a signed certificate of locality · Stones photographed, not rendered — except here.</p>
+ </footer>
+ </main>
+
+ <div class="press" aria-hidden="true"><svg viewBox="0 0 80 80"><circle cx="40" cy="40" r="34"/><circle class="p" cx="40" cy="40" r="34" pathLength="1"/></svg><span class="cz">Hold</span></div>
+ <div class="toast cz" role="status"></div>
+ <div class="light-hint cz" aria-hidden="true">Your cursor is the light</div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/lithos/main.js b/examples/lithos/main.js
new file mode 100644
index 0000000..4ade3c7
--- /dev/null
+++ b/examples/lithos/main.js
@@ -0,0 +1,511 @@
+import { Engine, THREE, normalize, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { bakeTexture } from '../../src/core/textures.js';
+import { DepthOfFieldEffect } from 'postprocessing';
+import { velvetMaterial, crystalMaterial, patchPyrite, nacreMaterial } from './materials.js';
+import { Geode } from './geode.js';
+import { Sound } from './sound.js';
+
+const Q = new URLSearchParams(location.search);
+const D = Math.PI / 180;
+const V3 = (x = 0, y = 0, z = 0) => new THREE.Vector3(x, y, z);
+const touch = matchMedia('(pointer: coarse)').matches;
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+let vol, dof;
+const engine = new Engine({
+ canvas: document.getElementById('gl'), fov: 30, near: 0.05, far: 60, dpr: 1.6, background: 0x040306,
+ post: {
+ ao: { aoRadius: 0.35, intensity: 2.4, distanceFalloff: 0.6, halfRes: false, denoiseRadius: 8 },
+ bloom: { intensity: 1.0, luminanceThreshold: 0.6, luminanceSmoothing: 0.3, radius: 0.64 },
+ pre: cam => {
+ vol = new VolumetricSpotEffect(cam, { density: 0.026, noise: 0.92, noiseScale: 1.7, maxDist: 12, floorY: 0, wind: V3(0.03, 0.06, 0.01) });
+ dof = new DepthOfFieldEffect(cam, { focusDistance: 3.5, focusRange: 1.4, bokehScale: 2.2, resolutionScale: 0.5 });
+ return Q.has('nodof') ? [vol] : [vol, dof];
+ },
+ tone: 'agx', vignette: { offset: 0.18, darkness: 0.84 }, noise: 0.045, ca: 0.0008,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.shadowMap.type = THREE.PCFShadowMap;
+scene.fog = new THREE.FogExp2(0x040306, 0.035);
+scene.environment = studioEnvironment(renderer, {
+ top: 0x0b0910, bottom: 0x020203, blur: 0.015,
+ panels: [
+ { pos: [0, 7, 1.5], size: [4.5, 2.0], intensity: 5.5, color: 0xffffff },
+ { pos: [-6.5, 2.6, 2.5], size: [0.6, 5.5], intensity: 5, color: 0xf3efff },
+ { pos: [6.5, 3.2, -1.2], size: [0.45, 5], intensity: 3.5, color: 0xe4ddff },
+ { pos: [0.5, 3.4, -7], size: [7, 0.45], intensity: 2.4, color: 0xb194ff },
+ { pos: [3.5, 1.0, 6.5], size: [1.2, 1.2], intensity: 2.0, color: 0xffeedd },
+ ],
+});
+
+// A brighter "light tent" environment for the metal and the crystal only.
+const jewelEnv = studioEnvironment(renderer, {
+ top: 0x24222a, bottom: 0x050506, blur: 0.02,
+ panels: [
+ { pos: [0, 6, 0.5], size: [6, 4], intensity: 4, color: 0xffffff },
+ { pos: [-5, 2, 3], size: [2, 5], intensity: 3.5, color: 0xfff4ea },
+ { pos: [5, 2.5, 2], size: [1.4, 5], intensity: 3, color: 0xeef0ff },
+ { pos: [0, 1.5, -6], size: [8, 1.2], intensity: 2.2, color: 0xc6b2ff },
+ { pos: [0, 1, 6], size: [3, 1], intensity: 2.5, color: 0xffffff },
+ ],
+});
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 6 });
+const sound = new Sound(document.querySelector('.sound'));
+
+// ─── Loader: the stone cracks as the vault loads, then splits open ────────────
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ },
+ exit: async () => {
+ const tl = gsap.timeline();
+ tl.to('.loader-crack', { strokeWidth: 2.4, duration: 0.25, ease: 'power2.in' })
+ .to('.loader-core', { opacity: 0, duration: 0.35, ease: 'power2.in' }, '+=0.05')
+ .to('.loader-top', { yPercent: -101, duration: 1.3, ease: 'expo.inOut' }, '-=0.1')
+ .to('.loader-bot', { yPercent: 101, duration: 1.3, ease: 'expo.inOut' }, '<');
+ await tl;
+ },
+});
+
+// ─── The vitrine: black velvet cove with hanging folds ────────────────────────
+const velvet = velvetMaterial(renderer, bakeTexture);
+function coveGeometry() {
+ const W = 30, x0 = -10, segX = 540, segS = 260;
+ const zF = 6, zC = -2.1, R = 1.9, yTop = 8;
+ const Lf = zF - zC, La = Math.PI / 2 * R, Lw = yTop - R, S = Lf + La + Lw;
+ const pos = new Float32Array((segX + 1) * (segS + 1) * 3), uv = new Float32Array((segX + 1) * (segS + 1) * 2);
+ const specs = [[0, 0], [3.3, -0.35], [6.5, 0], [9.7, -0.25]];
+ let k = 0;
+ for (let j = 0; j <= segS; j++) {
+ const s = S * j / segS;
+ let y, z, ny, nz;
+ if (s < Lf) { z = zF - s; y = 0; ny = 1; nz = 0; } else if (s < Lf + La) {
+ const a = (s - Lf) / R; z = zC - Math.sin(a) * R; y = R - Math.cos(a) * R; ny = Math.cos(a); nz = Math.sin(a);
+ } else { z = zC - R; y = R + (s - Lf - La); ny = 0; nz = 1; }
+ const wall = smooth(Lf + 0.2, Lf + La + 1.4, s);
+ for (let i = 0; i <= segX; i++) {
+ const x = x0 + W * i / segX;
+ const ph = Math.sin(x * 0.37) * 1.7 + Math.sin(x * 0.11 + 1.2) * 2.2;
+ const drape = (0.17 * Math.sin(x * 1.75 + ph) + 0.06 * Math.sin(x * 4.3 + ph * 1.6 + 1.3) + 0.022 * Math.sin(x * 9.7 + 0.5)) * wall * (0.5 + 0.5 * smooth(0, 4, y));
+ let away = 1;
+ for (const [sx, sz] of specs) away = Math.min(away, smooth(0.75, 1.7, Math.hypot(x - sx, z - sz)));
+ const ripple = (0.03 * Math.sin(x * 2.1 + z * 1.6 + Math.sin(z * 0.9) * 2) * Math.sin(z * 1.3 - x * 0.45) + 0.012 * Math.sin(x * 5.3 - z * 3.1)) * away * (1 - wall);
+ const d = drape + ripple;
+ pos[k * 3] = x; pos[k * 3 + 1] = y + ny * d; pos[k * 3 + 2] = z + nz * d;
+ uv[k * 2] = x / 2.2; uv[k * 2 + 1] = s / 2.2;
+ k++;
+ }
+ }
+ const idx = [];
+ for (let j = 0; j < segS; j++) for (let i = 0; i < segX; i++) {
+ const a = j * (segX + 1) + i, b = a + 1, c = a + segX + 1, e = c + 1;
+ idx.push(a, b, c, b, e, c);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ g.setIndex(idx);
+ g.computeVertexNormals();
+ return g;
+}
+const cove = new THREE.Mesh(coveGeometry(), velvet);
+cove.receiveShadow = true;
+scene.add(cove);
+
+// ─── Specimens ─────────────────────────────────────────────────────────────────
+const SPECS = [
+ { key: 'geode', file: 'models/lithos/geode.glb', pos: V3(0, 0, 0) },
+ { key: 'quartz', file: 'models/lithos/quartz.glb', pos: V3(3.3, 0, -0.35), size: 1.2, axis: 'y', yaw: -24 * D },
+ { key: 'pyrite', file: 'models/lithos/pyrite.glb', pos: V3(6.5, 0, 0), size: 1.08, axis: 'max', yaw: 18 * D },
+ { key: 'ammonite', file: 'models/lithos/ammonite.glb', pos: V3(9.7, 0, -0.25), size: 1.02, axis: 'y', yaw: -16 * D },
+];
+const FOCUS = [V3(0, 0.46, 0), V3(3.3, 0.55, -0.35), V3(6.5, 0.4, 0), V3(9.7, 0.5, -0.25), V3(4.85, 0.45, -0.15)];
+let geode = null;
+const loads = SPECS.map((s, i) => assets.gltf(s.file).then(g => {
+ if (s.key === 'geode') {
+ geode = new Geode(g, { size: 1.0, position: s.pos, scene, camera, renderer });
+ geode.on(e => onGeode(e));
+ return;
+ }
+ const m = g.scene;
+ normalize(m, s.size, { axis: s.axis });
+ const holder = new THREE.Group();
+ holder.position.copy(s.pos);
+ holder.rotation.y = s.yaw;
+ holder.add(m);
+ scene.add(holder);
+ s.model = m;
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+ m.traverse(o => {
+ if (!o.isMesh) return;
+ o.castShadow = o.receiveShadow = true;
+ const src = o.material;
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap']) if (src[k]) src[k].anisotropy = aniso;
+ if (s.key === 'quartz') o.material = crystalMaterial(src, { envMap: jewelEnv });
+ else if (s.key === 'pyrite') patchPyrite(src, jewelEnv);
+ else if (s.key === 'ammonite') o.material = nacreMaterial(src, jewelEnv);
+ });
+ holder.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(m);
+ FOCUS[i].copy(box.getCenter(V3())).setY(box.min.y + (box.max.y - box.min.y) * 0.46);
+}).catch(e => console.error('specimen', s.key, e)));
+
+// ─── Lights: a museum vitrine rig that travels with the camera ────────────────
+scene.add(new THREE.HemisphereLight(0x2a2438, 0x050407, 0.08));
+function spot(color, intensity, dist, angle, pen, decay = 2) {
+ const l = new THREE.SpotLight(color, intensity, dist, angle, pen, decay);
+ scene.add(l, l.target);
+ return l;
+}
+const key = spot(0xfff2e6, 0, 11, 0.36, 0.85);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+key.shadow.camera.near = 0.5; key.shadow.camera.far = 9;
+key.shadow.bias = -0.00012; key.shadow.normalBias = 0.012; key.shadow.radius = 3;
+const rim = spot(0xd4dcff, 0, 9, 0.5, 0.8);
+const pool = spot(0x8a6ee0, 0, 14, 0.4, 1, 1.4);
+const lamp = spot(0xf6f2ff, 0, 5, 0.85, 1); // the cursor light
+lamp.castShadow = true;
+lamp.shadow.mapSize.set(1024, 1024);
+lamp.shadow.camera.near = 0.05; lamp.shadow.camera.far = 5;
+lamp.shadow.bias = -0.0002; lamp.shadow.normalBias = 0.01; lamp.shadow.radius = 4;
+const pins = SPECS.map(s => {
+ const l = spot(0xfff0e0, 0, 7, 0.2, 0.75);
+ l.position.copy(s.pos).add(V3(0.25, 3.2, 0.95));
+ l.target.position.copy(s.pos).add(V3(0, 0.4, 0));
+ return l;
+});
+vol.add(key, { scale: 0.0022, range: 0.16, softness: 0.4 });
+const K = { key: 44, rim: 22, pool: 70, lamp: 4.5, pin: 7 };
+const power = { v: 0 }; // global light-up during the intro
+
+// Motes of dust drifting in the vitrine light.
+const motes = (() => {
+ const N = 3200;
+ const p = new Float32Array(N * 3), s = new Float32Array(N);
+ for (let i = 0; i < N; i++) { p.set([Math.random() * 13 - 1.8, Math.random() * 2.6, Math.random() * 3.4 - 1.8], i * 3); s[i] = Math.random(); }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(p, 3));
+ g.setAttribute('seed', new THREE.BufferAttribute(s, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uKP: { value: V3() }, uKD: { value: V3(0, -1, 0) }, uCos: { value: 0.94 }, uLP: { value: V3() }, uPow: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: /* glsl */`
+ attribute float seed; uniform float uTime, uCos, uPow, uDpr; uniform vec3 uKP, uKD, uLP; varying float vA;
+ void main(){
+ vec3 p = position; float t = uTime * (0.03 + seed * 0.04);
+ p += vec3(sin(t * 3.1 + seed * 40.), sin(t * 2.3 + seed * 13.) * 0.5 + t * 0.12, cos(t * 2.7 + seed * 27.)) * 0.3;
+ p.y = mod(p.y, 2.6) + 0.02;
+ vec3 d = p - uKP; float dist = length(d);
+ float cone = smoothstep(uCos, uCos + 0.025, dot(d / dist, uKD));
+ float nearL = exp(-length(p - uLP) * 3.5) * 0.8;
+ vA = (cone * 0.9 / (1. + dist * dist * 0.1) + nearL) * uPow * (0.35 + 0.65 * fract(seed * 91.7));
+ vec4 mv = modelViewMatrix * vec4(p, 1.); gl_Position = projectionMatrix * mv;
+ gl_PointSize = (0.8 + seed * 1.8) * uDpr * (3.0 / -mv.z);
+ if (vA < 0.002) gl_Position = vec4(2.0, 2.0, 2.0, 1.0);
+ }`,
+ fragmentShader: /* glsl */`varying float vA; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, 0., d) * vA; if (a < 0.003) discard; gl_FragColor = vec4(vec3(1., .95, 1.) * 1.6, min(a, 1.)); }`,
+ });
+ const pts = new THREE.Points(g, mat); pts.frustumCulled = false; scene.add(pts);
+ return mat;
+})();
+
+// ─── Camera stations ───────────────────────────────────────────────────────────
+// pos / look for a 16:10 frame; f = focus specimen for the light rig (4 = the whole row).
+const ST = {
+ hero: { pos: [0, 1.25, 5.8], look: [0, 0.95, 0], key: [-2.5, 1.45, 0.55], lampK: 0.45, f: 0, range: 3.4, wide: 0 },
+ heroO: { pos: [0.42, 2.75, 6.6], look: [0.42, 1.12, -0.2], f: 0, range: 3.2, wide: 0 },
+ crack: { pos: [-1.55, 1.15, 3.55], look: [-0.7, 0.5, 0.0], key: [-2.3, 1.6, 1.25], lampK: 0.55, lift: -0.07, f: 0, range: 3, wide: 0 },
+ crackO: { pos: [-0.9, 2.6, 3.9], look: [-0.25, 0.26, -0.2], f: 0, range: 2.2, wide: 0 },
+ amethyst: { pos: [0.2, 2.75, 3.45], look: [-0.02, 0.24, -0.28], f: 0, range: 2.6, wide: 0, card: true, mk: 1.3 },
+ quartz: { pos: [3.95, 0.8, 2.85], look: [3.72, 0.6, -0.35], f: 1, range: 2.8, wide: 0, card: true },
+ pyrite: { pos: [5.98, 1.3, 2.55], look: [6.12, 0.42, 0.0], f: 2, range: 2.8, wide: 0, card: true },
+ ammonite: { pos: [10.5, 0.8, 3.15], look: [10.32, 0.55, -0.25], f: 3, range: 2.8, wide: 0, card: true },
+ wide: { pos: [4.85, 5.4, 13.2], look: [4.85, -1.15, -0.15], f: 4, range: 8, wide: 1 },
+ low: { pos: [-1.35, 0.3, 1.4], look: [3.2, 0.44, -0.4], f: 0, range: 1.8, wide: 0.4, dofAt: 1 },
+ foot: { pos: [0.5, 4.3, 5.6], look: [0.42, -1.25, -0.35], f: 0, range: 3, wide: 0 },
+ final: { pos: [0.5, 3.75, 5.2], look: [0.42, -0.8, -0.35], f: 0, range: 2.6, wide: 0, lift: 0.1, mk: 1.15 },
+};
+const stationEls = [...document.querySelectorAll('[data-station]')];
+let spans = [];
+function measure() {
+ const vh = innerHeight;
+ spans = stationEls.map(el => {
+ const r = el.getBoundingClientRect();
+ const top = r.top + scrollY, h = r.height;
+ const hold = parseFloat(el.dataset.hold ?? 0.62);
+ const c = top + Math.max(0, h - vh) / 2, half = Math.max(0, h - vh) / 2 * hold;
+ return { name: el.dataset.station, a: c - half, b: c + half };
+ });
+ spans[0].a = 0; spans[0].b = 0;
+ const max = document.documentElement.scrollHeight - vh;
+ for (const sp of spans) { sp.a = Math.min(sp.a, max - 2); sp.b = Math.min(sp.b, max - 1); }
+ bindCards();
+}
+function stationFloat(y) {
+ for (let i = 0; i < spans.length; i++) {
+ if (y <= spans[i].b) return i === 0 || y >= spans[i].a ? i : i - 1 + smooth(spans[i - 1].b, spans[i].a, y);
+ }
+ return spans.length - 1;
+}
+
+const tmpA = V3(), tmpB = V3(), tmpC = V3();
+let cards = [];
+function bindCards() {
+ cards = [...document.querySelectorAll('.spec')].map(sec => ({ el: sec.querySelector('.spec-card'), idx: spans.findIndex(sp => sp.name === sec.dataset.station) }));
+}
+function stationPose(name, out) {
+ let s = ST[name];
+ out.pos.set(...s.pos); out.look.set(...s.look);
+ // Once the stone is open, the hero and crack framings rise to look into the cavities.
+ const alt = ST[name + 'O'];
+ if (alt && geode) {
+ const o = smooth(0, 1, geode.open);
+ out.pos.lerp(tmpA.set(...alt.pos), o); out.look.lerp(tmpB.set(...alt.look), o);
+ }
+ out.focus.copy(FOCUS[s.f]);
+ if (s.f === 0 && geode) out.focus.lerp(tmpC.set(0.44, 0.46, -0.16), smooth(0, 1, geode.open));
+ out.dofAt.copy(FOCUS[s.dofAt ?? s.f]);
+ out.range = s.range; out.wide = s.wide;
+ out.key.set(...(s.key ?? KEY)); out.lampK = s.lampK ?? 1;
+ if (alt && geode && !alt.key) { const o = smooth(0, 1, geode.open); out.key.lerp(tmpA.set(...KEY), o); out.lampK = lerp(out.lampK, 1, o); }
+ // Portrait screens: centre the specimen and step back so it fits the narrow frame.
+ const a = camera.aspect;
+ if (a < 1.25) {
+ const k = lerp(2.05, 1.1, clamp((a - 0.45) / 0.8)) * (s.mk ?? 1);
+ const f = s.f === 4 ? out.look : out.focus;
+ out.look.x = lerp(out.look.x, f.x, 0.8); out.look.z = lerp(out.look.z, f.z, 0.8);
+ out.look.y = lerp(out.look.y, f.y, 0.5) + 0.12;
+ out.pos.sub(out.look).multiplyScalar(k).add(out.look);
+ // Specimen stations: the card owns the lower part of a phone screen, so lift the specimen into the upper half.
+ if (s.card || s.lift) { const dz = out.pos.distanceTo(out.look) * (s.lift ?? 0.085); out.look.y -= dz; out.pos.y -= dz; }
+ }
+ return out;
+}
+const KEY = [-1.05, 2.85, 1.3];
+const mkPose = () => ({ pos: V3(), look: V3(), focus: V3(), dofAt: V3(), key: V3(), lampK: 1, range: 1, wide: 0 });
+const pA = mkPose(), pB = mkPose(), pose = mkPose();
+const cam = { pos: V3(0, 1.4, 6), look: V3(0, 0.8, 0), focus: V3().copy(FOCUS[0]), dofAt: V3().copy(FOCUS[0]), range: 1.2, wide: 0 };
+let stF = 0, stSmooth = 0;
+const intro = { k: 1 };
+const shake = { v: 0 };
+
+// ─── Interaction state ─────────────────────────────────────────────────────────
+const root = document.documentElement;
+const pressEl = document.querySelector('.press');
+const labelEl = document.querySelector('.hero .label');
+const labelHTML = labelEl.innerHTML;
+const toastEl = document.querySelector('.toast');
+const hintEl = document.querySelector('.light-hint');
+const hotspot = document.createElement('div');
+hotspot.className = 'hotspot';
+hotspot.innerHTML = '<i></i><span class="cz">Press &amp; hold</span>';
+document.body.appendChild(hotspot);
+let holding = false, started = false, lastMove = -10;
+let toastTimer;
+function toast(msg, ms = 3600) {
+ toastEl.textContent = msg; toastEl.classList.add('on');
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+const uiTarget = e => e.target.closest?.('a,button,.spec-card,.piece,.prov-inner,.visit-inner,.foot,.nav,.tw-nav');
+let overUI = false;
+pointer.on('move', e => { lastMove = engine.time; overUI = !!uiTarget(e); });
+addEventListener('pointerdown', e => {
+ if (!started || !geode || geode.state !== 'closed' || uiTarget(e) || e.button > 0) return;
+ if (stSmooth > 1.7) return;
+ holding = true;
+ document.body.classList.add('is-holding');
+});
+const release = () => { holding = false; document.body.classList.remove('is-holding'); };
+addEventListener('pointerup', release);
+addEventListener('pointercancel', release);
+addEventListener('blur', release);
+addEventListener('contextmenu', e => { if (holding) e.preventDefault(); });
+document.querySelector('.reseal').addEventListener('click', () => geode?.reseal());
+
+function onGeode(e) {
+ if (e === 'split') {
+ release();
+ sound.crack();
+ document.body.classList.add('is-open');
+ labelEl.innerHTML = '<b>Specimen I</b><br>Amethyst geode · Artigas<br>Opened by you, just now';
+ toast('Specimen I — seen for the first time in 132 million years');
+ gsap.fromTo(shake, { v: 1 }, { v: 0, duration: 1.1, ease: 'power2.out' });
+ }
+ if (e === 'closed') { document.body.classList.remove('is-open'); labelEl.innerHTML = labelHTML; }
+}
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const ray = new THREE.Raycaster();
+const aim = new THREE.Vector2();
+const right = V3(), up = V3(), fwd = V3();
+const lampPos = V3(0, 1, 2);
+engine.onResize((w, h, dpr) => {
+ measure();
+ geode?.setDpr(dpr);
+ motes.uniforms.uDpr.value = dpr;
+ dof?.cocMaterial.copyCameraSettings(camera);
+});
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ const y = scrollY;
+ stF = stationFloat(y);
+ stSmooth = damp(stSmooth, stF, 6, dt);
+ const i = Math.min(spans.length - 2, Math.floor(stSmooth));
+ const f = stSmooth - i;
+ stationPose(spans[i].name, pA);
+ stationPose(spans[Math.min(i + 1, spans.length - 1)].name, pB);
+ pose.pos.lerpVectors(pA.pos, pB.pos, f);
+ pose.look.lerpVectors(pA.look, pB.look, f);
+ pose.focus.lerpVectors(pA.focus, pB.focus, f);
+ pose.dofAt.lerpVectors(pA.dofAt, pB.dofAt, f);
+ pose.range = lerp(pA.range, pB.range, f);
+ pose.wide = lerp(pA.wide, pB.wide, f);
+ pose.key.lerpVectors(pA.key, pB.key, f);
+ pose.lampK = lerp(pA.lampK, pB.lampK, f);
+ // Crane move between stations: rise and ease back mid-flight.
+ const arc = Math.sin(f * Math.PI);
+ pose.pos.y += arc * 0.22;
+ tmpA.subVectors(pose.pos, pose.look).normalize();
+ pose.pos.addScaledVector(tmpA, arc * 0.45);
+ // Intro dolly.
+ pose.pos.addScaledVector(tmpA, intro.k * 2.2).y += intro.k * 0.5;
+
+ // Auto-open once the visitor scrolls into the collection without cracking it.
+ const colIdx = spans.findIndex(s => s.name === 'amethyst');
+ if (geode && geode.state === 'closed' && stF > colIdx - 0.55 && started) geode.split();
+
+ cam.pos.copy(pose.pos); cam.look.copy(pose.look);
+ camera.position.copy(cam.pos);
+ camera.lookAt(cam.look);
+ camera.updateMatrixWorld();
+ right.setFromMatrixColumn(camera.matrixWorld, 0); up.setFromMatrixColumn(camera.matrixWorld, 1);
+ const px = touch ? 0 : pointer.sx, py = touch ? 0 : pointer.sy;
+ camera.position.addScaledVector(right, px * 0.05).addScaledVector(up, py * 0.03);
+ if (geode && geode.state === 'closed') {
+ const h = geode.hold;
+ camera.position.addScaledVector(fwd.subVectors(cam.look, cam.pos).normalize(), h * h * 0.18);
+ }
+ if (shake.v > 0.001) camera.position.add(tmpA.set(Math.sin(t * 91), Math.sin(t * 77 + 1), Math.sin(t * 83 + 2)).multiplyScalar(shake.v * 0.018));
+ camera.lookAt(cam.look);
+ camera.updateMatrixWorld();
+
+ // Light rig follows the focus.
+ const F = cam.focus.copy(pose.focus);
+ const wide = pose.wide;
+ key.position.copy(F).add(pose.key).add(tmpA.set(-wide * 0.4, wide * 1.6, wide * 1.4));
+ key.target.position.copy(F);
+ key.angle = lerp(0.36, 0.62, wide);
+ key.intensity = K.key * power.v * (1 + wide * 1.2);
+ rim.position.copy(F).add(tmpA.set(1.4, 2.2, -2.3)); rim.target.position.copy(F).add(tmpA.set(0, 0.2, 0));
+ rim.intensity = K.rim * power.v;
+ pool.position.copy(F).add(tmpA.set(0.3, 3.4, 1.7)); pool.target.position.copy(F).add(tmpA.set(0, 1.2, -3.9));
+ pool.intensity = K.pool * power.v;
+ pins.forEach((l, k) => { l.intensity = K.pin * power.v * (0.35 + wide * 1.1 + (1 - Math.min(1, cam.focus.distanceTo(FOCUS[k]) / 2)) * 0.2); });
+
+ // The cursor is a light: it hangs on the pointer ray, in front of the specimen.
+ const user = touch ? (pointer.down ? 1 : 0) : clamp(1 - (t - lastMove - 4) / 2);
+ const ix = Math.sin(t * 0.31) * 0.55 + Math.sin(t * 0.77) * 0.12, iy = Math.cos(t * 0.43) * 0.25 + 0.2;
+ aim.set(lerp(ix, pointer.sx, user), lerp(iy, pointer.sy, user));
+ ray.setFromCamera(aim, camera);
+ const reach = camera.position.distanceTo(F) * 0.6;
+ tmpA.copy(ray.ray.origin).addScaledVector(ray.ray.direction, reach);
+ tmpA.y = Math.max(tmpA.y, 0.12);
+ lampPos.lerp(tmpA, 1 - Math.exp(-10 * dt));
+ lamp.position.copy(lampPos);
+ lamp.target.position.copy(F).add(tmpB.set(0, 0.1, 0));
+ lamp.intensity = K.lamp * power.v * (0.7 + 0.3 * user) * (1 - wide * 0.5) * pose.lampK;
+
+ // Geode.
+ if (geode) {
+ geode.update(dt, t, holding);
+ const u = geode.u;
+ u.uL1Pos.value.copy(lamp.position).applyMatrix4(camera.matrixWorldInverse);
+ u.uL1Col.value.set(1, 0.97, 1.02).multiplyScalar(lamp.intensity * 0.8);
+ u.uL2Pos.value.copy(key.position).applyMatrix4(camera.matrixWorldInverse);
+ u.uL2Col.value.set(1, 0.95, 0.9).multiplyScalar(key.intensity * 0.05);
+ geode.setLights(lamp.position, lamp.intensity * 1.4, key.position, key.intensity * 0.07);
+ root.style.setProperty('--hold', geode.hold.toFixed(3));
+ sound.setHold(holding ? geode.hold : 0);
+ // Hotspot on the seam.
+ const showHot = started && geode.state === 'closed' && stSmooth < 1.6 && !holding;
+ hotspot.classList.toggle('on', showHot);
+ if (showHot) {
+ tmpA.copy(geode.front).project(camera);
+ hotspot.style.transform = `translate3d(${((tmpA.x + 1) / 2 * innerWidth - 7).toFixed(1)}px, ${((1 - tmpA.y) / 2 * innerHeight - 7).toFixed(1)}px, 0)`;
+ }
+ pressEl.classList.toggle('on', holding || (started && geode.state === 'closed' && stSmooth < 1.6 && pointer.active && !touch && !overUI));
+ }
+ pressEl.style.transform = `translate3d(${pointer.px}px, ${pointer.py}px, 0)`;
+ hintEl.classList.toggle('on', started && !touch && stSmooth > 2.2 && stSmooth < 6.5);
+ // Specimen cards belong to their camera station: they rise in as the camera settles and leave as it moves on.
+ for (const c of cards) {
+ const d = stSmooth - c.idx;
+ const v = 1 - smooth(0.22, 0.5, Math.abs(d));
+ c.el.style.opacity = v.toFixed(3);
+ c.el.style.setProperty('--ty', ((d < 0 ? 1 : -1) * (1 - v) * 60).toFixed(1) + 'px');
+ c.el.style.visibility = v < 0.01 ? 'hidden' : 'visible';
+ }
+
+ // Motes.
+ motes.uniforms.uTime.value = t;
+ motes.uniforms.uKP.value.copy(key.position);
+ motes.uniforms.uKD.value.subVectors(key.target.position, key.position).normalize();
+ motes.uniforms.uCos.value = Math.cos(key.angle * 0.95);
+ motes.uniforms.uLP.value.copy(lamp.position);
+ motes.uniforms.uPow.value = power.v;
+
+ // Focus pull.
+ if (dof) {
+ dof.cocMaterial.focusDistance = camera.position.distanceTo(pose.dofAt);
+ dof.cocMaterial.focusRange = pose.range;
+ }
+});
+
+// ─── Boot ──────────────────────────────────────────────────────────────────────
+worldNav('lithos', { theme: 'dark', corner: 'bl' });
+const cur = cursor({ color: '#e9e2ff', blend: 'normal', size: 34 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.08 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id.length > 1 ? document.querySelector(id) : null;
+ e.preventDefault();
+ lenis.scrollTo(el ?? 0, { duration: 2.2, easing: t => 1 - Math.pow(1 - t, 4) });
+}));
+reveal('.h2', { type: 'lines', stagger: 0.1 });
+reveal('.lede, .spec-desc, .principles p', { type: 'lines', stagger: 0.05, y: '100%' });
+gsap.utils.toArray('.piece, .principles li, .stats > div').forEach(el => gsap.from(el, { opacity: 0, y: 50, duration: 1.4, ease: 'expo.out', scrollTrigger: { trigger: el, start: 'top 88%', once: true } }));
+window.__lithos = {
+ scrollTo: f => lenis.scrollTo(f * (document.documentElement.scrollHeight - innerHeight), { immediate: true }),
+ station: name => { const s = spans.find(x => x.name === name); lenis.scrollTo((s.a + s.b) / 2, { immediate: true }); },
+ split: () => geode?.split(), debug: () => ({ stF, stSmooth, y: scrollY, spans: spans.map(s => [s.name, Math.round(s.a), Math.round(s.b)]) }), get geode() { return geode; }, engine, scene, motes, cove, lights: { key, rim, pool, lamp, pins },
+};
+
+await Promise.all(loads);
+await document.fonts?.ready;
+measure();
+// Warm every program with all lights at full power before the curtain lifts.
+power.v = 1;
+geode.u.uGlint.value = 1; geode.u.uCrack.value = 0.5;
+renderer.compile(scene, camera);
+geode.u.uGlint.value = 0; geode.u.uCrack.value = 0;
+power.v = 0;
+engine.start();
+await loader.finish();
+gsap.to(power, { v: 1, duration: 2.6, ease: 'power2.inOut', delay: 0.1 });
+gsap.to(intro, { k: 0, duration: 3.4, ease: 'expo.out' });
+gsap.from('.title .line > span', { yPercent: 105, duration: 2.0, ease: 'expo.out', stagger: 0.14, delay: 0.35 });
+gsap.from('.hero .eyebrow, .hero-foot > *, .nav', { opacity: 0, y: 16, duration: 1.4, ease: 'power3.out', stagger: 0.08, delay: 0.9 });
+setTimeout(() => { started = true; window.__lithosReady = true; }, 1200);
diff --git a/examples/lithos/materials.js b/examples/lithos/materials.js
new file mode 100644
index 0000000..3f6891f
--- /dev/null
+++ b/examples/lithos/materials.js
@@ -0,0 +1,271 @@
+// Lithos materials: velvet, amethyst glints + crack glow, rock crystal, mirror pyrite, thin-film ammonite.
+// All patches are onBeforeCompile injections on three's physical/standard shaders, so the Meshy PBR maps stay in charge.
+import { THREE } from '../../src/core/engine.js';
+
+const HASH = /* glsl */`
+ float lh13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+ vec3 lh33(vec3 p){ p = fract(p * vec3(.1031, .1030, .0973)); p += dot(p, p.yxz + 33.33); return fract((p.xxy + p.yxx) * p.zyx); }
+ float vn3(vec3 x){ vec3 i = floor(x), f = fract(x); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(lh13(i), lh13(i + vec3(1,0,0)), f.x), mix(lh13(i + vec3(0,1,0)), lh13(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(lh13(i + vec3(0,0,1)), lh13(i + vec3(1,0,1)), f.x), mix(lh13(i + vec3(0,1,1)), lh13(i + vec3(1,1,1)), f.x), f.y), f.z); }
+`;
+
+const chunk = n => THREE.ShaderChunk[n];
+
+/**
+ * Amethyst geode half. `u` holds shared uniforms (both halves use one material):
+ * uToHalf (mesh-local -> half space: cut plane at y=0, +y out of the cavity), uCrack, uGlint, uInner, uTime,
+ * uL1Pos/uL1Col, uL2Pos/uL2Col (view-space glint lights), uCrackColor, uGlintScale.
+ */
+export function patchGeode(mat, u) {
+ mat.metalness = 0;
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform mat4 uToHalf;\nvarying vec3 vHalf;\nvarying vec3 vHalfN;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvHalf = (uToHalf * vec4(transformed, 1.0)).xyz;\nvHalfN = normalize(mat3(uToHalf) * objectNormal);');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ uniform float uCrack, uGlint, uInner, uTime, uGlintScale, uSeal, uSide, uSeamY;
+ uniform vec3 uL1Pos, uL1Col, uL2Pos, uL2Col, uCrackColor;
+ varying vec3 vHalf; varying vec3 vHalfN;
+ ${HASH}
+ float crackNet(vec3 p){
+ vec3 i = floor(p), f = fract(p); float d1 = 8., d2 = 8.;
+ for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
+ vec3 g = vec3(float(x), float(y), float(z)); vec3 r = g + lh33(i + g) - f; float d = dot(r, r);
+ if (d < d1) { d2 = d1; d1 = d; } else if (d < d2) d2 = d;
+ }
+ return sqrt(d2) - sqrt(d1);
+ }
+ // Botryoidal crust: rounded, grape-like lumps (inverted Worley F1), finer lumps, grain and pits.
+ float botry(vec3 p){
+ vec3 i = floor(p), f = fract(p); float d1 = 8.;
+ for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++) {
+ vec3 g = vec3(float(x), float(y), float(z)); vec3 r = g + lh33(i + g) * 0.85 - f; d1 = min(d1, dot(r, r));
+ }
+ return 1.0 - d1;
+ }
+ float crustH(vec3 p){
+ float b = botry(p * 15.0);
+ float b2 = botry(p * 38.0 + 5.3);
+ float n = vn3(p * 95.0) * 0.5 + vn3(p * 210.0) * 0.25;
+ float pit = smoothstep(0.64, 0.86, vn3(p * 58.0 + 9.1)) + smoothstep(0.7, 0.9, vn3(p * 130.0 + 2.7)) * 0.6;
+ return b * 0.85 + b2 * 0.3 + n * 0.3 - pit * 0.5;
+ }`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ vec3 gN = normalize(vHalfN);
+ // Cavity: surface whose normal faces the sphere centre (the exterior faces away from it), below the cut plane.
+ float gCav = smoothstep(0.0, 0.3, -dot(gN, normalize(vHalf + vec3(0.0, 0.06, 0.0)))) * (1.0 - smoothstep(-0.016, -0.002, vHalf.y));
+ vec3 gBase = diffuseColor.rgb;
+ float gPurple = smoothstep(0.004, 0.045, gBase.b - gBase.g);
+ float gLum = dot(gBase, vec3(0.2126, 0.7152, 0.0722));
+ float gRim = smoothstep(0.86, 0.96, gN.y) * (1.0 - smoothstep(0.006, 0.02, abs(vHalf.y)));
+ // Deeper, more saturated amethyst; the agate band stays milky.
+ diffuseColor.rgb = mix(diffuseColor.rgb, pow(max(gBase, 0.0), vec3(1.22)) * vec3(1.12, 0.86, 1.3), gCav * gPurple);
+ // Weathered crust: dark brown-grey basalt skin, rusty iron staining, crevices darker than the lumps.
+ // Exterior = outward-facing and out at the shell radius; crystals inside never qualify.
+ float gExt = (1.0 - gCav) * (1.0 - gRim) * (1.0 - gPurple) * smoothstep(0.05, 0.35, dot(gN, normalize(vHalf))) * smoothstep(0.39, 0.44, length(vHalf));
+ float gAy = abs(vHalf.y);
+ vec3 cp = vHalf + uSide * vec3(3.17, 0.0, 1.71);
+ float cH = crustH(cp);
+ float cStain = smoothstep(0.5, 0.8, vn3(cp * 5.5) * 0.65 + vn3(cp * 16.0) * 0.35);
+ float cGrime = vn3(cp * 8.0) * 0.7 + vn3(cp * 31.0) * 0.3;
+ vec3 crust = mix(vec3(0.055, 0.048, 0.042), vec3(0.17, 0.15, 0.13), cGrime);
+ crust = mix(crust, gBase * 0.42, 0.3);
+ crust = mix(crust, vec3(0.2, 0.085, 0.03), cStain * 0.62);
+ crust *= 0.45 + 0.75 * clamp(cH, 0.0, 1.0);
+ diffuseColor.rgb = mix(diffuseColor.rgb, crust, gExt);
+ // Sealed: the white agate rind shows as a thin chipped line either side of the dark join.
+ float cRind = (1.0 - smoothstep(0.022, 0.03, gAy + (vn3(cp * 90.0) - 0.5) * 0.016 + (vn3(cp * 23.0) - 0.5) * 0.008)) * gExt;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.44, 0.42, 0.47), cRind * uSeal * 0.85);
+ float gCrust = gExt * (1.0 - cRind * uSeal * 0.7);
+ `)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(roughnessFactor, mix(0.24, 0.08, gPurple), gCav);
+ roughnessFactor = mix(roughnessFactor, 0.2, gRim);
+ roughnessFactor = mix(roughnessFactor, 0.62 + 0.3 * (1.0 - clamp(cH, 0.0, 1.0)) + cStain * 0.1, gCrust);
+ roughnessFactor = mix(roughnessFactor, 0.32, cRind * uSeal);`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ // Triplanar-free bump: the crust height is a 3D field, differentiated in screen space (Mikkelsen).
+ vec2 dH = vec2(dFdx(cH), dFdy(cH)) * 0.015 * gCrust;
+ vec3 sp = -vViewPosition;
+ vec3 sx = dFdx(sp), sy = dFdy(sp);
+ vec3 R1 = cross(sy, normal), R2 = cross(normal, sx);
+ float det = dot(sx, R1) * faceDirection;
+ vec3 grad = sign(det) * (dH.x * R1 + dH.y * R2);
+ normal = normalize(abs(det) * normal - grad);
+ }`)
+ .replace('#include <metalnessmap_fragment>', '#include <metalnessmap_fragment>\nmetalnessFactor = 0.0;')
+ .replace('#include <opaque_fragment>', `
+ {
+ vec3 V = normalize(vViewPosition);
+ vec3 fp = -vViewPosition;
+ if (uGlint > 0.001 && gCav > 0.01) {
+ vec3 gp = vHalf * uGlintScale;
+ vec3 id = floor(gp); vec3 fc = fract(gp) - 0.5;
+ vec3 rnd = lh33(id);
+ float star = (1.0 - smoothstep(0.0, 0.45, length(fc))) * step(0.35, rnd.z);
+ vec3 nf = normalize(normal + (rnd - 0.5) * 1.35);
+ vec3 L1 = normalize(uL1Pos - fp), L2 = normalize(uL2Pos - fp);
+ float s1 = pow(max(dot(nf, normalize(L1 + V)), 0.0), 260.0);
+ float s2 = pow(max(dot(nf, normalize(L2 + V)), 0.0), 260.0);
+ float tw = 0.5 + 0.5 * sin(uTime * (1.3 + rnd.x * 3.5) + rnd.y * 40.0);
+ vec3 gcol = mix(vec3(1.0, 0.97, 1.0), vec3(0.78, 0.62, 1.0), rnd.x);
+ outgoingLight += gcol * (s1 * uL1Col + s2 * uL2Col) * star * (0.3 + 0.7 * tw) * gCav * (0.5 + gPurple + gLum * 2.0) * uGlint * 12.0;
+ }
+ if (uCrack > 0.001) {
+ float ay = abs(vHalf.y);
+ vec3 cq = vHalf + uSide * vec3(3.17, 0.0, 1.71);
+ float e = crackNet(cq * vec3(6.5, 8.5, 6.5) + vn3(cq * 19.0) * 0.55);
+ float w = mix(0.01, 0.034, clamp(uCrack, 0.0, 1.0));
+ // Only some cell walls fracture: the crack is a few branching lines, not a turtle shell.
+ float keep = smoothstep(0.42, 0.62, vn3(cq * 5.0 + 11.0) + (1.0 - smoothstep(0.0, 0.12, abs(vHalf.y))) * 0.35);
+ float line = (1.0 - smoothstep(0.0, w, e)) * keep;
+ float cr = clamp(uCrack, 0.0, 1.0);
+ float reach = 1.0 - smoothstep(cr * 0.24, cr * 0.24 + 0.07, ay);
+ float seam = exp(-abs(ay - uSeamY) * 190.0) * smoothstep(0.0, 0.18, uCrack);
+ float fl = 0.78 + 0.22 * sin(uTime * 31.0 + vHalf.x * 60.0) * sin(uTime * 7.3 + vHalf.z * 20.0);
+ outgoingLight += uCrackColor * max(seam * 7.0 + line * reach * max(1.0 - ay * 3.2, 0.0) * 4.0, 0.0) * (1.0 - gCav) * uCrack * fl;
+ }
+ outgoingLight += diffuseColor.rgb * uCrackColor * gCav * uInner * (0.4 + gPurple);
+ }
+ #include <opaque_fragment>`);
+ };
+ mat.customProgramCacheKey = () => 'lithos-geode';
+ mat.needsUpdate = true;
+ return mat;
+}
+
+/** Rock crystal: transmission + dispersion + a whisper of thin-film, masked to the crystal (the matrix rock stays opaque). */
+export function crystalMaterial(src, { envIntensity = 1.6, envMap = null } = {}) {
+ const m = new THREE.MeshPhysicalMaterial({
+ map: src.map, normalMap: src.normalMap, roughnessMap: src.roughnessMap, normalScale: new THREE.Vector2(0.7, 0.7),
+ metalness: 0, roughness: 1, transmission: 1, thickness: 0.55, ior: 1.544, dispersion: 2.2,
+ iridescence: 0.2, iridescenceIOR: 1.3, iridescenceThicknessRange: [300, 700],
+ specularIntensity: 1, envMapIntensity: envIntensity, envMap,
+ });
+ m.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vObj;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvObj = transformed;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vObj;\n' + HASH)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ float qLum = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));
+ float qCry = smoothstep(0.16, 0.36, qLum);
+ // Rock crystal is milky where it grew from the matrix and water-clear towards the terminations.
+ float qMilk = (1.0 - smoothstep(-0.9, -0.2, vObj.y + (vn3(vObj * 6.0) - 0.5) * 0.5)) * qCry;
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(vec3(0.96, 0.955, 0.97), diffuseColor.rgb * 1.5, 0.12), qCry);`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(roughnessFactor, 0.02 + roughnessFactor * 0.05, qCry);
+ roughnessFactor = mix(roughnessFactor, 0.3, qMilk * 0.6);`)
+ .replace('#include <lights_physical_fragment>', chunk('lights_physical_fragment') + `
+ #ifdef USE_IRIDESCENCE
+ material.iridescence *= qCry;
+ #endif`)
+ .replace('#include <transmission_fragment>', chunk('transmission_fragment').replace('material.transmission = transmission;', 'material.transmission = transmission * qCry * (1.0 - qMilk * 0.7);'))
+ .replace('#include <opaque_fragment>', `
+ #ifdef USE_ENVMAP
+ {
+ // Fake total internal reflection with a per-channel IOR: light bouncing inside the crystal, split into fire.
+ vec3 V = normalize(vViewPosition);
+ vec3 N = normal;
+ vec3 dR = refract(-V, N, 1.0 / 1.52);
+ vec3 dG = refract(-V, N, 1.0 / 1.545);
+ vec3 dB = refract(-V, N, 1.0 / 1.575);
+ vec3 inner = vec3(getIBLRadiance(dR, dR, 0.03).r, getIBLRadiance(dG, dG, 0.03).g, getIBLRadiance(dB, dB, 0.03).b);
+ float fres = pow(1.0 - max(dot(N, V), 0.0), 2.0);
+ outgoingLight += inner * qCry * (1.0 - qMilk * 0.55) * (0.3 + fres * 0.8) * uTir;
+ }
+ #endif
+ #include <opaque_fragment>`);
+ sh.uniforms.uTir = m.userData.uTir;
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nuniform float uTir;');
+ };
+ m.userData.uTir = { value: 0.6 };
+ m.customProgramCacheKey = () => 'lithos-quartz';
+ return m;
+}
+
+/** Pyrite: the brassy cubes become mirror metal with the striations from the normal map; the matrix stays dull. */
+export function patchPyrite(mat, envMap = null) {
+ mat.envMapIntensity = 0.85;
+ if (envMap) mat.envMap = envMap;
+ mat.normalScale = new THREE.Vector2(1.1, 1.1);
+ mat.onBeforeCompile = sh => {
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ vec3 pBase = diffuseColor.rgb;`)
+ .replace('#include <metalnessmap_fragment>', `#include <metalnessmap_fragment>
+ float pMet = smoothstep(0.35, 0.75, metalnessFactor);
+ metalnessFactor = pMet;
+ roughnessFactor = mix(max(roughnessFactor, 0.55), 0.09 + roughnessFactor * 0.25, pMet);
+ diffuseColor.rgb = mix(pBase * 0.8, pow(max(pBase, 0.0), vec3(0.95)) * vec3(1.08, 1.02, 0.82), pMet);`);
+ };
+ mat.customProgramCacheKey = () => 'lithos-pyrite';
+ mat.needsUpdate = true;
+ return mat;
+}
+
+/** Ammonite: physical nacre — clearcoat + thin-film interference whose thickness drifts over the shell. */
+export function nacreMaterial(src, envMap = null) {
+ const m = new THREE.MeshPhysicalMaterial({
+ map: src.map, normalMap: src.normalMap, roughnessMap: src.roughnessMap, envMap,
+ metalness: 0, roughness: 1, envMapIntensity: 0.75,
+ iridescence: 0.7, iridescenceIOR: 1.62, iridescenceThicknessRange: [180, 640],
+ clearcoat: 0.5, clearcoatRoughness: 0.14, specularIntensity: 1, sheen: 0,
+ });
+ m.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vObj;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvObj = transformed;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 vObj;\n${HASH}`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ float aShell = smoothstep(-0.58, -0.4, vObj.y / 0.95) * (1.0 - smoothstep(0.62, 0.78, roughnessFactor));
+ roughnessFactor = mix(roughnessFactor, 0.16 + roughnessFactor * 0.2, aShell);
+ // Warmer, deeper nacre: the Meshy albedo is washed out under a hard key.
+ diffuseColor.rgb = mix(diffuseColor.rgb, pow(max(diffuseColor.rgb, 0.0), vec3(1.35)) * vec3(1.02, 0.9, 0.8), aShell);`)
+ .replace('#include <lights_physical_fragment>', chunk('lights_physical_fragment') + `
+ #ifdef USE_IRIDESCENCE
+ material.iridescence *= aShell;
+ float aN = vn3(vObj * 3.2) * 0.65 + vn3(vObj * 9.0 + 3.1) * 0.35;
+ material.iridescenceThickness = mix(iridescenceThicknessMinimum, iridescenceThicknessMaximum, aN);
+ #endif
+ #ifdef USE_CLEARCOAT
+ material.clearcoat *= aShell;
+ #endif`);
+ };
+ m.customProgramCacheKey = () => 'lithos-nacre';
+ return m;
+}
+
+/** Black crushed velvet: sheen lobe, fibre-scale normal noise and patchy "crush" in the sheen colour. */
+export function velvetMaterial(renderer, bake) {
+ const crush = bake(renderer, 1024, `
+ void main(){
+ float a = fbm(vUv * 5.0, 5.0, 6, 0.55);
+ float b = fbm(vUv * 13.0 + a * 1.4, 13.0, 4, 0.5);
+ float v = smoothstep(-0.35, 0.45, a * 0.8 + b * 0.5);
+ gl_FragColor = vec4(vec3(0.42 + v * 0.58), 1.0);
+ }`);
+ const nrm = bake(renderer, 1024, `
+ float H(vec2 p){ return fbm(p * 90.0, 90.0, 3, 0.5) * 0.35 + fbm(p * 7.0, 7.0, 5, 0.55) * 1.0; }
+ void main(){
+ float e = 1.0 / 1024.0;
+ float hx = H(vUv + vec2(e, 0.)) - H(vUv - vec2(e, 0.));
+ float hy = H(vUv + vec2(0., e)) - H(vUv - vec2(0., e));
+ vec3 n = normalize(vec3(-hx * 14.0, -hy * 14.0, 1.0));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);
+ }`);
+ for (const t of [crush, nrm]) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(1, 1); }
+ crush.colorSpace = THREE.SRGBColorSpace;
+ const m = new THREE.MeshPhysicalMaterial({
+ color: 0x0a0810, roughness: 0.9, metalness: 0,
+ sheen: 1, sheenRoughness: 0.32, sheenColor: new THREE.Color(0x6a6480), sheenColorMap: crush,
+ normalMap: nrm, normalScale: new THREE.Vector2(0.26, 0.26), envMapIntensity: 0.22, specularIntensity: 0.25,
+ });
+ return m;
+}
diff --git a/examples/lithos/sound.js b/examples/lithos/sound.js
new file mode 100644
index 0000000..a727df7
--- /dev/null
+++ b/examples/lithos/sound.js
@@ -0,0 +1,76 @@
+// Optional, synthesized sound: a low vault hum, stone grinding under the hold, the crack and a crystal ring.
+// Off by default; the nav toggle creates the AudioContext on a user gesture.
+export class Sound {
+ constructor(btn) {
+ this.on = false;
+ this.btn = btn;
+ btn?.addEventListener('click', () => this.toggle());
+ }
+
+ toggle() {
+ this.on = !this.on;
+ this.btn?.setAttribute('aria-pressed', String(this.on));
+ if (this.on) this._ensure();
+ if (this.ctx) {
+ const t = this.ctx.currentTime;
+ this.master.gain.cancelScheduledValues(t);
+ this.master.gain.setTargetAtTime(this.on ? 0.9 : 0, t, 0.25);
+ if (this.on) this.ctx.resume();
+ }
+ }
+
+ _noise(sec = 2) {
+ const b = this.ctx.createBuffer(1, this.ctx.sampleRate * sec, this.ctx.sampleRate);
+ const d = b.getChannelData(0);
+ for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
+ return b;
+ }
+
+ _ensure() {
+ if (this.ctx) return;
+ const ctx = this.ctx = new AudioContext();
+ this.master = ctx.createGain(); this.master.gain.value = 0; this.master.connect(ctx.destination);
+ // Hum: two detuned low sines through a gentle lowpass.
+ const hum = ctx.createGain(); hum.gain.value = 0.05; hum.connect(this.master);
+ for (const [f, g] of [[55, 0.6], [82.6, 0.3], [110.3, 0.12]]) {
+ const o = ctx.createOscillator(); o.frequency.value = f;
+ const og = ctx.createGain(); og.gain.value = g;
+ o.connect(og).connect(hum); o.start();
+ }
+ // Grind: band-passed noise with a crackle LFO; gain follows the hold.
+ const src = ctx.createBufferSource(); src.buffer = this._noise(3); src.loop = true;
+ const bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 900; bp.Q.value = 0.8;
+ this.grind = ctx.createGain(); this.grind.gain.value = 0;
+ src.connect(bp).connect(this.grind).connect(this.master); src.start();
+ this.grindF = bp.frequency;
+ }
+
+ setHold(v) {
+ if (!this.ctx || !this.on) return;
+ const t = this.ctx.currentTime;
+ this.grind.gain.setTargetAtTime(v > 0.01 ? (0.04 + v * v * 0.35) * (0.6 + Math.random() * 0.8) : 0, t, 0.04);
+ this.grindF.setTargetAtTime(500 + v * 1600, t, 0.1);
+ }
+
+ crack() {
+ if (!this.ctx || !this.on) return;
+ const ctx = this.ctx, t = ctx.currentTime;
+ // The snap.
+ const n = ctx.createBufferSource(); n.buffer = this._noise(0.6);
+ const hp = ctx.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 1400;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0.9, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.35);
+ n.connect(hp).connect(g).connect(this.master); n.start(t);
+ // The thump of the stone.
+ const o = ctx.createOscillator(); o.frequency.setValueAtTime(120, t); o.frequency.exponentialRampToValueAtTime(38, t + 0.4);
+ const og = ctx.createGain(); og.gain.setValueAtTime(0.6, t); og.gain.exponentialRampToValueAtTime(0.001, t + 0.7);
+ o.connect(og).connect(this.master); o.start(t); o.stop(t + 0.8);
+ // Crystal ring: inharmonic partials, long decay.
+ [1318.5, 1975.5, 2637, 3322.4, 4186].forEach((f, i) => {
+ const s = ctx.createOscillator(); s.type = 'sine'; s.frequency.value = f * (1 + (Math.random() - 0.5) * 0.004);
+ const sg = ctx.createGain(); const st = t + 0.08 + i * 0.07;
+ sg.gain.setValueAtTime(0, t); sg.gain.linearRampToValueAtTime(0.05 / (1 + i * 0.4), st); sg.gain.exponentialRampToValueAtTime(0.0001, st + 3.5 - i * 0.3);
+ s.connect(sg).connect(this.master); s.start(t); s.stop(st + 4);
+ });
+ this.setHold(0);
+ }
+}
diff --git a/examples/lithos/style.css b/examples/lithos/style.css
new file mode 100644
index 0000000..bb26f6f
--- /dev/null
+++ b/examples/lithos/style.css
@@ -0,0 +1,220 @@
+:root {
+ --bg: #050407;
+ --ink: #efeaf6;
+ --plat: #cdc8d8;
+ --muted: #8e889c;
+ --faint: rgba(239, 234, 246, .1);
+ --line: rgba(205, 200, 216, .18);
+ --violet: #9d6bff;
+ --violet-hi: #c3a4ff;
+ --display: 'Italiana', 'Didot', 'Bodoni 72', serif;
+ --caps: 'Cinzel', 'Trajan Pro', serif;
+ --sans: 'Jost', 'Futura', system-ui, sans-serif;
+ --gut: clamp(18px, 4.4vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 300 16px/1.65 var(--sans); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+img { display: block; max-width: 100%; }
+::selection { background: var(--violet); color: #0b0612; }
+.cz { font-family: var(--caps); font-weight: 500; font-size: 11px; letter-spacing: .24em; text-transform: uppercase; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; -webkit-touch-callout: none; user-select: none; }
+.is-holding, .is-holding * { user-select: none; -webkit-user-select: none; }
+
+/* ── loader: a stone that cracks open ───────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; pointer-events: all; }
+.loader-half { position: absolute; left: 0; right: 0; height: 50.2%; background: var(--bg); }
+.loader-top { top: 0; } .loader-bot { bottom: 0; }
+.loader-core { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; gap: 16px; color: var(--plat); }
+.loader-stone { width: 132px; height: 132px; overflow: visible; }
+.loader-crack { fill: none; stroke: var(--violet-hi); stroke-width: 1.1; stroke-linejoin: round; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--p, 0));
+ filter: drop-shadow(0 0 4px rgba(157,107,255,.9)) drop-shadow(0 0 12px rgba(157,107,255,.5)); }
+.loader-word { font: 400 30px/1 var(--display); letter-spacing: .5em; text-transform: uppercase; margin-right: -.5em; color: var(--ink); }
+.loader-line { font: 500 10px/1 var(--caps); letter-spacing: .3em; text-transform: uppercase; color: var(--muted); }
+.loader-pct { font-variant-numeric: tabular-nums; color: var(--plat); }
+
+/* ── nav ─────────────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 22px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: inline-flex; align-items: center; gap: 12px; text-decoration: none; font: 500 14px/1 var(--caps); letter-spacing: .42em; text-transform: uppercase; justify-self: start; }
+.brand svg { width: 22px; height: 22px; color: var(--violet-hi); }
+.links { display: flex; gap: 38px; }
+.links a { text-decoration: none; font: 500 10.5px/1 var(--caps); letter-spacing: .26em; text-transform: uppercase; color: var(--muted); transition: color .3s; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: .26em; bottom: -8px; height: 1px; background: var(--violet); transform: scaleX(0); transition: transform .5s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after { transform: scaleX(1); }
+.nav-right { justify-self: end; display: flex; align-items: center; gap: 18px; }
+.sound { display: inline-flex; align-items: flex-end; gap: 2px; height: 20px; padding: 0 4px; color: var(--muted); font: 500 10px/1 var(--caps); letter-spacing: .24em; text-transform: uppercase; }
+.sound i { display: block; width: 2px; height: 4px; background: currentColor; transition: height .3s; }
+.sound span { margin-left: 8px; line-height: 14px; }
+.sound[aria-pressed="true"] { color: var(--violet-hi); }
+.sound[aria-pressed="true"] i { animation: bar 1.1s ease-in-out infinite; }
+.sound[aria-pressed="true"] i:nth-child(2) { animation-delay: -.4s; }
+.sound[aria-pressed="true"] i:nth-child(3) { animation-delay: -.8s; }
+@keyframes bar { 0%, 100% { height: 4px; } 50% { height: 14px; } }
+
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 44px; padding: 0 24px; border-radius: 999px;
+ text-decoration: none; font: 500 10.5px/1 var(--caps); letter-spacing: .24em; text-transform: uppercase; white-space: nowrap;
+ transition: background .4s, color .4s, box-shadow .4s; }
+.btn-ghost { box-shadow: inset 0 0 0 1px var(--line); color: var(--ink); background: rgba(8, 6, 12, .35); backdrop-filter: blur(10px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--violet); color: #fff; }
+.btn-solid { background: linear-gradient(180deg, #f3eff9, #c9c3d6); color: #120d1a; box-shadow: 0 0 0 1px rgba(255,255,255,.2) inset; }
+.btn-solid:hover { background: linear-gradient(180deg, #fff, #ddd6ea); box-shadow: 0 0 44px rgba(157,107,255,.45); }
+.btn-lg { height: 56px; padding: 0 34px; font-size: 11px; }
+
+/* ── type ────────────────────────────────────────────────────────── */
+.eyebrow { color: var(--violet-hi); margin-bottom: 22px; }
+.h2 { font: 400 clamp(44px, 5.8vw, 96px)/.98 var(--display); letter-spacing: -.005em; }
+.h2 em, .title em, .visit-title em { font-style: normal; color: var(--violet-hi); }
+.lede { max-width: 30em; margin-top: 28px; font: 300 clamp(16px, 1.25vw, 19px)/1.62 var(--sans); color: #bdb7c9; }
+.lede.strong { margin-top: 14px; color: var(--ink); font-weight: 400; }
+
+/* ── hero ────────────────────────────────────────────────────────── */
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, main .spec-card, main .piece, main .prov-inner, main .visit-inner, main .foot { pointer-events: auto; }
+.hero { position: relative; height: 100vh; min-height: 620px; display: grid; grid-template-rows: auto 1fr auto; justify-items: center; text-align: center;
+ padding: 17vh var(--gut) 5.5vh; }
+.hero .eyebrow { margin-bottom: 26px; }
+.title { font: 400 clamp(54px, 9.2vw, 164px)/.9 var(--display); letter-spacing: -.012em; color: #f6f2fb;
+ text-shadow: 0 0 80px rgba(157, 107, 255, .16); }
+.title .line { display: block; overflow: hidden; padding: .04em .06em .08em; }
+.title .line > span { display: inline-block; }
+.hero-foot { grid-row: 3; width: 100%; display: flex; justify-content: space-between; align-items: flex-end; text-align: left; gap: 40px; }
+.sub { max-width: 25em; font: 300 clamp(15px, 1.1vw, 17px)/1.6 var(--sans); color: #b8b2c4; }
+.label { text-align: right; color: var(--muted); line-height: 2; font-size: 10px; }
+.label b { color: var(--violet-hi); font-weight: 500; }
+
+/* hotspot projected onto the geode seam */
+.hotspot { position: fixed; left: 0; top: 0; z-index: 6; pointer-events: none; display: flex; align-items: center; gap: 14px; opacity: 0; transition: opacity .6s; will-change: transform; }
+.hotspot.on { opacity: 1; }
+.hotspot i { position: relative; width: 14px; height: 14px; border-radius: 50%; background: radial-gradient(circle, #fff 0 18%, var(--violet) 40%, transparent 72%); }
+.hotspot i::before, .hotspot i::after { content: ''; position: absolute; inset: -9px; border-radius: 50%; border: 1px solid rgba(195,164,255,.7); animation: ping 2.2s cubic-bezier(.2,.7,.3,1) infinite; }
+.hotspot i::after { animation-delay: 1.1s; }
+@keyframes ping { 0% { transform: scale(.4); opacity: 1; } 100% { transform: scale(2.1); opacity: 0; } }
+.hotspot span { color: var(--ink); white-space: nowrap; text-shadow: 0 1px 12px #000; }
+
+/* ── crack ───────────────────────────────────────────────────────── */
+.crack { position: relative; height: 190vh; padding: 0 var(--gut); }
+.crack-copy { position: sticky; top: 0; height: 100vh; display: flex; flex-direction: column; justify-content: center; max-width: 34em; }
+.hold-cta { display: flex; align-items: center; gap: 16px; margin-top: 42px; color: var(--plat); }
+.hold-ring svg { width: 40px; height: 40px; transform: rotate(-90deg); overflow: visible; }
+.hold-ring circle { fill: none; stroke: var(--line); stroke-width: 1; }
+.hold-ring circle.p { stroke: var(--violet-hi); stroke-width: 1.4; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--hold, 0)); filter: drop-shadow(0 0 4px var(--violet)); }
+.reseal { align-self: flex-start; margin-top: 26px; color: var(--muted); font-size: 10px; border-bottom: 1px solid var(--line); padding-bottom: 6px; opacity: 0; pointer-events: none !important; transition: opacity .6s, color .3s; }
+.is-open .reseal { opacity: 1; pointer-events: auto !important; }
+.is-open .hold-cta { opacity: .35; }
+.reseal:hover { color: var(--ink); }
+
+/* ── collection ──────────────────────────────────────────────────── */
+.collection { position: relative; }
+.col-head { height: 70vh; display: grid; place-content: center; text-align: center; padding: 0 var(--gut); }
+.spec { position: relative; height: 170vh; padding: 0 var(--gut); }
+.spec-card { position: sticky; top: 50%; transform: translateY(calc(-50% + var(--ty, 0px))); will-change: transform, opacity; width: min(400px, 100%); padding: 34px 34px 34px;
+ background: linear-gradient(180deg, rgba(14, 11, 20, .62), rgba(8, 6, 12, .42)); backdrop-filter: blur(16px) saturate(1.3); -webkit-backdrop-filter: blur(16px) saturate(1.3);
+ box-shadow: inset 0 0 0 1px rgba(205, 200, 216, .12), 0 40px 80px -30px rgba(0,0,0,.9); border-radius: 2px; }
+.spec-right .spec-card { margin-left: auto; }
+.spec-card::before { content: ''; position: absolute; top: 0; left: 34px; right: 34px; height: 1px; background: linear-gradient(90deg, transparent, var(--violet), transparent); opacity: .7; }
+.spec-num { display: flex; justify-content: space-between; color: var(--violet-hi); font-size: 10px; margin-bottom: 20px; }
+.spec-num span:last-child { color: var(--muted); letter-spacing: .12em; text-transform: none; }
+.spec-card h3 { font: 400 clamp(34px, 3vw, 46px)/1 var(--display); margin-bottom: 16px; }
+.spec-desc { font-size: 14.5px; line-height: 1.65; color: #bab4c6; }
+.facts { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; margin: 26px 0 28px; background: var(--faint); box-shadow: 0 0 0 1px var(--faint); }
+.facts div { background: rgba(9, 7, 13, .85); padding: 13px 14px 12px; }
+.facts dt { font: 500 9px/1 var(--caps); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); margin-bottom: 7px; }
+.facts dd { font: 400 15px/1.3 var(--sans); color: var(--ink); }
+.facts div:last-child dd { font: 400 21px/1.1 var(--display); color: var(--violet-hi); }
+
+/* ── jewellery ───────────────────────────────────────────────────── */
+.jewel { position: relative; overflow-x: clip; padding: 30vh var(--gut) 18vh; background: linear-gradient(180deg, rgba(5,4,7,0) 0%, rgba(5,4,7,.72) 24%, rgba(5,4,7,.78) 100%); }
+.jewel-head { max-width: 1240px; margin: 0 auto; display: grid; grid-template-columns: 1.2fr 1fr; gap: 20px 60px; align-items: end; }
+.jewel-head .eyebrow { grid-column: 1 / -1; margin-bottom: 0; }
+.jewel-head .lede { margin: 0; }
+.pieces { max-width: 1240px; margin: 90px auto 0; display: grid; grid-template-columns: repeat(3, 1fr); gap: clamp(18px, 2.4vw, 40px); }
+.piece-mid { transform: translateY(12vh); }
+.piece-img { position: relative; overflow: hidden; aspect-ratio: 4 / 5; background: #0b0910; box-shadow: 0 0 0 1px var(--faint); }
+.piece-img img { width: 100%; height: 100%; object-fit: cover; transform: scale(1.04); transition: transform 1.6s cubic-bezier(.2,.7,.2,1), filter 1s; filter: saturate(.95) brightness(.92); }
+.piece:hover .piece-img img { transform: scale(1.1); filter: saturate(1.08) brightness(1.02); }
+.piece figcaption { padding-top: 22px; display: grid; grid-template-columns: 1fr auto; gap: 4px 20px; align-items: baseline; }
+.piece-from { grid-column: 1 / -1; color: var(--violet-hi); font-size: 9.5px; margin-bottom: 6px; }
+.piece h3 { font: 400 30px/1.05 var(--display); }
+.piece-price { grid-row: 2; grid-column: 2; font: 400 16px/1 var(--sans); color: var(--plat); }
+.piece figcaption p:not(.piece-from):not(.piece-price) { grid-column: 1 / -1; color: var(--muted); font-size: 14px; }
+
+/* ── provenance ──────────────────────────────────────────────────── */
+.prov { position: relative; overflow-x: clip; padding: 26vh var(--gut) 30vh; background: linear-gradient(180deg, rgba(5,4,7,.78) 0%, rgba(5,4,7,.3) 22%, rgba(5,4,7,.3) 70%, rgba(5,4,7,0) 100%); }
+.prov-inner { max-width: 1240px; margin: 0 auto; }
+.prov-grid { display: grid; grid-template-columns: 1.1fr 1fr; gap: clamp(30px, 5vw, 90px); margin-top: 80px; align-items: start; }
+.prov-photo { position: sticky; top: 16vh; }
+.prov-photo img { width: 100%; height: auto; aspect-ratio: 16 / 10; object-fit: cover; box-shadow: 0 0 0 1px var(--faint), 0 50px 100px -40px #000; filter: saturate(.9); }
+.prov-photo figcaption { margin-top: 14px; color: var(--muted); font-size: 9.5px; }
+.principles { list-style: none; display: grid; gap: 0; }
+.principles { position: relative; }
+.principles::before { content: ''; position: absolute; inset: -60px -40px; z-index: -1; background: radial-gradient(closest-side, rgba(5,4,7,.78), rgba(5,4,7,0)); pointer-events: none; }
+.principles li { padding: 30px 0 34px; border-top: 1px solid var(--line); display: grid; grid-template-columns: 56px 1fr; gap: 0 10px; text-shadow: 0 1px 18px rgba(0,0,0,.9); }
+.principles li span { color: var(--violet-hi); grid-row: span 2; padding-top: 10px; }
+.principles h3 { font: 400 32px/1.1 var(--display); margin-bottom: 10px; }
+.principles p { color: #b1abbd; font-size: 15px; max-width: 30em; }
+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 40px; margin-top: 110px; padding-top: 44px; border-top: 1px solid var(--line); }
+.stats b { display: block; font: 400 clamp(64px, 7vw, 120px)/.9 var(--display); color: var(--ink); }
+.stats span { display: block; margin-top: 14px; color: var(--muted); font-size: 10px; }
+
+/* ── visit & footer ──────────────────────────────────────────────── */
+.visit { position: relative; min-height: 130vh; display: grid; place-items: end center; text-align: center; padding: 30vh var(--gut) 14vh; }
+.visit-inner { display: grid; justify-items: center; }
+.visit-title { font: 400 clamp(52px, 8vw, 150px)/.92 var(--display); letter-spacing: -.01em; text-shadow: 0 10px 60px rgba(0,0,0,.8); }
+.visit .lede { margin: 30px auto 0; text-shadow: 0 1px 20px #000; }
+.visit-cta { display: flex; flex-wrap: wrap; gap: 14px; justify-content: center; margin-top: 44px; }
+.foot { position: relative; background: var(--bg); padding: 70px var(--gut) 90px; border-top: 1px solid var(--line); }
+.foot-grid { display: grid; grid-template-columns: 1.4fr 1fr 1fr 1fr; gap: 40px; color: var(--muted); font-size: 14px; line-height: 1.9; }
+.foot-brand .cz { display: block; font-size: 15px; letter-spacing: .42em; color: var(--ink); margin-bottom: 14px; }
+.fine { margin-top: 70px; color: #5f596c; font-size: 9px; letter-spacing: .2em; }
+
+/* ── overlays ────────────────────────────────────────────────────── */
+.press { position: fixed; left: 0; top: 0; z-index: 40; width: 80px; height: 80px; margin: -40px 0 0 -40px; pointer-events: none; opacity: 0; transition: opacity .3s; display: grid; place-items: center; }
+.press svg { position: absolute; inset: 0; transform: rotate(-90deg); overflow: visible; }
+.press circle { fill: none; stroke: rgba(239,234,246,.28); stroke-width: 1; }
+.press circle.p { stroke: var(--violet-hi); stroke-width: 1.8; stroke-dasharray: 1; stroke-dashoffset: calc(1 - var(--hold, 0)); filter: drop-shadow(0 0 6px var(--violet)); }
+.press span { color: var(--ink); font-size: 9px; letter-spacing: .3em; margin-right: -.3em; }
+.press.on { opacity: 1; }
+.toast { position: fixed; left: 50%; bottom: 5.5vh; z-index: 30; transform: translate(-50%, 16px); padding: 15px 26px; border-radius: 999px; font-size: 10px;
+ background: rgba(12, 9, 18, .72); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px rgba(157,107,255,.35); color: var(--ink);
+ opacity: 0; transition: opacity .6s, transform .6s; pointer-events: none; white-space: nowrap; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+.light-hint { position: fixed; right: var(--gut); top: 50%; z-index: 8; writing-mode: vertical-rl; color: var(--muted); font-size: 9.5px; opacity: 0; transition: opacity 1s; pointer-events: none; }
+.light-hint::before { content: ''; display: inline-block; width: 7px; height: 7px; margin-bottom: 14px; border-radius: 50%; background: #fff; box-shadow: 0 0 10px 2px var(--violet); }
+.light-hint.on { opacity: 1; }
+
+/* custom cursor: a small light source */
+.tw-cursor .tw-cursor-dot { width: 8px; height: 8px; margin: -4px 0 0 -4px; background: #fff; box-shadow: 0 0 12px 3px rgba(195,164,255,.85), 0 0 28px 8px rgba(157,107,255,.35); }
+.is-holding .tw-cursor { opacity: 0; }
+
+@media (max-width: 900px) {
+ .nav { grid-template-columns: 1fr auto; padding: 16px 18px; }
+ .links, .sound span { display: none; }
+ .nav .btn { height: 36px; padding: 0 16px; font-size: 9.5px; }
+ .hero { padding-top: 15vh; padding-bottom: 12vh; }
+ .title { font-size: clamp(46px, 13.4vw, 90px); }
+ .hero-foot { flex-direction: column; align-items: flex-start; gap: 18px; }
+ .label { display: none; }
+ .crack { height: 170vh; }
+ .crack-copy { justify-content: flex-start; padding-top: 14vh; }
+ .crack-copy .lede { font-size: 15px; margin-top: 18px; }
+ .spec { height: 150vh; }
+ .spec-card { position: fixed; top: auto; left: 16px; right: 16px; bottom: 64px; width: auto; margin: 0 !important; transform: translateY(var(--ty, 0px)); padding: 20px 20px 22px; }
+ .spec-desc { display: none; }
+ .facts { margin: 14px 0 16px; }
+ .facts div { padding: 10px 12px 9px; }
+ .spec-card .btn { height: 40px; }
+ .spec-card h3 { font-size: 32px; margin-bottom: 4px; }
+ .jewel-head, .prov-grid { grid-template-columns: 1fr; }
+ .pieces { grid-template-columns: 1fr; gap: 50px; }
+ .piece-mid { transform: none; }
+ .prov-photo { position: relative; top: 0; }
+ .stats { grid-template-columns: 1fr; gap: 26px; }
+ .foot-grid { grid-template-columns: 1fr 1fr; }
+ .light-hint { display: none; }
+ .toast { white-space: normal; width: calc(100vw - 36px); text-align: center; top: 74px; bottom: auto; }
+}
diff --git a/examples/lowfreq/audio.js b/examples/lowfreq/audio.js
new file mode 100644
index 0000000..869c31c
--- /dev/null
+++ b/examples/lowfreq/audio.js
@@ -0,0 +1,476 @@
+// Low Frequency — everything you hear is synthesised here.
+// Each track is an 8-bar loop rendered once into an AudioBuffer with an OfflineAudioContext
+// (kick, snare/clap, hats, bass, FM Rhodes, pads, tape wobble, vinyl crackle), then played by a
+// deck that follows the platter: playbackRate = platter speed, backwards via a reversed buffer.
+
+const hz = m => 440 * 2 ** ((m - 69) / 12);
+function rng(seed) {
+ return () => {
+ seed = (seed + 0x6D2B79F5) | 0;
+ let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// Chord = bass root + upper voicing (MIDI).
+const C = (bass, ...v) => ({ bass, v });
+export const TRACKS = [
+ { id: 'A1', title: 'Last Train, Shimokita', bpm: 122, time: '4:12', style: 'house', swing: 0.54, seed: 11,
+ scale: [65, 68, 70, 72, 75, 77, 80],
+ prog: [C(41, 56, 60, 63, 67), C(41, 56, 60, 63, 67), C(37, 53, 56, 60, 63), C(39, 55, 58, 60, 65),
+ C(41, 56, 60, 63, 67), C(41, 56, 60, 63, 68), C(37, 53, 56, 60, 63), C(36, 51, 55, 58, 62)] },
+ { id: 'A2', title: 'Aubergine Hours', bpm: 84, time: '5:03', style: 'hop', swing: 0.63, seed: 23,
+ scale: [62, 64, 65, 67, 69, 72, 74, 76],
+ prog: [C(38, 53, 57, 60, 64), C(43, 53, 59, 64, 69), C(36, 52, 55, 59, 62), C(45, 55, 61, 65, 69),
+ C(38, 53, 57, 60, 64), C(43, 53, 59, 64, 69), C(36, 52, 55, 59, 62), C(45, 55, 61, 65, 68)] },
+ { id: 'A3', title: 'Seat Seven', bpm: 118, time: '3:48', style: 'deep', swing: 0.56, seed: 37,
+ scale: [69, 72, 74, 76, 79, 81, 84],
+ prog: [C(45, 60, 64, 67, 71), C(41, 57, 60, 64, 67), C(45, 60, 64, 67, 71), C(43, 59, 62, 64, 69),
+ C(45, 60, 64, 67, 71), C(41, 57, 60, 64, 67), C(38, 57, 60, 64, 65), C(40, 55, 59, 62, 67)] },
+ { id: 'A4', title: 'Needle Rain', bpm: 96, time: '6:20', style: 'dub', swing: 0.52, seed: 41,
+ scale: [63, 65, 67, 70, 72, 75],
+ prog: [C(39, 55, 58, 62, 65), C(39, 55, 58, 62, 65), C(44, 55, 60, 62, 63), C(44, 55, 60, 62, 63),
+ C(41, 56, 58, 63, 67), C(41, 56, 58, 63, 67), C(46, 56, 60, 63, 65), C(46, 56, 60, 63, 65)] },
+];
+
+function makeCurve(k) {
+ const n = 2048, c = new Float32Array(n);
+ for (let i = 0; i < n; i++) { const x = (i / (n - 1)) * 2 - 1; c[i] = Math.tanh(k * x) / Math.tanh(k); }
+ return c;
+}
+function impulse(ctx, secs, decay, R) {
+ const len = Math.floor(ctx.sampleRate * secs), b = ctx.createBuffer(2, len, ctx.sampleRate);
+ for (let ch = 0; ch < 2; ch++) {
+ const d = b.getChannelData(ch); let lp = 0;
+ for (let i = 0; i < len; i++) { const w = R() * 2 - 1; lp += (w - lp) * (0.35 - 0.3 * i / len); d[i] = lp * Math.pow(1 - i / len, decay); }
+ }
+ return b;
+}
+
+export async function renderTrack(def, sampleRate = 44100) {
+ const R = rng(def.seed);
+ const S0 = def.style;
+ const spb = 60 / def.bpm, st = spb / 4, bar = spb * 4, bars = def.prog.length;
+ const dur = bars * bar, tail = 3.5;
+ const len = Math.ceil((dur + tail) * sampleRate);
+ const ctx = new OfflineAudioContext(2, len, sampleRate);
+ const sr = sampleRate;
+
+ const noise = ctx.createBuffer(1, sr * 2, sr);
+ { const d = noise.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = R() * 2 - 1; }
+
+ // Master: mix -> wow/flutter -> tape saturation -> band limit -> glue compression.
+ const out = ctx.createGain(); out.gain.value = 0.62;
+ const sat = ctx.createWaveShaper(); sat.curve = makeCurve(1.5); sat.oversample = '2x';
+ const hp = ctx.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 28;
+ const lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = def.style === 'hop' ? 6800 : 9800; lp.Q.value = 0.4;
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -16; comp.ratio.value = 3; comp.attack.value = 0.006; comp.release.value = 0.18; comp.knee.value = 8;
+ out.connect(sat).connect(hp).connect(lp).connect(comp).connect(ctx.destination);
+ const mix = ctx.createGain();
+ const wow = ctx.createDelay(0.1); wow.delayTime.value = 0.02;
+ const w1 = ctx.createOscillator(), w1g = ctx.createGain(); w1.frequency.value = 0.47; w1g.gain.value = 0.0011;
+ const w2 = ctx.createOscillator(), w2g = ctx.createGain(); w2.frequency.value = 5.9; w2g.gain.value = 0.00012;
+ w1.connect(w1g).connect(wow.delayTime); w2.connect(w2g).connect(wow.delayTime); w1.start(0); w2.start(0);
+ mix.connect(wow).connect(out);
+
+ // Sends: room reverb and a tape echo.
+ const verb = ctx.createConvolver(); verb.buffer = impulse(ctx, 2.6, 2.6, R);
+ const verbIn = ctx.createGain(); verbIn.gain.value = def.style === 'dub' ? 0.5 : 0.28;
+ verbIn.connect(verb).connect(mix);
+ const echo = ctx.createDelay(2); echo.delayTime.value = spb * 0.75;
+ const echoFb = ctx.createGain(); echoFb.gain.value = def.style === 'dub' ? 0.55 : 0.32;
+ const echoLp = ctx.createBiquadFilter(); echoLp.type = 'lowpass'; echoLp.frequency.value = 2200;
+ const echoIn = ctx.createGain(); echoIn.gain.value = 0.5;
+ echoIn.connect(echo); echo.connect(echoLp).connect(echoFb).connect(echo); echoLp.connect(mix); echoLp.connect(verbIn);
+
+ const drums = ctx.createGain(); drums.gain.value = 0.9; drums.connect(mix);
+ const bassBus = ctx.createGain(); bassBus.gain.value = S0 === 'hop' ? 0.5 : 0.42;
+ const bassLp = ctx.createBiquadFilter(); bassLp.type = 'lowpass'; bassLp.frequency.value = 900;
+ bassBus.connect(bassLp).connect(mix);
+ // Rhodes bus: tremolo autopan + sidechain duck from the kick.
+ const keys = ctx.createGain(); keys.gain.value = def.style === 'hop' ? 0.78 : 0.62;
+ const pan = ctx.createStereoPanner();
+ const tl = ctx.createOscillator(), tlg = ctx.createGain(); tl.frequency.value = def.style === 'hop' ? 3.2 : 4.4; tlg.gain.value = 0.42;
+ tl.connect(tlg).connect(pan.pan); tl.start(0);
+ const duck = ctx.createGain();
+ keys.connect(pan).connect(duck).connect(mix);
+ keys.connect(verbIn);
+ const duckOn = def.style === 'house' || def.style === 'deep';
+
+ const at = (b, s) => {
+ // time of 16th step s in bar b, with swing on off-16ths (or off-8ths for hip-hop)
+ let t = b * bar + s * st;
+ if (def.style === 'hop') { if (s % 4 === 2) t += (def.swing - 0.5) * 2 * (st * 2); }
+ else if (s % 2 === 1) t += (def.swing - 0.5) * 2 * st;
+ return Math.max(0, t + (R() - 0.5) * 0.006);
+ };
+
+ const noiseHit = (t, dur, type, f, v, dest, q = 0.7) => {
+ const s = ctx.createBufferSource(); s.buffer = noise;
+ const fl = ctx.createBiquadFilter(); fl.type = type; fl.frequency.value = f; fl.Q.value = q;
+ const g = ctx.createGain(); g.gain.setValueAtTime(v, t); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
+ s.connect(fl).connect(g); for (const d of [dest].flat()) g.connect(d);
+ s.start(t, R() * 1.6, dur + 0.03);
+ };
+ const tone = (t, f0, f1, dur, v, type, dest) => {
+ const o = ctx.createOscillator(); o.type = type;
+ o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(f1, t + dur);
+ const g = ctx.createGain(); g.gain.setValueAtTime(v, t); g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
+ o.connect(g); for (const d of [dest].flat()) g.connect(d);
+ o.start(t); o.stop(t + dur + 0.02);
+ };
+ const kick = (t, v = 1) => {
+ const o = ctx.createOscillator(), g = ctx.createGain();
+ o.frequency.setValueAtTime(165, t); o.frequency.exponentialRampToValueAtTime(58, t + 0.07); o.frequency.exponentialRampToValueAtTime(43, t + 0.4);
+ v *= 1.2;
+ g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(v, t + 0.004);
+ g.gain.exponentialRampToValueAtTime(v * 0.35, t + 0.13); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.5);
+ o.connect(g).connect(drums); o.start(t); o.stop(t + 0.52);
+ noiseHit(t, 0.012, 'highpass', 1800, 0.22 * v, drums);
+ if (duckOn) { duck.gain.setTargetAtTime(0.42, t, 0.004); duck.gain.setTargetAtTime(1, t + 0.04, 0.085); }
+ };
+ const snare = (t, v = 1) => {
+ noiseHit(t, 0.22, 'bandpass', 1900, 0.55 * v, [drums, verbIn], 0.6);
+ tone(t, 200, 150, 0.1, 0.32 * v, 'triangle', drums);
+ };
+ const clap = (t, v = 1) => {
+ for (let k = 0; k < 3; k++) noiseHit(t + k * 0.011, 0.018, 'bandpass', 1250, 0.45 * v, drums, 1.3);
+ noiseHit(t + 0.024, 0.2, 'bandpass', 1250, 0.4 * v, [drums, verbIn], 1);
+ };
+ const rim = (t, v = 1, dest = drums) => { noiseHit(t, 0.035, 'bandpass', 3100, 0.5 * v, dest, 3); tone(t, 1720, 1650, 0.025, 0.12 * v, 'square', dest); };
+ const hat = (t, v, open = false) => noiseHit(t, open ? 0.24 : 0.035, 'highpass', open ? 7200 : 8200, v * 0.24, drums, 0.6);
+ const shaker = (t, v) => noiseHit(t, 0.06, 'bandpass', 5600, v * 0.2, drums, 1.4);
+
+ const bass = (t, m, dur, v = 1, sub = false) => {
+ const f = hz(m);
+ const o = ctx.createOscillator(); o.type = 'sine'; o.frequency.value = f;
+ const o2 = ctx.createOscillator(); o2.type = sub ? 'triangle' : 'sawtooth'; o2.frequency.value = f; o2.detune.value = 4;
+ const fl = ctx.createBiquadFilter(); fl.type = 'lowpass'; fl.Q.value = 3;
+ fl.frequency.setValueAtTime(sub ? 400 : 1100, t); fl.frequency.exponentialRampToValueAtTime(sub ? 180 : 240, t + 0.22);
+ const g2 = ctx.createGain(); g2.gain.value = sub ? 0.18 : 0.32;
+ const g = ctx.createGain();
+ g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(0.9 * v, t + 0.008);
+ g.gain.setTargetAtTime(0.62 * v, t + 0.02, 0.18);
+ g.gain.setTargetAtTime(0.0001, t + dur, 0.03);
+ o.connect(g); o2.connect(fl).connect(g2).connect(g); g.connect(bassBus);
+ o.start(t); o2.start(t); o.stop(t + dur + 0.25); o2.stop(t + dur + 0.25);
+ };
+ // FM electric piano: 1:1 modulator with decaying index (bright bark -> mellow), plus a tine partial.
+ const rhodes = (t, m, dur, v = 0.6, dest = keys) => {
+ const f = hz(m);
+ const car = ctx.createOscillator(); car.frequency.value = f;
+ const mod = ctx.createOscillator(); mod.frequency.value = f;
+ const mg = ctx.createGain();
+ mg.gain.setValueAtTime(f * (0.7 + v * 1.9), t); mg.gain.exponentialRampToValueAtTime(f * 0.12, t + 1.1);
+ mod.connect(mg).connect(car.frequency);
+ const amp = ctx.createGain();
+ amp.gain.setValueAtTime(0.0001, t); amp.gain.exponentialRampToValueAtTime(v * 0.2, t + 0.005);
+ amp.gain.setTargetAtTime(v * 0.085, t + 0.012, 0.5);
+ amp.gain.setTargetAtTime(0.0001, t + dur, 0.14);
+ car.connect(amp).connect(dest);
+ const tine = ctx.createOscillator(); tine.frequency.value = f * 7.05;
+ const tg = ctx.createGain(); tg.gain.setValueAtTime(0.028 * v, t); tg.gain.exponentialRampToValueAtTime(0.0001, t + 0.14);
+ tine.connect(tg).connect(dest);
+ const end = t + dur + 0.9;
+ car.start(t); mod.start(t); tine.start(t); car.stop(end); mod.stop(end); tine.stop(t + 0.2);
+ };
+ const vibe = (t, m, v = 0.5) => {
+ const f = hz(m);
+ for (const [mul, a, d] of [[1, 1, 1.6], [4, 0.32, 0.35], [10.2, 0.08, 0.12]]) {
+ const o = ctx.createOscillator(); o.frequency.value = f * mul;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.exponentialRampToValueAtTime(v * 0.11 * a, t + 0.004);
+ g.gain.exponentialRampToValueAtTime(0.0001, t + d);
+ o.connect(g).connect(keys); g.connect(echoIn); o.start(t); o.stop(t + d + 0.05);
+ }
+ };
+ const pad = (t, notes, dur, v = 0.5) => {
+ const fl = ctx.createBiquadFilter(); fl.type = 'lowpass'; fl.Q.value = 0.8;
+ fl.frequency.setValueAtTime(420, t); fl.frequency.linearRampToValueAtTime(1100, t + dur * 0.5); fl.frequency.linearRampToValueAtTime(500, t + dur);
+ const g = ctx.createGain(); g.gain.setValueAtTime(0.0001, t); g.gain.linearRampToValueAtTime(v * 0.05, t + 0.9);
+ g.gain.setTargetAtTime(0.0001, t + dur, 0.4);
+ fl.connect(g); g.connect(duck); g.connect(verbIn);
+ for (const m of notes) for (const d of [-7, 6]) {
+ const o = ctx.createOscillator(); o.type = 'sawtooth'; o.frequency.value = hz(m); o.detune.value = d;
+ o.connect(fl); o.start(t); o.stop(t + dur + 2);
+ }
+ };
+
+ // ── Arrangement ───────────────────────────────────────────────────────────
+ const S = def.style;
+ let lastLead = def.scale[2];
+ for (let b = 0; b < bars; b++) {
+ const ch = def.prog[b], next = def.prog[(b + 1) % bars];
+ const hv = () => 0.75 + R() * 0.35;
+ // drums
+ for (let s = 0; s < 16; s++) {
+ const t = at(b, s);
+ if (S === 'house') {
+ if (s % 4 === 0) kick(t, 0.95);
+ if (s === 4 || s === 12) clap(t, 0.8);
+ if (s % 4 === 2) hat(t, 0.7 * hv(), true);
+ else if (s % 2 === 1) hat(t, 0.38 * hv());
+ if (s % 2 === 1 && b % 2) shaker(t, 0.35 * hv());
+ } else if (S === 'hop') {
+ if (s === 0 || s === 10 || (s === 7 && b % 2 === 1) || (s === 15 && b % 4 === 3)) kick(t, s === 0 ? 1 : 0.8);
+ if (s === 4 || s === 12) snare(t, 0.85 * hv());
+ else if (R() < 0.1) snare(t, 0.12);
+ if (s % 2 === 0) hat(t, (s % 4 === 0 ? 0.5 : 0.34) * hv());
+ else if (R() < 0.22) hat(t, 0.14);
+ } else if (S === 'deep') {
+ if (s % 4 === 0) kick(t, 0.9);
+ if (s === 4 || s === 12) rim(t, 0.55);
+ if (s === 12 && b % 2 === 1) clap(t, 0.5);
+ if (s % 4 === 2) hat(t, 0.55 * hv(), true);
+ else hat(t, 0.16 * hv());
+ if (s % 2 === 1) shaker(t, 0.45 * hv());
+ } else { // dub: one drop
+ if (s === 8 || (s === 0 && b % 2 === 0)) kick(t, 0.95);
+ if (s === 8) rim(t, 0.7, [drums, echoIn]);
+ if (s % 2 === 1 && R() < 0.55) hat(t, 0.2 * hv());
+ if (s === 14 && b % 4 === 3) snare(t, 0.4);
+ }
+ }
+ // bass
+ const r = ch.bass;
+ const bl = st * 0.95;
+ if (S === 'house') {
+ for (const s of [2, 6, 10, 14]) bass(at(b, s), r, bl * 1.6, 0.9);
+ if (R() < 0.5) bass(at(b, 15), r + 12, bl * 0.7, 0.55);
+ } else if (S === 'hop') {
+ bass(at(b, 0), r, bl * 5.5, 1);
+ bass(at(b, 6), r + 7, bl * 2, 0.7);
+ bass(at(b, 10), r, bl * 3, 0.85);
+ bass(at(b, 14), next.bass - 1, bl * 1.6, 0.6);
+ } else if (S === 'deep') {
+ bass(at(b, 0), r, bl * 2.5, 0.95); bass(at(b, 3), r, bl, 0.6); bass(at(b, 6), r + 12, bl, 0.55);
+ bass(at(b, 8), r, bl * 2, 0.85); bass(at(b, 11), r + 7, bl, 0.6); bass(at(b, 14), r, bl * 1.5, 0.7);
+ } else {
+ bass(at(b, 0), r, bl * 6, 1, true); bass(at(b, 7), r, bl, 0.6, true); bass(at(b, 10), r + 7, bl * 4, 0.8, true);
+ }
+ // chords
+ const strum = (t, len, v, gap = 0.008) => ch.v.forEach((m, k) => rhodes(t + k * gap + R() * 0.004, m, len, v * (0.85 + R() * 0.2)));
+ if (S === 'house') {
+ for (const [s, l] of [[0, 3], [3, 3], [7, 2], [10, 4]]) strum(at(b, s), l * st, 0.52, 0.004);
+ } else if (S === 'hop') {
+ strum(at(b, 0), st * 9.5, 0.62, 0.016);
+ strum(at(b, 10), st * 5.5, 0.5, 0.014);
+ } else if (S === 'deep') {
+ for (const s of [2, 6, 10, 14]) strum(at(b, s), st * 1.1, 0.46, 0.003);
+ if (b % 2 === 0) pad(at(b, 0), ch.v, bar * 2, 0.45);
+ } else {
+ pad(at(b, 0), ch.v, bar, 0.7);
+ for (const s of [4, 12]) ch.v.forEach(m => rhodes(at(b, s), m, st * 0.8, 0.42, echoIn));
+ for (const s of [4, 12]) ch.v.forEach(m => rhodes(at(b, s), m, st * 0.8, 0.36));
+ }
+ // a little melody in the second half
+ if (b >= bars / 2 && S !== 'house') {
+ for (let s = 0; s < 16; s += 2) {
+ if (R() > (S === 'hop' ? 0.34 : 0.3)) continue;
+ const i = def.scale.indexOf(lastLead);
+ let j = Math.max(0, Math.min(def.scale.length - 1, (i < 0 ? 2 : i) + Math.round((R() - 0.5) * 4)));
+ lastLead = def.scale[j];
+ if (S === 'hop') rhodes(at(b, s), lastLead + 12, st * 3, 0.5);
+ else vibe(at(b, s), lastLead + (S === 'dub' ? 12 : 0), 0.55);
+ }
+ }
+ if (S === 'house' && b >= 4) for (const s of [3, 11]) if (R() < 0.6) vibe(at(b, s), def.scale[Math.floor(R() * def.scale.length)] + 12, 0.35);
+ }
+ if (S === 'dub') { // rain on the window
+ const s = ctx.createBufferSource(); s.buffer = noise; s.loop = true;
+ const f = ctx.createBiquadFilter(); f.type = 'bandpass'; f.frequency.value = 3200; f.Q.value = 0.4;
+ const g = ctx.createGain(); g.gain.value = 0.035; s.connect(f).connect(g).connect(mix); s.start(0);
+ }
+
+ const rendered = await ctx.startRendering();
+ // Fold the tail back onto the head so the loop is seamless.
+ const n = Math.round(dur * sr);
+ const buf = new AudioBuffer({ length: n, numberOfChannels: 2, sampleRate: sr });
+ let peak = 0;
+ const chans = [0, 1].map(c => {
+ const d = rendered.getChannelData(c), o = new Float32Array(n);
+ o.set(d.subarray(0, n));
+ for (let i = 0; i < len - n && i < n; i++) o[i] += d[n + i];
+ for (let i = 0; i < n; i++) peak = Math.max(peak, Math.abs(o[i]));
+ return o;
+ });
+ // Surface noise and crackle, pressed into the same groove (so it scratches with the music).
+ const k = 0.88 / Math.max(peak, 1e-3);
+ const CR = rng(def.seed * 7 + 1);
+ let hiss = 0;
+ for (let i = 0; i < n; i++) {
+ hiss += ((CR() * 2 - 1) - hiss) * 0.08;
+ const h = hiss * 0.006;
+ chans[0][i] = chans[0][i] * k + h; chans[1][i] = chans[1][i] * k + h * 0.9;
+ }
+ const pops = Math.floor(dur * 9);
+ for (let p = 0; p < pops; p++) {
+ const i0 = Math.floor(CR() * (n - 64));
+ const a = (CR() < 0.08 ? 0.16 : 0.035) * (0.4 + CR());
+ const side = CR();
+ for (let j = 0; j < 40; j++) {
+ const v = a * Math.exp(-j / 5) * (j % 2 ? -0.6 : 1);
+ chans[0][i0 + j] += v * (side < 0.7 ? 1 : 0.3); chans[1][i0 + j] += v * (side > 0.3 ? 1 : 0.3);
+ }
+ }
+ buf.copyToChannel(chans[0], 0); buf.copyToChannel(chans[1], 1);
+ return buf;
+}
+
+export function reverseBuffer(b) {
+ const r = new AudioBuffer({ length: b.length, numberOfChannels: b.numberOfChannels, sampleRate: b.sampleRate });
+ for (let c = 0; c < b.numberOfChannels; c++) { const d = b.getChannelData(c).slice(); d.reverse(); r.copyToChannel(d, c); }
+ return r;
+}
+
+/** RMS envelope (0..1), `n` points across the loop — used to cut the visible grooves. */
+export function envelope(b, n = 256) {
+ const d = b.getChannelData(0), step = Math.floor(d.length / n), out = new Float32Array(n);
+ let mx = 0;
+ for (let i = 0; i < n; i++) {
+ let s = 0; for (let j = 0; j < step; j += 4) { const v = d[i * step + j]; s += v * v; }
+ out[i] = Math.sqrt(s / (step / 4)); mx = Math.max(mx, out[i]);
+ }
+ for (let i = 0; i < n; i++) out[i] /= mx || 1;
+ return out;
+}
+
+// ── The deck: a player that is driven by the platter ─────────────────────────
+export class Deck {
+ constructor() {
+ this.ctx = null;
+ this.fwd = []; this.rev = []; this.env = [];
+ this.track = 0; this.pos = 0; this.dir = 1; this.src = null; this.applied = 0;
+ this.volume = 0.8; this.muted = false; this.ready = false;
+ this.levels = { bass: 0, mid: 0, high: 0, rms: 0 };
+ }
+
+ async prerender(onEach) {
+ for (let i = 0; i < TRACKS.length; i++) {
+ const b = await renderTrack(TRACKS[i]);
+ this.fwd[i] = b; this.rev[i] = reverseBuffer(b); this.env[i] = envelope(b);
+ onEach?.(i, this.env[i]);
+ }
+ }
+
+ /** Must be called from a user gesture. */
+ unlock() {
+ if (this.ctx) { if (this.ctx.state !== 'running') this.ctx.resume(); return; }
+ const ctx = this.ctx = new AudioContext({ latencyHint: 'interactive' });
+ this.gate = ctx.createGain(); this.gate.gain.value = 0;
+ this.sfx = ctx.createGain(); this.sfx.gain.value = 0.9;
+ this.tone = ctx.createBiquadFilter(); this.tone.type = 'lowpass'; this.tone.frequency.value = 17000;
+ this.analyser = ctx.createAnalyser(); this.analyser.fftSize = 2048; this.analyser.smoothingTimeConstant = 0.7;
+ this.analyser.minDecibels = -92; this.analyser.maxDecibels = -22;
+ this.master = ctx.createGain(); this.master.gain.value = 0;
+ this.master.gain.setTargetAtTime(this.muted ? 0 : this.volume, ctx.currentTime, 0.4);
+ this.gate.connect(this.tone); this.sfx.connect(this.tone);
+ this.tone.connect(this.analyser).connect(this.master).connect(ctx.destination);
+ this.freq = new Uint8Array(this.analyser.frequencyBinCount);
+ this.wave = new Float32Array(this.analyser.fftSize);
+ this.noise = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
+ const d = this.noise.getChannelData(0); for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
+ this.lastA = ctx.currentTime;
+ this.ready = true;
+ }
+
+ setMuted(m) {
+ this.muted = m;
+ if (this.ctx) this.master.gain.setTargetAtTime(m ? 0 : this.volume, this.ctx.currentTime, 0.08);
+ }
+
+ cue(i) { this.track = i; this.pos = 0; this._stopSrc(); }
+
+ /** Called every frame. rate = platter speed / 33⅓ (negative = backwards). */
+ update(rate, needleDown) {
+ const ctx = this.ctx;
+ if (!ctx) return;
+ const now = ctx.currentTime, dA = Math.min(0.1, now - this.lastA);
+ this.lastA = now;
+ const fwd = this.fwd[this.track];
+ if (!fwd) return;
+ const D = fwd.duration;
+ if (this.src) this.pos = (((this.pos + this.applied * dA) % D) + D) % D;
+ if (!needleDown) {
+ this.gate.gain.setTargetAtTime(0, now, 0.01);
+ if (this._gateOffAt == null) this._gateOffAt = now + 0.1;
+ if (this.src && now > this._gateOffAt) this._stopSrc();
+ this.applied = 0;
+ return;
+ }
+ this._gateOffAt = null;
+ const mag = Math.abs(rate);
+ const dir = rate < -0.003 ? -1 : rate > 0.003 ? 1 : this.dir;
+ if (!this.src || dir !== this.dir) this._startSrc(dir, now, mag);
+ this.src.playbackRate.setTargetAtTime(Math.max(mag, 0.0005), now, 0.008);
+ this.gate.gain.setTargetAtTime(mag < 0.02 ? 0 : Math.min(1, mag * 3), now, 0.01);
+ this.applied = dir * Math.max(this.src.playbackRate.value, 0);
+ }
+
+ _startSrc(dir, now, mag) {
+ const buf = dir > 0 ? this.fwd[this.track] : this.rev[this.track];
+ const D = buf.duration;
+ if (this.src) { const o = this.src, og = this.srcGain; og.gain.setTargetAtTime(0, now, 0.003); o.stop(now + 0.03); }
+ const s = this.ctx.createBufferSource(); s.buffer = buf; s.loop = true;
+ s.playbackRate.value = Math.max(mag, 0.0005);
+ const g = this.ctx.createGain(); g.gain.value = 0; g.gain.setTargetAtTime(1, now, 0.003);
+ s.connect(g).connect(this.gate);
+ const off = dir > 0 ? this.pos : D - this.pos;
+ s.start(now, Math.min(D - 0.001, Math.max(0, off)));
+ this.src = s; this.srcGain = g; this.dir = dir;
+ }
+
+ _stopSrc() {
+ if (!this.src || !this.ctx) { this.src = null; return; }
+ const now = this.ctx.currentTime;
+ this.srcGain.gain.setTargetAtTime(0, now, 0.004);
+ this.src.stop(now + 0.04);
+ this.src = null;
+ }
+
+ /** Stylus touching down: a soft thump and a burst of surface noise. */
+ needleDrop() {
+ if (!this.ctx) return;
+ const ctx = this.ctx, t = ctx.currentTime;
+ const o = ctx.createOscillator(), g = ctx.createGain();
+ o.frequency.setValueAtTime(90, t); o.frequency.exponentialRampToValueAtTime(38, t + 0.14);
+ g.gain.setValueAtTime(0.5, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.2);
+ o.connect(g).connect(this.sfx); o.start(t); o.stop(t + 0.22);
+ const s = ctx.createBufferSource(); s.buffer = this.noise;
+ const f = ctx.createBiquadFilter(); f.type = 'bandpass'; f.frequency.value = 1800; f.Q.value = 0.5;
+ const ng = ctx.createGain(); ng.gain.setValueAtTime(0.12, t); ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.5);
+ s.connect(f).connect(ng).connect(this.sfx); s.start(t, Math.random() * 0.5, 0.55);
+ }
+
+ needleLift() {
+ if (!this.ctx) return;
+ const ctx = this.ctx, t = ctx.currentTime;
+ const s = ctx.createBufferSource(); s.buffer = this.noise;
+ const f = ctx.createBiquadFilter(); f.type = 'highpass'; f.frequency.value = 2500;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0.08, t); g.gain.exponentialRampToValueAtTime(0.0001, t + 0.06);
+ s.connect(f).connect(g).connect(this.sfx); s.start(t, Math.random() * 0.5, 0.08);
+ }
+
+ /** Fill `out` (length N) with a log-spaced spectrum; updates this.levels. Returns false if silent. */
+ spectrum(out) {
+ if (!this.analyser) return false;
+ const a = this.analyser, fr = this.freq;
+ a.getByteFrequencyData(fr);
+ const binHz = this.ctx.sampleRate / a.fftSize, N = out.length;
+ let any = 0;
+ for (let i = 0; i < N; i++) {
+ const f = 38 * Math.pow(11000 / 38, i / (N - 1));
+ const b = f / binHz, i0 = Math.floor(b), t = b - i0;
+ const v = ((fr[i0] ?? 0) * (1 - t) + (fr[i0 + 1] ?? 0) * t) / 255;
+ out[i] = Math.min(1, v * (0.85 + i / N * 0.45));
+ any += v;
+ }
+ const band = (f0, f1) => { let s = 0, c = 0; for (let i = Math.floor(f0 / binHz); i <= Math.ceil(f1 / binHz); i++) { s += fr[i]; c++; } return s / (c * 255); };
+ a.getFloatTimeDomainData(this.wave);
+ let rms = 0; for (let i = 0; i < this.wave.length; i++) rms += this.wave[i] * this.wave[i];
+ const L = this.levels;
+ L.bass = band(40, 120); L.mid = band(300, 2000); L.high = band(4500, 11000); L.rms = Math.sqrt(rms / this.wave.length);
+ return any / N > 0.02;
+ }
+}
diff --git a/examples/lowfreq/deck.js b/examples/lowfreq/deck.js
new file mode 100644
index 0000000..9ff20f7
--- /dev/null
+++ b/examples/lowfreq/deck.js
@@ -0,0 +1,365 @@
+// The deck: Meshy turntable with its tonearm cut free (so it can cue), a procedural vinyl record with
+// anisotropic grooves cut from the actual audio, a printed label, and a spectrum halo around the platter.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture } from '../../src/core/textures.js';
+
+// Measured in the turntable mesh's local (quantised) space.
+export const L = {
+ cx: -0.205, cz: 0, R: 0.703, top: 0.1755, bottom: 0.1585, label: 0.232, hole: 0.0165,
+ pivot: new THREE.Vector3(0.655, 0.285, -0.458),
+ stylus: new THREE.Vector2(0.214, 0.287),
+ armDir: new THREE.Vector2(-0.5143, 0.8576),
+ plinthTop: 0.022,
+};
+// Groove bands (radius in local units, outer → inner), proportional to the track lengths.
+const SECS = [252, 303, 228, 380];
+const G_OUT = 0.688, G_IN = 0.292, GAP = 0.0075;
+export const BANDS = (() => {
+ const span = G_OUT - G_IN - GAP * (SECS.length - 1), tot = SECS.reduce((a, b) => a + b, 0);
+ let r = G_OUT;
+ return SECS.map(s => { const w = span * s / tot; const b = { outer: r, inner: r - w }; r -= w + GAP; return b; });
+})();
+
+// ─── Tonearm split ─────────────────────────────────────────────────────────────
+function splitArm(mesh) {
+ const g = mesh.geometry, pos = g.attributes.position, idx = g.index.array;
+ const P = L.pivot, d = L.armDir;
+ // per vertex: inside the arm's corridor (xz) and above the plinth; "up" = above that zone's cut height
+ const corr = new Uint8Array(pos.count), up = new Uint8Array(pos.count);
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), y = pos.getY(i), z = pos.getZ(i);
+ const rx = x - P.x, rz = z - P.z;
+ const s = rx * d.x + rz * d.y; // along the arm, + toward the headshell
+ const q = Math.abs(rx * d.y - rz * d.x); // off-axis distance
+ let c = false, cut = 1;
+ if (s > 0.7) { c = q < 0.13 && s < 1.03 && y > 0.14; cut = 0.1762; } // headshell + cartridge
+ else if (s > 0.1) { c = q < 0.045 && y > 0.19; cut = 0.2; } // arm tube
+ else if (s > -0.13) { c = q < 0.105 && y > 0.2; cut = 0.222; } // bearing housing (tower stays)
+ else { c = s > -0.42 && q < 0.11 && y > 0.19; cut = 0.205; } // counterweight stub
+ corr[i] = c ? 1 : 0; up[i] = y > cut ? 1 : 0;
+ }
+ const a = [], b = [];
+ for (let t = 0; t < idx.length; t += 3) {
+ const i0 = idx[t], i1 = idx[t + 1], i2 = idx[t + 2];
+ const inArm = corr[i0] && corr[i1] && corr[i2] && (up[i0] || up[i1] || up[i2]);
+ (inArm ? a : b).push(i0, i1, i2);
+ }
+ const make = list => {
+ const ng = new THREE.BufferGeometry();
+ for (const k in g.attributes) ng.setAttribute(k, g.attributes[k]);
+ ng.setIndex(list);
+ ng.computeBoundingBox(); ng.computeBoundingSphere();
+ return ng;
+ };
+ return { base: make(b), arm: make(a), armTris: a.length / 3 };
+}
+
+// ─── Textures ─────────────────────────────────────────────────────────────────
+export function labelTexture(renderer, { title = 'AUBERGINE HOURS', artist = 'KAZU NOMURA & THE LATE ROOM', cat = 'LF-011', side = 'A', tracks = [] } = {}) {
+ const S = 1024, c = document.createElement('canvas'); c.width = c.height = S;
+ const g = c.getContext('2d');
+ const cx = S / 2, r = S / 2;
+ // paper: lavender with a faint print grain
+ const grd = g.createRadialGradient(cx, cx, 0, cx, cx, r);
+ grd.addColorStop(0, '#9d93ff'); grd.addColorStop(1, '#8676f0');
+ g.fillStyle = grd; g.beginPath(); g.arc(cx, cx, r, 0, Math.PI * 2); g.fill();
+ const img = g.getImageData(0, 0, S, S), px = img.data;
+ for (let i = 0; i < px.length; i += 4) { const n = (Math.random() - 0.5) * 14; px[i] += n; px[i + 1] += n; px[i + 2] += n; }
+ g.putImageData(img, 0, 0);
+ const ink = '#1a1030', cream = '#f6efe2';
+ g.strokeStyle = ink; g.lineWidth = 3;
+ g.beginPath(); g.arc(cx, cx, r - 30, 0, Math.PI * 2); g.stroke();
+ g.lineWidth = 1.5; g.beginPath(); g.arc(cx, cx, r - 42, 0, Math.PI * 2); g.stroke();
+ // circular rim text
+ const rim = `LOW FREQUENCY RECORDS · 低周波 · SHIMOKITAZAWA · TOKYO · ${cat} · ALL RIGHTS OF THE PRODUCER AND OF THE OWNER OF THE RECORDED WORK RESERVED · `;
+ g.fillStyle = ink; g.font = '600 19px "Space Mono", monospace'; g.textAlign = 'center'; g.textBaseline = 'middle';
+ const chars = [...rim]; const step = (Math.PI * 2) / chars.length;
+ chars.forEach((ch, i) => { g.save(); g.translate(cx, cx); g.rotate(i * step); g.translate(0, -(r - 62)); g.fillText(ch, 0, 0); g.restore(); });
+ // logo block
+ g.fillStyle = ink;
+ g.font = '800 88px "Syne", sans-serif'; g.fillText('LOW', cx, cx - 250);
+ g.font = '800 58px "Syne", sans-serif'; g.fillText('FREQUENCY', cx, cx - 180);
+ // wave mark
+ g.strokeStyle = ink; g.lineWidth = 5; g.beginPath();
+ for (let x = -150; x <= 150; x += 3) { const y = Math.sin(x / 150 * Math.PI * 2.5) * 16 * Math.cos(x / 150 * Math.PI / 2); x === -150 ? g.moveTo(cx + x, cx - 118 + y) : g.lineTo(cx + x, cx - 118 + y); }
+ g.stroke();
+ // side / speed around the hole
+ g.font = '700 54px "Syne", sans-serif'; g.fillText(side, cx - 190, cx + 4);
+ g.font = '600 20px "Space Mono", monospace'; g.fillText('SIDE', cx - 190, cx - 46);
+ g.font = '700 44px "Syne", sans-serif'; g.fillText('33⅓', cx + 190, cx + 4);
+ g.font = '600 20px "Space Mono", monospace'; g.fillText('RPM', cx + 190, cx - 46); g.fillText(cat, cx + 190, cx + 52); g.fillText('STEREO', cx - 190, cx + 52);
+ // centre ring
+ g.lineWidth = 2; g.beginPath(); g.arc(cx, cx, 92, 0, Math.PI * 2); g.stroke();
+ // title + tracks
+ g.fillStyle = cream; g.font = '800 44px "Syne", sans-serif'; g.fillText(title, cx, cx + 150);
+ g.fillStyle = ink; g.font = '700 19px "Space Mono", monospace'; g.fillText(artist, cx, cx + 196);
+ g.font = '400 17px "Space Mono", monospace';
+ tracks.forEach((t, i) => g.fillText(`${t.id} ${t.title.toUpperCase()} ${t.time}`, cx, cx + 240 + i * 25));
+ // spindle hole
+ g.globalCompositeOperation = 'destination-out'; g.beginPath(); g.arc(cx, cx, S / 2 * (L.hole / L.label) * 1.05, 0, Math.PI * 2); g.fill();
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return t;
+}
+
+/** Dust specks (R) and hairline scratches + dead-wax etching (G), planar over the record. */
+function dustTexture(renderer) {
+ const S = 2048, c = document.createElement('canvas'); c.width = c.height = S;
+ const g = c.getContext('2d');
+ g.fillStyle = '#000'; g.fillRect(0, 0, S, S);
+ g.globalCompositeOperation = 'lighter';
+ const cx = S / 2, k = S / 2 / L.R;
+ for (let i = 0; i < 700; i++) {
+ const a = Math.random() * Math.PI * 2, rr = (0.25 + Math.random() * 0.45) * k;
+ const s = Math.random() < 0.9 ? 0.8 + Math.random() * 1.2 : 2 + Math.random() * 2.5;
+ g.fillStyle = `rgba(255,0,0,${0.35 + Math.random() * 0.65})`;
+ g.beginPath(); g.arc(cx + Math.cos(a) * rr, cx + Math.sin(a) * rr, s, 0, Math.PI * 2); g.fill();
+ }
+ for (let i = 0; i < 70; i++) {
+ const a = Math.random() * Math.PI * 2, rr = (0.27 + Math.random() * 0.42) * k, len = 0.05 + Math.random() * 0.5;
+ g.strokeStyle = `rgba(0,255,0,${0.15 + Math.random() * 0.4})`; g.lineWidth = 0.6 + Math.random() * 1.2;
+ g.beginPath();
+ if (Math.random() < 0.75) g.arc(cx, cx, rr, a, a + len); // tangential scuffs follow the grooves
+ else { const l = 20 + Math.random() * 120; g.moveTo(cx + Math.cos(a) * rr, cx + Math.sin(a) * rr); g.lineTo(cx + Math.cos(a) * (rr + l), cx + Math.sin(a) * (rr + l) + (Math.random() - 0.5) * 30); }
+ g.stroke();
+ }
+ // matrix etching in the dead wax
+ g.fillStyle = 'rgba(0,255,0,0.7)'; g.font = '500 17px "Space Mono", monospace'; g.textAlign = 'center';
+ const etch = [...'LF-011-A1 · CUT AT THE COUNTER · ☾'];
+ const re = 0.268 * k;
+ etch.forEach((ch, i) => { g.save(); g.translate(cx, cx); g.rotate(1.2 + i * 0.034); g.translate(0, -re); g.fillText(ch, 0, 0); g.restore(); });
+ const t = new THREE.CanvasTexture(c);
+ t.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return t;
+}
+
+/** Radial groove map: R = loudness, G = fine ring noise, B = grooved (1) vs smooth land (0). */
+export function grooveTexture() {
+ const W = 2048;
+ const data = new Uint8Array(W * 4);
+ const tex = new THREE.DataTexture(data, W, 1, THREE.RGBAFormat);
+ tex.magFilter = THREE.LinearFilter; tex.minFilter = THREE.LinearMipmapLinearFilter; tex.generateMipmaps = true;
+ tex.wrapS = tex.wrapT = THREE.ClampToEdgeWrapping;
+ tex.userData.fill = (envs) => {
+ for (let i = 0; i < W; i++) {
+ const r = (i + 0.5) / W * L.R;
+ let amp = 0, grooved = 0;
+ const hash = (Math.sin(i * 12.9898) * 43758.5453) % 1;
+ const fine = Math.abs(hash);
+ if (r > G_OUT && r < L.R - 0.007) { grooved = 1; amp = 0.08; } // lead-in
+ else if (r < 0.285 && r > 0.252) { grooved = 0.55; amp = 0.03; } // lead-out
+ else {
+ BANDS.forEach((b, k) => {
+ if (r <= b.outer && r >= b.inner) {
+ grooved = 1;
+ const p = (b.outer - r) / (b.outer - b.inner);
+ const env = envs?.[k];
+ const loops = SECS[k] / 16;
+ if (env) { const e = (p * loops) % 1; amp = env[Math.floor(e * env.length)]; }
+ else amp = 0.5 + 0.35 * Math.sin(p * loops * Math.PI * 2 + k) * Math.sin(p * 31.0 + k * 2);
+ // soft fade in/out at band edges (the cutter ramps)
+ amp *= Math.min(1, p * 30, (1 - p) * 30);
+ }
+ });
+ }
+ data[i * 4] = Math.round(Math.min(1, amp) * 255);
+ data[i * 4 + 1] = Math.round(fine * 255);
+ data[i * 4 + 2] = Math.round(grooved * 255);
+ data[i * 4 + 3] = 255;
+ }
+ tex.needsUpdate = true;
+ };
+ tex.userData.fill(null);
+ return tex;
+}
+
+// ─── Vinyl material ───────────────────────────────────────────────────────────
+function vinylMaterial(grooves, dust) {
+ const m = new THREE.MeshPhysicalMaterial({
+ color: 0x070608, roughness: 0.25, metalness: 0, anisotropy: 0.8, clearcoat: 0.0, envMapIntensity: 1.2,
+ specularIntensity: 1, ior: 1.52,
+ });
+ m.userData.u = { uGroove: { value: grooves }, uDust: { value: dust }, uRecR: { value: L.R }, uAniso: { value: 0.88 }, uWarp: { value: 0 } };
+ m.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, m.userData.u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vRecP; varying vec3 vRadV; uniform float uWarp;')
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ vRecP = position;
+ vec3 radO = normalize(vec3(position.x, 0.0, position.z) + vec3(1e-5, 0.0, 0.0));
+ vRadV = normalize((modelViewMatrix * vec4(radO, 0.0)).xyz);`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vRecP; varying vec3 vRadV;
+ uniform sampler2D uGroove, uDust; uniform float uRecR, uAniso;
+ float lfGroove, lfAmp, lfScr;`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ {
+ float rr = length(vRecP.xz) / uRecR;
+ vec4 gv = texture2D(uGroove, vec2(rr, 0.5));
+ vec4 ds = texture2D(uDust, vRecP.xz / (2.0 * uRecR) + 0.5);
+ lfGroove = gv.b; lfAmp = gv.r; lfScr = ds.g;
+ roughnessFactor = mix(0.07, 0.17 + lfAmp * 0.22 + gv.g * 0.07, lfGroove);
+ roughnessFactor = mix(roughnessFactor, 0.55, lfScr * 0.8);
+ diffuseColor.rgb += ds.r * vec3(0.16, 0.15, 0.14);
+ diffuseColor.rgb *= 0.85 + gv.g * 0.3 * lfGroove;
+ }`)
+ .replace('#include <lights_physical_fragment>', `#include <lights_physical_fragment>
+ #ifdef USE_ANISOTROPY
+ {
+ vec3 radV = normalize(vRadV - normal * dot(vRadV, normal));
+ material.anisotropy = clamp(uAniso * lfGroove * (0.75 + lfAmp * 0.25) * (1.0 - lfScr), 0.0, 0.97);
+ material.alphaT = mix(pow2(material.roughness), 1.0, pow2(material.anisotropy));
+ material.anisotropyT = radV;
+ material.anisotropyB = normalize(cross(normal, radV));
+ }
+ #endif`);
+ };
+ m.customProgramCacheKey = () => 'lf-vinyl';
+ return m;
+}
+
+// ─── Spectrum halo ────────────────────────────────────────────────────────────
+export function spectrumRing(N = 144) {
+ const amp = new Float32Array(N);
+ const tex = new THREE.DataTexture(amp, N, 1, THREE.RedFormat, THREE.FloatType);
+ tex.magFilter = tex.minFilter = THREE.LinearFilter; tex.needsUpdate = true;
+ const base = new THREE.PlaneGeometry(1, 1).rotateX(-Math.PI / 2).translate(0.5, 0, 0);
+ const geo = new THREE.InstancedBufferGeometry().copy(base);
+ geo.instanceCount = N;
+ const ids = new Float32Array(N); for (let i = 0; i < N; i++) ids[i] = i;
+ geo.setAttribute('aId', new THREE.InstancedBufferAttribute(ids, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false,
+ uniforms: {
+ uAmp: { value: tex }, uN: { value: N }, uR0: { value: 0.742 }, uLen: { value: 0.34 }, uW: { value: 0.015 },
+ uA: { value: new THREE.Color(0xa78bfa) }, uB: { value: new THREE.Color(0xffb45c) }, uI: { value: 1 },
+ uMaskA: { value: 0.47 }, uTime: { value: 0 },
+ },
+ vertexShader: /* glsl */`
+ attribute float aId; uniform sampler2D uAmp; uniform float uN, uR0, uLen, uW, uMaskA;
+ varying float vU, vAmp, vV;
+ void main(){
+ float a = aId / uN * 6.28318530718;
+ float amp = texture2D(uAmp, vec2((aId + 0.5) / uN, 0.5)).r;
+ float d = abs(atan(sin(a - uMaskA), cos(a - uMaskA)));
+ amp *= smoothstep(0.2, 0.42, d);
+ float len = 0.012 + amp * uLen;
+ vec3 p = vec3(uR0 + position.x * len, 0.0, position.z * uW * (0.6 + amp));
+ float c = cos(a), s = sin(a);
+ p = vec3(p.x * c + p.z * s, 0.0, -p.x * s + p.z * c);
+ vU = position.x; vAmp = amp; vV = position.z;
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uA, uB; uniform float uI; varying float vU, vAmp, vV;
+ void main(){
+ float edge = 1.0 - smoothstep(0.1, 0.5, abs(vV));
+ vec3 col = mix(uA, uB, smoothstep(0.25, 1.0, vU * (0.4 + vAmp)));
+ float a = edge * (0.5 + vAmp * 2.6) * (1.0 - vU * 0.5) * uI;
+ gl_FragColor = vec4(col * a, 1.0);
+ }`,
+ });
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.frustumCulled = false;
+ mesh.renderOrder = 5;
+ // a hairline base circle
+ const circ = new THREE.Mesh(new THREE.RingGeometry(0.736, 0.7395, 256, 1).rotateX(-Math.PI / 2),
+ new THREE.MeshBasicMaterial({ color: new THREE.Color(0xa78bfa).multiplyScalar(1.4), transparent: true, opacity: 0.55, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false }));
+ mesh.add(circ);
+ return { mesh, amp, tex, mat, circ, N };
+}
+
+// ─── Assemble ─────────────────────────────────────────────────────────────────
+export function buildDeck(renderer, root, { tracks }) {
+ let mesh = null;
+ root.traverse(o => { if (!mesh && o.isMesh) mesh = o; });
+ const { base, arm } = splitArm(mesh);
+ mesh.geometry = base;
+ const armMesh = new THREE.Mesh(arm, mesh.material);
+ armMesh.castShadow = armMesh.receiveShadow = true;
+ const yaw = new THREE.Group(), lift = new THREE.Group();
+ yaw.position.copy(L.pivot);
+ armMesh.position.copy(L.pivot).negate();
+ yaw.add(lift); lift.add(armMesh);
+ mesh.add(yaw);
+ const liftAxis = new THREE.Vector3(L.armDir.y, 0, -L.armDir.x).normalize(); // (0.865, 0, 0.502)
+
+ // Record
+ const grooves = grooveTexture();
+ const dust = dustTexture(renderer);
+ const record = new THREE.Group();
+ record.position.set(L.cx, 0, L.cz);
+ mesh.add(record);
+ const vinyl = vinylMaterial(grooves, dust);
+ const top = new THREE.Mesh(new THREE.RingGeometry(L.label - 0.004, 0.6925, 256, 24).rotateX(-Math.PI / 2).translate(0, L.top, 0), vinyl);
+ top.receiveShadow = true; top.castShadow = true;
+ record.add(top);
+ // raised edge bead + rim + underside, as a lathe (normals are fine here, it's all curves)
+ const T = L.top, B = L.bottom;
+ const prof = [[0.6925, T], [0.6965, T + 0.0021], [0.7008, T + 0.0014], [0.7032, T - 0.002], [0.7034, B + 0.003], [0.701, B + 0.0002], [0.62, B]].map(([x, y]) => new THREE.Vector2(x, y));
+ const edgeMat = new THREE.MeshPhysicalMaterial({ color: 0x08070a, roughness: 0.2, metalness: 0, envMapIntensity: 1.2, side: THREE.DoubleSide });
+ const edge = new THREE.Mesh(new THREE.LatheGeometry(prof, 256), edgeMat);
+ edge.castShadow = true; edge.receiveShadow = true;
+ record.add(edge);
+ const labelTex = labelTexture(renderer, { tracks });
+ const labelMat = new THREE.MeshStandardMaterial({ map: labelTex, roughness: 0.62, metalness: 0, envMapIntensity: 0.5, transparent: false, alphaTest: 0.5 });
+ const labelGeo = new THREE.CircleGeometry(L.label, 128).rotateX(-Math.PI / 2).translate(0, T + 0.0016, 0);
+ const label = new THREE.Mesh(labelGeo, labelMat);
+ label.receiveShadow = true;
+ record.add(label);
+ // label step (the thicker pressing around the label)
+ const step = new THREE.Mesh(new THREE.CylinderGeometry(L.label + 0.004, L.label + 0.006, 0.0016, 128, 1, true).translate(0, T + 0.0008, 0), edgeMat);
+ record.add(step);
+
+ // Brushed aluminium platter skirt over the model's grungy one.
+ const skirtRough = bakeTexture(renderer, 512, `void main(){ float l = fbm(vec2(vUv.y * 180.0, vUv.x * 2.0), 180.0, 4, 0.55); float r = 0.22 + l * 0.1 + fbm(vUv * vec2(3.0, 60.0), 60.0, 3, 0.5) * 0.06; gl_FragColor = vec4(1.0, clamp(r, 0.08, 1.0), 0.0, 1.0); }`);
+ const skirtMat = new THREE.MeshPhysicalMaterial({ color: 0x8a898f, metalness: 1, roughness: 0.42, roughnessMap: skirtRough, envMapIntensity: 0.7 });
+ const skirt = new THREE.Mesh(new THREE.CylinderGeometry(0.7165, 0.7165, B - L.plinthTop - 0.001, 256, 1, true).translate(0, (B + L.plinthTop) / 2, 0), skirtMat);
+ skirt.castShadow = true; skirt.receiveShadow = true;
+ skirt.position.set(L.cx, 0, L.cz);
+ mesh.add(skirt);
+ const skirtLip = new THREE.Mesh(new THREE.RingGeometry(0.703, 0.7166, 256, 1).rotateX(-Math.PI / 2).translate(0, B - 0.0004, 0), skirtMat);
+ skirtLip.position.copy(skirt.position);
+ mesh.add(skirtLip);
+
+ // Spectrum halo (stationary, around the platter, just above the record plane)
+ const ring = spectrumRing();
+ ring.mesh.position.set(L.cx, T + 0.02, L.cz);
+ mesh.add(ring.mesh);
+
+ // ─ helpers
+ const stylusAt = (yawA, out = new THREE.Vector2()) => {
+ const vx = L.stylus.x - L.pivot.x, vz = L.stylus.y - L.pivot.z;
+ const c = Math.cos(yawA), s = Math.sin(yawA);
+ return out.set(L.pivot.x + vx * c + vz * s, L.pivot.z - vx * s + vz * c);
+ };
+ const radiusAt = y => { const p = stylusAt(y); return Math.hypot(p.x - L.cx, p.y - L.cz); };
+ function yawFor(r) {
+ // the arm sweeps monotonically near yaw 0; pick the root closest to 0
+ let best = 0, bestErr = 1e9;
+ for (let y = -0.9; y <= 0.9; y += 0.0015) { const e = Math.abs(radiusAt(y) - r); if (e < bestErr - 1e-9 || (Math.abs(e - bestErr) < 1e-6 && Math.abs(y) < Math.abs(best))) { bestErr = e; best = y; } }
+ return best;
+ }
+ const restYaw = (() => { // off the record, toward the front-right
+ let best = 0; for (let y = -0.9; y <= 0.9; y += 0.002) { const p = stylusAt(y); if (radiusAt(y) > 0.845 && p.x > L.cx && Math.abs(y) < Math.abs(best || 9)) best = y; }
+ return best;
+ })();
+ const bandYaw = BANDS.map(b => yawFor(b.outer - 0.006));
+
+ function setArm(yawA, liftA) {
+ yaw.rotation.y = yawA;
+ lift.quaternion.setFromAxisAngle(liftAxis, -liftA);
+ }
+ setArm(restYaw, 0.02);
+
+ const _v = new THREE.Vector3();
+ return {
+ mesh, record, vinyl, label, labelMat, grooves, ring, arm: { yaw, lift, mesh: armMesh }, setArm, restYaw, bandYaw, yawFor, radiusAt,
+ /** world-space centre of the record's top surface */
+ center: (out = new THREE.Vector3()) => mesh.localToWorld(out.set(L.cx, T, L.cz)),
+ toWorld: (x, y, z, out = new THREE.Vector3()) => mesh.localToWorld(out.set(x, y, z)),
+ stylusWorld: (out = new THREE.Vector3()) => { armMesh.updateWorldMatrix(true, false); return armMesh.localToWorld(out.set(L.stylus.x, 0.18, L.stylus.y)); },
+ radiusWorld: () => mesh.localToWorld(_v.set(L.cx + L.R, T, L.cz)).distanceTo(mesh.localToWorld(new THREE.Vector3(L.cx, T, L.cz))),
+ };
+}
diff --git a/examples/lowfreq/index.html b/examples/lowfreq/index.html
new file mode 100644
index 0000000..3242850
--- /dev/null
+++ b/examples/lowfreq/index.html
@@ -0,0 +1,216 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Low Frequency — Listening bar &amp; record label, Tokyo</title>
+ <meta name="description" content="A twelve-seat listening bar and record label in Shimokitazawa. Put your hand on the record.">
+ <meta name="theme-color" content="#0a0610">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 32 32%22%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%2215%22 fill=%22%230d0a10%22/%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%225.5%22 fill=%22%23a78bfa%22/%3E%3Ccircle cx=%2216%22 cy=%2216%22 r=%221%22 fill=%22%230d0a10%22/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=Space+Mono:ital,wght@0,400;0,700;1,400&display=swap" rel="stylesheet">
+ <link href="https://fonts.googleapis.com/css2?family=M+PLUS+Rounded+1c:wght@400&family=Zen+Kaku+Gothic+New:wght@500&text=%E4%BD%8E%E5%91%A8%E6%B3%A2%E3%83%AC%E3%82%B3%E3%83%BC%E3%83%89%E3%81%AB%E6%89%8B%E3%82%92%E7%BD%AE%E3%81%84%E3%81%A6%E5%B8%AD%E4%B8%8B%E5%8C%97%E6%B2%A2&display=block" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="grain" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-disc" aria-hidden="true">
+ <svg viewBox="0 0 200 200">
+ <circle class="ld-body" cx="100" cy="100" r="96"/>
+ <g class="ld-grooves"></g>
+ <circle class="ld-label" cx="100" cy="100" r="31"/>
+ <circle class="ld-hole" cx="100" cy="100" r="2.4"/>
+ </svg>
+ <span class="loader-pct">000</span>
+ </div>
+ <p class="loader-line mono">Warming the valves</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Low Frequency home">
+ <svg viewBox="0 0 32 32" aria-hidden="true"><circle cx="16" cy="16" r="14.5" fill="none" stroke="currentColor" stroke-width="1.3"/><circle cx="16" cy="16" r="4.5" fill="currentColor"/><path d="M4.5 16c2.2-4 3.6-4 5.8 0s3.6 4 5.7 0 3.6-4 5.8 0 3.5 4 5.7 0" fill="none" stroke="currentColor" stroke-width="1.3" opacity=".0"/></svg>
+ <span>Low&nbsp;Frequency</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#pressing">Pressing</a>
+ <a href="#bar">The bar</a>
+ <a href="#catalogue">Catalogue</a>
+ <a href="#club">Record club</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" data-cursor="link">
+ <span class="eq" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
+ <span class="sound-label mono">Sound off</span>
+ </button>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Reserve a seat</a>
+ </div>
+ </header>
+
+ <main id="top">
+ <!-- 01 · Hero -->
+ <section class="sec hero" id="hero" data-cam="hero">
+ <div class="hero-copy">
+ <p class="eyebrow mono"><span class="dot"></span> Listening bar &amp; record label · Shimokitazawa, Tokyo</p>
+ <h1 class="title"><span class="line">Put your hand</span><span class="line">on the record<em>.</em></span></h1>
+ <p class="sub">Twelve seats, one turntable and four thousand eight hundred records. We press what we play — and we play it loud enough to feel it through the counter.</p>
+ <div class="hero-cta">
+ <button class="btn btn-solid play-main" type="button" data-magnetic>
+ <span class="pi" aria-hidden="true"></span><span class="pl">Drop the needle</span>
+ </button>
+ <a class="btn btn-ghost" href="#pressing" data-magnetic>This week’s pressing</a>
+ </div>
+ </div>
+ <p class="vert jp" aria-hidden="true">レコードに手を置いて</p>
+ <div class="hero-meta mono" aria-hidden="true">
+ <span>LF-011 · Side A</span><span class="rpm-read">33⅓ rpm</span><span class="bpm-read">— bpm</span>
+ </div>
+ </section>
+
+ <!-- 02 · This week's pressing -->
+ <section class="sec pressing" id="pressing" data-cam="press">
+ <div class="col col-right">
+ <p class="eyebrow mono">02 — This week’s pressing · LF-011</p>
+ <h2>Aubergine <em>Hours</em></h2>
+ <p class="byline mono">Kazu Nomura &amp; The Late Room · 180 g black vinyl · 300 copies</p>
+ <p class="lede">Recorded in a single night at the bar after close, with the room mics still up. Nomura plays the house Rhodes; the rhythm section plays the counter. Pick a band — the arm will find it.</p>
+ <ol class="tracks">
+ <li data-track="0"><button type="button" class="cue" data-cursor="link" aria-label="Cue A1"><span class="ci" aria-hidden="true"></span></button><span class="tn mono">A1</span><span class="tt">Last Train, Shimokita</span><span class="tb mono">122 bpm</span><span class="td mono">4:12</span></li>
+ <li data-track="1"><button type="button" class="cue" data-cursor="link" aria-label="Cue A2"><span class="ci" aria-hidden="true"></span></button><span class="tn mono">A2</span><span class="tt">Aubergine Hours</span><span class="tb mono">84 bpm</span><span class="td mono">5:03</span></li>
+ <li data-track="2"><button type="button" class="cue" data-cursor="link" aria-label="Cue A3"><span class="ci" aria-hidden="true"></span></button><span class="tn mono">A3</span><span class="tt">Seat Seven</span><span class="tb mono">118 bpm</span><span class="td mono">3:48</span></li>
+ <li data-track="3"><button type="button" class="cue" data-cursor="link" aria-label="Cue A4"><span class="ci" aria-hidden="true"></span></button><span class="tn mono">A4</span><span class="tt">Needle Rain</span><span class="tb mono">96 bpm</span><span class="td mono">6:20</span></li>
+ </ol>
+ <p class="fine mono">Each cue is sixteen bars, synthesised in your browser the moment you press it. Nothing is streamed; nothing is sampled.</p>
+ <div class="buy">
+ <span class="price">¥4,400</span>
+ <a class="btn btn-solid" href="#club" data-magnetic>Pre-order the LP</a>
+ <span class="mono stock"><i></i> 41 of 300 left</span>
+ </div>
+ </div>
+ </section>
+
+ <!-- 03 · The bar -->
+ <section class="sec bar" id="bar" data-cam="bar">
+ <div class="col col-left">
+ <p class="eyebrow mono">03 — The bar · B1, 2-chōme</p>
+ <h2>Twelve seats. <em>One rule</em> you’ll actually keep.</h2>
+ <p class="lede">We are a listening bar in the old kissa tradition: the records are the menu, the speakers are the view, and conversation happens between sides. Sit down, order something brown, and let a whole album go by.</p>
+ </div>
+ <div class="bar-grid">
+ <article class="rule">
+ <p class="mono k">House rule</p>
+ <p class="big">No phones on the counter.</p>
+ <p class="small">Put it in the drawer under your seat. You will get it back at the end of the side.</p>
+ </article>
+ <article>
+ <p class="mono k">Hours</p>
+ <p class="mid">Wed — Sun<br>19:00 — 02:00</p>
+ <p class="small">Last side goes on at 01:30. Closed Mondays, Tuesdays and whenever the owner is digging in Osaka.</p>
+ </article>
+ <article>
+ <p class="mono k">Seats</p>
+ <p class="mid">12 at the counter</p>
+ <p class="small">No standing, no tables, no groups over four. Six seats are held for walk-ins every night.</p>
+ </article>
+ <article>
+ <p class="mono k">Requests</p>
+ <p class="mid">On paper, not out loud</p>
+ <p class="small">Write it on the card by your glass. Both sides, always. We never skip a track.</p>
+ </article>
+ </div>
+ <div class="stats">
+ <div><b>12</b><span class="mono">seats</span></div>
+ <div><b>4,800</b><span class="mono">records on the wall</span></div>
+ <div><b>1</b><span class="mono">turntable</span></div>
+ <div><b>0</b><span class="mono">playlists</span></div>
+ </div>
+ </section>
+
+ <!-- 04 · Catalogue -->
+ <section class="sec catalogue" id="catalogue" data-cam="cat">
+ <div class="cat-head">
+ <p class="eyebrow mono">04 — Low Frequency Records · Catalogue</p>
+ <h2>Pressed for <em>the room</em> first.</h2>
+ <p class="lede">Every release on the label is played here before it is cut. If it can’t hold twelve strangers quiet for a whole side, it doesn’t get a number.</p>
+ </div>
+ <div class="sleeves">
+ <article class="sleeve" data-img="aubergine"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-011 · 2026</p><h3>Aubergine Hours</h3><p class="sl-by">Kazu Nomura &amp; The Late Room</p><p class="mono sl-st on">Pre-order</p></article>
+ <article class="sleeve" data-img="tidal"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-010 · 2025</p><h3>Tidal Room</h3><p class="sl-by">Hiromi Sato</p><p class="mono sl-st">In stock</p></article>
+ <article class="sleeve" data-img="counter"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-009 · 2025</p><h3>Counter Culture</h3><p class="sl-by">Night Crate Ensemble</p><p class="mono sl-st">Repress · May</p></article>
+ <article class="sleeve" data-img="rain"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-008 · 2024</p><h3>Shimokita Rain</h3><p class="sl-by">Yuki Mori</p><p class="mono sl-st off">Sold out</p></article>
+ <article class="sleeve" data-img="valves"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-007 · 2024</p><h3>Warm Valves</h3><p class="sl-by">The Low Hours</p><p class="mono sl-st">In stock</p></article>
+ <article class="sleeve" data-img="geometry"><div class="sl-art"><div class="sl-disc"></div><div class="sl-cover"></div></div><p class="mono sl-cat">LF-006 · 2023</p><h3>Offbeat Geometry</h3><p class="sl-by">Mika Arai Quartet</p><p class="mono sl-st off">Sold out</p></article>
+ </div>
+ </section>
+
+ <!-- 05 · Record club -->
+ <section class="sec club" id="club" data-cam="club">
+ <div class="col col-left">
+ <p class="eyebrow mono">05 — Record club</p>
+ <h2>A seat that’s saved. A record that <em>arrives.</em></h2>
+ <p class="lede">Members hear every pressing before it reaches the wall, and keep a standing claim on the counter. Cancel whenever — the records are yours to keep.</p>
+ </div>
+ <div class="tiers">
+ <article class="tier">
+ <header><p class="mono k">Sleeve</p><p class="price">¥2,800<span class="mono">/ month</span></p></header>
+ <ul><li>Every LF pressing, mailed flat</li><li>Liner notes written at the counter</li><li>10% off anything on the wall</li></ul>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Join Sleeve</a>
+ </article>
+ <article class="tier tier-lit">
+ <header><p class="mono k">Counter <span class="tag">Most kept</span></p><p class="price">¥6,400<span class="mono">/ month</span></p></header>
+ <ul><li>Everything in Sleeve</li><li>One reserved seat a month, any night</li><li>First pick of the test pressings</li><li>Your request played before 21:00</li></ul>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Join Counter</a>
+ </article>
+ <article class="tier">
+ <header><p class="mono k">Crate</p><p class="price">¥48,000<span class="mono">/ year</span></p></header>
+ <ul><li>Everything in Counter</li><li>A private listening hour for you and three friends</li><li>Your name on a spine on the wall</li></ul>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Speak to us</a>
+ </article>
+ </div>
+ </section>
+
+ <!-- 06 · Visit / footer -->
+ <footer class="sec visit" id="visit" data-cam="end">
+ <div class="visit-inner">
+ <p class="eyebrow mono">06 — Tonight</p>
+ <h2 class="foot-title">Doors at seven.<br><em>Needle</em> at five past.</h2>
+ <div class="foot-cta">
+ <a class="btn btn-solid" href="#top" data-magnetic>Reserve a seat</a>
+ <a class="btn btn-ghost" href="#club" data-magnetic>Join the record club</a>
+ </div>
+ <div class="foot-cols">
+ <p class="mono">Low Frequency<br>B1, 2-14-7 Kitazawa<br>Setagaya-ku, Tokyo</p>
+ <p class="mono">Wed — Sun · 19:00 — 02:00<br>Walk-ins from 19:00<br>Reservations up to four</p>
+ <p class="mono"><a href="#top">Instagram</a><br><a href="#top">Bandcamp</a><br><a href="#top">Newsletter</a></p>
+ <p class="mono colophon">Every sound on this page is synthesised live with the Web Audio API — no samples, no streams. © Low Frequency Records K.K.</p>
+ </div>
+ </div>
+ </footer>
+ </main>
+
+ <!-- Projected over the 3D record -->
+ <div class="fx">
+ <div class="scratch" data-cursor="drag" data-cursor-label="Scratch" aria-label="Drag the record to scratch" role="slider" aria-valuetext="record"></div>
+ <div class="hint" aria-hidden="true">
+ <svg viewBox="0 0 200 200">
+ <defs><path id="hintPath" d="M100,100 m-92,0 a92,92 0 1,1 184,0 a92,92 0 1,1 -184,0"/></defs>
+ <text><textPath href="#hintPath" startOffset="0">HOLD &amp; DRAG TO SCRATCH · LET GO AND IT RIDES AGAIN · HOLD &amp; DRAG TO SCRATCH · LET GO AND IT RIDES AGAIN ·</textPath></text>
+ </svg>
+ </div>
+ <div class="hint-chip mono" aria-hidden="true"><span class="hand"></span>Drag the record</div>
+ <svg class="leader" aria-hidden="true"><path d=""/><circle r="3.5"/></svg>
+ </div>
+
+ <div class="player" role="region" aria-label="Deck">
+ <button class="pp" type="button" aria-label="Play" data-cursor="link"><span class="pi" aria-hidden="true"></span></button>
+ <div class="now"><span class="mono np-k">Now on the deck</span><span class="np-t">A1 · Last Train, Shimokita</span></div>
+ <div class="rpm mono" role="group" aria-label="Speed"><button type="button" class="on" data-rpm="1">33</button><button type="button" data-rpm="1.35">45</button></div>
+ </div>
+ <div class="toast mono" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/lowfreq/main.js b/examples/lowfreq/main.js
new file mode 100644
index 0000000..b38ad2f
--- /dev/null
+++ b/examples/lowfreq/main.js
@@ -0,0 +1,738 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, BASE } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { DepthOfFieldEffect, EffectPass } from 'postprocessing';
+import { buildDeck, BANDS, L } from './deck.js';
+import { buildRoom, WALL_Z, FLOOR_Y } from './room.js';
+import { Deck, TRACKS } from './audio.js';
+
+const Q = new URLSearchParams(location.search);
+const $ = s => document.querySelector(s);
+const $$ = s => [...document.querySelectorAll(s)];
+const portrait = () => innerWidth / innerHeight < 0.85;
+const coarse = matchMedia('(pointer: coarse)').matches;
+if (Q.has('noui')) document.documentElement.classList.add('noui');
+
+const fontsReady = Promise.race([
+ Promise.all([
+ document.fonts.load('800 88px "Syne"'), document.fonts.load('700 40px "Syne"'),
+ document.fonts.load('400 20px "Space Mono"'), document.fonts.load('700 20px "Space Mono"'),
+ document.fonts.load('400 300px "M PLUS Rounded 1c"', '低周波'),
+ ]).catch(() => {}),
+ new Promise(r => setTimeout(r, 3000)),
+]);
+
+// ─── Engine & post ────────────────────────────────────────────────────────────
+const canvas = $('#gl');
+let vol;
+const engine = new Engine({
+ canvas, fov: 34, near: 0.01, far: 30, dpr: 1.5, background: 0x07040a,
+ post: {
+ ao: Q.has('noao') ? false : { aoRadius: 0.12, intensity: 2.4, distanceFalloff: 0.22 },
+ bloom: { intensity: 0.85, luminanceThreshold: 0.78, luminanceSmoothing: 0.3, radius: 0.8 },
+ pre: cam => Q.has('novol') ? ((vol = { add() {} }), []) : [(vol = new VolumetricSpotEffect(cam, { density: 0.055, noise: 0.9, noiseScale: 3.4, maxDist: 7, floorY: FLOOR_Y, wind: new THREE.Vector3(0.03, 0.07, 0.01) }))],
+ tone: Q.get('tone') ?? 'aces',
+ vignette: { offset: 0.22, darkness: 0.82 },
+ noise: 0.07,
+ ca: 0.0013,
+ },
+});
+const { scene, camera, renderer } = engine;
+const dof = new DepthOfFieldEffect(camera, { focusDistance: 0.55, focusRange: 0.18, bokehScale: 3, resolutionScale: 0.5 });
+if (!Q.has('nodof')) {
+ const comp = engine.post.composer, i = comp.passes.indexOf(engine.post.ao);
+ comp.addPass(new EffectPass(camera, dof), i >= 0 ? i + 1 : 1);
+}
+scene.fog = new THREE.FogExp2(0x07040b, 0.08);
+scene.environment = studioEnvironment(renderer, {
+ top: 0x1b1024, bottom: 0x040305, panels: [
+ { pos: [0, 7, 1.5], size: [3, 2.2], intensity: 6, color: 0xffc27e },
+ { pos: [0, 2.4, -7], size: [1.6, 4.5], intensity: 3.2, color: 0xa78bfa },
+ { pos: [-7, 2, 3], size: [1.4, 4], intensity: 1.1, color: 0xff9a4d },
+ { pos: [7, 3, 2], size: [1.2, 5], intensity: 1.4, color: 0x8e76ff },
+ { pos: [0, 1, 8], size: [6, 1.2], intensity: 0.5, color: 0xffd9b0 },
+ ],
+});
+scene.environmentIntensity = 0.24;
+const hemi = new THREE.HemisphereLight(0x2c1b3e, 0x0a0508, 0.2);
+scene.add(hemi);
+
+// ─── Lights ───────────────────────────────────────────────────────────────────
+const KEY_ON = 7.5;
+const key = new THREE.SpotLight(0xffcf9e, 0, 3.6, 0.27, 0.7, 2);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+key.shadow.camera.near = 0.3; key.shadow.camera.far = 2.4;
+key.shadow.bias = -0.00012; key.shadow.normalBias = 0.006; key.shadow.radius = 4;
+scene.add(key, key.target);
+vol.add(key, { scale: 0.28, range: 0.4, softness: 0.55 });
+const counterSpots = [-1.5, 0, 1.5].map((x, i) => {
+ const s = new THREE.SpotLight(0xffbf80, 0, 3, 0.5, 0.7, 2);
+ s.position.set(x, 1.0, 1.12); s.target.position.set(x, 0, 1.12);
+ scene.add(s, s.target);
+ if (i !== 1) vol.add(s, { scale: 0.18, range: 0.6, softness: 0.6 });
+ return s;
+});
+const wallWash = new THREE.SpotLight(0xd6b8ff, 0, 4, 0.9, 0.9, 1.6);
+wallWash.position.set(0, 2.35, 0.6); wallWash.target.position.set(0, 0.6, WALL_Z - 0.2);
+scene.add(wallWash, wallWash.target);
+const rim = new THREE.DirectionalLight(0xb9a3ff, 0);
+rim.position.set(-1.2, 1.6, -2.4);
+scene.add(rim, rim.target);
+const streak = new THREE.SpotLight(0xd9ccff, 0, 3, 0.2, 0.8, 1.5);
+scene.add(streak, streak.target);
+const fill = new THREE.PointLight(0x8c6cff, 0, 5, 1.4);
+fill.position.set(-0.8, 1.2, 1.6);
+scene.add(fill);
+const touch = new THREE.PointLight(0xcdb8ff, 0, 0.35, 2);
+scene.add(touch);
+const LIGHTS = { key: KEY_ON, counter: 1.5, wash: 1.1, rim: 0.55, fill: 0.5, streak: Q.has('nostreak') ? 0 : 0.9 };
+
+// ─── Loading ──────────────────────────────────────────────────────────────────
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+const loaderEl = $('.loader');
+{
+ const g = loaderEl.querySelector('.ld-grooves');
+ for (let i = 0; i < 26; i++) {
+ const c = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
+ c.setAttribute('cx', 100); c.setAttribute('cy', 100); c.setAttribute('r', 94 - i * 2.35); c.style.opacity = 0;
+ g.appendChild(c);
+ }
+}
+const grooveEls = [...loaderEl.querySelectorAll('.ld-grooves circle')];
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1600,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = String(Math.round(v * 100)).padStart(3, '0');
+ grooveEls.forEach((c, i) => { c.style.opacity = v * 26 > i ? 1 : 0.08; });
+ },
+});
+const texLoad = name => assets.texture(`img/lowfreq/${name}.webp`);
+const COVER_NAMES = ['aubergine', 'tidal', 'counter', 'rain', 'valves', 'geometry'];
+const loads = {
+ tt: assets.gltf('models/lowfreq/turntable.glb'),
+ sp: assets.gltf('models/lowfreq/speaker.glb'),
+ covers: Promise.all(COVER_NAMES.map(texLoad)),
+};
+
+// ─── State ────────────────────────────────────────────────────────────────────
+const OMEGA = 2 * Math.PI * (100 / 3) / 60; // 33⅓ rpm in rad/s
+const IDLE = 0.26;
+const S = { playing: false, needle: false, track: 0, speed: 1, spin: 0, recAngle: 0, held: false, scratched: false, intro: 0, motor: false };
+const arm = { yaw: 0, lift: 0.03 };
+const audio = new Deck();
+const woofer = { value: 0 };
+let deck3, room, RC = new THREE.Vector3(), recR = 0.152, speakers = [];
+const SPEC = new Float32Array(72);
+const env = { bass: 0, mid: 0, high: 0, rms: 0, kick: 0 };
+let fakeMix = 1;
+
+// ─── Build the world ─────────────────────────────────────────────────────────
+async function build() {
+ const [ttG, spG, covers] = await Promise.all([loads.tt, loads.sp, loads.covers]);
+ await fontsReady;
+ for (const c of covers) { c.anisotropy = renderer.capabilities.getMaxAnisotropy(); }
+
+ room = buildRoom(renderer, scene, { covers });
+
+ // Turntable
+ const tt = ttG.scene;
+ normalize(tt, 0.41);
+ prepModel(tt, renderer, { env: 0.9, onMat: m => { m.color.setRGB(0.62, 0.56, 0.54); } });
+ tt.position.x += 0.02;
+ scene.add(tt);
+ deck3 = buildDeck(renderer, tt, { tracks: TRACKS });
+ tt.updateMatrixWorld(true);
+ deck3.center(RC);
+ recR = deck3.radiusWorld();
+ arm.yaw = deck3.restYaw;
+
+ // Speakers (woofer cones pump with the kick)
+ const spk = spG.scene;
+ normalize(spk, 0.43, { axis: 'y' });
+ prepModel(spk, renderer, { env: 0.9, onMat: m => {
+ m.onBeforeCompile = sh => {
+ sh.uniforms.uWoof = woofer;
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nuniform float uWoof;')
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ { float r = length(position.xy - vec2(0.0, -0.285)); float w = 1.0 - smoothstep(0.16, 0.37, r); w *= smoothstep(0.35, 0.5, position.z);
+ transformed.z += uWoof * w * 0.055; }`);
+ };
+ } });
+ for (const [x, ry] of [[-0.87, 0.28], [0.88, -0.28]]) {
+ const g = new THREE.Group(); g.add(x < 0 ? spk : spk.clone());
+ g.position.set(x, 0.006, -0.1); g.rotation.y = ry;
+ scene.add(g); speakers.push(g);
+ const pad = new THREE.Mesh(new THREE.CylinderGeometry(0.02, 0.02, 0.006, 16), new THREE.MeshStandardMaterial({ color: 0x111, roughness: 0.6 }));
+ for (const [px, pz] of [[-0.08, -0.1], [0.08, -0.1], [-0.08, 0.1], [0.08, 0.1]]) { const p = pad.clone(); p.position.set(px, -0.003, pz); g.add(p); }
+ }
+
+ // Key light hangs in the deck pendant, aimed at the record.
+ key.position.copy(room.keyPendant.position).add(new THREE.Vector3(0, -0.02, 0));
+ key.target.position.copy(RC).add(new THREE.Vector3(0.03, 0, -0.035));
+ rim.target.position.copy(RC);
+ // a low lavender practical behind the deck: its reflection draws the radial streak across the vinyl
+ streak.position.copy(RC).add(new THREE.Vector3(-0.55, 0.3, -1.05));
+ streak.target.position.copy(RC);
+
+ // Glossy back counter reflects the deck, the valves and the halo.
+ const refl = new PlanarReflection(renderer, { resolution: 0.5 });
+ const topMat = room.counterTopMat.clone();
+ room.reflectFloor.material = topMat;
+ refl.hidden.push(room.reflectFloor);
+ refl.patch(topMat, { strength: 1.1, distort: 0.006, lodScale: 5.5, lodBias: 0.25, f0: 0.05 });
+ engine.onResize((w, h, dpr) => refl.setSize(w, h, dpr));
+ reflection = refl;
+
+ // Band markers: a lavender wash over the grooves of the band a cue will land on
+ bandMarkers = BANDS.map(b => {
+ const m = new THREE.Mesh(new THREE.RingGeometry(b.inner, b.outer, 192, 1).rotateX(-Math.PI / 2),
+ new THREE.MeshBasicMaterial({ color: new THREE.Color(0xa78bfa).multiplyScalar(0.55), transparent: true, opacity: 0, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false }));
+ m.position.set(L.cx, L.top + 0.0035, L.cz);
+ deck3.mesh.add(m);
+ return m;
+ });
+
+ makeDust();
+ makeTrail();
+ defineShots();
+}
+let bandMarkers = [], reflection;
+
+// ─── Dust in the beam ─────────────────────────────────────────────────────────
+let dust;
+function makeDust(N = 1400) {
+ const pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const a = Math.random() * Math.PI * 2, r = Math.sqrt(Math.random()) * 0.5;
+ pos[i * 3] = RC.x + Math.cos(a) * r; pos[i * 3 + 1] = 0.03 + Math.random() * 1.0; pos[i * 3 + 2] = RC.z + Math.sin(a) * r;
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uLPos: { value: new THREE.Vector3() }, uLDir: { value: new THREE.Vector3(0, -1, 0) }, uCos: { value: 0.93 },
+ uPow: { value: 0 }, uKick: { value: 0 }, uEnergy: { value: 0 }, uDpr: { value: 1 }, uAxis: { value: new THREE.Vector3() } },
+ vertexShader: /* glsl */`
+ attribute float seed; uniform float uTime, uCos, uPow, uKick, uEnergy, uDpr; uniform vec3 uLPos, uLDir, uAxis; varying float vA;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.03 + seed * 0.05) * (1.0 + uEnergy * 2.5);
+ p += vec3(sin(t * 3.1 + seed * 40.), sin(t * 2.3 + seed * 13.) * 0.5 + t * 0.06, cos(t * 2.7 + seed * 27.)) * 0.12;
+ p.y = mod(p.y - 0.03, 1.0) + 0.03;
+ vec2 rad = p.xz - uAxis.xz;
+ p.xz += normalize(rad + 1e-4) * uKick * 0.018 * seed;
+ p.y += uKick * 0.012 * (seed - 0.3);
+ vec3 d = p - uLPos; float dist = length(d);
+ float cone = smoothstep(uCos, uCos + 0.04, dot(d / dist, uLDir));
+ float tw = 0.55 + 0.45 * sin(uTime * (1.5 + seed * 5.0) + seed * 60.0);
+ vA = cone * uPow * tw * (0.35 + 0.65 * fract(seed * 91.7)) * (1.0 + uKick * 1.5);
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (0.6 + seed * 1.3) * uDpr * (0.5 / -mv.z);
+ }`,
+ fragmentShader: /* glsl */`varying float vA; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .0, d); gl_FragColor = vec4(vec3(1.0, .82, .6) * a * vA * 1.6, 1.); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ scene.add(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ dust = mat;
+}
+
+// ─── Scratch comet: glowing points that follow the hand across the vinyl ─────
+let trail;
+function makeTrail(N = 900) {
+ const pos = new Float32Array(N * 3), born = new Float32Array(N).fill(-99), heat = new Float32Array(N);
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('born', new THREE.BufferAttribute(born, 1));
+ geo.setAttribute('heat', new THREE.BufferAttribute(heat, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, toneMapped: false,
+ uniforms: { uTime: { value: 0 }, uDpr: { value: 1 }, uA: { value: new THREE.Color(0xa78bfa) }, uB: { value: new THREE.Color(0xffb45c) } },
+ vertexShader: /* glsl */`
+ attribute float born, heat; uniform float uTime, uDpr; varying float vA, vH;
+ void main(){
+ float age = uTime - born;
+ vA = exp(-age * 0.95) * step(0.0, age);
+ vH = heat;
+ vec4 mv = modelViewMatrix * vec4(position + vec3(0.0, age * 0.012, 0.0), 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = uDpr * (9.0 + 26.0 * vA) * (0.35 / -mv.z) * (0.75 + heat * 0.5);
+ }`,
+ fragmentShader: /* glsl */`
+ uniform vec3 uA, uB; varying float vA, vH;
+ void main(){ float d = length(gl_PointCoord - 0.5); float core = smoothstep(0.5, 0.0, d); float hot = smoothstep(0.18, 0.0, d);
+ vec3 c = mix(uA, uB, clamp(vH, 0.0, 1.0));
+ gl_FragColor = vec4((c * core * core * 3.2 + vec3(1.0, 0.95, 0.9) * hot * 2.2) * vA, 1.0); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false; pts.renderOrder = 7;
+ scene.add(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ let head = 0; const last = new THREE.Vector3(); let has = false;
+ const emit = (p, t, h) => { pos.set([p.x, p.y, p.z], head * 3); born[head] = t; heat[head] = h; head = (head + 1) % N; };
+ trail = {
+ update(dt, t, hand, speed) {
+ mat.uniforms.uTime.value = t;
+ if (!hand) { has = false; return; }
+ const p = _p4.copy(hand); p.y = RC.y + 0.006;
+ if (!has) { last.copy(p); has = true; emit(p, t, speed / 2.5); }
+ const d = last.distanceTo(p), steps = Math.min(24, Math.floor(d / 0.0016));
+ for (let k = 1; k <= steps; k++) emit(_p3.lerpVectors(last, p, k / steps), t - (1 - k / steps) * dt, Math.min(1.2, speed / 2.5));
+ if (steps) last.copy(p);
+ geo.attributes.position.needsUpdate = geo.attributes.born.needsUpdate = geo.attributes.heat.needsUpdate = true;
+ },
+ };
+}
+
+// ─── Camera shots ─────────────────────────────────────────────────────────────
+const K = {};
+const INTRO = { pos: new THREE.Vector3(0.35, 1.25, 2.9), look: new THREE.Vector3(0, 0.25, -0.2), fov: 40 };
+function defineShots() {
+ const v = (x, y, z) => new THREE.Vector3(x, y, z);
+ const r = (x, y, z) => RC.clone().add(v(x, y, z));
+ const woof = speakers[1].localToWorld(v(0, 0.12, 0.1));
+ K.hero = { pos: r(0.43, 0.17, 0.5), look: r(-0.2, 0.01, -0.06), fov: 33, focus: r(0.02, 0, 0.05), range: 0.16, bokeh: 3.4, par: 1,
+ m: { pos: r(0.03, 0.5, 0.52), look: r(0.0, -0.2, 0.12), fov: 46 } };
+ K.press = { pos: r(0.22, 0.8, 0.14), look: r(0.22, 0, 0.0), fov: 33, focus: r(0, 0, 0), range: 0.32, bokeh: 1.4, par: 0.35, key: 0.55,
+ m: { pos: r(0.0, 0.7, 0.4), look: r(0.0, 0, 0.13), fov: 44 } };
+ K.bar = { pos: v(2.25, 1.1, 3.7), look: v(0.72, 0.22, 0.1), fov: 38, focus: v(0.0, 0.2, 0.0), range: 2.2, bokeh: 1.4, par: 1, streak: 0.15,
+ m: { pos: v(0.4, 0.9, 3.9), look: v(0.0, 0.2, -0.2), fov: 52 } };
+ K.cat = { pos: v(-1.45, 0.92, 0.78), look: v(-1.7, 0.86, WALL_Z), fov: 38, focus: v(-1.7, 0.92, WALL_Z), range: 0.9, bokeh: 1.3, drift: v(1.1, 0.0, 0), par: 0.5,
+ m: { pos: v(-1.2, 0.92, 0.72), look: v(-1.35, 0.86, WALL_Z), fov: 52 } };
+ K.club = { pos: v(0.46, 0.2, 0.62), look: v(0.9, 0.16, -0.12), fov: 35, focus: woof, range: 0.28, bokeh: 3, par: 1,
+ m: { pos: v(0.62, 0.3, 0.95), look: v(0.8, 0.14, -0.1), fov: 46 } };
+ K.end = { pos: r(-0.36, 0.045, 0.19), look: r(0.09, 0.012, -0.03), fov: 30, focus: r(-0.03, 0.0, 0.03), range: 0.3, bokeh: 2.6, par: 0.6,
+ m: { pos: r(-0.28, 0.12, 0.34), look: r(0.03, 0.0, -0.02), fov: 42 } };
+}
+const SECTIONS = $$('[data-cam]');
+let ranges = [];
+function measure() {
+ const vh = innerHeight, max = document.documentElement.scrollHeight - vh;
+ ranges = SECTIONS.map(el => {
+ let a = el.offsetTop - vh * 0.25, b = el.offsetTop + el.offsetHeight - vh * 0.75;
+ if (b < a) a = b = (a + b) / 2;
+ return { a: clamp(a, 0, max), b: clamp(b, 0, max) };
+ });
+ ranges[0].a = 0; ranges[ranges.length - 1].b = max;
+}
+addEventListener('resize', measure);
+new ResizeObserver(measure).observe(document.body);
+
+const shot = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fov: 34, focus: new THREE.Vector3(), range: 0.2, bokeh: 3, par: 1, key: 1, streak: 1 };
+const _a = new THREE.Vector3(), _b = new THREE.Vector3(), _c = new THREE.Vector3(), _d = new THREE.Vector3();
+let secIdx = 0, secBlend = 0;
+function kf(k, idx, y, pm, oPos, oLook) {
+ const P = pm && k.m ? k.m : k;
+ oPos.copy(P.pos); oLook.copy(P.look);
+ if (k.drift) {
+ const R = ranges[idx], u = clamp((y - R.a) / Math.max(1, R.b - R.a)) - 0.5;
+ oPos.addScaledVector(k.drift, u * (pm ? 0.5 : 1)); oLook.addScaledVector(k.drift, u * (pm ? 0.5 : 1));
+ }
+ return P;
+}
+function shotAt(y, out) {
+ let i = 0;
+ while (i < ranges.length - 1 && y > ranges[i].b) i++;
+ // inside a hold range -> that shot; between ranges -> eased blend from the previous one
+ let ia, ib, e;
+ if (y >= ranges[i].a || i === 0) { ia = ib = i; e = 0; }
+ else { ia = i - 1; ib = i; e = smooth(0, 1, (y - ranges[ia].b) / Math.max(1, ranges[ib].a - ranges[ia].b)); }
+ const A = K[SECTIONS[ia].dataset.cam], B = K[SECTIONS[ib].dataset.cam];
+ const pm = portrait();
+ const PA = kf(A, ia, y, pm, _a, _c), PB = kf(B, ib, y, pm, _b, _d);
+ out.pos.lerpVectors(_a, _b, e);
+ out.look.lerpVectors(_c, _d, e);
+ out.pos.y += Math.sin(e * Math.PI) * 0.08;
+ out.fov = lerp(PA.fov, PB.fov, e);
+ out.focus.lerpVectors(A.focus, B.focus, e);
+ out.range = lerp(A.range, B.range, e);
+ out.bokeh = lerp(A.bokeh, B.bokeh, e);
+ out.par = lerp(A.par, B.par, e);
+ out.key = lerp(A.key ?? 1, B.key ?? 1, e);
+ out.streak = lerp(A.streak ?? 1, B.streak ?? 1, e);
+ secIdx = e < 0.5 ? ia : ib; secBlend = ia === ib ? 0 : e;
+ return out;
+}
+
+// ─── Playback control ─────────────────────────────────────────────────────────
+const toastEl = $('.toast');
+let toastT;
+function toast(msg, ms = 2600) { toastEl.textContent = msg; toastEl.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => toastEl.classList.remove('on'), ms); }
+let armTl = null, cueToken = 0;
+const trackReady = i => new Promise(res => { const k = () => (audio.fwd[i] ? res() : setTimeout(k, 60)); k(); });
+function soundOn() {
+ audio.unlock();
+ const b = $('.sound');
+ if (!audio.muted) { b.setAttribute('aria-pressed', 'true'); b.querySelector('.sound-label').textContent = 'Sound on'; }
+}
+async function play(i = S.track, { quick = false } = {}) {
+ soundOn();
+ const token = ++cueToken;
+ S.playing = true; S.track = i;
+ updateUI();
+ if (!audio.fwd[i]) { $$('.tracks li')[i]?.classList.add('wait'); toast(`Pressing ${TRACKS[i].id} — one moment`); await trackReady(i); $$('.tracks li')[i]?.classList.remove('wait'); }
+ if (token !== cueToken) return;
+ if (S.needle) { S.needle = false; audio.needleLift(); }
+ armTl?.kill();
+ armTl = gsap.timeline()
+ .to(arm, { lift: 0.09, duration: quick ? 0.18 : 0.32, ease: 'power2.out' })
+ .to(arm, { yaw: deck3.bandYaw[i], duration: quick ? 0.55 : 1.15, ease: 'power2.inOut' })
+ .to(arm, { lift: 0, duration: quick ? 0.25 : 0.55, ease: 'power2.in', onComplete: () => {
+ if (token !== cueToken) return;
+ audio.cue(i); S.needle = true; audio.needleDrop(); dropPulse = 1;
+ } });
+}
+function pause() {
+ const token = ++cueToken;
+ S.playing = false;
+ updateUI();
+ // brake with the needle still down (the platter winds down), then lift and park
+ armTl?.kill();
+ armTl = gsap.timeline({ delay: S.needle ? 1.25 : 0 })
+ .add(() => { if (token !== cueToken) return; if (S.needle) audio.needleLift(); S.needle = false; })
+ .to(arm, { lift: 0.09, duration: 0.3, ease: 'power2.out' })
+ .to(arm, { yaw: deck3.restYaw, duration: 1.1, ease: 'power2.inOut' })
+ .to(arm, { lift: 0.03, duration: 0.4, ease: 'power2.in' });
+}
+let dropPulse = 0;
+function updateUI() {
+ document.body.classList.toggle('is-playing', S.playing);
+ $$('.tracks li').forEach((li, k) => li.classList.toggle('on', S.playing && k === S.track));
+ const t = TRACKS[S.track];
+ $('.np-t').textContent = `${t.id} · ${t.title}`;
+ $('.play-main .pl').textContent = S.playing ? 'Lift the needle' : 'Drop the needle';
+ $('.pp').setAttribute('aria-label', S.playing ? 'Pause' : 'Play');
+ $('.bpm-read').textContent = `${Math.round(t.bpm * S.speed)} bpm`;
+ document.documentElement.style.setProperty('--spin-state', S.playing ? 'running' : 'paused');
+}
+const togglePlay = () => (S.playing ? pause() : play(S.track));
+$('.play-main').addEventListener('click', togglePlay);
+$('.pp').addEventListener('click', togglePlay);
+$('.sound').addEventListener('click', () => {
+ const b = $('.sound');
+ if (!audio.ctx) { audio.unlock(); audio.setMuted(false); }
+ else audio.setMuted(!audio.muted);
+ const on = !audio.muted;
+ b.setAttribute('aria-pressed', String(on));
+ b.querySelector('.sound-label').textContent = on ? 'Sound on' : 'Sound off';
+ if (on && !S.playing) toast('Sound is on — drop the needle or put your hand on the record');
+});
+$$('.rpm button').forEach(b => b.addEventListener('click', () => {
+ $$('.rpm button').forEach(x => x.classList.toggle('on', x === b));
+ S.speed = +b.dataset.rpm;
+ $('.rpm-read').textContent = S.speed > 1 ? '45 rpm' : '33⅓ rpm';
+ updateUI();
+}));
+$$('.tracks li').forEach((li, k) => {
+ li.addEventListener('click', () => play(k));
+ li.addEventListener('pointerenter', () => { hoverTrack = k; });
+ li.addEventListener('pointerleave', () => { if (hoverTrack === k) hoverTrack = -1; });
+});
+let hoverTrack = -1;
+
+// ─── Scratching ───────────────────────────────────────────────────────────────
+const scratchEl = $('.scratch');
+const hintEl = $('.hint'), chipEl = $('.hint-chip');
+const ray = new THREE.Raycaster();
+const plane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0);
+const ndc = new THREE.Vector2(), hitP = new THREE.Vector3();
+function hitRecord(cx, cy) {
+ ndc.set(cx / innerWidth * 2 - 1, -(cy / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ plane.constant = -RC.y;
+ if (!ray.ray.intersectPlane(plane, hitP)) return null;
+ const dx = hitP.x - RC.x, dz = hitP.z - RC.z;
+ return { r: Math.hypot(dx, dz), phi: Math.atan2(-dz, dx), p: hitP };
+}
+const grab = { phi: 0, acc: 0, rec0: 0, target: 0, hover: false, world: new THREE.Vector3() };
+scratchEl.addEventListener('pointerdown', e => {
+ const h = hitRecord(e.clientX, e.clientY);
+ if (!h || h.r > recR * 1.06) return;
+ e.preventDefault();
+ scratchEl.setPointerCapture(e.pointerId);
+ S.held = true;
+ grab.phi = h.phi; grab.acc = 0; grab.rec0 = S.recAngle; grab.target = S.recAngle; grab.world.copy(h.p);
+ if (!S.playing) play(S.track, { quick: true });
+ else soundOn();
+ if (!S.scratched) { S.scratched = true; hintEl.classList.remove('on'); chipEl.classList.remove('on'); }
+ document.body.classList.add('is-scratching');
+});
+scratchEl.addEventListener('pointermove', e => {
+ const h = hitRecord(e.clientX, e.clientY);
+ grab.hover = !!h && h.r < recR * 1.04;
+ if (h) { touch.position.set(h.p.x, RC.y + 0.035, h.p.z); grab.world.copy(h.p); }
+ if (!S.held || !h) return;
+ if (h.r < recR * 0.12) { grab.phi = h.phi; return; } // dead zone at the spindle
+ let d = h.phi - grab.phi;
+ d = Math.atan2(Math.sin(d), Math.cos(d));
+ grab.phi = h.phi; grab.acc += d;
+ grab.target = grab.rec0 + grab.acc;
+});
+const release = () => { if (!S.held) return; S.held = false; document.body.classList.remove('is-scratching'); cur?.set(grab.hover ? 'drag' : '', grab.hover ? 'Scratch' : ''); };
+scratchEl.addEventListener('pointerup', release);
+scratchEl.addEventListener('pointercancel', release);
+scratchEl.addEventListener('pointerleave', () => { grab.hover = false; });
+addEventListener('pointerup', release);
+
+// ─── Projection helpers ───────────────────────────────────────────────────────
+const proj = (p, out = new THREE.Vector3()) => { out.copy(p).project(camera); out.x = (out.x + 1) / 2 * innerWidth; out.y = (1 - out.y) / 2 * innerHeight; return out; };
+const _p0 = new THREE.Vector3(), _p1 = new THREE.Vector3(), _p2 = new THREE.Vector3(), _p3 = new THREE.Vector3(), _p4 = new THREE.Vector3();
+const leader = $('.leader'), leaderPath = leader.querySelector('path'), leaderDot = leader.querySelector('circle');
+
+// ─── Fake spectrum for the silent state ──────────────────────────────────────
+function fakeSpectrum(out, t) {
+ const beat = t * 118 / 60, ph = beat % 1;
+ const kick = Math.exp(-ph * 6.5), hat = Math.exp(-((beat + 0.5) % 1) * 9), bar = Math.floor(beat / 4);
+ const chord = 0.5 + 0.5 * Math.sin(t * 0.8 + bar);
+ for (let i = 0; i < out.length; i++) {
+ const f = i / (out.length - 1);
+ out[i] = 0.06 + 0.05 * (0.5 + 0.5 * Math.sin(t * 2.1 + i * 0.9) * Math.sin(t * 1.3 + i * 0.37))
+ + kick * 0.62 * Math.exp(-f * 7) + hat * 0.32 * smooth(0.62, 0.95, f)
+ + chord * 0.22 * Math.exp(-((f - 0.38) ** 2) / 0.015) + 0.1 * Math.exp(-((f - 0.2) ** 2) / 0.004) * (0.5 + 0.5 * Math.sin(t * 3 + 1));
+ }
+ return { bass: kick * 0.75, mid: 0.2 + chord * 0.2, high: hat * 0.5, rms: 0.12 + kick * 0.12 };
+}
+
+// ─── Frame ────────────────────────────────────────────────────────────────────
+const camPos = new THREE.Vector3(), camLook = new THREE.Vector3(), tmp = new THREE.Vector3();
+let tubeWarm = 0, neonOn = 0, lightsOn = 0, heroFade = 1, lastRec = 0;
+const vuState = { v: 0 };
+const heroEl = $('.hero');
+function tick(dt, t) {
+ pointer.update(dt);
+ // Camera: scroll shot, intro blend, hand-held drift, parallax
+ shotAt(window.__lenis?.animatedScroll ?? scrollY, shot);
+ const ie = S.intro;
+ camPos.lerpVectors(INTRO.pos, shot.pos, ie); camLook.lerpVectors(INTRO.look, shot.look, ie);
+ const par = shot.par * (coarse ? 0.3 : 1);
+ tmp.subVectors(camLook, camPos).normalize();
+ const right = _p4.crossVectors(tmp, camera.up).normalize();
+ const dist = camPos.distanceTo(camLook);
+ camPos.addScaledVector(right, (pointer.sx * 0.028 + Math.sin(t * 0.29) * 0.004) * par * dist);
+ camPos.y += (pointer.sy * 0.018 + Math.sin(t * 0.41) * 0.003) * par * dist;
+ camera.position.copy(camPos);
+ camera.lookAt(camLook);
+ const fov = lerp(INTRO.fov, shot.fov, ie);
+ if (Math.abs(camera.fov - fov) > 0.01) { camera.fov = fov; camera.updateProjectionMatrix(); }
+ dof.cocMaterial.focusDistance = camera.position.distanceTo(shot.focus);
+ dof.cocMaterial.focusRange = shot.range;
+ dof.bokehScale = shot.bokeh;
+
+ // Platter: motor, hand, speed
+ const target = (S.playing ? OMEGA * S.speed : OMEGA * IDLE) * (S.motor ? 1 : 0);
+ if (S.held) {
+ const prev = S.recAngle;
+ S.recAngle = damp(S.recAngle, grab.target, 38, dt);
+ const raw = -(S.recAngle - prev) / Math.max(dt, 1e-4);
+ S.spin = damp(S.spin, raw, 28, dt);
+ } else {
+ const up = target > S.spin;
+ S.spin = damp(S.spin, target, up ? (S.playing ? 3.2 : 2) : (S.playing ? 2.4 : 1.25), dt);
+ S.recAngle -= S.spin * dt;
+ }
+ if (deck3) {
+ deck3.record.rotation.y = S.recAngle;
+ trail?.update(dt, t, S.held ? grab.world : null, Math.abs(S.spin) / OMEGA);
+ if (S.held && cur) cur.set('drag', `${S.spin < -0.05 ? '◀' : '▶'} ${Math.abs(S.spin / OMEGA).toFixed(1)}×`);
+ const wob = S.needle ? Math.sin(S.recAngle) * 0.0035 : 0;
+ deck3.setArm(arm.yaw + wob, arm.lift);
+ }
+ const rate = S.spin / OMEGA;
+ audio.update(rate, S.needle);
+
+ // Spectrum: real when the needle is in the groove, a believable fake otherwise
+ let live = false;
+ if (audio.ready && S.needle) live = audio.spectrum(SPEC);
+ fakeMix = damp(fakeMix, live ? 0 : 1, 3, dt);
+ let lv = audio.levels;
+ if (fakeMix > 0.01) {
+ const FK = fakeSpectrum(fakeSpec, t);
+ const k = fakeMix * (S.playing ? 1 : 0.8);
+ for (let i = 0; i < SPEC.length; i++) SPEC[i] = lerp(live ? SPEC[i] : 0, fakeSpec[i] * 0.85, k);
+ lv = { bass: lerp(live ? audio.levels.bass : 0, FK.bass, k), mid: lerp(live ? audio.levels.mid : 0, FK.mid, k), high: lerp(live ? audio.levels.high : 0, FK.high, k), rms: lerp(live ? audio.levels.rms * 3 : 0, FK.rms, k) };
+ } else lv = { ...audio.levels, rms: audio.levels.rms * 3 };
+ env.bass = lv.bass > env.bass ? lerp(env.bass, lv.bass, 0.6) : damp(env.bass, lv.bass, 9, dt);
+ env.mid = damp(env.mid, lv.mid, 6, dt); env.high = damp(env.high, lv.high, 10, dt);
+ env.rms = damp(env.rms, lv.rms, 5, dt);
+ const kickNow = Math.max(0, lv.bass - 0.35) / 0.65;
+ env.kick = Math.max(kickNow, env.kick * Math.exp(-dt * 7));
+
+ if (deck3) {
+ const ring = deck3.ring, N = ring.N;
+ for (let i = 0; i < N; i++) {
+ // lows face the camera side (front), highs run round to the back
+ const a = i / N * Math.PI * 2;
+ const dA = Math.abs(Math.atan2(Math.sin(a + Math.PI / 2), Math.cos(a + Math.PI / 2))) / Math.PI;
+ const b = Math.min(SPEC.length - 1, Math.floor(dA * (SPEC.length - 1)));
+ const v = SPEC[b] * (0.75 + 0.25 * Math.sin(a * 3 + t * 0.6));
+ ring.amp[i] = v > ring.amp[i] ? lerp(ring.amp[i], v, 0.6) : damp(ring.amp[i], v, 7, dt);
+ }
+ ring.tex.needsUpdate = true;
+ dropPulse = damp(dropPulse, 0, 2.5, dt);
+ ring.mat.uniforms.uI.value = (0.42 + env.rms * 0.45 + dropPulse * 1.2 + (S.held ? 0.25 : 0)) * lightsOn;
+ ring.circ.material.opacity = (0.35 + env.bass * 0.5 + dropPulse) * lightsOn;
+ // cue marker + leader
+ const show = hoverTrack >= 0 ? hoverTrack : (S.playing && secIdx === 1 ? S.track : -1);
+ bandMarkers.forEach((m, k) => { m.material.opacity = damp(m.material.opacity, k === show && secIdx === 1 ? (hoverTrack === k ? 0.55 : 0.28) : 0, 7, dt); });
+ const leaderOn = show >= 0 && secIdx === 1 && secBlend < 0.05 && !portrait();
+ leader.classList.toggle('on', leaderOn);
+ if (leaderOn) {
+ const li = $$('.tracks li')[show].getBoundingClientRect();
+ const b = BANDS[show], mid = (b.outer + b.inner) / 2;
+ const w = proj(deck3.toWorld(L.cx + mid * 0.94, L.top, L.cz + mid * 0.34, _p3), _p3);
+ const x0 = li.left - 8, y0 = li.top + li.height / 2;
+ leaderPath.setAttribute('d', `M${x0},${y0} L${x0 - 36},${y0} L${w.x.toFixed(1)},${w.y.toFixed(1)}`);
+ leaderDot.setAttribute('cx', w.x.toFixed(1)); leaderDot.setAttribute('cy', w.y.toFixed(1));
+ }
+ }
+
+ // Room reacts
+ woofer.value = env.bass * 0.8 + env.kick * 0.6 + (S.held ? Math.min(1, Math.abs(rate - 1)) * 0.15 * Math.sin(t * 60) : 0);
+ const breathe = 1 + env.rms * 0.35 + env.kick * 0.08;
+ key.intensity = LIGHTS.key * lerp(1, shot.key, S.intro) * lightsOn * (1 + Math.sin(t * 37) * Math.sin(t * 13.7) * 0.012) * (0.97 + env.kick * 0.05);
+ counterSpots.forEach(s => { s.intensity = LIGHTS.counter * lightsOn; });
+ wallWash.intensity = LIGHTS.wash * lightsOn * breathe;
+ rim.intensity = LIGHTS.rim * lightsOn;
+ streak.intensity = LIGHTS.streak * lightsOn * (0.9 + env.mid * 0.3) * shot.streak;
+ fill.intensity = LIGHTS.fill * lightsOn * (0.4 + env.mid * 1.0 + env.kick * 0.4);
+ hemi.intensity = 0.2 * (0.8 + env.rms * 0.4) * (0.3 + lightsOn * 0.7);
+ touch.intensity = damp(touch.intensity, (grab.hover || S.held) && !coarse ? (S.held ? 0.03 : 0.018) : 0, 8, dt);
+ if (room) {
+ const n = room.neon;
+ const buzz = neonOn * (0.94 + 0.06 * Math.sin(t * 120) * Math.sin(t * 7.3) + env.kick * 0.12);
+ n.mat.color.copy(n.base).multiplyScalar(buzz);
+ n.halo.opacity = neonOn * (0.8 + env.bass * 0.4);
+ n.light.intensity = 1.3 * buzz * (0.8 + env.mid * 0.6);
+ for (const tb of room.tubes) {
+ const f = tubeWarm * (0.9 + 0.1 * Math.sin(t * (3 + tb.phase) + tb.phase) + env.rms * 0.35);
+ tb.fil.color.copy(tb.base).multiplyScalar(f);
+ tb.glow.opacity = 0.4 * f;
+ }
+ room.ampLight.intensity = 0.28 * tubeWarm * (1 + env.rms * 0.6);
+ room.shelfGlow.value = lightsOn * (0.8 + env.rms * 0.5 + env.kick * 0.12);
+ room.ledMat.color.copy(room.ledBase).multiplyScalar(lightsOn * (0.9 + env.kick * 0.25));
+ vuState.v = damp(vuState.v, clamp(env.rms * 1.4 + env.kick * 0.25), 7, dt);
+ room.vuNeedle.rotation.z = lerp(0.85, -0.75, vuState.v);
+ }
+ if (dust) {
+ const u = dust.uniforms;
+ u.uTime.value = t; u.uLPos.value.copy(key.position);
+ u.uLDir.value.copy(key.target.position).sub(key.position).normalize();
+ u.uCos.value = Math.cos(key.angle * 0.98);
+ u.uPow.value = lightsOn; u.uKick.value = env.kick; u.uEnergy.value = env.rms; u.uAxis.value.copy(RC);
+ }
+
+ // Projected UI: scratch zone and hint ring follow the record on screen
+ if (deck3) {
+ const c = proj(RC, _p0);
+ const ex = proj(_p1.copy(RC).add(tmp.set(recR, 0, 0)), _p1);
+ const ez = proj(_p2.copy(RC).add(tmp.set(0, 0, recR)), _p2);
+ const ex2 = proj(_p3.copy(RC).add(tmp.set(-recR, 0, 0)), _p3);
+ const rx = Math.max(Math.hypot(ex.x - c.x, ex.y - c.y), Math.hypot(ex2.x - c.x, ex2.y - c.y));
+ const ry = Math.abs(ez.y - c.y);
+ const zoneOn = ie > 0.72 && (secIdx === 0 || secIdx === 1 || secIdx === SECTIONS.length - 1) && rx > 70 && c.z < 1 && secBlend < 0.08;
+ scratchEl.classList.toggle('on', zoneOn || S.held);
+ if (zoneOn || S.held) {
+ const w = rx * 2.1, h = Math.max(ry, rx * 0.25) * 2.1;
+ scratchEl.style.transform = `translate3d(${(c.x - w / 2).toFixed(1)}px, ${(c.y - h / 2).toFixed(1)}px, 0)`;
+ scratchEl.style.width = `${w.toFixed(0)}px`; scratchEl.style.height = `${h.toFixed(0)}px`;
+ }
+ const hintOn = zoneOn && secIdx === 0 && !S.scratched && S.intro > 0.75;
+ hintEl.classList.toggle('on', hintOn);
+ chipEl.classList.toggle('on', hintOn);
+ if (hintOn) {
+ const sx = rx * 1.12 / 92, sy = Math.max(ry, 1) * 1.12 / 92;
+ hintEl.style.transform = `translate3d(${c.x.toFixed(1)}px, ${c.y.toFixed(1)}px, 0) scale(${sx.toFixed(3)}, ${sy.toFixed(3)})`;
+ const cw = chipEl.offsetWidth || 180;
+ const pm = portrait();
+ const cx = pm ? c.x - cw / 2 : clamp(c.x + rx * 0.35, 10, innerWidth - cw - 10), cy = pm ? c.y + ry * 0.2 : Math.min(innerHeight - 120, c.y + ry * 1.2 + 26);
+ chipEl.style.transform = `translate3d(${cx.toFixed(0)}px, ${cy.toFixed(0)}px, 0)`;
+ }
+ }
+ heroFade = damp(heroFade, secIdx === 0 ? 1 : 0, 6, dt);
+ heroEl.style.opacity = heroFade.toFixed(3);
+}
+const fakeSpec = new Float32Array(SPEC.length);
+
+// ─── Catalogue sleeves ────────────────────────────────────────────────────────
+$$('.sleeve').forEach(el => {
+ el.querySelector('.sl-cover').style.backgroundImage = `url(${BASE}img/lowfreq/${el.dataset.img}.webp)`;
+ const art = el.querySelector('.sl-art');
+ el.addEventListener('pointermove', e => {
+ const r = art.getBoundingClientRect();
+ const x = (e.clientX - r.left) / r.width - 0.5, y = (e.clientY - r.top) / r.height - 0.5;
+ gsap.to(art, { rotateY: x * 22, rotateX: -y * 16, z: 30, duration: 0.6, ease: 'power3.out' });
+ art.style.setProperty('--glare', (0.45 + x * 0.6).toFixed(2));
+ });
+ el.addEventListener('pointerleave', () => gsap.to(art, { rotateY: 0, rotateX: 0, z: 0, duration: 1.1, ease: 'elastic.out(1, 0.5)' }));
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('lowfreq', { theme: 'dark', corner: 'bl' });
+const cur = cursor({ color: '#eadcff', blend: 'normal', size: 30 });
+magnetic();
+smoothScroll({ lerp: 0.08 });
+$$('.title .line').forEach(l => { const s = document.createElement('span'); while (l.firstChild) s.appendChild(l.firstChild); l.appendChild(s); });
+
+const T0 = performance.now();
+await build();
+const T1 = performance.now();
+measure();
+updateUI();
+engine.onTick(tick);
+engine.onTick(() => { if (!Q.has('norefl')) reflection.update(scene, camera); });
+// compile everything with the lights on so nothing hitches later
+lightsOn = 1; tubeWarm = 1; neonOn = 1; S.intro = 1;
+tick(0.016, 0);
+// compile against an HDR target: the scene is always drawn into the composer's buffers, and programs are keyed on output colour space
+renderer.setRenderTarget(engine.post.composer.inputBuffer);
+try { await renderer.compileAsync(scene, camera); } catch { renderer.compile(scene, camera); }
+renderer.setRenderTarget(null);
+const T2 = performance.now();
+if (Q.has('debug')) console.warn('timing', { assetsAndBuild: Math.round(T1 - T0), compile: Math.round(T2 - T1), sinceNav: Math.round(T2) });
+lightsOn = 0; tubeWarm = 0; neonOn = 0; S.intro = 0;
+engine.start();
+// let the first frames (post-processing programs, shadow maps) compile behind the loader
+await new Promise(r => { let n = 0; const f = () => (++n > 3 ? r() : requestAnimationFrame(f)); requestAnimationFrame(f); });
+if (Q.has('debug')) console.warn('timing', { firstFrames: Math.round(performance.now() - T2) });
+await loader.finish();
+reveal('.sec h2', { type: 'lines', stagger: 0.08 });
+reveal('.lede', { type: 'lines', stagger: 0.05, y: '100%' });
+for (const [sel, trig] of [['.tracks li', '.tracks'], ['.bar-grid article', '.bar-grid'], ['.stats > div', '.stats'], ['.sleeve', '.sleeves'], ['.tier', '.tiers'], ['.foot-cols > p', '.foot-cols']]) {
+ gsap.from(sel, { opacity: 0, y: 36, duration: 1.1, ease: 'power3.out', stagger: 0.08, scrollTrigger: { trigger: trig, start: 'top 88%', once: true } });
+}
+addEventListener('keydown', e => {
+ if (e.code !== 'Space' || e.target.closest('input, textarea, button, a')) return;
+ e.preventDefault(); togglePlay();
+});
+
+// Intro: valves warm, neon stutters on, the pendant fades up, camera settles on the record, platter spins up.
+const intro = gsap.timeline();
+intro.to(S, { intro: 1, duration: Q.has('fast') ? 0.01 : 3.4, ease: 'power3.inOut' }, 0)
+ .to({ v: 0 }, { v: 1, duration: 2.6, ease: 'power1.in', onUpdate() { tubeWarm = this.targets()[0].v; } }, 0)
+ .to({ v: 0 }, { v: 1, duration: 1.5, ease: 'power2.out', onUpdate() { lightsOn = this.targets()[0].v; } }, 0.3)
+ .add(() => { S.motor = true; }, 0.9)
+ .add(() => {
+ const seq = [0.8, 0, 1, 0.2, 0, 1];
+ seq.forEach((v, k) => setTimeout(() => { neonOn = v; }, k * 90));
+ }, 0.7);
+gsap.from('.title .line > span', { yPercent: 105, duration: 1.6, ease: 'expo.out', stagger: 0.12, delay: 1.7 });
+gsap.from('.hero .eyebrow, .hero .sub, .hero-cta, .nav, .player, .hero-meta, .vert', { opacity: 0, y: 16, duration: 1.3, ease: 'power3.out', stagger: 0.07, delay: 2.1 });
+
+// Press the whole side in the background (offline rendering, no gesture needed).
+setTimeout(() => {
+ audio.prerender(() => deck3.grooves.userData.fill(audio.env)).catch(e => console.warn('audio render failed', e));
+}, 600);
+
+window.__lf = { S, arm, audio, play, pause, deck: () => deck3, K, camera, shot };
+if (Q.has('debug')) Object.assign(window, { THREE, scene });
diff --git a/examples/lowfreq/room.js b/examples/lowfreq/room.js
new file mode 100644
index 0000000..76d2c0a
--- /dev/null
+++ b/examples/lowfreq/room.js
@@ -0,0 +1,396 @@
+// The listening bar: back counter, record wall, neon, valve amp, counter + twelve stools, pendants.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+
+export const WALL_Z = -0.42; // face of the record shelves
+export const FLOOR_Y = -0.95;
+export const CEIL_Y = 2.45;
+
+function rng(seed) { return () => { seed = (seed + 0x6D2B79F5) | 0; let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
+
+// ─── Procedural surfaces ──────────────────────────────────────────────────────
+function woodTextures(renderer, { dark = 1, size = 1024, stretch = 14 } = {}) {
+ const albedo = bakeTexture(renderer, size, `
+ void main(){
+ vec2 p = vUv;
+ float warp = fbm(p * vec2(3.0, 0.6), 3.0, 4, 0.5) * 0.35;
+ float rings = fbm(vec2(p.x * 2.0 + warp, p.y * ${stretch.toFixed(1)}), 2.0, 5, 0.55);
+ float grain = fbm(vec2(p.x * 60.0, p.y * 1.5 + warp * 4.0), 60.0, 4, 0.5);
+ float fig = sin((p.y * 40.0 + rings * 9.0 + warp * 14.0)) * 0.5 + 0.5;
+ vec3 a = vec3(0.105, 0.052, 0.030), b = vec3(0.19, 0.098, 0.052);
+ vec3 col = mix(a, b, smoothstep(0.1, 0.9, fig * 0.6 + rings * 0.7 + 0.2));
+ col *= 0.8 + grain * 0.45;
+ gl_FragColor = vec4(col * ${dark.toFixed(2)}, 1.0);
+ }`);
+ const rough = bakeTexture(renderer, 512, `
+ void main(){ float g = fbm(vec2(vUv.x * 50.0, vUv.y * 2.0), 50.0, 4, 0.5); float w = fbm(vUv * 4.0, 4.0, 4, 0.5);
+ gl_FragColor = vec4(1.0, clamp(0.2 + g * 0.1 + w * 0.12, 0.05, 1.0), 0.0, 1.0); }`);
+ return { albedo, rough };
+}
+
+// ─── Spines atlas ─────────────────────────────────────────────────────────────
+const SPINE_COLS = ['#141214', '#1b1a1d', '#e9e1d2', '#d8cfbd', '#2a2833', '#7d2c28', '#b98b35', '#20283f', '#233a2d', '#6a4f38', '#3b2f4f', '#a78bfa', '#cf6a2e', '#4d5a64', '#e7d6a9', '#5b1f34', '#0f0f10', '#c9c2b4'];
+const WORDS = ['NIGHT', 'COUNTER', 'SOLAR', 'BLUE', 'HOURS', 'KYOTO', 'TRIO', 'QUARTET', 'SESSIONS', 'SIDE B', 'LIVE AT', 'NOCTURNE', 'RAIN', 'MOOD', 'SHIBUYA', 'DAWN', 'VALVE', 'ECHO', 'SLOW', 'ROOM', 'SUITE', 'STEREO', 'MONO', 'AFTER', 'DUSK', 'TIDE', 'PULSE', 'HUSH', 'NEON', 'CRATE'];
+function spineAtlas(renderer, R) {
+ const cols = 64, W = 2048, H = 1024, sw = W / cols;
+ const c = document.createElement('canvas'); c.width = W; c.height = H;
+ const g = c.getContext('2d');
+ for (let i = 0; i < cols; i++) {
+ const x = i * sw;
+ const col = SPINE_COLS[Math.floor(R() * SPINE_COLS.length)];
+ g.fillStyle = col; g.fillRect(x, 0, sw, H);
+ const light = parseInt(col.slice(1, 3), 16) > 150;
+ const ink = light ? 'rgba(20,16,20,.85)' : R() < 0.3 ? 'rgba(235,190,110,.85)' : 'rgba(240,232,220,.8)';
+ // bands
+ if (R() < 0.5) { g.fillStyle = SPINE_COLS[Math.floor(R() * SPINE_COLS.length)]; const y = R() * H; g.fillRect(x, y, sw, 30 + R() * 160); }
+ if (R() < 0.35) { g.fillStyle = ink; g.fillRect(x + 3, 40 + R() * 40, sw - 6, 3); }
+ // vertical text
+ g.save(); g.translate(x + sw / 2, H - 30 - R() * 80); g.rotate(-Math.PI / 2);
+ g.fillStyle = ink; g.textBaseline = 'middle';
+ g.font = `${R() < 0.5 ? 700 : 400} ${13 + Math.floor(R() * 7)}px "Space Mono", monospace`;
+ const t = `${WORDS[Math.floor(R() * WORDS.length)]} ${R() < 0.5 ? WORDS[Math.floor(R() * WORDS.length)] : ''}`;
+ g.fillText(t, 0, 0);
+ g.font = '400 11px "Space Mono", monospace';
+ g.fillText(`${['LF', 'BN', 'TR', 'ECM', 'NS', 'CTI'][Math.floor(R() * 6)]}-${Math.floor(100 + R() * 900)}`, H * 0.55 + R() * 200, 0);
+ g.restore();
+ // wear
+ g.fillStyle = `rgba(255,255,255,${R() * 0.06})`; g.fillRect(x, 0, 1, H);
+ g.fillStyle = 'rgba(0,0,0,.35)'; g.fillRect(x + sw - 1, 0, 1, H);
+ }
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return { tex: t, cols };
+}
+
+// ─── Neon ─────────────────────────────────────────────────────────────────────
+function neonTexture(text, { font = '"M PLUS Rounded 1c", "Zen Kaku Gothic New", sans-serif', vertical = true, size = 300 } = {}) {
+ const chars = [...text];
+ const W = vertical ? 420 : 1600, H = vertical ? 420 * chars.length + 80 : 420;
+ const c = document.createElement('canvas'); c.width = W; c.height = H;
+ const g = c.getContext('2d');
+ g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.font = `400 ${size}px ${font}`;
+ g.fillStyle = '#fff';
+ g.shadowColor = '#fff'; g.shadowBlur = 6;
+ if (vertical) chars.forEach((ch, i) => g.fillText(ch, W / 2, 40 + 420 * i + 210));
+ else g.fillText(text, W / 2, H / 2);
+ const t = new THREE.CanvasTexture(c);
+ // halo copy
+ const h = document.createElement('canvas'); h.width = W / 4; h.height = H / 4;
+ const hg = h.getContext('2d'); hg.filter = 'blur(10px)'; hg.drawImage(c, 0, 0, W / 4, H / 4); hg.filter = 'blur(4px)'; hg.drawImage(c, 0, 0, W / 4, H / 4);
+ const ht = new THREE.CanvasTexture(h);
+ return { tex: t, halo: ht, aspect: W / H };
+}
+
+// ─── Build ────────────────────────────────────────────────────────────────────
+export function buildRoom(renderer, scene, { covers }) {
+ const R = rng(7);
+ const out = { tubes: [], pendants: [], animated: [] };
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+
+ // Materials
+ const wood = woodTextures(renderer, { dark: 1 });
+ const woodDark = woodTextures(renderer, { dark: 0.55, stretch: 8 });
+ for (const t of [wood.albedo, wood.rough, woodDark.albedo, woodDark.rough]) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = aniso; }
+ const counterTop = new THREE.MeshPhysicalMaterial({ map: wood.albedo, roughnessMap: wood.rough, roughness: 0.55, clearcoat: 1, clearcoatRoughness: 0.06, envMapIntensity: 0.5 });
+ counterTop.map.repeat.set(3, 1);
+ const counterSide = new THREE.MeshStandardMaterial({ map: woodDark.albedo, roughnessMap: woodDark.rough, roughness: 0.9, envMapIntensity: 0.3 });
+ const shelfMat = new THREE.MeshStandardMaterial({ map: woodDark.albedo, roughness: 0.75, envMapIntensity: 0.3, color: 0x9a8a80 });
+ const plasterN = fbmNormal(renderer, { size: 512, scale: 6, octaves: 6, strength: 1.2 });
+ plasterN.wrapS = plasterN.wrapT = THREE.RepeatWrapping; plasterN.repeat.set(6, 3);
+ const wallMat = new THREE.MeshStandardMaterial({ color: 0x1a1220, roughness: 0.95, normalMap: plasterN, normalScale: new THREE.Vector2(0.6, 0.6) });
+ const floorTex = woodTextures(renderer, { dark: 0.4, stretch: 20 });
+ for (const t of [floorTex.albedo, floorTex.rough]) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(6, 2); t.anisotropy = aniso; }
+ const floorMat = new THREE.MeshStandardMaterial({ map: floorTex.albedo, roughnessMap: floorTex.rough, roughness: 1, envMapIntensity: 0.25 });
+ const blackMetal = new THREE.MeshStandardMaterial({ color: 0x0c0b0d, roughness: 0.38, metalness: 0.7, envMapIntensity: 1 });
+ const brass = new THREE.MeshStandardMaterial({ color: 0x8a6a3a, roughness: 0.32, metalness: 1, envMapIntensity: 1.3, side: THREE.DoubleSide });
+ const chrome = new THREE.MeshStandardMaterial({ color: 0xd8d8dc, roughness: 0.14, metalness: 1, envMapIntensity: 1.4 });
+ const leather = new THREE.MeshPhysicalMaterial({ side: THREE.DoubleSide, color: 0x2a1426, roughness: 0.5, sheen: 0.6, sheenColor: new THREE.Color(0x6b4a7a), sheenRoughness: 0.5, clearcoat: 0.25, clearcoatRoughness: 0.4 });
+
+ // ── Back counter (the deck lives here); its top is the reflective plane y = 0
+ const backCounter = new THREE.Group(); scene.add(backCounter);
+ const bc = new THREE.Mesh(new RoundedBoxGeometry(4.6, 0.95, 0.74, 3, 0.012), counterSide);
+ bc.position.set(0, -0.475 - 0.0005, -0.02); bc.receiveShadow = true; backCounter.add(bc);
+ const bcTop = new THREE.Mesh(new THREE.PlaneGeometry(4.6, 0.74), counterTop);
+ bcTop.rotation.x = -Math.PI / 2; bcTop.position.set(0, 0, -0.02); bcTop.receiveShadow = true;
+ backCounter.add(bcTop);
+ out.reflectFloor = bcTop; out.counterTopMat = counterTop;
+
+ // ── Room shell
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(14, 10), floorMat);
+ floor.rotation.x = -Math.PI / 2; floor.position.set(0, FLOOR_Y, 2); floor.receiveShadow = true; scene.add(floor);
+ const back = new THREE.Mesh(new THREE.PlaneGeometry(14, CEIL_Y - FLOOR_Y), wallMat);
+ back.position.set(0, (CEIL_Y + FLOOR_Y) / 2, WALL_Z - 0.36); back.receiveShadow = true; scene.add(back);
+ const ceil = new THREE.Mesh(new THREE.PlaneGeometry(14, 10), new THREE.MeshStandardMaterial({ color: 0x0b0710, roughness: 1 }));
+ ceil.rotation.x = Math.PI / 2; ceil.position.set(0, CEIL_Y, 2); scene.add(ceil);
+ for (const s of [-1, 1]) {
+ const side = new THREE.Mesh(new THREE.PlaneGeometry(10, CEIL_Y - FLOOR_Y), wallMat);
+ side.rotation.y = -s * Math.PI / 2; side.position.set(s * 3.6, (CEIL_Y + FLOOR_Y) / 2, 2); side.receiveShadow = true; scene.add(side);
+ }
+
+ // ── Record wall: two shelving blocks either side of a neon panel
+ const cell = 0.36, rows = 6, y0 = 0.03, board = 0.022, depth = 0.34;
+ const blocks = [{ x0: -2.9, cols: 7, rows }, { x0: 0.38, cols: 7, rows }, { x0: -0.38, cols: 2, rows: 1, cw: 0.38 }];
+ const boards = [];
+ const spines = [];
+ const faceOut = [];
+ for (const blk of blocks) {
+ const w = blk.cols * cell;
+ // shelves & dividers
+ const cw = blk.cw ?? cell, w2 = blk.cols * cw;
+ for (let r = 0; r <= blk.rows; r++) boards.push({ p: [blk.x0 + w2 / 2, y0 + r * cell, WALL_Z - depth / 2], s: [w2 + board, board, depth] });
+ for (let c = 0; c <= blk.cols; c++) boards.push({ p: [blk.x0 + c * cw, y0 + blk.rows * cell / 2, WALL_Z - depth / 2], s: [board, blk.rows * cell + board, depth] });
+ for (let r = 0; r < blk.rows; r++) for (let c = 0; c < blk.cols; c++) {
+ const cx0 = blk.x0 + c * cw + board / 2, cy0 = y0 + r * cell + board / 2, inner = cw - board;
+ const special = R();
+ if (special < 0.12 && covers.length) { faceOut.push({ x: cx0 + inner / 2, y: cy0, cover: covers[faceOut.length % covers.length] }); }
+ let x = cx0 + 0.002;
+ const fill = special < 0.12 ? 0.9 : 0.5 + R() * 0.5;
+ const lean = fill < 0.85;
+ let n = 0;
+ while (x < cx0 + inner * fill) {
+ const th = 0.0032 + R() * R() * 0.007;
+ const h = 0.305 + R() * 0.012;
+ spines.push({ x: x + th / 2, y: cy0, z: WALL_Z - 0.012 - R() * 0.01, th, h, d: 0.305, rot: 0, strip: Math.floor(R() * 64), tint: 0.7 + R() * 0.45 });
+ x += th + 0.0004; n++;
+ }
+ if (lean) { // the last few records lean into the gap
+ const k = Math.min(n, 6 + Math.floor(R() * 8));
+ const ang = (0.12 + R() * 0.28);
+ for (let j = 0; j < k; j++) {
+ const sp = spines[spines.length - k + j];
+ const a = ang * (j + 1) / k;
+ sp.rot = -a;
+ sp.x += Math.sin(a) * sp.h * 0.5 * (j + 1) / k * 0.9;
+ }
+ }
+ }
+ }
+ const boardGeo = new THREE.BoxGeometry(1, 1, 1);
+ const boardsMesh = new THREE.InstancedMesh(boardGeo, shelfMat, boards.length);
+ const m4 = new THREE.Matrix4(), q = new THREE.Quaternion(), e = new THREE.Euler(), v = new THREE.Vector3(), sc = new THREE.Vector3();
+ boards.forEach((b, i) => { m4.compose(v.set(...b.p), q.identity(), sc.set(...b.s)); boardsMesh.setMatrixAt(i, m4); });
+ boardsMesh.castShadow = boardsMesh.receiveShadow = true;
+ scene.add(boardsMesh);
+ // warm LED strips under every shelf lip
+ const ledMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffc080).multiplyScalar(3.2) });
+ out.ledMat = ledMat; out.ledBase = ledMat.color.clone();
+ for (const blk of blocks) for (let r = 1; r <= blk.rows; r++) {
+ const bw = blk.cols * (blk.cw ?? cell);
+ const led = new THREE.Mesh(new THREE.BoxGeometry(bw - 0.01, 0.004, 0.008), ledMat);
+ led.position.set(blk.x0 + bw / 2, y0 + r * cell - board / 2 - 0.003, WALL_Z - 0.012);
+ scene.add(led);
+ }
+ const backPanels = new THREE.Mesh(new THREE.PlaneGeometry(6.4, rows * cell), new THREE.MeshStandardMaterial({ color: 0x0d0a0f, roughness: 1 }));
+ backPanels.position.set(0, y0 + rows * cell / 2, WALL_Z - depth - 0.001); scene.add(backPanels);
+
+ const atlas = spineAtlas(renderer, R);
+ const spineMat = new THREE.MeshStandardMaterial({ map: atlas.tex, roughness: 0.62, metalness: 0, envMapIntensity: 0.35 });
+ out.shelfGlow = { value: 1 };
+ spineMat.onBeforeCompile = sh => {
+ sh.uniforms.uGlow = out.shelfGlow;
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying float vShelfY; uniform float uGlow;')
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ { float fy = fract((vShelfY - ${y0.toFixed(3)}) / ${cell.toFixed(3)});
+ totalEmissiveRadiance += diffuseColor.rgb * vec3(1.0, 0.78, 0.55) * uGlow * (pow(fy, 3.0) * 0.55 + 0.015); }`);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute float aStrip; varying float vShelfY;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\n vShelfY = (modelMatrix * instanceMatrix * vec4(transformed, 1.0)).y;')
+ .replace('#include <uv_vertex>', `#include <uv_vertex>
+ #ifdef USE_MAP
+ vMapUv = vec2((aStrip + uv.x) / ${atlas.cols.toFixed(1)}, uv.y);
+ #endif`);
+ };
+ const spineGeo = new THREE.BoxGeometry(1, 1, 1);
+ const strips = new Float32Array(spines.length);
+ const spineMesh = new THREE.InstancedMesh(spineGeo, spineMat, spines.length);
+ const col = new THREE.Color();
+ spines.forEach((s, i) => {
+ e.set(0, 0, s.rot); q.setFromEuler(e);
+ // pivot leaning records at their bottom-left corner
+ const px = s.x - Math.sin(s.rot) * s.h / 2 * -1, py = s.y + Math.cos(s.rot) * s.h / 2;
+ m4.compose(v.set(px, py, s.z - s.d / 2), q, sc.set(s.th, s.h, s.d));
+ spineMesh.setMatrixAt(i, m4);
+ spineMesh.setColorAt(i, col.setScalar(s.tint));
+ strips[i] = s.strip;
+ });
+ spineGeo.setAttribute('aStrip', new THREE.InstancedBufferAttribute(strips, 1));
+ spineMesh.castShadow = spineMesh.receiveShadow = true;
+ scene.add(spineMesh);
+ out.spineCount = spines.length;
+
+ // face-out covers
+ const sleeveGeo = new THREE.BoxGeometry(0.315, 0.315, 0.004);
+ for (const f of faceOut) {
+ const m = new THREE.Mesh(sleeveGeo, [shelfMat, shelfMat, shelfMat, shelfMat,
+ new THREE.MeshStandardMaterial({ map: f.cover, roughness: 0.55, envMapIntensity: 0.4, emissiveMap: f.cover, emissive: 0x3a2c22 }), shelfMat]);
+ m.position.set(f.x, f.y + 0.158, WALL_Z + 0.004);
+ m.rotation.x = -0.09; m.rotation.z = (R() - 0.5) * 0.03;
+ m.castShadow = m.receiveShadow = true;
+ scene.add(m);
+ }
+
+ // ── Neon panel in the middle: 低周波
+ const panel = new THREE.Mesh(new RoundedBoxGeometry(0.72, rows * cell - 0.4, 0.04, 2, 0.01), new THREE.MeshStandardMaterial({ map: woodDark.albedo, color: 0x5a4a58, roughness: 0.7, envMapIntensity: 0.3 }));
+ panel.position.set(-0.01, y0 + 0.4 + (rows * cell - 0.4) / 2, WALL_Z - depth + 0.03); panel.receiveShadow = true; scene.add(panel);
+ const neon = neonTexture('低周波');
+ const nh = 1.25, nw = nh * neon.aspect;
+ const neonMat = new THREE.MeshBasicMaterial({ map: neon.tex, transparent: true, color: new THREE.Color(0xb49cff).multiplyScalar(5), depthWrite: false, toneMapped: true, fog: false });
+ const neonMesh = new THREE.Mesh(new THREE.PlaneGeometry(nw, nh), neonMat);
+ neonMesh.position.set(-0.01, 1.2, WALL_Z - depth + 0.06);
+ scene.add(neonMesh);
+ const haloMat = new THREE.MeshBasicMaterial({ map: neon.halo, transparent: true, color: new THREE.Color(0x9b7cff).multiplyScalar(1.1), blending: THREE.AdditiveBlending, depthWrite: false, fog: false });
+ const halo = new THREE.Mesh(new THREE.PlaneGeometry(nw * 1.5, nh * 1.18), haloMat);
+ halo.position.copy(neonMesh.position).add(v.set(0, 0, -0.005)); scene.add(halo);
+ const neonLight = new THREE.PointLight(0xa78bfa, 1.4, 3.2, 1.6);
+ neonLight.position.set(0, 1.2, WALL_Z - depth + 0.4); scene.add(neonLight);
+ out.neon = { mat: neonMat, halo: haloMat, light: neonLight, base: neonMat.color.clone(), on: 1 };
+
+ // ── Patron counter + stools
+ const pc = new THREE.Group(); scene.add(pc);
+ const pcTopY = 0.14, pcZ = 1.12;
+ const pcTop = new THREE.Mesh(new RoundedBoxGeometry(6.2, 0.07, 0.62, 3, 0.02), counterTop);
+ pcTop.position.set(0, pcTopY - 0.035, pcZ); pcTop.castShadow = pcTop.receiveShadow = true; pc.add(pcTop);
+ const pcBody = new THREE.Mesh(new THREE.BoxGeometry(6.1, pcTopY - FLOOR_Y - 0.07, 0.42), counterSide);
+ pcBody.position.set(0, (pcTopY - 0.07 + FLOOR_Y) / 2, pcZ - 0.04); pcBody.receiveShadow = true; pc.add(pcBody);
+ const rail = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, 6.1, 16).rotateZ(Math.PI / 2), brass);
+ rail.position.set(0, FLOOR_Y + 0.22, pcZ + 0.3); pc.add(rail);
+ // stools
+ const seatProf = [[0, 0.075], [0.17, 0.075], [0.19, 0.06], [0.195, 0.03], [0.185, 0.0], [0.05, -0.01], [0, -0.01]].map(([x, y]) => new THREE.Vector2(x, y));
+ const baseProf = [[0, 0.02], [0.2, 0.012], [0.21, 0.0], [0, 0]].map(([x, y]) => new THREE.Vector2(x, y));
+ const seatGeo = new THREE.LatheGeometry(seatProf, 48);
+ const postGeo = new THREE.CylinderGeometry(0.022, 0.026, 0.66, 20);
+ const ringGeo = new THREE.TorusGeometry(0.16, 0.009, 10, 48).rotateX(Math.PI / 2);
+ const baseGeo = new THREE.LatheGeometry(baseProf, 48);
+ const N = 12;
+ const iSeat = new THREE.InstancedMesh(seatGeo, leather, N), iPost = new THREE.InstancedMesh(postGeo, chrome, N);
+ const iRing = new THREE.InstancedMesh(ringGeo, chrome, N), iBase = new THREE.InstancedMesh(baseGeo, chrome, N);
+ for (let i = 0; i < N; i++) {
+ const x = -2.75 + i * 0.5, z = pcZ + 0.62;
+ q.setFromEuler(e.set(0, R() * 6, 0));
+ m4.compose(v.set(x, FLOOR_Y + 0.72, z), q, sc.set(1, 1, 1)); iSeat.setMatrixAt(i, m4);
+ m4.compose(v.set(x, FLOOR_Y + 0.38, z), q, sc.set(1, 1, 1)); iPost.setMatrixAt(i, m4);
+ m4.compose(v.set(x, FLOOR_Y + 0.26, z), q, sc.set(1, 1, 1)); iRing.setMatrixAt(i, m4);
+ m4.compose(v.set(x, FLOOR_Y + 0.001, z), q, sc.set(1, 1, 1)); iBase.setMatrixAt(i, m4);
+ }
+ for (const m of [iSeat, iPost, iRing, iBase]) { m.castShadow = m.receiveShadow = true; scene.add(m); }
+ // two glasses and a card on the counter
+ const glassMat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.04, metalness: 0, transparent: true, opacity: 0.22, envMapIntensity: 2.2, clearcoat: 1, depthWrite: false, side: THREE.DoubleSide });
+ const whisky = new THREE.MeshPhysicalMaterial({ color: 0xc46a1a, roughness: 0.1, transparent: true, opacity: 0.72, emissive: 0x3a1500, envMapIntensity: 1.2, depthWrite: false });
+ const glassProf = [[0, 0.0], [0.038, 0.0], [0.04, 0.004], [0.041, 0.085], [0.037, 0.085], [0.036, 0.012], [0, 0.012]].map(([x, y]) => new THREE.Vector2(x, y));
+ for (const [x, z] of [[-0.62, pcZ - 0.05], [0.74, pcZ + 0.06]]) {
+ const gl = new THREE.Mesh(new THREE.LatheGeometry(glassProf, 40), glassMat); gl.position.set(x, pcTopY, z); gl.renderOrder = 3; pc.add(gl);
+ const liq = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, 0.03, 32), whisky); liq.position.set(x, pcTopY + 0.028, z); liq.renderOrder = 2; pc.add(liq);
+ const ice = new THREE.Mesh(new RoundedBoxGeometry(0.04, 0.04, 0.04, 2, 0.008), new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.15, transparent: true, opacity: 0.35, envMapIntensity: 2, depthWrite: false }));
+ ice.position.set(x + 0.005, pcTopY + 0.04, z); ice.rotation.set(0.3, 0.6, 0.2); ice.renderOrder = 3; pc.add(ice);
+ }
+
+ // ── Pendants: one over the deck (the key light), three over the counter
+ const shadeProf = [[0.012, 0.16], [0.03, 0.155], [0.05, 0.1], [0.11, 0.015], [0.115, 0.0], [0.108, 0.0], [0.046, 0.095], [0.026, 0.148], [0.01, 0.152]].map(([x, y]) => new THREE.Vector2(x, y));
+ const shadeGeo = new THREE.LatheGeometry(shadeProf, 64);
+ const bulbMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0xffc27a).multiplyScalar(8), toneMapped: true });
+ const innerGlow = new THREE.MeshBasicMaterial({ map: glowSprite(), color: new THREE.Color(0xffc88a).multiplyScalar(2.2), transparent: true, depthWrite: false });
+ const mkPendant = (x, y, z, scale = 1) => {
+ const g = new THREE.Group();
+ const shade = new THREE.Mesh(shadeGeo, brass); shade.material = brass; shade.scale.setScalar(scale); shade.castShadow = false;
+ const inner = new THREE.Mesh(new THREE.CircleGeometry(0.104 * scale, 48).rotateX(Math.PI / 2), innerGlow);
+ inner.position.y = 0.012 * scale;
+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.028 * scale, 24, 16), bulbMat); bulb.position.y = 0.04 * scale;
+ const cord = new THREE.Mesh(new THREE.CylinderGeometry(0.003, 0.003, CEIL_Y - y, 6), blackMetal); cord.position.y = (CEIL_Y - y) / 2 + 0.15 * scale;
+ g.add(shade, inner, bulb, cord);
+ g.position.set(x, y, z);
+ scene.add(g);
+ out.pendants.push(g);
+ return g;
+ };
+ out.keyPendant = mkPendant(0.03, 1.02, 0.02, 1.15);
+ for (const x of [-1.5, 0, 1.5]) mkPendant(x, 1.05, pcZ, 1);
+ out.pcTopY = pcTopY; out.pcZ = pcZ;
+
+ // ── Valve amplifier (right of the deck)
+ const amp = new THREE.Group();
+ amp.position.set(0.47, 0, -0.06); amp.rotation.y = -0.1;
+ scene.add(amp);
+ const chassis = new THREE.Mesh(new RoundedBoxGeometry(0.32, 0.085, 0.24, 3, 0.006), blackMetal);
+ chassis.position.y = 0.0425 + 0.012; chassis.castShadow = chassis.receiveShadow = true; amp.add(chassis);
+ for (const [fx, fz] of [[-0.14, -0.1], [0.14, -0.1], [-0.14, 0.1], [0.14, 0.1]]) {
+ const foot = new THREE.Mesh(new THREE.CylinderGeometry(0.014, 0.016, 0.012, 20), chrome); foot.position.set(fx, 0.006, fz); amp.add(foot);
+ }
+ const face = new THREE.Mesh(new RoundedBoxGeometry(0.33, 0.09, 0.012, 2, 0.003), new THREE.MeshPhysicalMaterial({ color: 0x8f8d92, metalness: 1, roughness: 0.46, envMapIntensity: 0.7 }));
+ face.position.set(0, 0.057, 0.124); face.castShadow = true; amp.add(face);
+ // VU meter
+ const vuC = document.createElement('canvas'); vuC.width = 256; vuC.height = 128;
+ { const g = vuC.getContext('2d'); const gr = g.createLinearGradient(0, 0, 0, 128); gr.addColorStop(0, '#ffd99a'); gr.addColorStop(1, '#f0a850'); g.fillStyle = gr; g.fillRect(0, 0, 256, 128);
+ g.strokeStyle = '#2a1608'; g.lineWidth = 2; g.beginPath(); g.arc(128, 150, 110, Math.PI * 1.2, Math.PI * 1.8); g.stroke();
+ for (let i = 0; i <= 10; i++) { const a = Math.PI * (1.2 + i * 0.06); g.lineWidth = i > 7 ? 3 : 1.5; g.strokeStyle = i > 7 ? '#a8231a' : '#2a1608'; g.beginPath(); g.moveTo(128 + Math.cos(a) * 110, 150 + Math.sin(a) * 110); g.lineTo(128 + Math.cos(a) * 96, 150 + Math.sin(a) * 96); g.stroke(); }
+ g.fillStyle = '#2a1608'; g.font = '700 18px "Space Mono", monospace'; g.textAlign = 'center'; g.fillText('VU', 128, 105); }
+ const vuTex = new THREE.CanvasTexture(vuC); vuTex.colorSpace = THREE.SRGBColorSpace;
+ const vuMat = new THREE.MeshBasicMaterial({ map: vuTex, color: new THREE.Color(1, 1, 1).multiplyScalar(1.6) });
+ const vu = new THREE.Mesh(new THREE.PlaneGeometry(0.075, 0.0375), vuMat); vu.position.set(-0.06, 0.06, 0.1305); amp.add(vu);
+ const needle = new THREE.Mesh(new THREE.PlaneGeometry(0.0012, 0.03).translate(0, 0.015, 0), new THREE.MeshBasicMaterial({ color: 0x1a0c05 }));
+ needle.position.set(-0.06, 0.0435, 0.131); amp.add(needle);
+ out.vuNeedle = needle;
+ const vuLight = new THREE.PointLight(0xffb060, 0.06, 0.4, 2); vuLight.position.set(-0.06, 0.06, 0.2); amp.add(vuLight);
+ for (const [kx, ks] of [[0.05, 1], [0.11, 0.8]]) {
+ const knob = new THREE.Mesh(new THREE.CylinderGeometry(0.014 * ks, 0.015 * ks, 0.016, 32).rotateX(Math.PI / 2), chrome);
+ knob.position.set(kx, 0.055, 0.137); amp.add(knob);
+ }
+ // transformers
+ for (const tx of [-0.1, 0.08]) {
+ const tr = new THREE.Mesh(new RoundedBoxGeometry(0.075, 0.07, 0.07, 2, 0.006), blackMetal); tr.position.set(tx, 0.097 + 0.035, -0.07); tr.castShadow = true; amp.add(tr);
+ }
+ // valves
+ const glassM = new THREE.MeshPhysicalMaterial({ color: 0x8d8272, roughness: 0.02, metalness: 0, transparent: true, opacity: 0.1, envMapIntensity: 1.3, specularIntensity: 1, depthWrite: false, side: THREE.DoubleSide });
+ const plateM = new THREE.MeshStandardMaterial({ color: 0x3a3a3e, roughness: 0.5, metalness: 0.8 });
+ const getterM = new THREE.MeshStandardMaterial({ color: 0x9a9aa6, roughness: 0.08, metalness: 1, envMapIntensity: 2 });
+ const tube = (x, z, big) => {
+ const r = big ? 0.019 : 0.0115, h = big ? 0.095 : 0.055;
+ const prof = big
+ ? [[0.001, 0], [r * 0.9, 0], [r, h * 0.12], [r * 1.15, h * 0.45], [r, h * 0.8], [r * 0.55, h * 0.97], [0.001, h]]
+ : [[0.001, 0], [r, 0], [r, h * 0.85], [r * 0.8, h * 0.97], [0.001, h]];
+ const g = new THREE.Group(); g.position.set(x, 0.097, z);
+ const socket = new THREE.Mesh(new THREE.CylinderGeometry(r * 1.2, r * 1.3, 0.008, 24), blackMetal); socket.position.y = 0.004; g.add(socket);
+ const glass = new THREE.Mesh(new THREE.LatheGeometry(prof.map(([a, b]) => new THREE.Vector2(a, b + 0.008)), 32), glassM); glass.renderOrder = 4; g.add(glass);
+ const plate = new THREE.Mesh(new THREE.BoxGeometry(r * 1.1, h * 0.45, r * 0.55), plateM); plate.position.y = 0.008 + h * 0.4; g.add(plate);
+ const filMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(0xff7a2a).multiplyScalar(6) });
+ const fil = new THREE.Mesh(new THREE.CylinderGeometry(r * 0.16, r * 0.16, h * 0.34, 8), filMat); fil.position.y = 0.008 + h * 0.4; g.add(fil);
+ const glowMat = new THREE.SpriteMaterial({ map: glowSprite(), color: 0xff7a2a, transparent: true, opacity: 0.4, blending: THREE.AdditiveBlending, depthWrite: false });
+ const glow = new THREE.Sprite(glowMat); glow.scale.setScalar(r * 4.2); glow.position.y = 0.008 + h * 0.38; g.add(glow);
+ const getter = new THREE.Mesh(new THREE.SphereGeometry(r * 0.72, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2), getterM); getter.position.y = 0.008 + h * 0.83; getter.scale.y = 0.5; g.add(getter);
+ amp.add(g);
+ out.tubes.push({ fil: filMat, glow: glowMat, base: filMat.color.clone(), phase: R() * 10 });
+ };
+ for (const tx of [-0.12, -0.06, 0.0, 0.06]) tube(tx, 0.045, false);
+ for (const tx of [-0.02, 0.15]) tube(tx, -0.06, true);
+ const ampLight = new THREE.PointLight(0xff8a3c, 0.25, 1.1, 2); ampLight.position.set(0.47, 0.2, -0.05); scene.add(ampLight);
+ out.ampLight = ampLight;
+
+ // ── Now-playing stand (left of the deck)
+ if (covers[0]) {
+ const stand = new THREE.Group(); stand.position.set(-1.28, 0, -0.16); stand.rotation.y = 0.3; scene.add(stand);
+ const ledge = new THREE.Mesh(new RoundedBoxGeometry(0.34, 0.018, 0.06, 2, 0.004), shelfMat); ledge.position.y = 0.009; ledge.castShadow = ledge.receiveShadow = true; stand.add(ledge);
+ const lip = new THREE.Mesh(new RoundedBoxGeometry(0.34, 0.03, 0.008, 2, 0.003), shelfMat); lip.position.set(0, 0.03, 0.025); stand.add(lip);
+ const sleeve = new THREE.Mesh(sleeveGeo, [shelfMat, shelfMat, shelfMat, shelfMat, new THREE.MeshStandardMaterial({ map: covers[0], roughness: 0.5, envMapIntensity: 0.5 }), shelfMat]);
+ sleeve.position.set(0, 0.018 + 0.155, -0.005); sleeve.rotation.x = -0.2; sleeve.castShadow = sleeve.receiveShadow = true; stand.add(sleeve);
+ const sign = document.createElement('canvas'); sign.width = 512; sign.height = 64;
+ const sg = sign.getContext('2d'); sg.fillStyle = '#f2e9da'; sg.fillRect(0, 0, 512, 64); sg.fillStyle = '#1a1030'; sg.font = '700 30px "Space Mono", monospace'; sg.textAlign = 'center'; sg.textBaseline = 'middle'; sg.fillText('NOW PLAYING', 256, 34);
+ const st = new THREE.CanvasTexture(sign); st.colorSpace = THREE.SRGBColorSpace;
+ const card = new THREE.Mesh(new THREE.PlaneGeometry(0.16, 0.02), new THREE.MeshStandardMaterial({ map: st, roughness: 0.8 }));
+ card.position.set(0, 0.03, 0.0295); stand.add(card);
+ }
+ // a crate of records at the far left of the back counter
+ out.lights = { neonLight, ampLight };
+ return out;
+}
+
+let _glow;
+function glowSprite() {
+ if (_glow) return _glow;
+ const c = document.createElement('canvas'); c.width = c.height = 64;
+ const g = c.getContext('2d'); const gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
+ gr.addColorStop(0, 'rgba(255,255,255,1)'); gr.addColorStop(0.3, 'rgba(255,255,255,.35)'); gr.addColorStop(1, 'rgba(255,255,255,0)');
+ g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
+ _glow = new THREE.CanvasTexture(c);
+ return _glow;
+}
diff --git a/examples/lowfreq/style.css b/examples/lowfreq/style.css
new file mode 100644
index 0000000..d12a013
--- /dev/null
+++ b/examples/lowfreq/style.css
@@ -0,0 +1,268 @@
+:root {
+ --bg: #0a0610;
+ --bg2: #120a1a;
+ --ink: #f2eaf8;
+ --soft: #cfc3db;
+ --muted: #968aa6;
+ --faint: rgba(242, 234, 248, .12);
+ --lav: #a78bfa;
+ --lav2: #c9b8ff;
+ --amber: #ffb45c;
+ --amber2: #ffd49a;
+ --display: 'Syne', 'Helvetica Neue', Arial, sans-serif;
+ --mono: 'Space Mono', ui-monospace, Menlo, monospace;
+ --jp: 'Zen Kaku Gothic New', 'M PLUS Rounded 1c', 'Hiragino Sans', 'Yu Gothic', sans-serif;
+ --gut: clamp(16px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { overflow-x: clip; background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
+body { font: 400 15px/1.65 var(--mono); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+em { font-style: normal; color: var(--amber); }
+.mono { font-family: var(--mono); font-size: 11px; letter-spacing: .14em; text-transform: uppercase; }
+.jp { font-family: var(--jp); }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+.grain { position: fixed; inset: 0; z-index: 40; pointer-events: none; opacity: .075; mix-blend-mode: overlay;
+ background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='220' height='220'><filter id='n'><feTurbulence type='fractalNoise' baseFrequency='.85' numOctaves='3' stitchTiles='stitch'/><feColorMatrix values='0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 1.3 0'/></filter><rect width='100%' height='100%' filter='url(%23n)'/></svg>");
+ background-size: 220px 220px; animation: grain 1.1s steps(6) infinite; }
+@keyframes grain { 0% { background-position: 0 0; } 20% { background-position: -60px 40px; } 40% { background-position: 50px -80px; } 60% { background-position: -90px -40px; } 80% { background-position: 70px 60px; } 100% { background-position: 0 0; } }
+
+/* ── loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: radial-gradient(60% 60% at 50% 45%, #170d22, var(--bg) 70%); display: grid; place-content: center; justify-items: center; gap: 28px; }
+.loader-disc { position: relative; width: 190px; height: 190px; }
+.loader-disc svg { width: 100%; height: 100%; animation: spin 1.8s linear infinite; }
+.ld-body { fill: #0d0a10; stroke: rgba(167,139,250,.25); stroke-width: .6; }
+.ld-grooves circle { fill: none; stroke: rgba(201,184,255,.22); stroke-width: .45; transition: opacity .4s; }
+.ld-label { fill: var(--lav); }
+.ld-hole { fill: var(--bg); }
+.loader-pct { position: absolute; inset: 0; display: grid; place-items: center; font: 800 17px/1 var(--display); color: #140b22; letter-spacing: .02em; font-variant-numeric: tabular-nums; }
+.loader-line { color: var(--muted); }
+.loader-line::after { content: ''; display: inline-block; width: 1.4em; text-align: left; animation: dots 1.4s steps(4) infinite; }
+@keyframes dots { 0% { content: ''; } 25% { content: '.'; } 50% { content: '..'; } 75% { content: '...'; } }
+@keyframes spin { to { transform: rotate(360deg); } }
+
+/* ── nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 24px;
+ padding: 22px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav::before { content: ''; position: absolute; inset: 0 0 -40px; z-index: -1; pointer-events: none; background: linear-gradient(180deg, rgba(10,6,16,.78), rgba(10,6,16,.35) 60%, transparent); }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 700 12px/1 var(--mono); letter-spacing: .3em; text-transform: uppercase; }
+.brand svg { width: 26px; height: 26px; color: var(--lav); animation: spin 1.8s linear infinite; animation-play-state: var(--spin-state, paused); }
+.links { display: flex; gap: 36px; }
+.links a { text-decoration: none; font: 500 14px/1 var(--display); color: var(--soft); letter-spacing: .01em; transition: color .3s; position: relative; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: -6px; height: 1px; background: var(--lav); transform: scaleX(0); transform-origin: right; transition: transform .45s cubic-bezier(.2,.8,.2,1); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after { transform: scaleX(1); transform-origin: left; }
+.nav-right { display: flex; align-items: center; gap: 14px; }
+.sound { display: flex; align-items: center; gap: 10px; height: 40px; padding: 0 16px 0 14px; border-radius: 999px; box-shadow: inset 0 0 0 1px var(--faint); background: rgba(12,8,18,.35); backdrop-filter: blur(10px); }
+.sound-label { color: var(--soft); }
+.eq { display: flex; align-items: flex-end; gap: 2px; height: 12px; }
+.eq i { width: 2px; height: 3px; background: var(--muted); border-radius: 1px; transition: background .3s; }
+.sound[aria-pressed="true"] .eq i { background: var(--amber); animation: eq .9s ease-in-out infinite; }
+.sound[aria-pressed="true"] .eq i:nth-child(2) { animation-delay: -.3s; } .sound[aria-pressed="true"] .eq i:nth-child(3) { animation-delay: -.55s; } .sound[aria-pressed="true"] .eq i:nth-child(4) { animation-delay: -.15s; }
+@keyframes eq { 0%, 100% { height: 3px; } 50% { height: 12px; } }
+
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 12px; height: 46px; padding: 0 24px; border-radius: 999px; text-decoration: none;
+ font: 600 14px/1 var(--display); letter-spacing: .01em; white-space: nowrap; transition: background .35s, color .35s, box-shadow .35s; pointer-events: auto; }
+.btn-ghost { box-shadow: inset 0 0 0 1px rgba(242,234,248,.26); color: var(--ink); background: rgba(12,8,18,.32); backdrop-filter: blur(10px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--lav); color: #fff; }
+.btn-solid { background: var(--amber); color: #1c0f04; }
+.btn-solid:hover { background: var(--amber2); box-shadow: 0 0 44px rgba(255,180,92,.4); }
+.pi { position: relative; width: 12px; height: 12px; display: inline-block; }
+.pi::before { content: ''; position: absolute; inset: 0; background: currentColor; clip-path: polygon(10% 0, 100% 50%, 10% 100%); transition: clip-path .3s; }
+.is-playing .pi::before { clip-path: polygon(0 0, 36% 0, 36% 100%, 0 100%, 0 0, 64% 0, 100% 0, 100% 100%, 64% 100%, 64% 0); }
+
+/* ── sections ───────────────────────────────────────────── */
+main { position: relative; z-index: 2; }
+.sec { position: relative; min-height: 100vh; padding: 17vh var(--gut) 14vh; pointer-events: none; }
+.sec a, .sec button, .sec .tracks li, .sec .sleeve, .sec .tier { pointer-events: auto; }
+.eyebrow { color: var(--lav2); margin-bottom: 22px; display: flex; align-items: center; gap: 10px; }
+.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--amber); box-shadow: 0 0 12px var(--amber); animation: pulse 2s ease-in-out infinite; }
+@keyframes pulse { 50% { opacity: .35; } }
+h2 { font: 800 clamp(38px, 4.4vw, 76px)/.92 var(--display); letter-spacing: -.035em; }
+.lede { max-width: 34em; margin-top: 28px; color: var(--soft); font-size: 14.5px; line-height: 1.75; }
+.col { position: relative; }
+.col-right { margin-left: auto; width: min(560px, 42vw); }
+.col-left { width: min(720px, 50vw); }
+.col::before { content: ''; position: absolute; inset: -12% -18% -12% -18%; z-index: -1; pointer-events: none;
+ background: radial-gradient(closest-side, rgba(10,6,16,.72), rgba(10,6,16,.35) 60%, transparent); filter: blur(10px); }
+
+/* hero */
+.hero { height: 100vh; min-height: 640px; display: grid; align-content: end; padding-bottom: 12vh; }
+.hero-copy { max-width: min(760px, 52vw); position: relative; }
+.hero-copy::before { content: ''; position: absolute; inset: -30% -30% -20% -20%; z-index: -1; pointer-events: none;
+ background: radial-gradient(closest-side, rgba(10,6,16,.6), transparent); }
+.title { font: 800 clamp(56px, 7.2vw, 124px)/.86 var(--display); letter-spacing: -.045em; }
+.title .line { display: block; overflow: hidden; padding-bottom: .04em; }
+.title .line > span { display: inline-block; }
+.sub { max-width: 31em; margin-top: 30px; color: var(--soft); font-size: 14.5px; line-height: 1.75; }
+.hero-cta { display: flex; gap: 14px; margin-top: 36px; flex-wrap: wrap; }
+.vert { position: absolute; right: var(--gut); top: 50%; transform: translateY(-50%); writing-mode: vertical-rl; font-size: 13px; letter-spacing: .6em; color: var(--muted); }
+.hero-meta { position: absolute; top: 104px; right: var(--gut); display: flex; gap: 22px; color: var(--muted); }
+.hero-meta span:first-child { color: var(--lav2); }
+
+/* pressing */
+.pressing { min-height: 125vh; display: grid; align-content: center; padding-top: 12vh; padding-bottom: 8vh; }
+.pressing h2 { font-size: clamp(40px, 4.6vw, 76px); }
+.pressing .lede { margin-top: 18px; }
+.byline { color: var(--muted); margin-top: 18px; line-height: 1.8; }
+.tracks { list-style: none; margin-top: 28px; border-bottom: 1px solid var(--faint); }
+.tracks li { display: grid; grid-template-columns: 38px 42px 1fr auto 52px; align-items: center; gap: 12px; min-height: 54px; border-top: 1px solid var(--faint);
+ padding: 0 10px; transition: background .35s; position: relative; cursor: pointer; }
+.tracks li:hover, .tracks li.hot { background: linear-gradient(90deg, rgba(167,139,250,.12), rgba(167,139,250,0)); }
+.tracks .tn { color: var(--lav2); }
+.tracks .tt { font: 600 19px/1.2 var(--display); letter-spacing: -.01em; }
+.tracks .tb, .tracks .td { color: var(--muted); text-align: right; }
+.cue { width: 34px; height: 34px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(242,234,248,.3); display: grid; place-items: center; transition: box-shadow .3s, background .3s; }
+.cue .ci { width: 9px; height: 10px; background: var(--ink); clip-path: polygon(0 0, 100% 50%, 0 100%); }
+.tracks li:hover .cue { box-shadow: inset 0 0 0 1px var(--lav); }
+.tracks li.on .cue { background: var(--amber); box-shadow: none; }
+.tracks li.on .cue .ci { background: #1c0f04; clip-path: none; width: 10px; height: 10px; background: linear-gradient(90deg, #1c0f04 0 3px, transparent 3px 7px, #1c0f04 7px); }
+.tracks li.on .tt { color: var(--amber2); }
+.tracks li.wait .cue .ci { animation: pulse .7s infinite; }
+.fine { color: var(--muted); margin-top: 18px; line-height: 1.8; font-size: 10px; }
+.buy { display: flex; align-items: center; gap: 18px; margin-top: 34px; flex-wrap: wrap; }
+.buy .price { font: 700 30px/1 var(--display); letter-spacing: -.02em; }
+.stock { color: var(--muted); display: flex; align-items: center; gap: 8px; }
+.stock i { width: 6px; height: 6px; border-radius: 50%; background: #7df0a8; box-shadow: 0 0 10px #7df0a8; }
+
+/* bar */
+.bar { min-height: 160vh; display: grid; align-content: space-between; gap: 10vh; }
+.bar-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; width: min(700px, 50vw); margin-left: auto; }
+.bar-grid article { padding: 26px 24px 28px; border-radius: 3px; background: linear-gradient(180deg, rgba(22,13,30,.72), rgba(12,8,18,.55)); backdrop-filter: blur(14px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px var(--faint); pointer-events: auto; }
+.bar-grid .k { color: var(--lav2); margin-bottom: 18px; }
+.bar-grid .big { font: 800 clamp(26px, 2.5vw, 38px)/1 var(--display); letter-spacing: -.03em; color: var(--amber2); }
+.bar-grid .mid { font: 700 21px/1.15 var(--display); letter-spacing: -.01em; }
+.bar-grid .small { color: var(--muted); font-size: 12.5px; line-height: 1.65; margin-top: 14px; }
+.bar-grid .rule { box-shadow: inset 0 0 0 1px rgba(255,180,92,.45); background: linear-gradient(180deg, rgba(40,20,14,.7), rgba(16,9,14,.55)); }
+.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px; border-top: 1px solid var(--faint); padding-top: 28px; }
+.stats b { display: block; font: 800 clamp(44px, 5vw, 84px)/1 var(--display); letter-spacing: -.04em; }
+.stats span { color: var(--muted); display: block; margin-top: 10px; }
+
+/* catalogue */
+.catalogue { min-height: 175vh; }
+.cat-head { max-width: 640px; position: relative; }
+.cat-head::before { content: ''; position: absolute; inset: -20% -20%; z-index: -1; background: radial-gradient(closest-side, rgba(10,6,16,.7), transparent); }
+.sleeves { display: grid; grid-template-columns: repeat(3, 1fr); gap: clamp(22px, 3.2vw, 56px) clamp(22px, 3vw, 48px); margin-top: 12vh; perspective: 1400px; max-width: 1180px; margin-left: auto; }
+.sleeve { pointer-events: auto; cursor: pointer; }
+.sl-art { position: relative; aspect-ratio: 1; transform-style: preserve-3d; transition: transform .8s cubic-bezier(.2,.8,.2,1); will-change: transform; }
+.sl-cover { position: absolute; inset: 0; background: #1a1220 center/cover no-repeat; border-radius: 2px;
+ box-shadow: 0 30px 60px -20px rgba(0,0,0,.85), 0 0 0 1px rgba(255,255,255,.06), inset 0 0 0 1px rgba(255,255,255,.05); }
+.sl-cover::after { content: ''; position: absolute; inset: 0; border-radius: 2px; pointer-events: none;
+ background: linear-gradient(115deg, rgba(255,255,255,.14), rgba(255,255,255,0) 38%, rgba(0,0,0,0) 60%, rgba(0,0,0,.25)); mix-blend-mode: screen; opacity: var(--glare, .6); }
+.sl-disc { position: absolute; inset: 3%; border-radius: 50%; transition: transform .9s cubic-bezier(.2,.8,.2,1);
+ background: radial-gradient(circle, #0b0a0c 0 3%, var(--lav) 3.3% 30%, #0b0a0c 30.5% 32%, #16141a 32% 33%, #0d0c0f 33% 100%);
+ box-shadow: 0 10px 30px rgba(0,0,0,.6); }
+.sl-disc::before { content: ''; position: absolute; inset: 0; border-radius: 50%; background: repeating-radial-gradient(circle, rgba(255,255,255,.035) 0 1px, transparent 1px 3px); }
+.sl-disc::after { content: ''; position: absolute; inset: 0; border-radius: 50%; background: conic-gradient(from 30deg, transparent 0 40deg, rgba(255,255,255,.16) 55deg, transparent 75deg 220deg, rgba(255,255,255,.12) 235deg, transparent 255deg); }
+.sleeve:hover .sl-disc, .sleeve.peek .sl-disc { transform: translateX(34%) rotate(40deg); }
+.sl-cat { color: var(--lav2); margin-top: 20px; }
+.sleeve h3 { font: 700 23px/1.1 var(--display); letter-spacing: -.02em; margin-top: 8px; }
+.sl-by { color: var(--muted); font-size: 13px; margin-top: 4px; }
+.sl-st { margin-top: 10px; color: var(--soft); font-size: 10px; }
+.sl-st.on { color: var(--amber); }
+.sl-st.off { color: var(--muted); text-decoration: line-through; }
+
+/* club */
+.club { min-height: 130vh; display: grid; align-content: center; gap: 9vh; }
+.tiers { display: grid; grid-template-columns: repeat(3, 1fr); gap: 16px; max-width: 1180px; }
+.tier { padding: 30px 28px 30px; display: grid; gap: 26px; align-content: start; border-radius: 3px; box-shadow: inset 0 0 0 1px var(--faint);
+ background: linear-gradient(180deg, rgba(22,13,30,.76), rgba(12,8,18,.6)); backdrop-filter: blur(14px); }
+.tier-lit { box-shadow: inset 0 0 0 1px rgba(167,139,250,.6); background: radial-gradient(120% 90% at 50% -10%, rgba(167,139,250,.22), rgba(12,8,18,.7) 70%); }
+.tier .k { color: var(--lav2); display: flex; justify-content: space-between; align-items: center; }
+.tag { color: #140b22; background: var(--lav); padding: 4px 8px; border-radius: 99px; font-size: 9px; letter-spacing: .12em; }
+.tier .price { margin-top: 16px; font: 800 44px/1 var(--display); letter-spacing: -.03em; }
+.tier .price span { color: var(--muted); margin-left: 8px; font-weight: 400; letter-spacing: .1em; }
+.tier ul { list-style: none; display: grid; gap: 10px; color: var(--soft); font-size: 13px; }
+.tier li { display: flex; gap: 12px; }
+.tier li::before { content: '◦'; color: var(--amber); }
+.tier .btn { justify-self: start; }
+
+/* visit / footer */
+.visit { min-height: 100vh; display: grid; align-content: end; padding-bottom: 9vh; }
+.visit-inner { position: relative; }
+.visit-inner::before { content: ''; position: absolute; inset: -20% -10% -10%; z-index: -1; background: radial-gradient(70% 70% at 30% 60%, rgba(10,6,16,.75), transparent); }
+.foot-title { font-size: clamp(56px, 9.2vw, 164px) !important; line-height: .86 !important; }
+.foot-cta { display: flex; gap: 14px; margin-top: 40px; flex-wrap: wrap; }
+.foot-cols { display: grid; grid-template-columns: 1fr 1fr .8fr 1.3fr; gap: 32px; margin-top: 10vh; padding-top: 28px; border-top: 1px solid var(--faint); color: var(--muted); line-height: 2; }
+.foot-cols a { text-decoration: none; color: var(--soft); pointer-events: auto; }
+.foot-cols a:hover { color: var(--amber); }
+.colophon { text-transform: none; letter-spacing: .02em; font-size: 11px; line-height: 1.7; }
+
+/* ── projected UI ───────────────────────────────────────── */
+.fx { position: fixed; inset: 0; z-index: 3; overflow: hidden; pointer-events: none; }
+.scratch { pointer-events: auto; position: absolute; left: 0; top: 0; width: 10px; height: 10px; border-radius: 50%; z-index: 3; touch-action: none; display: none; }
+.scratch.on { display: block; }
+.hint { position: absolute; left: 0; top: 0; width: 200px; height: 200px; margin: -100px 0 0 -100px; z-index: 3; pointer-events: none; opacity: 0; transition: opacity .8s; will-change: transform; }
+.hint.on { opacity: 1; }
+.hint svg { width: 100%; height: 100%; overflow: visible; animation: spin 38s linear infinite reverse; }
+.hint text { font: 700 5.2px var(--mono); letter-spacing: .32em; fill: var(--lav2); }
+.hint-chip { position: absolute; left: 0; top: 0; z-index: 4; pointer-events: none; display: flex; align-items: center; gap: 10px; padding: 10px 16px 10px 12px; border-radius: 999px;
+ background: rgba(14,9,20,.66); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(167,139,250,.45); color: var(--ink); opacity: 0; transition: opacity .6s; white-space: nowrap; }
+.hint-chip.on { opacity: 1; }
+.hand { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset 0 0 0 1.5px var(--amber); position: relative; }
+.hand::after { content: ''; position: absolute; inset: 5px; border-radius: 50%; background: var(--amber); animation: press 1.6s ease-in-out infinite; }
+@keyframes press { 0%, 100% { transform: scale(.4); opacity: .5; } 40% { transform: scale(1); opacity: 1; } 70% { transform: scale(1) translateX(3px); } }
+.leader { position: absolute; inset: 0; width: 100vw; height: 100vh; z-index: 3; pointer-events: none; opacity: 0; transition: opacity .5s; }
+.leader.on { opacity: 1; }
+.leader path { fill: none; stroke: var(--lav2); stroke-width: 1.3; stroke-dasharray: 2 5; stroke-linecap: round; filter: drop-shadow(0 0 4px rgba(167,139,250,.8)); }
+.leader circle { fill: var(--amber); }
+
+.player { position: fixed; right: 16px; bottom: 16px; z-index: 35; display: flex; align-items: center; gap: 14px; padding: 6px 8px 6px 6px; border-radius: 999px;
+ background: rgba(14,9,20,.62); backdrop-filter: blur(14px) saturate(1.3); box-shadow: inset 0 0 0 1px rgba(242,234,248,.1); }
+.pp { width: 40px; height: 40px; border-radius: 50%; background: var(--amber); color: #1c0f04; display: grid; place-items: center; }
+.pp .pi { width: 11px; height: 11px; }
+.now { display: grid; gap: 3px; min-width: 190px; }
+.np-k { font-size: 9px; color: var(--muted); }
+.np-t { font: 600 13px/1 var(--display); white-space: nowrap; }
+.rpm { display: flex; border-radius: 999px; box-shadow: inset 0 0 0 1px var(--faint); overflow: hidden; }
+.rpm button { padding: 0 11px; height: 30px; font-size: 10px; letter-spacing: .1em; color: var(--muted); transition: background .3s, color .3s; }
+.rpm button.on { background: rgba(167,139,250,.22); color: var(--ink); }
+.toast { position: fixed; left: 50%; bottom: 84px; transform: translate(-50%, 16px); z-index: 50; padding: 13px 20px; border-radius: 999px;
+ background: rgba(14,9,20,.8); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(167,139,250,.35); color: var(--ink);
+ opacity: 0; transition: opacity .45s, transform .45s; pointer-events: none; text-align: center; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+.noui main, .noui .nav, .noui .player, .noui .fx, .noui .tw-nav, .noui .tw-cursor { visibility: hidden !important; }
+
+@media (max-width: 1100px) {
+ .bar-grid { width: min(700px, 64vw); }
+ .links { gap: 24px; }
+}
+@media (max-width: 760px) {
+ body { font-size: 14px; }
+ .links, .hero-meta, .vert { display: none; }
+ .nav { padding: 16px; }
+ .brand span { display: none; }
+ .nav .btn { display: none; }
+ .sound { height: 38px; padding: 0 12px; }
+ .hero { padding-bottom: 12vh; }
+ .hero-copy::before { inset: -20% -10% -10% -10%; background: linear-gradient(180deg, transparent, rgba(10,6,16,.78) 30%, rgba(10,6,16,.85)); }
+ .hero-copy { max-width: 100%; }
+ .title { font-size: clamp(40px, 11.6vw, 56px); }
+ .sub { font-size: 12.5px; margin-top: 16px; line-height: 1.6; }
+ .hero-cta .btn { height: 42px; padding: 0 18px; font-size: 13px; }
+ .eyebrow { font-size: 9.5px; margin-bottom: 14px; }
+ .hero-cta { margin-top: 22px; }
+ .col-right, .col-left { width: 100%; }
+ .col::before { inset: -22vh -16px -4vh; filter: none; background: linear-gradient(180deg, rgba(10,6,16,0), rgba(10,6,16,.72) 22vh, rgba(10,6,16,.8)); }
+ .pressing { align-content: end; padding-top: 58vh; }
+ .tracks li { grid-template-columns: 36px 34px 1fr 44px; }
+ .tracks .tb { display: none; }
+ .tracks .tt { font-size: 16px; }
+ .bar-grid, .tiers, .stats { grid-template-columns: 1fr; }
+ .bar-grid { width: 100%; }
+ .stats { grid-template-columns: 1fr 1fr; }
+ .sleeves { grid-template-columns: 1fr 1fr; gap: 26px 16px; }
+ .sleeve h3 { font-size: 17px; }
+ .foot-cols { grid-template-columns: 1fr; gap: 18px; }
+ .player { right: 10px; bottom: 10px; gap: 8px; }
+ .now { display: none; }
+ .rpm button { padding: 0 8px; }
+ .hint-chip { font-size: 9px; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .grain, .hint svg, .loader-disc svg { animation: none; }
+}
diff --git a/examples/monolith/diagram.js b/examples/monolith/diagram.js
new file mode 100644
index 0000000..f6644fc
--- /dev/null
+++ b/examples/monolith/diagram.js
@@ -0,0 +1,198 @@
+// The sun-path diagram drawn in 3D around the diorama: horizon ring, compass, three seasonal arcs,
+// hour marks, and the sun itself — the handle the visitor drags.
+import * as THREE from 'three';
+import { DECS } from './sun.js';
+
+const D = Math.PI / 180;
+export const RH = 4.0, RV = 3.1;
+
+function textSprite(text, { size = 0.2, weight = 500, font = '"IBM Plex Mono", ui-monospace, monospace', track = 1 } = {}) {
+ const c = document.createElement('canvas');
+ const g = c.getContext('2d');
+ const px = 64;
+ g.font = `${weight} ${px}px ${font}`;
+ const w = Math.ceil(g.measureText(text).width + text.length * track * 4 + 16);
+ c.width = w; c.height = px + 20;
+ g.font = `${weight} ${px}px ${font}`;
+ g.fillStyle = '#fff'; g.textBaseline = 'middle';
+ if ('letterSpacing' in g) g.letterSpacing = `${track * 4}px`;
+ g.fillText(text, 8, c.height / 2 + 2);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
+ const m = new THREE.SpriteMaterial({ map: t, transparent: true, depthWrite: false, fog: false });
+ const s = new THREE.Sprite(m);
+ s.scale.set(size * c.width / c.height, size, 1);
+ s.userData.baseOpacity = 1;
+ return s;
+}
+
+function radial(stops) {
+ const c = document.createElement('canvas'); c.width = c.height = 128;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ for (const [o, col] of stops) grd.addColorStop(o, col);
+ g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
+}
+function ringTex() {
+ const c = document.createElement('canvas'); c.width = c.height = 256;
+ const g = c.getContext('2d');
+ g.strokeStyle = '#fff'; g.lineWidth = 5;
+ g.beginPath(); g.arc(128, 128, 118, 0, Math.PI * 2); g.stroke();
+ // four grip ticks
+ g.lineWidth = 7;
+ for (let i = 0; i < 4; i++) { const a = i * Math.PI / 2 + Math.PI / 4; g.beginPath(); g.moveTo(128 + Math.cos(a) * 96, 128 + Math.sin(a) * 96); g.lineTo(128 + Math.cos(a) * 110, 128 + Math.sin(a) * 110); g.stroke(); }
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
+}
+
+export function buildDiagram({ scene, center, sunAngles, compassDir, T0, T1 }) {
+ const group = new THREE.Group();
+ group.position.copy(center);
+ scene.add(group);
+ const lineMats = [], hiddenMats = [], sprites = [], accentMats = [];
+ const tmp = new THREE.Vector3();
+
+ const mkLine = (pts, { opacity = 0.5, dashed = false, hidden = 0.22, accent = false, loop = false } = {}) => {
+ const geo = new THREE.BufferGeometry().setFromPoints(pts);
+ const P = dashed ? THREE.LineDashedMaterial : THREE.LineBasicMaterial;
+ const opts = { color: 0x111111, transparent: true, opacity, depthWrite: false, fog: false, ...(dashed ? { dashSize: 0.07, gapSize: 0.09 } : {}) };
+ const m = new P(opts); m.userData.base = opacity;
+ const L = loop ? THREE.LineLoop : THREE.Line;
+ const line = new L(geo, m);
+ if (dashed) line.computeLineDistances();
+ line.renderOrder = 5;
+ group.add(line);
+ (accent ? accentMats : lineMats).push(m);
+ if (hidden > 0) {
+ const hm = new P({ ...opts, depthTest: false, opacity: opacity * hidden }); hm.userData.base = opacity * hidden;
+ const hl = new L(geo, hm); if (dashed) hl.computeLineDistances(); hl.renderOrder = 4;
+ group.add(hl);
+ (accent ? accentMats : hiddenMats).push(hm);
+ }
+ return line;
+ };
+ const pos = (t, dec, out = new THREE.Vector3()) => {
+ const { alt, az } = sunAngles(t, dec);
+ compassDir(az, alt, out);
+ return out.set(out.x * RH, out.y * RV, out.z * RH);
+ };
+
+ // Horizon ring and compass.
+ const ring = [];
+ for (let i = 0; i < 256; i++) { const a = i / 256 * Math.PI * 2; ring.push(new THREE.Vector3(Math.cos(a) * RH, 0, Math.sin(a) * RH)); }
+ mkLine(ring, { opacity: 0.42, loop: true, hidden: 0.3 });
+ const tick = [];
+ for (let d = 0; d < 360; d += 5) {
+ const len = d % 90 === 0 ? 0.36 : d % 30 === 0 ? 0.2 : 0.08;
+ const a = compassDir(d * D, 0, new THREE.Vector3());
+ tick.push(a.clone().multiplyScalar(RH), a.clone().multiplyScalar(RH + len));
+ }
+ {
+ const geo = new THREE.BufferGeometry().setFromPoints(tick);
+ const m = new THREE.LineBasicMaterial({ color: 0x111111, transparent: true, opacity: 0.5, depthWrite: false, fog: false }); m.userData.base = 0.5;
+ const l = new THREE.LineSegments(geo, m); l.renderOrder = 5; group.add(l); lineMats.push(m);
+ }
+ for (const [d, s] of [[0, 'N'], [90, 'E'], [180, 'S'], [270, 'W']]) {
+ const sp = textSprite(s, { size: 0.34, weight: 500, font: '"Inter Tight", Arial, sans-serif', track: 0 });
+ sp.position.copy(compassDir(d * D, 0, new THREE.Vector3()).multiplyScalar(RH - 0.42)).add(new THREE.Vector3(0, 0.02, 0));
+ group.add(sp); sprites.push(sp);
+ }
+ // Facade bearing: the pool terrace faces 240°.
+ {
+ const a = compassDir(240 * D, 0, new THREE.Vector3());
+ mkLine([a.clone().multiplyScalar(2.3), a.clone().multiplyScalar(RH + 0.5)], { opacity: 0.9, hidden: 0, accent: true });
+ const sp = textSprite('240° FACADE', { size: 0.17 });
+ sp.position.copy(a.clone().multiplyScalar(RH + 0.62)).add(new THREE.Vector3(0, 0.16, 0));
+ sp.userData.accent = true;
+ group.add(sp); sprites.push(sp);
+ }
+
+ // Seasonal arcs.
+ const arcAbove = (dec, a, b) => { const pts = []; for (let t = a; t <= b + 1e-6; t += 1 / 30) { const p = pos(t, dec); if (p.y >= -1e-4) pts.push(p); } return pts; };
+ const arcBelow = (dec, a, b) => { const pts = []; for (let t = a; t <= b + 1e-6; t += 1 / 30) pts.push(pos(t, dec)); return pts; };
+ mkLine(arcAbove(DECS.equinox, 4, 23), { opacity: 0.2, hidden: 0.25 });
+ mkLine(arcAbove(DECS.dec, 4, 23), { opacity: 0.16, hidden: 0.25 });
+ // Solstice: solid above the horizon, dashed below (the handle keeps travelling into the night).
+ const sol = arcBelow(DECS.jun, T0, T1);
+ mkLine(sol.filter(p => p.y >= 0), { opacity: 0.62, hidden: 0.25 });
+ const pre = sol.filter((p, i) => p.y < 0 && i < sol.length / 2), post = sol.filter((p, i) => p.y < 0 && i > sol.length / 2);
+ if (pre.length > 1) mkLine(pre, { opacity: 0.38, dashed: true, hidden: 0.2 });
+ if (post.length > 1) mkLine(post, { opacity: 0.38, dashed: true, hidden: 0.2 });
+ // Date labels sit where each path clears 19° in the east, away from the house.
+ for (const [dec, s] of [[DECS.jun, '21 JUN'], [DECS.equinox, '21 MAR · 23 SEP'], [DECS.dec, '21 DEC']]) {
+ let t = 4; while (t < 13 && sunAngles(t, dec).alt < 19 * D) t += 1 / 60;
+ const sp = textSprite(s, { size: 0.15 });
+ const p = pos(t, dec);
+ sp.position.copy(p).add(p.clone().setY(0).normalize().multiplyScalar(0.2)).add(new THREE.Vector3(0, 0.16, 0));
+ sp.userData.baseOpacity = 0.7;
+ group.add(sp); sprites.push(sp);
+ }
+ // Hour marks along the solstice path.
+ const dots = [];
+ for (let h = 6; h <= 22; h++) {
+ const p = pos(h, DECS.jun);
+ dots.push(p.x, p.y, p.z);
+ if (h % 3 === 0) {
+ const sp = textSprite(String(h).padStart(2, '0'), { size: 0.17 });
+ const out = p.clone().setY(0).normalize().multiplyScalar(0.34);
+ sp.position.copy(p).add(out).add(new THREE.Vector3(0, 0.12, 0));
+ sp.userData.baseOpacity = 0.85;
+ group.add(sp); sprites.push(sp);
+ }
+ }
+ const dotGeo = new THREE.BufferGeometry(); dotGeo.setAttribute('position', new THREE.Float32BufferAttribute(dots, 3));
+ const dotMat = new THREE.PointsMaterial({ color: 0x111111, size: 5, sizeAttenuation: false, map: radial([[0, '#fff'], [0.55, '#fff'], [0.7, 'rgba(255,255,255,0)']]), transparent: true, depthWrite: false, fog: false });
+ dotMat.userData.base = 0.9;
+ const dotPts = new THREE.Points(dotGeo, dotMat); dotPts.renderOrder = 6; group.add(dotPts); lineMats.push(dotMat);
+
+ // Altitude / azimuth construction lines from the sun.
+ const dropGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3(), new THREE.Vector3()]);
+ const dropMat = new THREE.LineDashedMaterial({ color: 0xe88c2c, transparent: true, opacity: 0.8, depthWrite: false, depthTest: false, fog: false, dashSize: 0.06, gapSize: 0.06 });
+ const drop = new THREE.LineSegments(dropGeo, dropMat); drop.renderOrder = 7; group.add(drop);
+
+ // The sun handle.
+ const glow = new THREE.Sprite(new THREE.SpriteMaterial({ map: radial([[0, 'rgba(255,255,255,.9)'], [0.18, 'rgba(255,255,255,.35)'], [0.5, 'rgba(255,255,255,.07)'], [1, 'rgba(255,255,255,0)']]),
+ transparent: true, depthWrite: false, depthTest: false, fog: false, blending: THREE.AdditiveBlending }));
+ const core = new THREE.Sprite(new THREE.SpriteMaterial({ map: radial([[0, '#fff'], [0.62, '#fff'], [0.78, 'rgba(255,255,255,0)']]), transparent: true, depthWrite: false, depthTest: false, fog: false }));
+ const grip = new THREE.Sprite(new THREE.SpriteMaterial({ map: ringTex(), transparent: true, depthWrite: false, depthTest: false, fog: false }));
+ glow.renderOrder = 8; core.renderOrder = 10; grip.renderOrder = 9;
+ const handle = new THREE.Group();
+ handle.add(glow, core, grip);
+ group.add(handle);
+
+ const ink = new THREE.Color(), inkDay = new THREE.Color('#161614'), inkNight = new THREE.Color('#e6e6e2'), accent = new THREE.Color('#e88c2c');
+ return {
+ group,
+ handlePos(t, out = new THREE.Vector3()) { return pos(t, DECS.jun, out).add(center); },
+ update({ clockT, altDeg, opacity, ink: inkK, sunColor, t, camera, hot = 0 }) {
+ group.visible = opacity > 0.01;
+ ink.copy(inkDay).lerp(inkNight, inkK);
+ for (const m of lineMats) { m.color.copy(ink); m.opacity = m.userData.base * opacity; }
+ for (const m of hiddenMats) { m.color.copy(ink); m.opacity = m.userData.base * opacity; }
+ for (const m of accentMats) { m.color.copy(accent); m.opacity = m.userData.base * opacity; }
+ for (const s of sprites) {
+ s.material.color.copy(s.userData.accent ? accent : ink);
+ // Labels that would be cropped by the viewport edge fade out instead.
+ tmp.copy(s.position).add(group.position).project(camera);
+ const edge = (1 - THREE.MathUtils.smoothstep(Math.abs(tmp.x), 0.84, 0.95)) * (1 - THREE.MathUtils.smoothstep(Math.abs(tmp.y), 0.84, 0.96));
+ s.material.opacity = s.userData.baseOpacity * opacity * opacity * edge;
+ }
+ const p = pos(clockT, DECS.jun, tmp);
+ handle.position.copy(p);
+ const up = THREE.MathUtils.smoothstep(altDeg, -3, 1);
+ const pulse = 1 + Math.sin(t * 2.4) * 0.06;
+ core.scale.setScalar(0.34 + up * 0.08);
+ core.material.color.copy(accent).multiplyScalar(0.55 + up * 0.75).lerp(ink, (1 - up) * 0.6);
+ core.material.opacity = Math.max(opacity, 0.35);
+ glow.scale.setScalar((1.7 + up * 1.4) * pulse);
+ glow.material.color.copy(sunColor).lerp(accent, 0.5).multiplyScalar(0.75 * up);
+ glow.material.opacity = Math.max(opacity, 0.35);
+ grip.scale.setScalar((0.82 + hot * 0.2) * (1 + Math.sin(t * 2.4 + 1) * 0.04));
+ grip.material.color.copy(ink);
+ grip.material.opacity = Math.max(opacity, 0.35) * 0.75;
+ const a = dropGeo.attributes.position;
+ a.setXYZ(0, p.x, p.y, p.z); a.setXYZ(1, p.x, 0, p.z); a.setXYZ(2, 0, 0, 0); a.setXYZ(3, p.x, 0, p.z);
+ a.needsUpdate = true; drop.computeLineDistances();
+ dropMat.opacity = 0.85 * opacity;
+ },
+ };
+}
diff --git a/examples/monolith/index.html b/examples/monolith/index.html
new file mode 100644
index 0000000..9b5f21e
--- /dev/null
+++ b/examples/monolith/index.html
@@ -0,0 +1,234 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Monolith — Houses that answer to the sun</title>
+ <meta name="description" content="Monolith Arquitetos, Lisbon and Oslo. Houses for cliffs, fjords and fault lines, drawn from the sun's path first.">
+ <meta name="theme-color" content="#ecebe6">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Serif:ital,wght@1,300;1,400&family=Inter+Tight:wght@300;400;500;600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <svg class="loader-dial" viewBox="0 0 240 132" aria-hidden="true">
+ <path class="loader-arc" d="M10 120 A110 110 0 0 1 230 120" />
+ <line x1="0" y1="120" x2="240" y2="120" class="loader-horizon" />
+ <g class="loader-ticks"></g>
+ <circle class="loader-sun" r="5" cx="10" cy="120" />
+ </svg>
+ <p class="loader-line"><span class="loader-label">Plotting the sun path</span><span class="loader-pct">00</span></p>
+ <p class="loader-meta mono">Cabo Espichel · 38°25′N 9°13′W · 21 June</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Monolith home">
+ <i class="brand-mark" aria-hidden="true"></i><span>Monolith</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#works"><span class="mono">01</span>Works</a>
+ <a href="#cliff"><span class="mono">02</span>The cliff house</a>
+ <a href="#principles"><span class="mono">03</span>Principles</a>
+ <a href="#studio"><span class="mono">04</span>Studio</a>
+ </nav>
+ <a class="btn btn-line" href="#contact" data-magnetic>Commission a house <span aria-hidden="true">→</span></a>
+ </header>
+
+ <!-- Sun HUD: always present, it is the page's main control -->
+ <div class="sun-tag" aria-hidden="true"><span class="sun-tag-time">18:52</span><span class="sun-tag-hint">Drag the sun</span></div>
+ <div class="hud" aria-label="Time of day">
+ <div class="hud-read">
+ <p class="hud-time" aria-live="off">18:52</p>
+ <p class="hud-meta mono"><span class="hud-phase">Afternoon</span><span>Az <b class="hud-az">283°</b></span><span>Alt <b class="hud-alt">21°</b></span><span class="hud-shw">Shadow <b class="hud-sh">×0.4</b></span></p>
+ </div>
+ <button class="play" type="button" aria-label="Play the whole day" data-cursor="label" data-cursor-label="Play"><svg viewBox="0 0 16 16" aria-hidden="true"><path class="i-play" d="M5 3.5v9l7.5-4.5z"/><path class="i-pause" d="M4.5 3.5h2.5v9H4.5zM9 3.5h2.5v9H9z"/></svg><span class="mono">Play the day</span></button>
+ <div class="daybar" role="slider" tabindex="0" aria-label="Time of day on 21 June" aria-valuemin="5.5" aria-valuemax="22.75" aria-valuenow="18.9" aria-valuetext="18:52">
+ <div class="daybar-sky"></div>
+ <div class="daybar-ticks"></div>
+ <div class="daybar-knob"><i></i></div>
+ </div>
+ </div>
+
+ <main id="top">
+ <!-- 00 · Hero -->
+ <section class="hero" data-k="hero">
+ <div class="grid">
+ <p class="hero-meta mono col-a">Monolith Arquitetos<br>Lisboa — Oslo<br>Est. 2011</p>
+ <p class="hero-meta mono col-b">Houses for cliffs, fjords<br>and fault lines</p>
+ <h1 class="hero-title">
+ <span class="line"><span>Houses that</span></span>
+ <span class="line"><span>answer <em>to the sun.</em></span></span>
+ </h1>
+ <p class="hero-sub">Before we draw a wall, we draw the sun's path over the site — every hour of the longest day. This is Casa do Penhasco, forty metres above the Atlantic. Take the sun and move it.</p>
+ </div>
+ <p class="scroll-cue mono" aria-hidden="true"><i></i>Scroll — noon until dark</p>
+ </section>
+
+ <!-- 01 · Works -->
+ <section class="works" id="works" data-k="works">
+ <div class="grid">
+ <header class="sec-head">
+ <p class="mono sec-num">01 — Selected works</p>
+ <h2>Five houses, <em>five kinds of light.</em></h2>
+ </header>
+ <ol class="work-list">
+ <li class="work" data-img="" data-self>
+ <span class="w-num mono">01</span>
+ <span class="w-name">Casa do Penhasco</span>
+ <span class="w-place">Cabo Espichel, PT</span>
+ <span class="w-light mono"><span class="wl-a">Built for 19:41, 21 June</span><span class="wl-b">On screen now — scroll for the study →</span></span>
+ <span class="w-year mono">2024</span>
+ </li>
+ <li class="work" data-img="stal">
+ <span class="w-num mono">02</span>
+ <span class="w-name">Hytte Stål</span>
+ <span class="w-place">Lofoten, NO</span>
+ <span class="w-light mono">Built for the midnight sun</span>
+ <span class="w-year mono">2023</span>
+ </li>
+ <li class="work" data-img="mertola">
+ <span class="w-num mono">03</span>
+ <span class="w-name">Casa Mértola</span>
+ <span class="w-place">Alentejo, PT</span>
+ <span class="w-light mono">Built against 44 °C noon</span>
+ <span class="w-year mono">2022</span>
+ </li>
+ <li class="work" data-img="ulvik">
+ <span class="w-num mono">04</span>
+ <span class="w-name">Fjordvilla Ulvik</span>
+ <span class="w-place">Hardanger, NO</span>
+ <span class="w-light mono">Built for four hours of winter sun</span>
+ <span class="w-year mono">2021</span>
+ </li>
+ <li class="work" data-img="lajes">
+ <span class="w-num mono">05</span>
+ <span class="w-name">Casa Lajes</span>
+ <span class="w-place">Pico, Azores, PT</span>
+ <span class="w-light mono">Built for the blue hour</span>
+ <span class="w-year mono">2019</span>
+ </li>
+ </ol>
+ <p class="works-note mono">Hover a project · 38 houses built since 2011, none of them on flat ground</p>
+ </div>
+ <figure class="work-reveal" aria-hidden="true"><div class="work-reveal-in"></div><figcaption class="mono"></figcaption></figure>
+ </section>
+
+ <!-- 02 · The cliff house -->
+ <section class="cliff" id="cliff">
+ <div class="cliff-intro" data-k="cliffIntro">
+ <div class="grid">
+ <header class="sec-head">
+ <p class="mono sec-num">02 — Case study</p>
+ <h2>The house <em>on the cliff.</em></h2>
+ </header>
+ <dl class="facts">
+ <div><dt class="mono">Site</dt><dd>Limestone shelf, 42 m above the Atlantic</dd></div>
+ <div><dt class="mono">Area</dt><dd>310 m² on two floors</dd></div>
+ <div><dt class="mono">Structure</dt><dd>Two walls, one 6.4 m cantilever</dd></div>
+ <div><dt class="mono">Completed</dt><dd>Spring 2024, after 31 months</dd></div>
+ </dl>
+ </div>
+ </div>
+
+ <article class="step step-plan" data-k="plan">
+ <div class="step-card">
+ <p class="mono step-num">A — Plan, 1:200</p>
+ <h3>One bar, laid <em>along the contour.</em></h3>
+ <p>The buildable shelf is eleven metres deep. We put the whole programme on it as a single bar, turned eleven degrees off the cliff edge so the living floor faces 240° — the bearing of the last light on the longest day.</p>
+ <p class="step-note mono">Roof lifted off at +38.10 · Sun at 17:18, 41° above the sea</p>
+ </div>
+ </article>
+
+ <article class="step step-section" data-k="section">
+ <div class="step-card">
+ <p class="mono step-num">B — Section A–A</p>
+ <h3>Two slabs <em>and a promise.</em></h3>
+ <p>The upper floor bears on two concrete walls pinned nine metres into the rock. The lower slab cantilevers 6.4 metres toward the sea and carries the pool like a tray. Nothing touches the cliff face that doesn't have to.</p>
+ <p class="step-note mono">Cut through the pool and living room · looking north-east</p>
+ </div>
+ </article>
+
+ <article class="step step-detail" data-k="detail">
+ <div class="step-card">
+ <p class="mono step-num">C — Detail, 19:18</p>
+ <h3>Where the water <em>meets the air.</em></h3>
+ <p>The pool's west wall is a single pane of 19 mm laminated glass, set flush with a 6 mm overflow. At golden hour the water keeps the sun for eleven minutes after it has left the terrace.</p>
+ <p class="step-note mono">Golden hour · sun at 291°, 11° above the sea</p>
+ </div>
+ </article>
+ </section>
+
+ <!-- 03 · Principles -->
+ <section class="principles" id="principles" data-k="principles">
+ <div class="grid">
+ <header class="sec-head">
+ <p class="mono sec-num">03 — Principles</p>
+ <h2>Four rules we haven't <em>broken since 2011.</em></h2>
+ </header>
+ <ol class="rules">
+ <li><span class="r-num">01</span><div><h3>Orientation before form.</h3><p>We plot the sun over the site for a full year before a single wall is drawn. The plan follows the light — never the other way round.</p></div></li>
+ <li><span class="r-num">02</span><div><h3>One material, honestly.</h3><p>Board-marked concrete poured against Portuguese pine. It takes the grain of the wood, the colour of the local aggregate and, over decades, the weather. We don't paint it.</p></div></li>
+ <li><span class="r-num">03</span><div><h3>Shadow is a material.</h3><p>A deep overhang does more than any glass coating. We design the shadows first: where they fall at noon in July, how far they reach at four in December.</p></div></li>
+ <li><span class="r-num">04</span><div><h3>Touch the ground lightly.</h3><p>Extreme sites are fragile sites. We stand on as few points as possible, rebuild with the rock we excavate, and leave the cliff looking as if we were never there.</p></div></li>
+ </ol>
+ </div>
+ </section>
+
+ <!-- 04 · Studio -->
+ <section class="studio" id="studio" data-k="studio">
+ <div class="grid">
+ <header class="sec-head">
+ <p class="mono sec-num">04 — Studio</p>
+ <h2>Two studios, <em>2,750 km of daylight apart.</em></h2>
+ </header>
+ <p class="studio-lede">Lisbon gets 2,800 hours of sun a year. Oslo gets 1,670 — and a June night that never quite gets dark. We work across both, so every house is argued over by people who treat daylight very differently.</p>
+ <figure class="studio-img"><img src="/img/monolith/studio.webp" alt="Concrete massing models on an oak table in the Lisbon studio, crossed by a shaft of late sun" loading="lazy"><figcaption class="mono">Lisbon studio, Rua das Janelas Verdes — 17:20</figcaption></figure>
+ <div class="stats">
+ <div><b>38</b><span class="mono">houses built</span></div>
+ <div><b>14</b><span class="mono">architects &amp; engineers</span></div>
+ <div><b>2</b><span class="mono">studios, one drawing set</span></div>
+ <div><b>0</b><span class="mono">flat sites</span></div>
+ </div>
+ <ul class="awards">
+ <li><span class="mono">2024</span><span>Casa do Penhasco</span><span>European Prize for Coastal Architecture — Shortlist</span></li>
+ <li><span class="mono">2023</span><span>Hytte Stål</span><span>Nordic Daylight Award — Winner</span></li>
+ <li><span class="mono">2022</span><span>Casa Mértola</span><span>Prémio Luz de Arquitetura — Winner</span></li>
+ <li><span class="mono">2021</span><span>Fjordvilla Ulvik</span><span>International Concrete Design Awards — Commendation</span></li>
+ <li><span class="mono">2019</span><span>Casa Lajes</span><span>Atlantic Houses Biennale — Selected</span></li>
+ </ul>
+ </div>
+ </section>
+
+ <!-- 05 · Contact -->
+ <section class="contact" id="contact" data-k="contact">
+ <div class="grid">
+ <p class="mono sec-num">05 — Commissions</p>
+ <h2 class="contact-title">Tell us where the sun <em>rises on your site.</em></h2>
+ <p class="contact-lede">Coordinates are enough to begin. Send us a pin and we'll send back a sun study of your land — every hour, every season — before we ever talk about a house.</p>
+ <div class="contact-cta">
+ <a class="btn btn-solid" href="mailto:[email protected]?subject=A%20site%20for%20a%20house" data-magnetic>Send us a pin <span aria-hidden="true">→</span></a>
+ <a class="btn btn-line" href="mailto:[email protected]" data-magnetic>[email protected]</a>
+ </div>
+ </div>
+ </section>
+
+ <footer class="foot" data-k="footer">
+ <div class="grid">
+ <div class="foot-office"><p class="mono">Lisboa</p><p>Rua das Janelas Verdes 38<br>1200-691 Lisboa</p><p class="mono foot-clock" data-off="0">—</p></div>
+ <div class="foot-office"><p class="mono">Oslo</p><p>Tollbugata 24<br>0152 Oslo</p><p class="mono foot-clock" data-off="1">—</p></div>
+ <nav class="foot-links" aria-label="Footer"><a href="#works">Works</a><a href="#principles">Principles</a><a href="#studio">Journal</a><a href="#contact">Careers</a><a href="#contact">Press kit</a></nav>
+ <p class="foot-mark">Monolith</p>
+ <p class="foot-legal mono">© 2026 Monolith Arquitetos Lda. · Time shown is the sun's, not yours.</p>
+ </div>
+ </footer>
+ </main>
+
+ <div class="anchors" aria-hidden="true"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/monolith/main.js b/examples/monolith/main.js
new file mode 100644
index 0000000..3db2086
--- /dev/null
+++ b/examples/monolith/main.js
@@ -0,0 +1,688 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp } from '../../src/core/engine.js';
+import { Assets, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { sunAngles, compassDir, palette, makePalette, phaseName, fmtTime, T0, T1, SUNRISE, SUNSET } from './sun.js';
+import { concreteTextures, floorTexture, patchModel, sectionOutline, GoldenGrade } from './materials.js';
+import { buildDiagram } from './diagram.js';
+
+const D = Math.PI / 180;
+const Q = new URLSearchParams(location.search);
+const IS_TOUCH = matchMedia('(pointer: coarse)').matches;
+const root = document.documentElement;
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let grade;
+const engine = new Engine({
+ canvas, fov: 26, near: 0.1, far: 600, dpr: 1.75, background: 0xecebe6,
+ post: {
+ ao: { aoRadius: 0.55, intensity: 1.7, distanceFalloff: 0.9 },
+ bloom: { intensity: 0.75, luminanceThreshold: 2.0, luminanceSmoothing: 0.3, radius: 0.74 },
+ tone: 'neutral',
+ extra: () => [(grade = new GoldenGrade())],
+ vignette: { offset: 0.45, darkness: 0.2 },
+ noise: 0.03,
+ ca: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.localClippingEnabled = true;
+scene.fog = new THREE.Fog(0xecebe6, 40, 170);
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 8 });
+
+// ─── Loader ────────────────────────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+{
+ const g = loaderEl.querySelector('.loader-ticks');
+ for (let i = 0; i <= 12; i++) {
+ const a = Math.PI - (i / 12) * Math.PI, r0 = 110, r1 = i % 3 ? 104 : 100;
+ g.insertAdjacentHTML('beforeend', `<line x1="${120 + Math.cos(a) * r0}" y1="${120 - Math.sin(a) * r0}" x2="${120 + Math.cos(a) * r1}" y2="${120 - Math.sin(a) * r1}"/>`);
+ }
+}
+const loaderSun = loaderEl.querySelector('.loader-sun');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = String(Math.round(v * 100)).padStart(2, '0') + '%';
+ const a = Math.PI - v * Math.PI * 0.5;
+ loaderSun.setAttribute('cx', (120 + Math.cos(a) * 110).toFixed(1));
+ loaderSun.setAttribute('cy', (120 - Math.sin(a) * 110).toFixed(1));
+ },
+ exit: () => gsap.to(loaderEl, { autoAlpha: 0, duration: 1.1, ease: 'power2.inOut' }),
+});
+
+// ─── Sky ───────────────────────────────────────────────────────────────────────
+const skyUniforms = {
+ uZen: { value: new THREE.Color() }, uHor: { value: new THREE.Color() }, uGround: { value: new THREE.Color() }, uBounce: { value: new THREE.Color() },
+ uSunCol: { value: new THREE.Color() }, uSunDir: { value: new THREE.Vector3(0, 1, 0) }, uSunI: { value: 0 }, uGlow: { value: 0 },
+ uMoonDir: { value: new THREE.Vector3() }, uMoon: { value: 0 }, uGain: { value: 1 }, uBelt: { value: 0 },
+};
+const SKY_VS = 'varying vec3 vDir; void main(){ vDir = position; vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.); gl_Position = p.xyww; }';
+const SKY_FS = `
+ uniform vec3 uZen, uHor, uGround, uBounce, uSunCol, uSunDir, uMoonDir; uniform float uSunI, uGlow, uMoon, uGain, uBelt; varying vec3 vDir;
+ void main(){
+ vec3 d = normalize(vDir);
+ float h = d.y;
+ vec3 col = mix(uHor, uZen, pow(clamp(h, 0., 1.), 0.42));
+ float cs = max(dot(d, uSunDir), 0.);
+ float hz = exp(-abs(h) * 5.0);
+ col += uSunCol * (pow(cs, 5.) * 0.42 * hz + pow(cs, 48.) * 0.3 + pow(max(dot(d, uSunDir) * 0.5 + 0.5, 0.), 3.) * 0.16 * hz) * uGlow;
+ // Belt of Venus: a pink band opposite the low sun, with the earth's blue shadow beneath it.
+ vec3 sflat = normalize(vec3(uSunDir.x, 0.0, uSunDir.z) + 1e-5);
+ float anti = 0.5 + 0.5 * dot(normalize(vec3(d.x, 0.0, d.z) + 1e-5), -sflat);
+ float band = smoothstep(0.015, 0.07, h) * (1.0 - smoothstep(0.09, 0.3, h));
+ col = mix(col, vec3(0.96, 0.64, 0.55) * (0.55 + 0.45 * length(uHor)), band * anti * uBelt * 0.18);
+ col = mix(col, uZen * 0.9, (1.0 - smoothstep(0.0, 0.035, h)) * smoothstep(-0.01, 0.0, h) * anti * uBelt * 0.2);
+ float cm = max(dot(d, uMoonDir), 0.);
+ col += vec3(0.5, 0.6, 0.9) * pow(cm, 90.) * 0.06 * uMoon;
+ #ifdef ENV
+ col = mix(col, uBounce, 1.0 - smoothstep(-0.14, 0.03, h));
+ col += uSunCol * uSunI * smoothstep(0.9993, 0.9998, cs) * 14.;
+ #else
+ col = mix(col, uGround, 1.0 - smoothstep(-0.03, 0.06, h));
+ col *= uGain;
+ #endif
+ gl_FragColor = vec4(col, 1.);
+ }`;
+const sky = new THREE.Mesh(new THREE.SphereGeometry(300, 64, 32),
+ new THREE.ShaderMaterial({ uniforms: skyUniforms, vertexShader: SKY_VS, fragmentShader: SKY_FS, side: THREE.BackSide, depthWrite: false, fog: false }));
+sky.renderOrder = -10;
+sky.frustumCulled = false;
+scene.add(sky);
+
+// Environment lighting re-baked from the same sky whenever the sun moves.
+const envScene = new THREE.Scene();
+envScene.add(new THREE.Mesh(new THREE.SphereGeometry(10, 48, 24),
+ new THREE.ShaderMaterial({ uniforms: skyUniforms, vertexShader: SKY_VS.replace('p.xyww', 'p'), fragmentShader: SKY_FS, side: THREE.BackSide, depthWrite: false, defines: { ENV: 1 } })));
+const cubeRT = new THREE.WebGLCubeRenderTarget(64, { type: THREE.HalfFloatType });
+const cubeCam = new THREE.CubeCamera(0.1, 50, cubeRT);
+const pmrem = new THREE.PMREMGenerator(renderer);
+let envRT = null;
+function bakeEnv() {
+ cubeCam.update(renderer, envScene);
+ envRT = pmrem.fromCubemap(cubeRT.texture, envRT);
+ scene.environment = envRT.texture;
+}
+
+// Stars, only after dark.
+const stars = (() => {
+ const N = 7000, pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const u = Math.random(), v = Math.random() * 0.96 + 0.04;
+ const th = u * Math.PI * 2, y = Math.pow(v, 1.9);
+ const r = Math.sqrt(1 - y * y);
+ pos.set([Math.cos(th) * r * 280, y * 280, Math.sin(th) * r * 280], i * 3);
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, fog: false,
+ uniforms: { uA: { value: 0 }, uT: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: `attribute float seed; uniform float uT, uDpr; varying float vA;
+ void main(){ vec4 mv = modelViewMatrix * vec4(position, 1.); gl_Position = projectionMatrix * mv;
+ float big = step(0.985, seed); float tw = 0.65 + 0.35 * sin(uT * (1.2 + seed * 3.) + seed * 60.);
+ vA = (0.35 + 0.65 * pow(fract(seed * 13.7), 2.)) * tw * (1. + big * 2.5) * smoothstep(0.0, 0.06, position.y / 280.);
+ gl_PointSize = (1.1 + big * 1.6 + fract(seed * 7.1)) * uDpr; }`,
+ fragmentShader: `uniform float uA; varying float vA; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .1, d);
+ gl_FragColor = vec4(vec3(0.85, 0.9, 1.0) * a * vA * uA * 2.2, 1.); }`,
+ });
+ const p = new THREE.Points(geo, mat);
+ p.frustumCulled = false; p.renderOrder = -9;
+ scene.add(p);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ return mat;
+})();
+
+// Moon: a small disc in the south-east sky with a soft halo.
+const MOON_DIR = compassDir(128 * D, 24 * D, new THREE.Vector3());
+const MOON_COL = new THREE.Color(0.55, 0.66, 1);
+function discTexture(inner, outer, soft = false) {
+ const c = document.createElement('canvas'); c.width = c.height = 128;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(64, 64, 0, 64, 64, 64);
+ if (soft) { grd.addColorStop(0, 'rgba(255,255,255,1)'); grd.addColorStop(inner, 'rgba(255,255,255,.35)'); grd.addColorStop(outer, 'rgba(255,255,255,.06)'); grd.addColorStop(1, 'rgba(255,255,255,0)'); }
+ else { grd.addColorStop(0, '#fff'); grd.addColorStop(inner, '#fff'); grd.addColorStop(outer, 'rgba(255,255,255,0)'); grd.addColorStop(1, 'rgba(255,255,255,0)'); }
+ g.fillStyle = grd; g.fillRect(0, 0, 128, 128);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; return t;
+}
+const moon = new THREE.Sprite(new THREE.SpriteMaterial({ map: discTexture(0.42, 0.5), color: new THREE.Color(2.2, 2.3, 2.6), transparent: true, depthWrite: false, fog: false }));
+moon.scale.setScalar(5.2);
+moon.position.copy(MOON_DIR).multiplyScalar(250);
+const moonHalo = new THREE.Sprite(new THREE.SpriteMaterial({ map: discTexture(0.08, 0.35, true), color: new THREE.Color(0.35, 0.42, 0.7), transparent: true, depthWrite: false, fog: false, blending: THREE.AdditiveBlending }));
+moonHalo.scale.setScalar(46);
+moonHalo.position.copy(moon.position);
+moon.renderOrder = moonHalo.renderOrder = -8;
+scene.add(moon, moonHalo);
+
+// ─── Light ─────────────────────────────────────────────────────────────────────
+const sun = new THREE.DirectionalLight(0xffffff, 3);
+sun.castShadow = true;
+sun.shadow.mapSize.set(4096, 4096);
+const SH = 4.6;
+Object.assign(sun.shadow.camera, { left: -SH, right: SH, top: SH, bottom: -SH, near: 0.5, far: 110 });
+sun.shadow.bias = -0.00012;
+sun.shadow.normalBias = 0.018;
+sun.shadow.radius = 2;
+sun.shadow.autoUpdate = false;
+scene.add(sun, sun.target);
+
+// ─── Plinth & floor ────────────────────────────────────────────────────────────
+const PH = 1.25; // plinth height; its top is y = 0, the floor is y = -PH
+const conc = concreteTextures(renderer);
+const plinthMat = new THREE.MeshStandardMaterial({ map: conc.map, normalMap: conc.normal, roughnessMap: conc.rough, roughness: 1, metalness: 0,
+ normalScale: new THREE.Vector2(1, 1), envMapIntensity: 1 });
+const floorMat = new THREE.MeshStandardMaterial({ color: '#dedad2', map: floorTexture(renderer), roughness: 0.6, metalness: 0, envMapIntensity: 1.35 });
+floorMat.map.repeat.set(26, 26);
+const floor = new THREE.Mesh(new THREE.CircleGeometry(290, 96), floorMat);
+floor.rotation.x = -Math.PI / 2;
+floor.position.y = -PH;
+floor.receiveShadow = true;
+scene.add(floor);
+
+function worldUVBox(w, h, d, tile) {
+ const g = new THREE.BoxGeometry(w, h, d);
+ const p = g.attributes.position, n = g.attributes.normal, uv = g.attributes.uv;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), y = p.getY(i) + h / 2, z = p.getZ(i);
+ const nx = Math.abs(n.getX(i)), ny = Math.abs(n.getY(i));
+ if (nx > 0.5) uv.setXY(i, z / tile, y / tile);
+ else if (ny > 0.5) uv.setXY(i, x / tile, z / tile);
+ else uv.setXY(i, x / tile, y / tile);
+ }
+ return g;
+}
+
+// ─── Night lights ──────────────────────────────────────────────────────────────
+const warmA = new THREE.PointLight(0xffb06a, 0, 5.5, 2);
+const warmB = new THREE.PointLight(0xffa860, 0, 5, 2);
+const poolLight = new THREE.PointLight(0x39d8ff, 0, 3.6, 2);
+scene.add(warmA, warmB, poolLight);
+
+// ─── Palette state ─────────────────────────────────────────────────────────────
+const pal = makePalette();
+const U = patchModel.uniforms; // shared uniforms for the model shader patch
+engine.onResize((w, h, dpr) => { U.uPx.value = dpr; });
+const sunDir = new THREE.Vector3(), lightDir = new THREE.Vector3();
+let dc = new THREE.Vector3(); // diagram centre (plinth top centre)
+let diagram = null, model = null;
+const cutLines = {};
+
+// ─── Model ─────────────────────────────────────────────────────────────────────
+const rawToWorld = (x, y, z) => model.localToWorld(new THREE.Vector3(x, y, z));
+const load = assets.gltf('models/monolith/house.glb').then(g => {
+ model = g.scene;
+ model.rotation.y = Math.PI;
+ normalize(model, 4);
+ prepModel(model, renderer, { env: 1, onMat: m => patchModel(m) });
+ scene.add(model);
+ model.updateMatrixWorld(true);
+ U.uWorldToRaw.value.copy(model.matrixWorld).invert();
+
+ // Footprint of the rock base -> plinth.
+ const mesh = firstMesh(model);
+ const pa = mesh.geometry.attributes.position, v = new THREE.Vector3();
+ let x0 = 1e9, x1 = -1e9, z0 = 1e9, z1 = -1e9;
+ for (let i = 0; i < pa.count; i += 3) {
+ v.fromBufferAttribute(pa, i).applyMatrix4(mesh.matrixWorld);
+ if (v.y > 0.05) continue;
+ x0 = Math.min(x0, v.x); x1 = Math.max(x1, v.x); z0 = Math.min(z0, v.z); z1 = Math.max(z1, v.z);
+ }
+ const m = 0.1;
+ const pw = x1 - x0 + m * 2, pd = z1 - z0 + m * 2;
+ const plinth = new THREE.Mesh(worldUVBox(pw, PH, pd, 4.8), plinthMat);
+ plinth.position.set((x0 + x1) / 2, -PH / 2, (z0 + z1) / 2);
+ plinth.castShadow = plinth.receiveShadow = true;
+ scene.add(plinth);
+ dc.set((x0 + x1) / 2, 0, (z0 + z1) / 2);
+
+ warmA.position.copy(rawToWorld(-0.12, 0.45, 0.24));
+ warmB.position.copy(rawToWorld(0.02, 0.24, 0.2));
+ poolLight.position.copy(rawToWorld(0.33, 0.2, -0.31));
+
+ diagram = buildDiagram({ scene, center: dc, sunAngles, compassDir, T0, T1 });
+ // The cut lines of the two drawings (plan at +38.10, section A–A), traced once from the mesh.
+ cutLines.plan = sectionOutline(mesh, new THREE.Vector3(0, -1, 0), rawToWorldY(0.5), { width: 1.6 });
+ cutLines.sect = sectionOutline(mesh, new THREE.Vector3(1, 0, 0), -rawToWorldX(0.22), { width: 2.2 });
+ scene.add(cutLines.plan, cutLines.sect);
+ engine.onResize((w, h) => { for (const l of Object.values(cutLines)) l.material.resolution.set(w, h); });
+ buildAnchors();
+});
+
+// ─── Scroll keyframes ──────────────────────────────────────────────────────────
+// az/el in degrees around the diorama; sx/sy shift the frame (fraction of the viewport).
+const KF = {
+ hero: { msy: -0.08, az: 16, el: 12, dist: 15, t: [0, 1.0, 0], sx: 0.2, sy: 0.03, time: 13.3, diag: 1, plan: 0, sect: 0 },
+ works: { az: -34, el: 15, dist: 18.5, t: [0, 0.7, 0], sx: 0.24, sy: 0.0, time: 14.6, diag: 0.5, plan: 0, sect: 0 },
+ cliffIntro: { az: 52, el: 21, dist: 16.5, t: [0, 0.8, 0], sx: 0.2, sy: 0.02, time: 16.2, diag: 0.7, plan: 0, sect: 0 },
+ plan: { msy: 0.17, az: 0, el: 89.2, dist: 14.8, fov: 15, t: [0.05, 0.6, -0.2], sx: 0.19, sy: 0.0, time: 17.3, diag: 1, plan: 1, sect: 0 },
+ section: { msy: 0.15, az: -90, el: 1.5, dist: 10.6, fov: 14, t: [0, 1.3, 0.15], sx: -0.18, sy: 0.02, time: 18.3, diag: 0.14, plan: 0, sect: 1 },
+ detail: { msy: 0.14, az: 20, el: 17, dist: 6.6, t: [-0.8, 1.2, 0.65], sx: 0.16, sy: 0.0, time: 19.3, diag: 0, plan: 0, sect: 0 },
+ principles: { az: 64, el: 12, dist: 18, t: [0, 0.8, 0], sx: -0.24, sy: 0.02, time: 19.95, diag: 0.6, plan: 0, sect: 0 },
+ studio: { msy: -0.02, az: -26, el: 8, dist: 18.5, t: [0, 0.8, 0], sx: -0.3, sy: 0.02, time: 21.32, diag: 0.45, plan: 0, sect: 0 },
+ contact: { az: 16, el: 6, dist: 18.5, t: [0, 0.6, 0], sx: 0.18, sy: -0.2, time: 22.2, diag: 0.5, plan: 0, sect: 0 },
+ footer: { msy: 0.26, az: 30, el: 11, dist: 30, t: [0, 0.4, 0], sx: 0.0, sy: 0.3, time: 22.6, diag: 0.25, plan: 0, sect: 0 },
+};
+let anchorsY = [];
+function measure() {
+ anchorsY = [...document.querySelectorAll('[data-k]')].map(el => {
+ const r = el.getBoundingClientRect();
+ const top = r.top + scrollY;
+ const y = el.dataset.k === 'hero' ? 0 : top + r.height / 2 - innerHeight / 2;
+ return { k: el.dataset.k, y: Math.max(0, y), kf: KF[el.dataset.k] };
+ }).sort((a, b) => a.y - b.y);
+ const max = document.documentElement.scrollHeight - innerHeight;
+ anchorsY[anchorsY.length - 1].y = Math.min(anchorsY[anchorsY.length - 1].y, max);
+}
+addEventListener('resize', measure);
+const cur = { msy: -0.05, az: 16, el: 12, dist: 15, fov: 26, t: new THREE.Vector3(0, 1.0, 0), sx: 0.2, sy: 0.03, time: 13.3, diag: 1, plan: 0, sect: 0 };
+const goal = { ...cur, t: new THREE.Vector3() };
+let activeK = 'hero', activeW = 1, hoverSelf = false;
+function sampleScroll(y) {
+ let i = 0;
+ while (i < anchorsY.length - 2 && y > anchorsY[i + 1].y) i++;
+ const A = anchorsY[i], B = anchorsY[i + 1] ?? A;
+ const f = B.y > A.y ? clamp((y - A.y) / (B.y - A.y)) : 0;
+ const e = smooth(0.18, 0.82, f);
+ const a = A.kf, b = B.kf;
+ for (const k of ['az', 'el', 'dist', 'sx', 'sy', 'time', 'diag', 'plan', 'sect']) goal[k] = lerp(a[k], b[k], e);
+ goal.fov = lerp(a.fov ?? 26, b.fov ?? 26, e);
+ goal.msy = lerp(a.msy ?? -0.05, b.msy ?? -0.05, e);
+ goal.t.set(lerp(a.t[0], b.t[0], e), lerp(a.t[1], b.t[1], e), lerp(a.t[2], b.t[2], e));
+ if (hoverSelf) goal.diag = 1;
+ activeK = e < 0.5 ? A.k : B.k;
+ activeW = e < 0.5 ? 1 - e * 2 : e * 2 - 1;
+}
+
+// ─── Time of day: scroll, drag, bar, keys ──────────────────────────────────────
+let clockT = 5.6; // what is rendered
+let introTween = null;
+let userT = null, userScroll = 0, dragging = false, introT = null;
+let coastV = 0, lastSet = { t: 0, at: 0 };
+const setUser = t => {
+ userT = clamp(t, T0, T1); userScroll = scrollY; document.body.classList.add('has-dragged');
+ const now = performance.now() / 1000;
+ if (dragging && now - lastSet.at < 0.2) coastV = lerp(coastV, (userT - lastSet.t) / Math.max(now - lastSet.at, 1 / 120), 0.35);
+ lastSet = { t: userT, at: now };
+};
+
+// Arc samples for picking.
+const ARC = [];
+const tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), tmpC = new THREE.Color();
+function arcPoint(t, out) { return diagram.handlePos(t, out); }
+function pickArc(px, py, around = null) {
+ let best = null, bd = 1e9;
+ const w = innerWidth, h = innerHeight;
+ let prev = null;
+ for (const s of ARC) {
+ if (around !== null && Math.abs(s.t - around) > 2.2) { prev = null; continue; }
+ tmp.copy(s.p).project(camera);
+ const x = (tmp.x + 1) / 2 * w, y = (1 - tmp.y) / 2 * h;
+ if (tmp.z > 1) { prev = null; continue; }
+ if (prev) {
+ const dx = x - prev.x, dy = y - prev.y, L = dx * dx + dy * dy || 1;
+ const u = clamp(((px - prev.x) * dx + (py - prev.y) * dy) / L);
+ const qx = prev.x + dx * u, qy = prev.y + dy * u, d = (px - qx) ** 2 + (py - qy) ** 2;
+ if (d < bd) { bd = d; best = lerp(prev.t, s.t, u); }
+ }
+ prev = { x, y, t: s.t };
+ }
+ return { t: best, d: Math.sqrt(bd) };
+}
+function handleScreen(out) {
+ arcPoint(clockT, tmp2).project(camera);
+ out.x = (tmp2.x + 1) / 2 * innerWidth; out.y = (1 - tmp2.y) / 2 * innerHeight; out.vis = tmp2.z < 1;
+ return out;
+}
+const hs = { x: 0, y: 0, vis: false };
+let touchStart = null;
+canvas.addEventListener('pointerdown', e => {
+ if (!diagram || e.button !== 0) return;
+ if (e.pointerType === 'touch') { touchStart = { x: e.clientX, y: e.clientY, t: userT ?? clockT, on: false }; return; }
+ const pick = pickArc(e.clientX, e.clientY);
+ if (pick.t === null) return;
+ stopPlay();
+ dragging = true;
+ canvas.setPointerCapture(e.pointerId);
+ setUser(pick.t);
+ curs?.set('drag', fmtTime(pick.t));
+});
+canvas.addEventListener('pointermove', e => {
+ if (e.pointerType === 'touch' && touchStart) {
+ const dx = e.clientX - touchStart.x, dy = e.clientY - touchStart.y;
+ if (!touchStart.on && Math.abs(dx) > 10 && Math.abs(dx) > Math.abs(dy) * 1.2) touchStart.on = true;
+ if (touchStart.on) { if (!dragging) stopPlay(); dragging = true; setUser(touchStart.t + dx / innerWidth * 11); }
+ return;
+ }
+ if (dragging) {
+ const pick = pickArc(e.clientX, e.clientY, userT);
+ if (pick.t !== null) setUser(pick.t);
+ curs?.set('drag', fmtTime(userT));
+ } else if (diagram && !IS_TOUCH) {
+ const near = Math.hypot(e.clientX - hs.x, e.clientY - hs.y) < 46 && hs.vis;
+ const onArc = !near && pickArc(e.clientX, e.clientY).d < 22;
+ curs?.set(near ? 'drag' : onArc ? 'label' : '', near ? 'Drag' : onArc ? 'Place' : '');
+ }
+});
+const endDrag = () => { if (dragging) { dragging = false; curs?.set(''); if (performance.now() / 1000 - lastSet.at > 0.12) coastV = 0; coastV = clamp(coastV, -2.2, 2.2); } touchStart = null; };
+canvas.addEventListener('pointerup', endDrag);
+canvas.addEventListener('pointercancel', endDrag);
+
+// Day bar.
+const bar = document.querySelector('.daybar');
+const knob = bar.querySelector('.daybar-knob');
+{
+ const ticks = bar.querySelector('.daybar-ticks');
+ for (let h = 6; h <= 22; h++) {
+ const x = ((h - T0) / (T1 - T0) * 100).toFixed(3);
+ ticks.insertAdjacentHTML('beforeend', `<i class="${h % 3 ? '' : 'major'}" style="left:${x}%"></i>`);
+ if (h % 3 === 0) ticks.insertAdjacentHTML('beforeend', `<span style="left:${x}%">${String(h).padStart(2, '0')}</span>`);
+ }
+ for (const [t, s] of [[SUNRISE, '↑'], [SUNSET, '↓']]) ticks.insertAdjacentHTML('beforeend', `<span class="ev" style="left:${((t - T0) / (T1 - T0) * 100).toFixed(3)}%">${s} ${fmtTime(t)}</span>`);
+ // Gradient of the actual horizon colour through the day.
+ const stops = [], p = makePalette();
+ for (let i = 0; i <= 40; i++) { const t = T0 + (T1 - T0) * i / 40; palette(t, p); stops.push(`#${p.hor.getHexString(THREE.SRGBColorSpace)} ${(i / 40 * 100).toFixed(1)}%`); }
+ bar.querySelector('.daybar-sky').style.background = `linear-gradient(90deg, ${stops.join(',')})`;
+}
+const barT = e => { const r = bar.getBoundingClientRect(); return T0 + clamp((e.clientX - r.left) / r.width) * (T1 - T0); };
+bar.addEventListener('pointerdown', e => { stopPlay(); bar.setPointerCapture(e.pointerId); dragging = true; setUser(barT(e)); e.preventDefault(); });
+bar.addEventListener('pointermove', e => { if (dragging && bar.hasPointerCapture(e.pointerId)) setUser(barT(e)); });
+bar.addEventListener('pointerup', e => { dragging = false; coastV = 0; bar.releasePointerCapture(e.pointerId); });
+bar.addEventListener('keydown', e => {
+ const step = e.shiftKey ? 0.5 : 1 / 12;
+ if (e.key === 'ArrowRight' || e.key === 'ArrowUp') { setUser((userT ?? clockT) + step); e.preventDefault(); }
+ if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') { setUser((userT ?? clockT) - step); e.preventDefault(); }
+});
+
+// ─── HTML anchored to 3D ───────────────────────────────────────────────────────
+const anchorsEl = document.querySelector('.anchors');
+const TAGS = [
+ { k: 'plan', raw: [-0.2, 0.36, 0.24], html: '<b>01</b>Living, 62 m²' },
+ { k: 'plan', raw: [0.38, 0.1, -0.3], html: '<b>02</b>Pool, 18.0 × 3.2 m' },
+ { k: 'plan', raw: [-0.38, 0.13, -0.3], html: '<b>03</b>Terrace, larch' },
+ { k: 'plan', raw: [0.6, 0.36, 0.22], html: '<b>04</b>Studio' },
+ { k: 'detail', raw: [0.77, 0.06, -0.3], html: 'Laminated glass, 19 mm' },
+ { k: 'detail', raw: [0.3, 0.1, -0.46], html: 'Overflow edge, 6 mm' },
+ { k: 'detail', raw: [0.55, -0.03, -0.44], html: 'Board-marked concrete' },
+];
+const LEVELS = [
+ { k: 'section', raw: [0.2, 0.58, -0.2], html: '+38.10 &nbsp;Roof' },
+ { k: 'section', raw: [0.2, 0.355, -0.2], html: '+34.60 &nbsp;Upper floor' },
+ { k: 'section', raw: [0.2, 0.12, -0.2], html: '+31.20 &nbsp;Terrace &amp; pool' },
+ { k: 'section', raw: [0.2, -0.49, -0.2], html: '±0.00 &nbsp;Atlantic' },
+];
+const tags = [];
+function buildAnchors() {
+ for (const a of TAGS) {
+ const el = document.createElement('div'); el.className = 'tag'; el.innerHTML = `<i></i><span>${a.html}</span>`;
+ anchorsEl.appendChild(el); tags.push({ ...a, el, p: rawToWorld(...a.raw), level: false });
+ }
+ for (const a of LEVELS) {
+ const el = document.createElement('div'); el.className = 'level'; el.innerHTML = `<span>${a.html}</span>`;
+ anchorsEl.appendChild(el); tags.push({ ...a, el, p: rawToWorld(...a.raw), level: true });
+ }
+}
+function updateAnchors() {
+ const w = innerWidth, h = innerHeight;
+ for (const a of tags) {
+ const on = activeK === a.k && activeW > 0.55;
+ a.el.classList.toggle('on', on);
+ tmp.copy(a.p).project(camera);
+ const x = (tmp.x + 1) / 2 * w, y = (1 - tmp.y) / 2 * h;
+ if (a.level) {
+ const x0 = Math.max(18, w * 0.03);
+ a.el.style.width = Math.max(0, x - x0) + 'px';
+ a.el.style.transform = `translate3d(${x0.toFixed(1)}px, ${y.toFixed(1)}px, 0)`;
+ a.el.querySelector('span').style.cssText = 'left:0; right:auto';
+ } else a.el.style.transform = `translate3d(${(x - 3.5).toFixed(1)}px, ${(y - 10).toFixed(1)}px, 0)`;
+ }
+}
+
+// ─── Works: hover-reveal photographs ───────────────────────────────────────────
+const reveal0 = document.querySelector('.work-reveal');
+const revealIn = reveal0.querySelector('.work-reveal-in');
+const revealCap = reveal0.querySelector('figcaption');
+const IMG = n => `${import.meta.env.BASE_URL}img/monolith/${n}.webp`;
+['stal', 'mertola', 'ulvik', 'lajes'].forEach(n => { const i = new Image(); i.src = IMG(n); });
+const rv = { x: innerWidth / 2, y: innerHeight / 2 };
+document.querySelectorAll('.work').forEach(li => {
+ li.addEventListener('pointerenter', () => {
+ if (!li.dataset.img) { reveal0.classList.remove('on'); document.body.classList.add('hover-self'); hoverSelf = true; return; }
+ revealIn.style.backgroundImage = `url(${IMG(li.dataset.img)})`;
+ revealCap.textContent = `${li.querySelector('.w-name').textContent} — ${li.querySelector('.w-year').textContent}`;
+ reveal0.classList.add('on');
+ });
+ li.addEventListener('pointerleave', () => { reveal0.classList.remove('on'); document.body.classList.remove('hover-self'); hoverSelf = false; });
+ li.addEventListener('click', () => { if (li.hasAttribute('data-self')) window.__lenis?.scrollTo('#cliff', { duration: 1.6 }); });
+});
+
+// Play the day: a fourteen-second time-lapse from wherever the sun is to full night.
+const playBtn = document.querySelector('.play');
+let playTween = null;
+function stopPlay() { playTween?.kill(); playTween = null; playBtn.classList.remove('on'); }
+playBtn.addEventListener('click', () => {
+ if (playTween) { stopPlay(); return; }
+ const from = (userT ?? clockT) > 22.2 ? T0 + 0.1 : (userT ?? clockT);
+ const o = { v: from };
+ userT = from; coastV = 0;
+ playBtn.classList.add('on');
+ playTween = gsap.to(o, { v: T1 - 0.05, duration: 14 * (T1 - from) / (T1 - T0), ease: 'none',
+ onUpdate: () => { userT = o.v; clockT = o.v; }, onComplete: stopPlay });
+ userScroll = scrollY;
+ document.body.classList.add('has-dragged');
+});
+
+// ─── HUD & theme ───────────────────────────────────────────────────────────────
+const hudSh = document.querySelector('.hud-sh');
+const hudTime = document.querySelector('.hud-time'), hudAz = document.querySelector('.hud-az'), hudAlt = document.querySelector('.hud-alt'), hudPhase = document.querySelector('.hud-phase');
+const tagEl = document.querySelector('.sun-tag'), tagTime = tagEl.querySelector('.sun-tag-time');
+const clocks = [...document.querySelectorAll('.foot-clock')];
+let lastStr = '', lastTheme = '';
+const INK_D = [17, 17, 16], INK_L = [236, 235, 230];
+function updateHud(altDeg, azDeg) {
+ const s = fmtTime(clockT);
+ if (s !== lastStr) {
+ lastStr = s;
+ hudTime.textContent = s; tagTime.textContent = s;
+ hudAz.textContent = Math.round(azDeg) + '°';
+ hudAlt.textContent = (altDeg < 0 ? '−' : '') + Math.abs(Math.round(altDeg)) + '°';
+ hudPhase.textContent = phaseName(clockT, altDeg);
+ hudSh.textContent = altDeg > 0.5 ? '×' + (1 / Math.tan(altDeg * D)).toFixed(altDeg > 20 ? 2 : 1) : '—';
+ bar.setAttribute('aria-valuenow', clockT.toFixed(2)); bar.setAttribute('aria-valuetext', s);
+ clocks.forEach(c => { c.textContent = `${fmtTime(clockT + +c.dataset.off)} — sun time`; });
+ }
+ knob.style.left = ((clockT - T0) / (T1 - T0) * 100).toFixed(2) + '%';
+ const k = pal.ink;
+ const ink = INK_D.map((d, i) => Math.round(lerp(d, INK_L[i], k))).join(' ');
+ const hc = pal.hor.clone().convertLinearToSRGB();
+ const paper = [hc.r, hc.g, hc.b].map(v => Math.round(clamp(v) * 255)).join(' ');
+ const theme = ink + '|' + paper;
+ if (theme !== lastTheme) {
+ lastTheme = theme;
+ root.style.setProperty('--ink-rgb', ink);
+ root.style.setProperty('--paper-rgb', paper);
+ }
+}
+
+// The type answers to the sun too: big headings cast a shadow away from the handle.
+let lastShadow = '';
+function castTypeShadow(altDeg) {
+ const k = smooth(-1, 4, altDeg) * (1 - pal.ink);
+ let css = 'none';
+ if (k > 0.01 && hs.vis) {
+ let dx = innerWidth * 0.3 - hs.x, dy = innerHeight * 0.4 - hs.y;
+ const L = Math.hypot(dx, dy) || 1; dx /= L; dy /= L;
+ const len = clamp(3 / Math.tan(Math.max(altDeg, 2) * D), 2, 26);
+ css = `${(dx * len).toFixed(1)}px ${(dy * len).toFixed(1)}px ${(0.8 + len * 0.14).toFixed(1)}px rgb(var(--ink-rgb) / ${(0.15 * k * (1 - len / 70)).toFixed(3)})`;
+ }
+ if (css !== lastShadow) { lastShadow = css; root.style.setProperty('--type-shadow', css); }
+}
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const camTarget = new THREE.Vector3();
+const upV = new THREE.Vector3();
+let lastEnv = -1, envFrames = 0, lastShadowT = -1;
+const aspectFit = () => camera.aspect < 1 ? Math.pow(1.25 / camera.aspect, 0.85) : camera.aspect < 1.3 ? 1.2 : 1;
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ if (!model) return;
+ sampleScroll(window.__lenis?.scroll ?? scrollY);
+
+ // Time: the intro, then the user's sun, then the scroll's. Scrolling away cuts the intro short.
+ if (introT !== null && introTween && scrollY > innerHeight * 0.25) { introTween.kill(); introTween = null; clockT = introT; introT = null; }
+ if (userT !== null && !dragging && Math.abs(scrollY - userScroll) > innerHeight * 0.55) { userT = null; coastV = 0; stopPlay(); }
+ // Let a flung sun coast along its path.
+ if (!dragging && userT !== null && Math.abs(coastV) > 0.02 && !playTween) {
+ userT = clamp(userT + coastV * dt, T0, T1); coastV *= Math.exp(-3.2 * dt);
+ if (userT <= T0 || userT >= T1) coastV = 0;
+ } else if (!dragging) coastV = 0;
+ const want = introT ?? userT ?? goal.time;
+ clockT = introT !== null ? introT : playTween ? userT : damp(clockT, want, dragging ? 12 : Math.abs(coastV) > 0.02 ? 9 : 2.6, dt);
+
+ // Camera.
+ const lam = 3.2;
+ for (const k of ['az', 'el', 'dist', 'fov', 'sx', 'sy', 'msy', 'diag', 'plan', 'sect']) cur[k] = damp(cur[k], goal[k], lam, dt);
+ cur.t.x = damp(cur.t.x, goal.t.x, lam, dt); cur.t.y = damp(cur.t.y, goal.t.y, lam, dt); cur.t.z = damp(cur.t.z, goal.t.z, lam, dt);
+ const narrow = camera.aspect < 0.9;
+ const az = (cur.az + pointer.sx * 3) * D, el = clamp(cur.el + pointer.sy * 1.5, -5, 89.4) * D;
+ // Narrow lenses for the drawings (plan, section): same framing, flatter perspective.
+ if (Math.abs(camera.fov - cur.fov) > 1e-3) { camera.fov = cur.fov; camera.updateProjectionMatrix(); }
+ const dist = cur.dist * aspectFit() * Math.tan(13 * D) / Math.tan(cur.fov / 2 * D);
+ camTarget.copy(cur.t).add(dc);
+ camera.position.set(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(dist).add(camTarget);
+ const top = smooth(70, 89, cur.el);
+ camera.up.set(0, 1, 0).lerp(upV.set(-Math.sin(az), 0, -Math.cos(az)), top).normalize();
+ camera.lookAt(camTarget);
+ const sx = narrow ? 0 : cur.sx, sy = narrow ? cur.msy : cur.sy;
+ const { w, h } = engine.size;
+ camera.setViewOffset(w, h, -sx * w, sy * h, w, h);
+
+ // Sun.
+ const { alt, az: sAz } = sunAngles(clockT);
+ compassDir(sAz, alt, sunDir);
+ palette(clockT, pal);
+ const altDeg = alt / D;
+ const sunUp = smooth(-4, 1.5, altDeg), moonUp = smooth(-5, -11, altDeg);
+ if (sunUp > 0.001) lightDir.copy(sunDir); else lightDir.copy(MOON_DIR);
+ sun.position.copy(dc).addScaledVector(lightDir, 40).add(tmp.set(0, 0.6, 0));
+ sun.target.position.copy(dc).add(tmp.set(0, 0.6, 0));
+ sun.color.copy(sunUp > 0.001 ? pal.sun : MOON_COL);
+ sun.intensity = pal.I * sunUp + 0.55 * moonUp;
+ if (Math.abs(clockT - lastShadowT) > 0.0015 || sunUp * moonUp !== 0) { sun.shadow.needsUpdate = true; lastShadowT = clockT; }
+
+ // Sky & environment.
+ skyUniforms.uGain.value = lerp(1.0, 1.16, sunUp);
+ skyUniforms.uZen.value.copy(pal.zen); skyUniforms.uHor.value.copy(pal.hor);
+ const dusk = smooth(22, 4, Math.abs(altDeg)) * 0.55 + (altDeg < 0 ? 0.1 : 0);
+ skyUniforms.uGround.value.copy(pal.hor).lerp(pal.zen, altDeg > 0 ? 0.05 : 0.05 + dusk * 0.4).multiplyScalar(lerp(0.98, altDeg > 0 ? 0.97 : 0.88, dusk));
+ skyUniforms.uSunCol.value.copy(pal.sun); skyUniforms.uSunDir.value.copy(sunDir);
+ skyUniforms.uSunI.value = pal.I * sunUp;
+ skyUniforms.uGlow.value = smooth(28, 0, altDeg) * smooth(-9, -1, altDeg) * 1.3;
+ skyUniforms.uMoonDir.value.copy(MOON_DIR); skyUniforms.uMoon.value = pal.stars;
+ const bounce = Math.max(0, Math.sin(alt)) * pal.I * sunUp * 0.18 + smooth(25, 4, altDeg) * sunUp * 0.12;
+ skyUniforms.uBounce.value.copy(skyUniforms.uGround.value).multiplyScalar(0.3).add(tmpC.copy(pal.sun).multiplyScalar(bounce));
+ scene.environmentIntensity = pal.amb;
+ skyUniforms.uBelt.value = smooth(6, -1, altDeg) * smooth(-8, -2, altDeg);
+ scene.fog.color.copy(skyUniforms.uGround.value).multiplyScalar(skyUniforms.uGain.value);
+ stars.uniforms.uA.value = pal.stars; stars.uniforms.uT.value = t;
+ moon.material.opacity = moonHalo.material.opacity = pal.stars;
+ moon.visible = moonHalo.visible = pal.stars > 0.01;
+ if ((Math.abs(clockT - lastEnv) > 0.02 && ++envFrames % 2 === 0) || lastEnv < 0) { bakeEnv(); lastEnv = clockT; }
+
+ // Night.
+ U.uNight.value = pal.night;
+ // Grade peaks from golden hour through sunset, off by blue hour.
+ grade.weight = smooth(18.7, 19.4, clockT) * (1 - smooth(20.75, 21.2, clockT));
+ U.uTime.value = t;
+ engine.post.bloom.luminanceMaterial.threshold = lerp(2.0, 0.85, pal.night);
+ warmA.intensity = pal.night * 7; warmB.intensity = pal.night * 5; poolLight.intensity = pal.night * 5;
+
+ // Plan and section cuts (world space planes).
+ const cutY = lerp(9, rawToWorldY(0.5), smooth(0, 1, cur.plan));
+ U.uCutA.value.set(0, -1, 0, cutY);
+ const cutX = lerp(-9, rawToWorldX(0.22), smooth(0, 1, cur.sect));
+ U.uCutB.value.set(1, 0, 0, -cutX);
+ patchModel.planes[0].set(new THREE.Vector3(0, -1, 0), cutY);
+ patchModel.planes[1].set(new THREE.Vector3(1, 0, 0), -cutX);
+ U.uPoche.value = Math.max(smooth(0.3, 0.9, cur.plan), smooth(0.3, 0.9, cur.sect));
+ cutLines.plan.material.opacity = smooth(0.85, 0.99, cur.plan) * 0.95;
+ cutLines.sect.material.opacity = smooth(0.85, 0.99, cur.sect) * 0.95;
+ cutLines.plan.visible = cutLines.plan.material.opacity > 0.01;
+ cutLines.sect.visible = cutLines.sect.material.opacity > 0.01;
+ for (const l of Object.values(cutLines)) l.material.color.copy(U.uInk.value).multiplyScalar(0.8);
+ U.uInk.value.setRGB(0.014, 0.013, 0.012).lerp(tmpC.setRGB(0.05, 0.055, 0.07), pal.ink);
+ // Poché fills follow the light a little so they never glow at night.
+ const fillK = lerp(1, 0.16, pal.ink) * lerp(0.9, 1.05, sunUp);
+ U.uFillC.value.set('#8f8a82').multiplyScalar(fillK);
+ U.uFillE.value.set('#b3ab9d').multiplyScalar(fillK);
+
+ // Diagram.
+ diagram.update({ clockT, altDeg, camera, opacity: cur.diag, ink: pal.ink, sunColor: pal.sun, t });
+ handleScreen(hs);
+ const showTag = hs.vis && introT === null && (narrow ? activeK === 'hero' : cur.diag > 0.4);
+ tagEl.classList.toggle('on', showTag);
+ if (hs.vis) {
+ const tw = tagEl.offsetWidth + 16, flip = hs.x + tw > innerWidth - 12;
+ tagEl.classList.toggle('flip', flip);
+ tagEl.style.transform = `translate3d(${(flip ? hs.x - tw : hs.x + 16).toFixed(1)}px, ${(hs.y - 8).toFixed(1)}px, 0)`;
+ }
+
+ updateHud(altDeg, ((sAz / D) % 360 + 360) % 360);
+ document.body.classList.toggle('hud-compact', activeK !== 'hero' || scrollY > innerHeight * 0.5);
+ castTypeShadow(altDeg);
+ updateAnchors();
+
+ rv.x = damp(rv.x, pointer.px, 9, dt); rv.y = damp(rv.y, pointer.py, 9, dt);
+ reveal0.style.transform = `translate3d(${(rv.x + 28).toFixed(1)}px, ${(rv.y - reveal0.offsetHeight * 0.55).toFixed(1)}px, 0) rotate(${clamp(pointer.vx * -2, -5, 5).toFixed(2)}deg)`;
+});
+const rawToWorldY = y => rawToWorld(0, y, 0).y;
+const rawToWorldX = x => rawToWorld(x, 0, 0).x;
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('monolith', { theme: 'light', corner: 'br' });
+const curs = cursor({ color: '#111110', blend: 'difference', size: 30 });
+if (curs) curs.root.style.setProperty('--c', '#f2f0ea');
+magnetic();
+const lenis = smoothScroll({ lerp: 0.09 });
+reveal('h2', { type: 'lines', stagger: 0.08 });
+reveal('.step-card h3, .studio-lede, .contact-lede', { type: 'lines', stagger: 0.06 });
+
+await load;
+measure();
+document.fonts?.ready.then(measure);
+setTimeout(measure, 1600);
+// In-page links glide with Lenis instead of jumping.
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? 0 : document.querySelector(id);
+ if (el === null) return;
+ e.preventDefault();
+ lenis.scrollTo(el, { duration: 1.8, easing: t => 1 - Math.pow(1 - t, 4) });
+}));
+ARC.length = 0;
+for (let t = T0; t <= T1 + 1e-6; t += 1 / 30) ARC.push({ t, p: arcPoint(t, new THREE.Vector3()) });
+// Warm the GPU in the night state (all lights on) before revealing.
+clockT = 22; U.uNight.value = 1;
+bakeEnv();
+renderer.compile(scene, camera);
+clockT = 5.6;
+engine.start();
+const REDUCED = matchMedia('(prefers-reduced-motion: reduce)').matches;
+if (!Q.has('t') && !REDUCED) introT = 5.6;
+await loader.finish();
+if (Q.has('t')) { userT = +Q.get('t'); clockT = userT; }
+else if (REDUCED) clockT = KF.hero.time;
+else {
+ // Sunrise over the house, then the day runs to the afternoon.
+ introTween = gsap.to({ v: 5.6 }, { v: KF.hero.time, duration: 4.6, ease: 'power2.inOut', delay: 0.15,
+ onUpdate() { introT = this.targets()[0].v; }, onComplete() { clockT = introT; introT = null; } });
+}
+gsap.from('.hero-title .line > span', { yPercent: 105, duration: 1.6, ease: 'expo.out', stagger: 0.1, delay: 0.5 });
+gsap.from('.hero-meta, .hero-sub, .nav, .hud, .scroll-cue', { opacity: 0, y: 12, duration: 1.3, ease: 'power3.out', stagger: 0.07, delay: 1.0 });
+// QA hooks (scripts/qa-monolith.mjs).
+window.__mono = { setTime: v => { userT = v; clockT = v; userScroll = scrollY; }, get t() { return clockT; }, handle: () => ({ x: hs.x / innerWidth, y: hs.y / innerHeight }), arcAt: tt => { arcPoint(tt, tmp).project(camera); return { x: (tmp.x + 1) / 2, y: (1 - tmp.y) / 2 }; } };
diff --git a/examples/monolith/materials.js b/examples/monolith/materials.js
new file mode 100644
index 0000000..9ffe204
--- /dev/null
+++ b/examples/monolith/materials.js
@@ -0,0 +1,186 @@
+// Board-marked concrete for the plinth, a quiet floor, and the shader patch that gives the house its night.
+import * as THREE from 'three';
+import { bakeTexture } from '../../src/core/textures.js';
+import { LineSegments2 } from 'three/examples/jsm/lines/LineSegments2.js';
+import { LineSegmentsGeometry } from 'three/examples/jsm/lines/LineSegmentsGeometry.js';
+import { LineMaterial } from 'three/examples/jsm/lines/LineMaterial.js';
+import { Effect } from 'postprocessing';
+
+// One tile = 2.4 × 2.4 m of wall: 1.2 × 0.6 m formwork panels, six tie holes each, 120 mm boards.
+const CONCRETE_H = `
+ float hash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+ struct C { float v; float hole; float ring; float seam; float bseam; float n; float pr; };
+ C concrete(vec2 uv){
+ C c;
+ vec2 w = uv * 2.4;
+ vec2 cs = vec2(1.2, 0.6);
+ vec2 id = floor(w / cs), f = fract(w / cs);
+ c.pr = hash(id + 3.1);
+ vec2 hp = f * vec2(3.0, 2.0); vec2 hc = fract(hp) - 0.5;
+ float d = length(hc * vec2(cs.x / 3.0, cs.y / 2.0));
+ c.hole = 1.0 - smoothstep(0.012, 0.016, d);
+ c.ring = smoothstep(0.014, 0.018, d) * (1.0 - smoothstep(0.018, 0.03, d));
+ vec2 e = min(f, 1.0 - f) * cs;
+ c.seam = 1.0 - smoothstep(0.0, 0.0035, min(e.x, e.y));
+ float bf = fract(w.y / 0.12);
+ c.bseam = 1.0 - smoothstep(0.0, 0.025, min(bf, 1.0 - bf));
+ float board = hash(vec2(floor(w.y / 0.12), id.x));
+ c.n = fbm(uv * 6.0, 6.0, 6, 0.55) + (board - 0.5) * 0.18 + fbm(uv * 48.0, 48.0, 3, 0.5) * 0.4;
+ return c;
+ }`;
+
+export function concreteTextures(renderer) {
+ const map = bakeTexture(renderer, 1024, `${CONCRETE_H}
+ void main(){
+ C c = concrete(vUv);
+ float v = 0.60 + c.n * 0.085 + (c.pr - 0.5) * 0.05;
+ v -= c.seam * 0.09 + c.bseam * 0.018 + c.ring * 0.035;
+ v = mix(v, 0.34, c.hole);
+ gl_FragColor = vec4(v, v * 0.988, v * 0.962, 1.0);
+ }`);
+ map.colorSpace = THREE.SRGBColorSpace;
+ const normal = bakeTexture(renderer, 1024, `${CONCRETE_H}
+ float H(vec2 uv){ C c = concrete(uv); return c.n * 0.25 - c.hole * 1.0 - c.seam * 0.45 - c.bseam * 0.08 + c.ring * 0.05; }
+ void main(){
+ float e = 1.0 / 1024.0;
+ float hx = H(vUv + vec2(e, 0.)) - H(vUv - vec2(e, 0.));
+ float hy = H(vUv + vec2(0., e)) - H(vUv - vec2(0., e));
+ vec3 n = normalize(vec3(-hx * 9.0, -hy * 9.0, 1.0));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);
+ }`);
+ const rough = bakeTexture(renderer, 512, `${CONCRETE_H}
+ void main(){ C c = concrete(vUv); float r = 0.8 + c.n * 0.12 + c.hole * 0.15 - c.ring * 0.05; gl_FragColor = vec4(1.0, clamp(r, 0.4, 1.0), 0.0, 1.0); }`);
+ return { map, normal, rough };
+}
+
+export function floorTexture(renderer) {
+ const t = bakeTexture(renderer, 1024, `
+ void main(){
+ float n = fbm(vUv * 3.0, 3.0, 6, 0.55) * 0.05 + fbm(vUv * 24.0, 24.0, 3, 0.5) * 0.025;
+ float v = 0.96 + n;
+ gl_FragColor = vec4(v, v * 0.995, v * 0.985, 1.0);
+ }`);
+ t.colorSpace = THREE.SRGBColorSpace;
+ return t;
+}
+
+// ─── Model patch: night windows, pool glow, reflective water, section poché ───────
+const uniforms = {
+ uNight: { value: 0 }, uPoche: { value: 0 }, uTime: { value: 0 },
+ uWorldToRaw: { value: new THREE.Matrix4() },
+ uWin: { value: new THREE.Color(1.0, 0.56, 0.24).multiplyScalar(2.4) },
+ uPool: { value: new THREE.Color(0.1, 0.85, 1.0).multiplyScalar(1.6) },
+ uCutA: { value: new THREE.Vector4(0, -1, 0, 99) }, uCutB: { value: new THREE.Vector4(1, 0, 0, 99) },
+ uInk: { value: new THREE.Color(0.012, 0.012, 0.011) },
+ uFillC: { value: new THREE.Color() }, uFillE: { value: new THREE.Color() }, uPx: { value: 1 },
+};
+const planes = [new THREE.Plane(new THREE.Vector3(0, -1, 0), 99), new THREE.Plane(new THREE.Vector3(1, 0, 0), 99)];
+
+export function patchModel(m) {
+ m.side = THREE.DoubleSide;
+ m.clippingPlanes = planes;
+ m.clipShadows = true;
+ m.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, uniforms);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform mat4 uWorldToRaw; varying vec3 vRaw; varying vec3 vWp;')
+ .replace('#include <fog_vertex>', '#include <fog_vertex>\n{ vec4 wp_ = modelMatrix * vec4(transformed, 1.0); vWp = wp_.xyz; vRaw = (uWorldToRaw * wp_).xyz; }');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ uniform float uNight, uPoche, uTime, uPx; uniform vec3 uWin, uPool, uInk, uFillC, uFillE; uniform vec4 uCutA, uCutB; varying vec3 vRaw; varying vec3 vWp;
+ float boxm(vec3 p, vec3 a, vec3 b, float s){ vec3 q = smoothstep(a - s, a + s, p) * (1.0 - smoothstep(b - s, b + s, p)); return q.x * q.y * q.z; }
+ float h1(float x){ return fract(sin(x * 91.17) * 43758.5453); }`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ float blu_ = diffuseColor.b - max(diffuseColor.r, diffuseColor.g * 0.86);
+ float water_ = smoothstep(0.05, 0.16, blu_) * step(vRaw.y, 0.125);
+ roughnessFactor = mix(roughnessFactor, 0.06, water_ * 0.9);`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ // Wind on the water: two drifting wave trains, enough to break the sun into glitter.
+ vec2 wp = vRaw.xz * vec2(160.0, 190.0);
+ float a1 = sin(wp.x + uTime * 1.7 + sin(wp.y * 0.37 + uTime * 0.6) * 1.8);
+ float a2 = sin(wp.y * 1.3 - uTime * 1.3 + sin(wp.x * 0.52 - uTime * 0.4) * 1.4);
+ float calm = step(0.05, vRaw.y); // the pool is calmer than the Atlantic
+ normal = normalize(normal + water_ * mix(0.16, 0.05, calm) * vec3(a1, a2, 0.0));
+ }`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ float lum = dot(diffuseColor.rgb, vec3(0.299, 0.587, 0.114));
+ float up = boxm(vRaw, vec3(-0.70, 0.358, -0.03), vec3(0.40, 0.542, 0.37), 0.003);
+ float lo = boxm(vRaw, vec3(-0.47, 0.142, 0.26), vec3(0.41, 0.314, 0.40), 0.003);
+ float room = mix(0.35, 1.0, step(0.3, h1(floor(vRaw.x * 7.0) + (up > 0.5 ? 11.0 : 0.0))));
+ float win = clamp(up + lo, 0.0, 1.0) * room;
+ totalEmissiveRadiance += uWin * win * smoothstep(0.1, 0.55, lum) * (0.35 + lum) * uNight;
+ float pool = boxm(vRaw, vec3(-0.14, 0.0, -0.48), vec3(0.8, 0.118, -0.15), 0.005) * water_;
+ totalEmissiveRadiance += uPool * pool * uNight * (0.5 + diffuseColor.g);
+ }`)
+ .replace('#include <opaque_fragment>', `#include <opaque_fragment>
+ if (uPoche > 0.001) {
+ // Architectural poché: surfaces seen through the cut (back faces) get a flat fill with a fine
+ // 45° hatch — warm concrete grey for the building, a paler, sparser earth hatch for the rock.
+ // Foliage keeps its rendered look so trees don't turn into grey flecks.
+ float px = uPx * 1.0;
+ float leaf = step(0.02, diffuseColor.g - max(diffuseColor.r, diffuseColor.b) * 1.05);
+ if (!gl_FrontFacing && leaf < 0.5) {
+ float earth = 1.0 - smoothstep(0.0, 0.03, vRaw.y);
+ float per = mix(6.0, 11.0, earth) * px;
+ float m = mod(gl_FragCoord.x + gl_FragCoord.y, per);
+ float line = 1.0 - smoothstep(0.35 * px, 1.05 * px, abs(m - per * 0.5));
+ vec3 fill = mix(uFillC, uFillE, earth);
+ vec3 hatch = fill * mix(0.58, 0.74, earth);
+ gl_FragColor.rgb = mix(gl_FragColor.rgb, mix(fill, hatch, line), uPoche);
+ }
+ }`);
+ };
+ m.needsUpdate = true;
+}
+patchModel.uniforms = uniforms;
+patchModel.planes = planes;
+
+// Exact cut outline: intersect every triangle with the plane once, draw the segments as fat lines.
+export function sectionOutline(mesh, normal, constant, { width = 2, color = 0x1a1917, lift = 0.004 } = {}) {
+ mesh.updateMatrixWorld(true);
+ const pos = mesh.geometry.attributes.position, idx = mesh.geometry.index;
+ const n = pos.count, W = new Float32Array(n * 3), v = new THREE.Vector3();
+ for (let i = 0; i < n; i++) { v.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld); W[i * 3] = v.x; W[i * 3 + 1] = v.y; W[i * 3 + 2] = v.z; }
+ const dist = new Float32Array(n);
+ for (let i = 0; i < n; i++) dist[i] = normal.x * W[i * 3] + normal.y * W[i * 3 + 1] + normal.z * W[i * 3 + 2] + constant;
+ const out = [];
+ const tri = idx ? idx.array : null, T = tri ? tri.length : n;
+ const hit = (a, b) => { const t = dist[a] / (dist[a] - dist[b]); for (let k = 0; k < 3; k++) out.push(W[a * 3 + k] + (W[b * 3 + k] - W[a * 3 + k]) * t - normal.getComponent(k) * lift); };
+ for (let f = 0; f < T; f += 3) {
+ const a = tri ? tri[f] : f, b = tri ? tri[f + 1] : f + 1, c = tri ? tri[f + 2] : f + 2;
+ const sa = dist[a] > 0, sb = dist[b] > 0, sc = dist[c] > 0;
+ if (sa === sb && sb === sc) continue;
+ const before = out.length;
+ if (sa !== sb) hit(a, b);
+ if (sb !== sc) hit(b, c);
+ if (sc !== sa) hit(c, a);
+ if (out.length - before !== 6) out.length = before;
+ }
+ const geo = new LineSegmentsGeometry().setPositions(out);
+ const mat = new LineMaterial({ color, linewidth: width, transparent: true, opacity: 0, depthWrite: false, worldUnits: false });
+ const lines = new LineSegments2(geo, mat);
+ lines.renderOrder = 3;
+ lines.frustumCulled = false;
+ return lines;
+}
+
+// Golden-hour grade (display space, after tone mapping): more saturation, a gold hue shift and lifted
+// mid-tones so low warm light reads golden instead of brown. Blacks and highlights are left alone.
+export class GoldenGrade extends Effect {
+ constructor() {
+ super('GoldenGrade', `
+ uniform float uW;
+ void mainImage(const in vec4 ic, const in vec2 uv, out vec4 oc) {
+ vec3 c = ic.rgb;
+ float l = dot(c, vec3(0.2126, 0.7152, 0.0722));
+ vec3 s = mix(vec3(l), c, 1.0 + 0.3 * uW);
+ vec3 g = s * vec3(1.04, 1.0, 0.9);
+ float mid = smoothstep(0.0, 0.2, l) * (1.0 - smoothstep(0.45, 0.95, l));
+ g = pow(max(g, vec3(0.0)), vec3(1.0 - 0.15 * mid));
+ oc = vec4(mix(c, g, uW), ic.a);
+ }`, { uniforms: new Map([['uW', new THREE.Uniform(0)]]) });
+ }
+ set weight(v) { this.uniforms.get('uW').value = v; }
+}
diff --git a/examples/monolith/style.css b/examples/monolith/style.css
new file mode 100644
index 0000000..553dc45
--- /dev/null
+++ b/examples/monolith/style.css
@@ -0,0 +1,261 @@
+:root {
+ /* Theme channels are driven by the sun (main.js writes them every frame). */
+ --ink-rgb: 17 17 16;
+ --paper-rgb: 236 235 230;
+ --accent-rgb: 232 140 44;
+ --ink: rgb(var(--ink-rgb));
+ --ink-2: rgb(var(--ink-rgb) / .72);
+ --ink-3: rgb(var(--ink-rgb) / .5);
+ --line: rgb(var(--ink-rgb) / .16);
+ --accent: rgb(var(--accent-rgb));
+ --sans: 'Inter Tight', 'Helvetica Neue', Arial, sans-serif;
+ --serif: 'IBM Plex Serif', Georgia, serif;
+ --mono: 'IBM Plex Mono', ui-monospace, monospace;
+ --pad: clamp(16px, 3.4vw, 56px);
+ --gut: clamp(12px, 1.6vw, 24px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: #ecebe6; color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+html.lenis, html.lenis body { height: auto; }
+body { font: 400 16px/1.55 var(--sans); overflow-x: hidden; background: transparent; }
+a { color: inherit; text-decoration: none; }
+em { font-family: var(--serif); font-style: italic; font-weight: 300; letter-spacing: -.01em; }
+.mono { font-family: var(--mono); font-size: 11px; line-height: 1.5; letter-spacing: .06em; text-transform: uppercase; font-weight: 400; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+.grid { display: grid; grid-template-columns: repeat(12, minmax(0, 1fr)); column-gap: var(--gut); padding: 0 var(--pad); }
+
+/* ─── Loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: #070a13; color: #d9dbe2; display: grid; place-content: center; justify-items: center; gap: 22px; }
+.loader-dial { width: 240px; overflow: visible; }
+.loader-arc { fill: none; stroke: rgba(217,219,226,.28); stroke-width: 1; stroke-dasharray: 2 4; }
+.loader-horizon { stroke: rgba(217,219,226,.5); stroke-width: 1; }
+.loader-ticks line { stroke: rgba(217,219,226,.45); stroke-width: 1; }
+.loader-sun { fill: #ffb45c; filter: drop-shadow(0 0 8px rgba(255,170,80,.9)); }
+.loader-line { display: flex; gap: 16px; align-items: baseline; font: 300 22px/1 var(--sans); letter-spacing: -.01em; }
+.loader-pct { font: 400 12px/1 var(--mono); letter-spacing: .08em; color: #ffb45c; font-variant-numeric: tabular-nums; }
+.loader-meta { color: rgba(217,219,226,.45); }
+
+/* ─── Nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 22px var(--pad); pointer-events: none; color: var(--ink); }
+.nav > * { pointer-events: auto; }
+.brand { display: inline-flex; align-items: center; gap: 12px; font: 600 15px/1 var(--sans); letter-spacing: -.01em; justify-self: start; }
+.brand-mark { width: 9px; height: 22px; background: var(--ink); display: block; box-shadow: 4px 0 0 -1px rgb(var(--accent-rgb) / .0); transition: box-shadow .4s; }
+.brand:hover .brand-mark { box-shadow: 5px 0 0 0 var(--accent); }
+.links { display: flex; gap: clamp(18px, 2.4vw, 40px); }
+.links a { font: 500 13px/1 var(--sans); color: var(--ink-2); display: inline-flex; gap: 8px; align-items: baseline; transition: color .3s; }
+.links a .mono { font-size: 9.5px; color: var(--ink-3); }
+.links a:hover { color: var(--ink); }
+.btn { display: inline-flex; align-items: center; gap: 12px; height: 44px; padding: 0 20px; border-radius: 0; font: 500 13px/1 var(--sans);
+ letter-spacing: .005em; white-space: nowrap; transition: background .35s, color .35s, box-shadow .35s; }
+.nav .btn { justify-self: end; }
+.btn-line { box-shadow: inset 0 0 0 1px rgb(var(--ink-rgb) / .35); color: var(--ink); }
+.btn-line:hover { box-shadow: inset 0 0 0 1px var(--ink); background: rgb(var(--ink-rgb) / .06); }
+.btn-solid { background: var(--accent); color: #140d05; }
+.btn-solid:hover { background: rgb(var(--ink-rgb)); color: rgb(var(--paper-rgb)); }
+
+/* ─── Sun tag & HUD ──────────────────────────────────────── */
+.sun-tag { position: fixed; left: 0; top: 0; z-index: 12; pointer-events: none; display: flex; align-items: center; gap: 10px;
+ transform: translate3d(-999px, 0, 0); will-change: transform; color: var(--ink); opacity: 0; transition: opacity .6s; }
+.sun-tag.on { opacity: 1; }
+.sun-tag-time { font: 500 11px/1 var(--mono); letter-spacing: .06em; font-variant-numeric: tabular-nums; }
+.sun-tag-hint { font: 500 10px/1 var(--mono); letter-spacing: .08em; text-transform: uppercase; padding: 6px 9px; color: #140d05; background: var(--accent);
+ transition: opacity .5s, transform .5s; }
+.has-dragged .sun-tag-hint { opacity: 0; transform: translateX(-6px); }
+.sun-tag::before { content: ''; width: 22px; height: 1px; background: var(--ink); opacity: .5; }
+.sun-tag.flip { flex-direction: row-reverse; }
+
+.hud { position: fixed; left: var(--pad); right: calc(var(--pad) + 150px); bottom: 22px; z-index: 12; display: flex; align-items: flex-end; gap: clamp(20px, 3vw, 48px);
+ pointer-events: none; color: var(--ink); }
+.hud-read { min-width: 190px; }
+.hud-time { font: 300 clamp(40px, 4.4vw, 64px)/.9 var(--sans); letter-spacing: -.04em; font-variant-numeric: tabular-nums; }
+.hud-meta { display: flex; gap: 14px; margin-top: 10px; color: var(--ink-2); font-size: 10px; }
+.hud-meta b { font-weight: 500; color: var(--ink); font-variant-numeric: tabular-nums; }
+.hud-phase { color: var(--accent); }
+.play { pointer-events: auto; display: inline-flex; align-items: center; gap: 10px; height: 34px; padding: 0 14px 0 10px; margin-bottom: 4px; border: 0; border-radius: 999px; cursor: pointer;
+ background: transparent; color: var(--ink); box-shadow: inset 0 0 0 1px rgb(var(--ink-rgb) / .3); transition: box-shadow .3s, background .3s; flex: none; }
+.play:hover { box-shadow: inset 0 0 0 1px var(--ink); }
+.play svg { width: 14px; height: 14px; fill: var(--accent); }
+.play .i-pause { display: none; } .play.on .i-pause { display: block; } .play.on .i-play { display: none; }
+.play .mono { font-size: 9.5px; }
+.hud-time { transform-origin: 0 100%; transition: transform .7s cubic-bezier(.2,.8,.2,1); }
+.hud-compact .hud-time { transform: scale(.52); margin-top: -.9em; }
+.hud-compact .hud-read { min-width: 150px; }
+.daybar { position: relative; flex: 1; max-width: 620px; height: 44px; pointer-events: auto; cursor: ew-resize; touch-action: none; outline: none; }
+.daybar-sky { position: absolute; left: 0; right: 0; bottom: 18px; height: 4px; background: linear-gradient(90deg, #0b1222, #e1a794 5%, #ecebe6 16%, #ecebe6 70%, #f2cc98 84%, #cf846f 89%, #1f2b4d 93%, #04060c);
+ box-shadow: 0 0 0 1px rgb(var(--ink-rgb) / .15); }
+.daybar-ticks { position: absolute; inset: 0; }
+.daybar-ticks span { position: absolute; bottom: 0; transform: translateX(-50%); font: 400 9.5px/1 var(--mono); letter-spacing: .04em; color: var(--ink-3); }
+.daybar-ticks i { position: absolute; bottom: 24px; width: 1px; height: 5px; background: var(--ink-3); }
+.daybar-ticks i.major { height: 9px; background: var(--ink-2); }
+.daybar-ticks .ev { color: var(--accent); bottom: 32px; }
+.daybar-knob { position: absolute; bottom: 12px; left: 0; width: 16px; height: 16px; margin-left: -8px; border-radius: 50%; background: var(--accent);
+ box-shadow: 0 0 0 4px rgb(var(--accent-rgb) / .22), 0 0 18px rgb(var(--accent-rgb) / .7); }
+.daybar-knob i { position: absolute; left: 50%; bottom: 16px; width: 1px; height: 14px; background: var(--ink-2); }
+.daybar:focus-visible .daybar-knob { box-shadow: 0 0 0 2px rgb(var(--paper-rgb)), 0 0 0 4px var(--ink); }
+
+/* ─── Hero ───────────────────────────────────────────────── */
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, main .work, main .daybar, main img { pointer-events: auto; }
+section, footer { position: relative; }
+.hero { height: 118vh; }
+.hero .grid { position: sticky; top: 0; height: 100vh; align-content: start; padding-top: 96px; }
+.hero-meta { grid-row: 1; color: var(--ink-2); }
+.col-a { grid-column: 1 / span 3; } .col-b { grid-column: 4 / span 3; }
+.hero-title, h2, .r-num, .stats b, .foot-mark { text-shadow: var(--type-shadow, none); }
+.hero-title { grid-column: 1 / span 8; grid-row: 2; margin-top: clamp(34px, 7.5vh, 90px); font: 500 clamp(52px, 7.9vw, 146px)/.9 var(--sans); letter-spacing: -.055em; }
+.hero-title .line { display: block; overflow: hidden; padding-bottom: .06em; margin-bottom: -.06em; }
+.hero-title .line > span { display: block; }
+.hero-title em { font-weight: 300; letter-spacing: -.035em; color: var(--ink); }
+.hero-sub { grid-column: 1 / span 4; grid-row: 3; margin-top: clamp(22px, 4vh, 40px); max-width: 30em; font: 400 clamp(15px, 1.1vw, 17px)/1.5 var(--sans); color: var(--ink-2); }
+.scroll-cue { position: absolute; right: var(--pad); top: 96px; display: flex; align-items: center; gap: 10px; color: var(--ink-3); }
+.scroll-cue i { width: 1px; height: 28px; background: currentColor; transform-origin: top; animation: cue 2.4s ease-in-out infinite; }
+@keyframes cue { 0% { transform: scaleY(0); } 50% { transform: scaleY(1); transform-origin: top; } 51% { transform-origin: bottom; } 100% { transform: scaleY(0); transform-origin: bottom; } }
+
+/* ─── Section heads ──────────────────────────────────────── */
+.sec-head { grid-column: 1 / span 6; }
+.sec-num { color: var(--ink-2); display: flex; gap: 10px; align-items: center; }
+.sec-num::before { content: ''; width: 8px; height: 8px; background: var(--accent); }
+h2 { font: 500 clamp(38px, 4.6vw, 80px)/.96 var(--sans); letter-spacing: -.045em; margin-top: 22px; }
+h2 em { font-weight: 300; }
+h3 { font: 500 clamp(24px, 2.1vw, 34px)/1.04 var(--sans); letter-spacing: -.03em; }
+
+/* ─── Works ──────────────────────────────────────────────── */
+.works { padding: 22vh 0 26vh; }
+.works .sec-head { grid-column: 1 / span 6; }
+.work-list { grid-column: 1 / span 7; list-style: none; margin-top: 8vh; border-top: 1px solid var(--line); }
+.work { display: grid; grid-template-columns: 44px 1.35fr 1fr 1.25fr 52px; gap: 14px; align-items: baseline; padding: 20px 0 19px; border-bottom: 1px solid var(--line);
+ cursor: pointer; transition: opacity .4s, padding .5s cubic-bezier(.2,.8,.2,1); }
+.w-num, .w-year { color: var(--ink-3); }
+.w-year { text-align: right; }
+.w-name { font: 500 clamp(19px, 1.6vw, 26px)/1.1 var(--sans); letter-spacing: -.025em; }
+.w-place { color: var(--ink-2); font-size: 14px; }
+.w-light { color: var(--ink-3); font-size: 9.5px; }
+.work-list:hover .work { opacity: .35; }
+.work-list .work:hover { opacity: 1; padding-left: 14px; }
+.work:hover .w-light { color: var(--accent); }
+.wl-b { display: none; } .work[data-self]:hover .wl-a { display: none; } .work[data-self]:hover .wl-b { display: inline; }
+.works-note { grid-column: 1 / span 7; margin-top: 18px; color: var(--ink-3); }
+.work-reveal { position: fixed; left: 0; top: 0; z-index: 14; width: clamp(220px, 19vw, 320px); aspect-ratio: 4 / 5; pointer-events: none; will-change: transform; }
+.work-reveal-in { position: absolute; inset: 0; background-size: cover; background-position: center; clip-path: inset(50% 50% 50% 50%);
+ transform: scale(1.12); transition: clip-path .6s cubic-bezier(.2,.8,.2,1), transform 1.1s cubic-bezier(.2,.8,.2,1); box-shadow: 0 30px 60px -30px rgba(0,0,0,.45); }
+.work-reveal.on .work-reveal-in { clip-path: inset(0 0 0 0); transform: scale(1); }
+.work-reveal figcaption { position: absolute; left: 0; top: calc(100% + 10px); color: var(--ink); white-space: nowrap; opacity: 0; transform: translateY(-6px); transition: opacity .4s, transform .5s; }
+.work-reveal.on figcaption { opacity: 1; transform: none; transition-delay: .15s; }
+
+/* ─── Cliff case study ───────────────────────────────────── */
+.cliff-intro { padding: 16vh 0 10vh; min-height: 100vh; }
+.cliff-intro .sec-head { grid-column: 1 / span 6; }
+.facts { grid-column: 1 / span 5; grid-row: 2; margin-top: 7vh; border-top: 1px solid var(--line); }
+.facts div { display: grid; grid-template-columns: 110px 1fr; gap: 16px; padding: 13px 0; border-bottom: 1px solid var(--line); align-items: baseline; }
+.facts dt { color: var(--ink-3); }
+.facts dd { font-size: 15px; }
+.step { min-height: 150vh; position: relative; }
+.step-card { position: sticky; top: 24vh; width: min(420px, calc(100vw - 2 * var(--pad))); margin-left: var(--pad); padding: 30px 30px 32px;
+ background: rgb(var(--paper-rgb) / .72); backdrop-filter: blur(14px) saturate(1.1); -webkit-backdrop-filter: blur(14px) saturate(1.1);
+ box-shadow: inset 0 0 0 1px var(--line); }
+.step-section .step-card { margin-left: auto; margin-right: var(--pad); }
+.step-num { color: var(--accent); }
+.step-card h3 { margin: 16px 0 14px; }
+.step-card p { color: var(--ink-2); font-size: 15px; }
+.step-card .step-note { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); color: var(--ink-3); font-size: 10px; }
+
+/* anchors projected from 3D */
+.anchors { position: fixed; inset: 0; z-index: 6; pointer-events: none; }
+.tag { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: 8px; color: var(--ink); opacity: 0; transition: opacity .5s; will-change: transform; white-space: nowrap; }
+.tag.on { opacity: 1; }
+.tag::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 0 3px rgb(var(--accent-rgb) / .25); flex: none; }
+.tag i { display: block; width: 26px; height: 1px; background: var(--ink); opacity: .45; }
+.tag span { font: 500 10.5px/1.3 var(--mono); letter-spacing: .05em; text-transform: uppercase; padding: 5px 7px; background: rgb(var(--paper-rgb) / .75); backdrop-filter: blur(6px); }
+.tag span b { color: var(--accent); font-weight: 500; margin-right: 6px; }
+.level { position: absolute; left: 0; top: 0; height: 1px; display: flex; align-items: center; opacity: 0; transition: opacity .5s; will-change: transform, width; }
+.level.on { opacity: 1; }
+.level::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 1px; background: repeating-linear-gradient(90deg, var(--ink) 0 6px, transparent 6px 10px); opacity: .45; }
+.level span { position: absolute; right: 0; bottom: 4px; font: 500 10.5px/1 var(--mono); letter-spacing: .05em; white-space: nowrap; color: var(--ink); padding: 4px 7px 3px 4px; margin-left: -4px; background: rgb(var(--paper-rgb) / .82); }
+.level span::before { content: '▽ '; color: var(--accent); }
+
+/* ─── Principles ─────────────────────────────────────────── */
+.principles { padding: 26vh 0 24vh; }
+.principles .sec-head { grid-column: 6 / span 7; }
+.rules { grid-column: 6 / span 7; list-style: none; margin-top: 9vh; border-top: 1px solid var(--line); }
+.rules li { display: grid; grid-template-columns: clamp(80px, 9vw, 150px) 1fr; gap: 20px; padding: 30px 0 34px; border-bottom: 1px solid var(--line); }
+.r-num { font: 300 clamp(56px, 6.2vw, 108px)/.8 var(--sans); letter-spacing: -.06em; color: var(--ink); font-variant-numeric: tabular-nums; }
+.rules h3 { margin-bottom: 10px; }
+.rules p { color: var(--ink-2); max-width: 32em; font-size: 15.5px; }
+
+/* ─── Studio ─────────────────────────────────────────────── */
+.studio { padding: 22vh 0 22vh; }
+.studio .sec-head { grid-column: 6 / span 7; }
+.studio-lede { grid-column: 6 / span 4; margin-top: 5vh; font: 400 clamp(16px, 1.25vw, 20px)/1.5 var(--sans); color: var(--ink-2); }
+.studio-img { grid-column: 10 / span 3; grid-row: 2; margin-top: 5vh; align-self: start; }
+.studio-img img { width: 100%; display: block; aspect-ratio: 4 / 5; object-fit: cover; }
+.studio-img figcaption { margin-top: 10px; color: var(--ink-3); font-size: 9.5px; }
+.stats { grid-column: 6 / span 7; display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--gut); margin-top: 10vh; border-top: 1px solid var(--line); }
+.stats div { padding-top: 22px; }
+.stats b { display: block; font: 300 clamp(56px, 6.4vw, 118px)/.8 var(--sans); letter-spacing: -.06em; font-variant-numeric: tabular-nums; }
+.stats span { display: block; margin-top: 16px; color: var(--ink-2); font-size: 10px; }
+.awards { grid-column: 6 / span 7; list-style: none; margin-top: 10vh; border-top: 1px solid var(--line); }
+.awards li { display: grid; grid-template-columns: 56px 1fr 1.7fr; gap: var(--gut); padding: 14px 0; border-bottom: 1px solid var(--line); align-items: baseline; font-size: 14.5px; }
+.awards li span:nth-child(2) { font-weight: 500; }
+.awards li span:nth-child(3) { color: var(--ink-2); }
+.awards li .mono { color: var(--ink-3); }
+
+/* ─── Contact & footer ───────────────────────────────────── */
+.contact { padding: 22vh 0 58vh; }
+.contact .sec-num { grid-column: 1 / span 12; }
+.contact-title { grid-column: 1 / span 10; font-size: clamp(46px, 7vw, 128px); }
+.contact-lede { grid-column: 1 / span 5; margin-top: 4vh; color: var(--ink-2); font-size: clamp(16px, 1.2vw, 19px); }
+.contact-cta { grid-column: 1 / span 12; display: flex; gap: 12px; flex-wrap: wrap; margin-top: 5vh; }
+.contact-cta .btn { height: 52px; padding: 0 26px; font-size: 14px; }
+.foot { padding: 120px 0 118px; background: linear-gradient(rgb(var(--paper-rgb) / 0), rgb(var(--paper-rgb) / .92) 90px, rgb(var(--paper-rgb)) 200px); }
+.foot .grid { border-top: 1px solid var(--line); padding-top: 34px; }
+.foot .grid { row-gap: 40px; }
+.foot-office { grid-column: span 3; display: grid; gap: 8px; color: var(--ink-2); font-size: 14px; }
+.foot-office .mono { color: var(--ink-3); }
+.foot-office .foot-clock { color: var(--accent); font-variant-numeric: tabular-nums; }
+.foot-links { grid-column: 8 / span 5; display: flex; flex-wrap: wrap; gap: 10px 26px; align-content: start; justify-content: flex-end; font-size: 14px; }
+.foot-links a { color: var(--ink-2); } .foot-links a:hover { color: var(--ink); }
+.foot-mark { grid-column: 1 / span 12; font: 600 clamp(72px, 15.5vw, 290px)/.78 var(--sans); letter-spacing: -.075em; margin-top: 18px; }
+.foot-legal { grid-column: 1 / span 12; color: var(--ink-3); }
+
+/* ─── Mobile ─────────────────────────────────────────────── */
+@media (max-width: 900px) {
+ .grid { grid-template-columns: repeat(4, minmax(0, 1fr)); }
+ .links { display: none; }
+ .nav { grid-template-columns: 1fr auto; padding: 16px var(--pad); }
+ .nav .btn { height: 38px; padding: 0 14px; font-size: 12px; }
+ .col-a { grid-column: 1 / span 2; } .col-b { grid-column: 3 / span 2; }
+ .hero .grid { padding-top: 76px; }
+ .hero-title { grid-column: 1 / -1; font-size: clamp(44px, 12.4vw, 80px); margin-top: 28px; }
+ .hero-sub { grid-column: 1 / -1; font-size: 14px; max-width: 26em; }
+ .scroll-cue { display: none; }
+ .sec-head, .works .sec-head, .cliff-intro .sec-head, .principles .sec-head, .studio .sec-head { grid-column: 1 / -1; }
+ .work-list, .works-note, .facts, .rules, .studio-lede, .studio-img, .contact-title, .contact-lede, .stats, .awards { grid-column: 1 / -1; }
+ .studio-img { grid-row: auto; margin-top: 5vh; }
+ .work { grid-template-columns: 30px 1fr auto; row-gap: 4px; }
+ .w-place { grid-column: 2; grid-row: 2; font-size: 13px; }
+ .w-light { display: none; }
+ .w-year { grid-column: 3; grid-row: 1; }
+ .rules li { grid-template-columns: 64px 1fr; }
+ .stats { grid-template-columns: repeat(2, 1fr); row-gap: 30px; }
+ .awards li { grid-template-columns: 48px 1fr; }
+ .awards li span:nth-child(3) { grid-column: 2; }
+ .foot-office { grid-column: span 2; }
+ .foot-links { grid-column: 1 / -1; justify-content: flex-start; }
+ .step-card { top: auto; bottom: 120px; position: sticky; margin: 0 var(--pad) !important; width: auto; padding: 20px; }
+ .step { display: flex; align-items: flex-end; }
+ .step-card p { font-size: 14px; }
+ .hud { right: var(--pad); bottom: 60px; gap: 16px; }
+ .hud-read { min-width: 0; }
+ .hud-time { font-size: 34px; }
+ .hud-meta { gap: 8px; font-size: 9px; }
+ .hud-meta span:nth-child(3), .hud-shw { display: none; }
+ .play .mono { display: none; } .play { padding: 0 10px; height: 30px; }
+ .hud-compact .hud-time { transform: scale(.7); }
+ .daybar-ticks span:not(.ev) { display: none; }
+ .tag span { font-size: 9px; }
+ .work-list { background: rgb(var(--paper-rgb) / .5); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
+ .rules, .stats, .awards, .facts { background: rgb(var(--paper-rgb) / .45); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px); }
+ .step-card h3 { font-size: 22px; margin: 10px 0 8px; }
+ .step-card .step-note { display: none; }
+}
diff --git a/examples/monolith/sun.js b/examples/monolith/sun.js
new file mode 100644
index 0000000..a99236b
--- /dev/null
+++ b/examples/monolith/sun.js
@@ -0,0 +1,94 @@
+// Solar geometry and the day's palette for Casa do Penhasco, Cabo Espichel, on the June solstice.
+import * as THREE from 'three';
+
+const D = Math.PI / 180;
+export const SITE = { lat: 38.42, lon: -9.22, name: 'Cabo Espichel', coords: '38°25′N 9°13′W' };
+const DEC = 23.44 * D; // solar declination, 21 June
+export const NOON = 13 + 38 / 60; // local clock (WEST, UTC+1) at solar noon
+export const T0 = 5.5, T1 = 22.75; // the handle's range, in clock hours
+// The house is rotated so the pool terrace (+z) faces 240° WSW, over the Atlantic.
+export const NORTH_OFFSET = -60 * D;
+
+export const DECS = { jun: DEC, equinox: 0, dec: -DEC };
+export function sunAngles(clock, dec = DEC) {
+ const H = (clock - NOON) * 15 * D;
+ const lat = SITE.lat * D;
+ const sinAlt = Math.sin(lat) * Math.sin(dec) + Math.cos(lat) * Math.cos(dec) * Math.cos(H);
+ const alt = Math.asin(sinAlt);
+ const az = Math.atan2(Math.sin(H), Math.cos(H) * Math.sin(lat) - Math.tan(dec) * Math.cos(lat)) + Math.PI;
+ return { alt, az };
+}
+
+/** World direction for a compass azimuth (radians, clockwise from north) and altitude. */
+export function compassDir(az, alt, out = new THREE.Vector3()) {
+ const a = az + NORTH_OFFSET;
+ return out.set(Math.sin(a) * Math.cos(alt), Math.sin(alt), -Math.cos(a) * Math.cos(alt));
+}
+
+// Sunrise / sunset with refraction (altitude −0.83°).
+function crossing(sign) {
+ const lat = SITE.lat * D;
+ const c = (Math.sin(-0.83 * D) - Math.sin(lat) * Math.sin(DEC)) / (Math.cos(lat) * Math.cos(DEC));
+ return NOON + sign * Math.acos(c) / D / 15;
+}
+export const SUNRISE = crossing(-1), SUNSET = crossing(1);
+
+export function fmtTime(h) {
+ let m = Math.round(h * 60);
+ const hh = Math.floor(m / 60) % 24, mm = m % 60;
+ return `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
+}
+
+export function phaseName(h, altDeg) {
+ if (altDeg < -12) return 'Night';
+ if (altDeg < -0.83) return h < NOON ? 'Blue hour' : 'Blue hour';
+ if (Math.abs(h - SUNRISE) < 0.25) return 'Sunrise';
+ if (Math.abs(h - SUNSET) < 0.25) return 'Sunset';
+ if (altDeg < 9) return h < NOON ? 'First light' : 'Golden hour';
+ if (Math.abs(h - NOON) < 0.4) return 'Solar noon';
+ return h < NOON ? 'Morning' : 'Afternoon';
+}
+
+// ─── Palette ──────────────────────────────────────────────────────────────────
+// Keyed on the clock. Colours are sRGB hex (converted to linear on use); intensities are linear.
+// zen/hor: sky; sun: light colour; I: sun intensity; amb: environment strength; ink: 0 = dark type on paper, 1 = light type.
+const K = [
+ { t: 5.50, zen: '#04060c', hor: '#0b1222', sun: '#8aa2ff', I: 0.00, amb: 0.55, ink: 1 },
+ { t: 5.75, zen: '#0a1428', hor: '#1f2c49', sun: '#8aa2ff', I: 0.00, amb: 0.6, ink: 1 },
+ { t: 6.00, zen: '#27344f', hor: '#7d7189', sun: '#ff9a7a', I: 0.00, amb: 0.7, ink: 1 },
+ { t: 6.22, zen: '#56637f', hor: '#e1a794', sun: '#ff8f6c', I: 0.55, amb: 0.7, ink: 0.55 },
+ { t: 6.80, zen: '#8997b1', hor: '#efc6b2', sun: '#ffb793', I: 1.4, amb: 0.62, ink: 0 },
+ { t: 8.00, zen: '#b3bfcd', hor: '#ebe1d6', sun: '#ffeedd', I: 2.0, amb: 0.56, ink: 0 },
+ { t: 10.0, zen: '#c6ced6', hor: '#ecebe6', sun: '#fff8ef', I: 2.3, amb: 0.52, ink: 0 },
+ { t: 13.6, zen: '#ccd3d9', hor: '#ecebe6', sun: '#fffdf8', I: 2.4, amb: 0.5, ink: 0 },
+ { t: 16.8, zen: '#c3cad2', hor: '#eeeae3', sun: '#fff3e2', I: 2.3, amb: 0.5, ink: 0 },
+ { t: 18.5, zen: '#b8c1cf', hor: '#f4e4c8', sun: '#ffdcaa', I: 2.5, amb: 0.5, ink: 0 },
+ { t: 19.5, zen: '#aeb8cb', hor: '#f8d7a0', sun: '#ffc278', I: 3.2, amb: 0.48, ink: 0 },
+ { t: 20.4, zen: '#8e97b4', hor: '#f6bd82', sun: '#ffa35a', I: 2.6, amb: 0.5, ink: 0 },
+ { t: 20.62, zen: '#727ca3', hor: '#f0a878', sun: '#ff8c4a', I: 1.8, amb: 0.52, ink: 0.35 },
+ { t: 21.02, zen: '#4b5281', hor: '#d98b76', sun: '#ff6a36', I: 0.45, amb: 0.58, ink: 1 },
+ { t: 21.35, zen: '#1c2644', hor: '#465176', sun: '#ff6a36', I: 0.0, amb: 0.62, ink: 1 },
+ { t: 21.9, zen: '#0b1227', hor: '#19223c', sun: '#8aa2ff', I: 0.0, amb: 0.6, ink: 1 },
+ { t: 22.75, zen: '#04060c', hor: '#0b1222', sun: '#8aa2ff', I: 0.0, amb: 0.55, ink: 1 },
+];
+const cache = K.map(k => ({ ...k, zenC: new THREE.Color(k.zen), horC: new THREE.Color(k.hor), sunC: new THREE.Color(k.sun) }));
+
+export function palette(h, out) {
+ let i = 0;
+ while (i < cache.length - 2 && h > cache[i + 1].t) i++;
+ const a = cache[i], b = cache[i + 1];
+ const f = THREE.MathUtils.clamp((h - a.t) / (b.t - a.t), 0, 1);
+ const s = f * f * (3 - 2 * f);
+ out.zen.copy(a.zenC).lerp(b.zenC, s);
+ out.hor.copy(a.horC).lerp(b.horC, s);
+ out.sun.copy(a.sunC).lerp(b.sunC, s);
+ out.I = a.I + (b.I - a.I) * s;
+ out.amb = a.amb + (b.amb - a.amb) * s;
+ out.ink = a.ink + (b.ink - a.ink) * s;
+ // Night: 0 by day, 1 in full dark (windows, pool, stars, moon).
+ const eve = THREE.MathUtils.smoothstep(h, 20.75, 21.7), morn = 1 - THREE.MathUtils.smoothstep(h, 5.7, 6.35);
+ out.night = Math.max(eve, morn);
+ out.stars = Math.max(THREE.MathUtils.smoothstep(h, 21.3, 22.1), 1 - THREE.MathUtils.smoothstep(h, 5.6, 6.0));
+ return out;
+}
+export const makePalette = () => ({ zen: new THREE.Color(), hor: new THREE.Color(), sun: new THREE.Color(), I: 0, amb: 1, ink: 0, night: 0, stars: 0 });
diff --git a/examples/nocturne/bottle.js b/examples/nocturne/bottle.js
new file mode 100644
index 0000000..b7c4c2f
--- /dev/null
+++ b/examples/nocturne/bottle.js
@@ -0,0 +1,348 @@
+// The flacon: a heavy cut-glass block, a gilt stopper, and ~50 ml of amber that behaves like liquid.
+//
+// Liquid model
+// - The cavity is sampled with a few thousand points in bottle space. Every frame they are pushed through the
+// bottle's world matrix and projected on the (wobbling) surface normal; the fill fraction is then a quantile of
+// that list, so the level is volume-preserving at any tilt, even upside down.
+// - The surface normal is a damped spring driven by the bottle's linear acceleration and angular velocity.
+// - Shader: fragments above the plane are discarded; back faces that survive are shaded as the free surface
+// (classic "liquid in a bottle" trick). The body refracts a half-res render of the scene behind it and absorbs
+// it with Beer–Lambert amber, so the letters and the floor are visible through the perfume.
+import { THREE, clamp, lerp } from '../../src/core/engine.js';
+import { mergeGeometries } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+
+export const DIM = {
+ W: 1.0, D: 0.64, H: 1.1, chamfer: 0.17, bevel: 0.055,
+ neckR: 0.148, neckH: 0.15,
+ cav: { W: 0.74, D: 0.40, y0: 0.25, y1: 0.97, r: 0.085 },
+ pivot: 0.62,
+};
+DIM.neckTop = DIM.H + DIM.neckH;
+
+function bodyGeometry() {
+ const { W, D, H, chamfer: c, bevel: b } = DIM;
+ const a = W / 2 - b, d = D / 2 - b;
+ const s = new THREE.Shape();
+ s.moveTo(a - c, d); s.lineTo(-a + c, d); s.lineTo(-a, d - c); s.lineTo(-a, -d + c);
+ s.lineTo(-a + c, -d); s.lineTo(a - c, -d); s.lineTo(a, -d + c); s.lineTo(a, d - c); s.lineTo(a - c, d);
+ const g = new THREE.ExtrudeGeometry(s, { depth: H - 2 * b, bevelEnabled: true, bevelThickness: b, bevelSize: b, bevelSegments: 1, curveSegments: 1 });
+ g.rotateX(-Math.PI / 2);
+ g.translate(0, b, 0);
+ g.deleteAttribute('uv');
+ g.computeVertexNormals();
+ return g;
+}
+
+function neckGeometry() {
+ const { H, neckR: r, neckH: h } = DIM;
+ const pts = [
+ [r + 0.05, H - 0.0005], [r + 0.012, H + 0.012], [r, H + 0.03], [r - 0.004, H + h - 0.03],
+ [r + 0.012, H + h - 0.022], [r + 0.012, H + h - 0.004], [r - 0.006, H + h], [0.001, H + h],
+ ].map(([x, y]) => new THREE.Vector2(x, y));
+ const g = new THREE.LatheGeometry(pts, 64);
+ g.deleteAttribute('uv');
+ return g.toNonIndexed();
+}
+
+// Rounded-box SDF (matches RoundedBoxGeometry closely enough for sampling).
+function sdRoundBox(x, y, z, bx, by, bz, r) {
+ const qx = Math.abs(x) - bx + r, qy = Math.abs(y) - by + r, qz = Math.abs(z) - bz + r;
+ const ox = Math.max(qx, 0), oy = Math.max(qy, 0), oz = Math.max(qz, 0);
+ return Math.hypot(ox, oy, oz) + Math.min(Math.max(qx, qy, qz), 0) - r;
+}
+
+// Camera-relative softboxes, evaluated analytically on the view-space reflection vector: the long vertical
+// highlights of a studio product shot, pinned to the lens like a photographer's rig (a PMREM can't hold them this thin).
+export const STRIPS_GLSL = /* glsl */`
+ uniform float uStripK;
+ float stripBand(float x, float c, float w) { return 1.0 - smoothstep(w * 0.3, w, abs(x - c)); }
+ vec3 studioStrips(vec3 n, vec3 v) {
+ vec3 r = reflect(-v, n);
+ float az = atan(r.x, r.z);
+ float el = r.y;
+ float vert = smoothstep(-0.8, -0.35, el) * (1.0 - smoothstep(0.5, 0.95, el)) * (0.8 + 0.2 * sin(el * 9.0));
+ float s = stripBand(az, -0.04, 0.026) * 1.0 + stripBand(az, 0.075, 0.008) * 0.6
+ + stripBand(az, -1.25, 0.10) * 0.6 + stripBand(az, 1.32, 0.07) * 0.45
+ + stripBand(az, -2.7, 0.07) * 0.4 + stripBand(az, 2.75, 0.05) * 0.35;
+ float top = smoothstep(0.82, 0.97, el) * 0.35;
+ float F = 0.043 + 0.957 * pow(1.0 - clamp(dot(n, v), 0.0, 1.0), 5.0);
+ return vec3(1.0, 0.95, 0.87) * (s * vert + top) * F * uStripK;
+ }
+`;
+
+const LIQ_PARS = /* glsl */`
+ uniform vec4 uPlane; uniform float uTime, uRipple, uGlowK, uAbsorb, uLevelVis;
+ uniform vec3 uDeep, uGlow, uSigma;
+ uniform sampler2D uBg; uniform mat4 uMainVP; uniform vec3 uKeyDir;
+ varying vec3 vWPos;
+ float ripH(vec3 p){
+ return uRipple * (sin(dot(p.xz, vec2(21.0, 13.0)) + uTime * 3.3) * 0.5 + sin(dot(p.xz, vec2(-15.0, 24.0)) - uTime * 2.7) * 0.35
+ + sin(dot(p.xz, vec2(37.0, -9.0)) + uTime * 5.1) * 0.15);
+ }
+`;
+
+export function createBottle({ renderer, env }) {
+ const root = new THREE.Group(); // on the floor; lifted while held
+ const pivot = new THREE.Group(); // rotation centre ~ centre of mass
+ const body = new THREE.Group();
+ pivot.position.y = DIM.pivot;
+ body.position.y = -DIM.pivot;
+ root.add(pivot); pivot.add(body);
+
+ // ── Glass ──────────────────────────────────────────────────────────────────
+ const glassGeo = mergeGeometries([bodyGeometry(), neckGeometry()]);
+ const glass = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff, metalness: 0, roughness: 0.0, transmission: 1, thickness: 0.62, ior: 1.52, dispersion: 2.2,
+ attenuationColor: new THREE.Color(0.9, 0.93, 0.9), attenuationDistance: 1.4,
+ specularIntensity: 1, envMapIntensity: 1.0, depthWrite: false,
+ });
+ const GU = { uBaseGlow: { value: new THREE.Color(0, 0, 0) }, uStripK: { value: 30 } };
+ glass.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, GU);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vLocalG;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvLocalG = position;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nvarying vec3 vLocalG; uniform vec3 uBaseGlow;\n' + STRIPS_GLSL)
+ .replace('#include <lights_fragment_end>', `#include <lights_fragment_end>
+ reflectedLight.indirectSpecular += studioStrips(normal, normalize(vViewPosition));`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ // Light trapped in the thick base by the perfume above it (total internal reflection, faked).
+ float ndvG = clamp(abs(dot(normal, normalize(vViewPosition))), 0.0, 1.0);
+ float inBase = smoothstep(${(DIM.cav.y0 + 0.02).toFixed(3)}, 0.02, vLocalG.y);
+ totalEmissiveRadiance += uBaseGlow * inBase * (0.35 + 0.65 * pow(1.0 - ndvG, 1.5));
+ }`);
+ };
+ glass.customProgramCacheKey = () => 'nocturne-glass';
+ const glassMesh = new THREE.Mesh(glassGeo, glass);
+ glassMesh.renderOrder = 3;
+ body.add(glassMesh);
+
+ // Far-side facets: only their reflections (they are what makes thick glass read as thick). Drawn additively into
+ // the opaque list so the front glass refracts them.
+ const backMat = new THREE.MeshPhysicalMaterial({
+ color: 0x000000, metalness: 0, roughness: 0.02, ior: 1.52, specularIntensity: 1,
+ side: THREE.BackSide, blending: THREE.AdditiveBlending, depthWrite: false, envMapIntensity: 0.6,
+ });
+ const BU = { uStripK: { value: 9 } };
+ backMat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, BU);
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\n' + STRIPS_GLSL)
+ .replace('#include <lights_fragment_end>', '#include <lights_fragment_end>\n reflectedLight.indirectSpecular += studioStrips(normal, normalize(vViewPosition));');
+ };
+ backMat.customProgramCacheKey = () => 'nocturne-back';
+ const backMesh = new THREE.Mesh(glassGeo, backMat);
+ backMesh.renderOrder = 2;
+ body.add(backMesh);
+
+ // ── Liquid ─────────────────────────────────────────────────────────────────
+ const { cav } = DIM;
+ const cavH = cav.y1 - cav.y0, cavY = (cav.y0 + cav.y1) / 2;
+ const liqGeo = new RoundedBoxGeometry(cav.W, cavH, cav.D, 6, cav.r);
+ liqGeo.translate(0, cavY, 0);
+ const U = {
+ uPlane: { value: new THREE.Vector4(0, 1, 0, 0.5) }, uTime: { value: 0 }, uRipple: { value: 0.002 },
+ uDeep: { value: new THREE.Color(0.14, 0.03, 0.003) }, uGlow: { value: new THREE.Color(1.0, 0.40, 0.055) },
+ uSigma: { value: new THREE.Vector3(0.9, 2.6, 7.5) }, uGlowK: { value: 1 }, uAbsorb: { value: 0 }, uLevelVis: { value: 1 },
+ uBg: { value: null }, uMainVP: { value: new THREE.Matrix4() }, uKeyDir: { value: new THREE.Vector3(-0.4, 0.8, -0.4).normalize() },
+ };
+ const liquid = new THREE.MeshPhysicalMaterial({
+ color: 0x000000, roughness: 0.04, metalness: 0, ior: 1.36, specularIntensity: 1, envMapIntensity: 1.5, side: THREE.DoubleSide,
+ });
+ liquid.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, U);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWPos; varying vec3 vLocal;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvWPos = (modelMatrix * vec4(transformed, 1.0)).xyz; vLocal = position;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vLocal;\n' + LIQ_PARS)
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>
+ float hPl = dot(uPlane.xyz, vWPos) - uPlane.w - ripH(vWPos);
+ if (hPl > 0.0 || uLevelVis < 0.001) discard;
+ float below = -hPl;
+ `)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ vec3 bodyN = normal;
+ if (!gl_FrontFacing) {
+ float e = 0.004;
+ vec3 pn = normalize(uPlane.xyz - vec3(ripH(vWPos + vec3(e,0.,0.)) - ripH(vWPos - vec3(e,0.,0.)), 0.0, ripH(vWPos + vec3(0.,0.,e)) - ripH(vWPos - vec3(0.,0.,e))) / (2.0 * e) * 0.9);
+ normal = normalize((viewMatrix * vec4(pn, 0.0)).xyz);
+ nonPerturbedNormal = normal;
+ }
+ `)
+ .replace('#include <lights_physical_fragment>', `#include <lights_physical_fragment>
+ // The glass/perfume interface barely reflects; only the free surface is a mirror.
+ if (gl_FrontFacing) { material.specularColor *= 0.12; material.specularColorBlended *= 0.12; material.specularF90 *= 0.12; }
+ `)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ {
+ vec3 V = normalize(vViewPosition);
+ float ndv = clamp(abs(dot(bodyN, V)), 0.0, 1.0);
+ vec2 lq = vLocal.xz / vec2(${(cav.W / 2).toFixed(3)}, ${(cav.D / 2).toFixed(3)});
+ float hB = (vLocal.y - ${cav.y0.toFixed(3)}) / ${cavH.toFixed(3)};
+ // Screen-space refraction of what is behind, through a lens-shaped volume (inverts toward the rim).
+ vec4 clip = uMainVP * vec4(vWPos, 1.0);
+ vec2 suv = clip.xy / clip.w * 0.5 + 0.5;
+ vec2 off = -bodyN.xy * (gl_FrontFacing ? 0.09 : 0.03) * (0.5 + (1.0 - ndv)) - vec2(lq.x * 0.035, 0.0);
+ vec3 bg = texture2D(uBg, clamp(suv + off, 0.001, 0.999)).rgb;
+ float L = gl_FrontFacing ? mix(0.25, 0.62, ndv) : 0.5;
+ vec3 T = exp(-uSigma * L);
+ float edge = smoothstep(0.5, 1.0, abs(lq.x));
+ float nearTop = smoothstep(0.30, 0.0, below);
+ // Light entering through the free surface and the key beam crossing the volume.
+ float shaft = exp(-pow((lq.x + 0.35 - hB * 0.7) / 0.42, 2.0));
+ // Sun-ray streaks under the surface, bent by the ripples; they shimmer harder when the perfume moves.
+ // (world-aligned: they hang from the level surface whatever the bottle does)
+ float hx = dot(vWPos.xz, vec2(0.83, 0.55));
+ float wv = sin(hx * 9.0 + uTime * 0.35 + vWPos.z * 3.0) * 1.6 + sin(hx * 4.0 - uTime * 0.21) * 2.0;
+ float rays = pow(0.5 + 0.5 * sin(hx * 34.0 + wv + below * 4.0), 10.0) * 0.6 + pow(0.5 + 0.5 * sin(hx * 17.0 - wv * 0.7 - below * 2.5), 14.0) * 0.5;
+ rays *= smoothstep(0.45, 0.0, below) * (0.35 + uRipple * 90.0);
+ // Backlit volume: the middle looks straight through to the dark studio (deep, cognac), while the rounded
+ // walls bend the side light into view (glowing rims), the base focuses it (a warm floor of light) and the
+ // free surface lets it in from above (a bright band under the meniscus, with a thin lens-dark line).
+ float rimX = smoothstep(0.52, 0.98, abs(lq.x));
+ float baseBand = smoothstep(0.16, 0.0, hB);
+ float amt = clamp(0.08 + 0.55 * rimX + 0.34 * nearTop + 0.34 * baseBand + 0.12 * shaft + 0.08 * rays, 0.0, 1.0);
+ vec3 body = mix(uDeep, uGlow, amt) * (0.42 + 0.45 * rimX + 0.32 * nearTop + 0.3 * baseBand + 0.1 * shaft);
+ float rim = pow(1.0 - ndv, 5.0);
+ float men = smoothstep(0.012, 0.0, below);
+ float underMen = smoothstep(0.012, 0.03, below) * smoothstep(0.08, 0.03, below);
+ vec3 col = bg * T * 1.6 + body * 0.62 * uGlowK * (1.0 - underMen * 0.4) + uGlow * (rim * 0.5 + men * 1.7 + rays * 0.06);
+ if (!gl_FrontFacing) {
+ float sp = step(0.992, fract(sin(dot(floor(vWPos.xz * 150.0) + floor(uTime * 9.0), vec2(12.9898, 78.233))) * 43758.5453));
+ col = bg * T * 0.9 + mix(uDeep, uGlow, 0.42) * 0.55 * uGlowK + vec3(1.0, 0.8, 0.45) * sp * uAbsorb * 3.0;
+ }
+ col += uGlow * uAbsorb * 0.22;
+ totalEmissiveRadiance += col;
+ }
+ `);
+ };
+ liquid.customProgramCacheKey = () => 'nocturne-liquid';
+ const liqMesh = new THREE.Mesh(liqGeo, liquid);
+ liqMesh.renderOrder = 1;
+ body.add(liqMesh);
+
+ // Inner cavity wall: the faint second outline that says "this glass is hollow".
+ const cavMat = new THREE.ShaderMaterial({
+ uniforms: { uPlane: U.uPlane, uI: { value: 1 } },
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ vertexShader: `varying vec3 vN; varying vec3 vV; varying vec3 vW;
+ void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; vN = normalize(mat3(modelMatrix) * normal); vV = normalize(cameraPosition - w.xyz);
+ gl_Position = projectionMatrix * viewMatrix * w; }`,
+ fragmentShader: `uniform vec4 uPlane; uniform float uI; varying vec3 vN; varying vec3 vV; varying vec3 vW;
+ void main(){ float above = smoothstep(-0.005, 0.02, dot(uPlane.xyz, vW) - uPlane.w);
+ float f = pow(1.0 - abs(dot(normalize(vN), vV)), 3.0);
+ gl_FragColor = vec4(vec3(1.0, 0.93, 0.8) * f * 0.07 * above * uI, 1.0); }`,
+ });
+ const cavGeo = new RoundedBoxGeometry(cav.W + 0.012, cavH + 0.012, cav.D + 0.012, 6, cav.r + 0.006);
+ cavGeo.translate(0, cavY, 0);
+ const cavMesh = new THREE.Mesh(cavGeo, cavMat);
+ cavMesh.renderOrder = 6;
+ body.add(cavMesh);
+
+ // ── Hot-stamped gilding on the front face ─────────────────────────────────
+ const label = (() => {
+ const c = document.createElement('canvas'); c.width = 2048; c.height = 320;
+ const g = c.getContext('2d');
+ g.fillStyle = '#000'; g.fillRect(0, 0, c.width, c.height);
+ g.fillStyle = '#fff'; g.textAlign = 'center'; g.textBaseline = 'middle';
+ g.font = '400 150px Italiana, "Bodoni Moda", serif';
+ if ('letterSpacing' in g) g.letterSpacing = '46px';
+ g.fillText('NOCTURNE', 1046, 128);
+ if ('letterSpacing' in g) g.letterSpacing = '14px';
+ g.font = 'italic 400 64px "Bodoni Moda", serif';
+ g.fillText('No 9 · Extrait de parfum', 1030, 262);
+ const t = new THREE.CanvasTexture(c); t.anisotropy = 16;
+ const m = new THREE.MeshStandardMaterial({ color: 0xe6c47c, metalness: 1, roughness: 0.24, alphaMap: t, alphaTest: 0.45, envMapIntensity: 2.4 });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(0.62, 0.62 * 320 / 2048), m);
+ mesh.position.set(0, 0.128, DIM.D / 2 + 0.0015);
+ return mesh;
+ })();
+ body.add(label);
+
+ // ── Cavity samples for the volume-preserving level ─────────────────────────
+ const N = 2600;
+ const pts = new Float32Array(N * 3), vals = new Float32Array(N);
+ {
+ let i = 0;
+ const bx = cav.W / 2, by = cavH / 2, bz = cav.D / 2;
+ while (i < N) {
+ const x = (Math.random() * 2 - 1) * bx, y = (Math.random() * 2 - 1) * by, z = (Math.random() * 2 - 1) * bz;
+ if (sdRoundBox(x, y, z, bx, by, bz, cav.r) > 0) continue;
+ pts[i * 3] = x; pts[i * 3 + 1] = y + cavY; pts[i * 3 + 2] = z; i++;
+ }
+ }
+ // Cavity-centre of mass for projecting caustics and aiming particles.
+ const tmp = new THREE.Vector3();
+
+ const state = {
+ fill: 0, plane: U.uPlane.value, normal: new THREE.Vector3(0, 1, 0),
+ wob: new THREE.Vector2(), wobV: new THREE.Vector2(),
+ prevC: new THREE.Vector3(), prevV: new THREE.Vector3(), acc: new THREE.Vector3(), prevQ: new THREE.Quaternion(), omega: new THREE.Vector3(),
+ surf: new THREE.Vector3(), centroid: new THREE.Vector3(), energy: 0, first: true,
+ };
+ const qd = new THREE.Quaternion(), vtmp = new THREE.Vector3(), c = new THREE.Vector3();
+
+ function solve(dt) {
+ body.updateWorldMatrix(true, false);
+ const M = body.matrixWorld;
+ // Kinematics of the liquid's centre and the bottle's spin.
+ c.set(0, cavY, 0).applyMatrix4(M);
+ const q = pivot.getWorldQuaternion(qd.clone());
+ if (state.first || dt <= 0) { state.prevC.copy(c); state.prevQ.copy(q); state.first = false; }
+ const v = vtmp.copy(c).sub(state.prevC).divideScalar(Math.max(dt, 1e-4));
+ state.acc.lerp(v.clone().sub(state.prevV).divideScalar(Math.max(dt, 1e-4)), 1 - Math.exp(-18 * dt));
+ state.prevV.copy(v);
+ state.prevC.copy(c);
+ qd.copy(q).multiply(state.prevQ.clone().invert());
+ if (qd.w < 0) { qd.x = -qd.x; qd.y = -qd.y; qd.z = -qd.z; qd.w = -qd.w; }
+ const ang = 2 * Math.acos(clamp(qd.w, -1, 1));
+ const s = Math.sqrt(Math.max(1 - qd.w * qd.w, 1e-9));
+ const om = ang > 1e-5 ? tmp.set(qd.x / s, qd.y / s, qd.z / s).multiplyScalar(ang / Math.max(dt, 1e-4)) : tmp.set(0, 0, 0);
+ state.omega.lerp(om, 1 - Math.exp(-20 * dt));
+ state.prevQ.copy(q);
+
+ // Slosh: a damped 2D spring on the surface tilt.
+ const K = 92, C = 2.3;
+ const fx = -state.acc.x * 0.055 - state.omega.z * 0.9;
+ const fz = -state.acc.z * 0.055 + state.omega.x * 0.9;
+ state.wobV.x += (-K * state.wob.x - C * state.wobV.x + fx * 20) * dt;
+ state.wobV.y += (-K * state.wob.y - C * state.wobV.y + fz * 20) * dt;
+ state.wob.x += state.wobV.x * dt; state.wob.y += state.wobV.y * dt;
+ const L = state.wob.length();
+ if (L > 0.5) state.wob.multiplyScalar(0.5 / L);
+ state.energy = Math.min(1, state.wob.length() * 2.2 + state.wobV.length() * 0.18);
+ state.normal.set(state.wob.x, 1, state.wob.y).normalize();
+
+ // Level as a quantile of the cavity samples along the surface normal.
+ const e = M.elements, n = state.normal;
+ for (let i = 0; i < N; i++) {
+ const x = pts[i * 3], y = pts[i * 3 + 1], z = pts[i * 3 + 2];
+ vals[i] = n.x * (e[0] * x + e[4] * y + e[8] * z + e[12]) + n.y * (e[1] * x + e[5] * y + e[9] * z + e[13]) + n.z * (e[2] * x + e[6] * y + e[10] * z + e[14]);
+ }
+ vals.sort();
+ const f = clamp(state.fill);
+ let d;
+ if (f <= 0.0005) d = vals[0] - 0.02;
+ else if (f >= 0.9995) d = vals[N - 1] + 0.02;
+ else { const k = f * (N - 1), i0 = Math.floor(k); d = lerp(vals[i0], vals[Math.min(i0 + 1, N - 1)], k - i0); }
+ state.plane.set(n.x, n.y, n.z, d);
+ U.uRipple.value = 0.0012 + state.energy * 0.006;
+ U.uLevelVis.value = f > 0.0005 ? 1 : 0;
+
+ // Centre of the free surface: bottle axis ∩ plane.
+ const ax = tmp.set(0, 1, 0).transformDirection(M);
+ const denom = n.dot(ax);
+ const tHit = Math.abs(denom) > 0.2 ? (d - n.dot(c)) / denom : 0;
+ state.surf.copy(c).addScaledVector(ax, clamp(tHit, -cavH / 2, cavH / 2));
+ // Rough centroid of the liquid (between the cavity centre and the surface, biased downhill).
+ state.centroid.copy(c).lerp(state.surf, 0.35);
+ state.centroid.y = Math.min(state.centroid.y, d - 0.05);
+ }
+
+ return {
+ root, pivot, body, glass, GU, backMat, liquid, U, glassMesh, backMesh, liqMesh, cavMesh, label, state, solve,
+ setCap(cap) { body.add(cap); },
+ cavY, cavH,
+ };
+}
diff --git a/examples/nocturne/floor.js b/examples/nocturne/floor.js
new file mode 100644
index 0000000..fea3a61
--- /dev/null
+++ b/examples/nocturne/floor.js
@@ -0,0 +1,100 @@
+// Polished Nero Marquina floor: baked veined albedo + roughness, planar reflection, and the flacon's footprint:
+// a contact shadow, a bright rim where the thick base focuses light, and an amber caustic pool that follows the liquid.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture } from '../../src/core/textures.js';
+
+export function createFloor(renderer, reflection) {
+ const albedo = bakeTexture(renderer, 2048, `
+ void main(){
+ float w = fbm(vUv * 2.0, 2.0, 5, 0.55);
+ float w2 = fbm(vUv * 4.0 + 3.1, 4.0, 5, 0.5);
+ // Main calcite veins: a warped diagonal field, only where it crosses zero.
+ float fld = fbm(vec2(vUv.x * 2.0 + vUv.y * 2.0, vUv.y * 1.0) + vec2(w, w2) * 0.9, 2.0, 7, 0.55);
+ float vein = (1.0 - smoothstep(0.0, 0.0045, abs(fld))) * smoothstep(0.1, 0.5, fbm(vUv * 3.0 + 7.0, 3.0, 4, 0.5) + 0.35);
+ float halo = (1.0 - smoothstep(0.0, 0.035, abs(fld))) * 0.12;
+ float f2 = fbm(vec2(vUv.x * 5.0 - vUv.y * 5.0, vUv.y * 5.0) + w * 1.6, 5.0, 6, 0.5);
+ float vein2 = (1.0 - smoothstep(0.0, 0.006, abs(f2))) * 0.22 * smoothstep(0.0, 0.4, w2 + 0.2);
+ float cloud = fbm(vUv * 3.0, 3.0, 6, 0.6) * 0.5 + 0.5;
+ vec3 base = vec3(0.013, 0.012, 0.011) * (0.6 + cloud * 0.8);
+ vec3 col = base + vec3(0.34, 0.30, 0.25) * vein + vec3(0.10, 0.088, 0.072) * (halo + vein2);
+ gl_FragColor = vec4(col, 1.0);
+ }`);
+ const rough = bakeTexture(renderer, 1024, `
+ void main(){
+ float c = fbm(vUv * 6.0, 6.0, 5, 0.5) * 0.5 + 0.5;
+ float m = fbm(vUv * 40.0, 40.0, 3, 0.5) * 0.5 + 0.5;
+ float r = 0.05 + c * 0.07 + m * 0.03;
+ gl_FragColor = vec4(1.0, clamp(r, 0.03, 1.0), 0.0, 1.0);
+ }`);
+ const REP = 2;
+ albedo.repeat.set(REP, REP); rough.repeat.set(REP * 2, REP * 2);
+ const mat = new THREE.MeshStandardMaterial({ map: albedo, roughnessMap: rough, roughness: 1, metalness: 0, envMapIntensity: 0.0 });
+ const U = {
+ uBase: { value: new THREE.Vector3() }, uYaw: { value: new THREE.Vector2(1, 0) }, uContact: { value: 1 },
+ uCauC: { value: new THREE.Vector3(0.5, 0, 0.6) }, uCauDir: { value: new THREE.Vector2(0.6, 0.8) }, uCauI: { value: 0 },
+ uCauLen: { value: 0.9 }, uTime: { value: 0 }, uWob: { value: 0 }, uFade: { value: new THREE.Vector2(3.5, 13) },
+ uPool: { value: new THREE.Vector3(0, 0, 0) }, uPoolI: { value: 1 },
+ };
+ reflection.patch(mat, { strength: 1.15, distort: 0.004, lodScale: 6, lodBias: 0.2, f0: 0.045 });
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (sh, r) => {
+ prev(sh, r);
+ Object.assign(sh.uniforms, U);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ uniform vec3 uBase, uCauC, uPool; uniform vec2 uYaw, uCauDir, uFade; uniform float uContact, uCauI, uCauLen, uTime, uWob, uPoolI;
+ // Tileable water caustic (after Dave Hoskins): thin bright filaments.
+ float caus(vec2 uv, float t){
+ vec2 p = mod(uv * 6.28318, 6.28318) - 250.0;
+ vec2 i = p; float c = 1.0; float inten = 0.005;
+ for (int n = 0; n < 5; n++) {
+ float tt = t * (1.0 - (3.5 / float(n + 1)));
+ i = p + vec2(cos(tt - i.x) + sin(tt + i.y), sin(tt - i.y) + cos(tt + i.x));
+ c += 1.0 / length(vec2(p.x / (sin(i.x + tt) / inten), p.y / (cos(i.y + tt) / inten)));
+ }
+ c /= 5.0; c = 1.17 - pow(clamp(c, 0.0, 8.0), 1.4);
+ return pow(clamp(abs(c), 0.0, 1.0), 8.0);
+ }`)
+ .replace('#include <aomap_fragment>', '#include <aomap_fragment>\n reflectedLight.directSpecular *= 0.0; reflectedLight.indirectSpecular *= 0.0;')
+ .replace(/#include <opaque_fragment>(?![\s\S]*#include <opaque_fragment>)/, `
+ {
+ vec2 fp = vReflW.xz - uBase.xz;
+ vec2 lp = vec2(uYaw.x * fp.x - uYaw.y * fp.y, uYaw.y * fp.x + uYaw.x * fp.y);
+ vec2 q = abs(lp) - vec2(0.44, 0.26);
+ float sd = length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - 0.06;
+ float lift = clamp(uBase.y * 6.0, 0.0, 1.0);
+ float contact = (1.0 - smoothstep(-0.02, mix(0.09, 0.45, lift), sd)) * uContact * (1.0 - lift * 0.7);
+ outgoingLight *= 1.0 - contact * 0.8;
+ float rim = exp(-pow(sd / 0.006, 2.0)) * (1.0 - lift) * uContact;
+ outgoingLight += vec3(1.0, 0.72, 0.38) * rim * 0.08 * uCauI;
+ // Light through the perfume: the bottle's shadow swept along the key light, filled with amber caustics
+ // and one focused streak where the liquid block acts as a lens.
+ vec2 cp = vReflW.xz - uCauC.xz;
+ vec2 cl = vec2(dot(cp, uCauDir), dot(cp, vec2(-uCauDir.y, uCauDir.x)));
+ vec2 bq = abs(cl - vec2(uCauLen * 0.5, 0.0)) - vec2(uCauLen * 0.5, 0.34);
+ float bsd = length(max(bq, 0.0)) + min(max(bq.x, bq.y), 0.0) - 0.1;
+ float mask = smoothstep(0.1, -0.16, bsd) * smoothstep(-0.25, 0.08, cl.x);
+ float along = clamp(cl.x / max(uCauLen, 0.01), 0.0, 1.0);
+ vec2 cuv = vec2(cl.x * 0.55, cl.y * 0.9);
+ float tt = uTime * (0.32 + uWob * 1.8);
+ float c = caus(cuv, tt) + caus(cuv * 1.37 + 3.7, tt * 0.8 + 5.0) * 0.6;
+ float focus = exp(-pow((along - 0.62) / 0.1, 2.0)) * exp(-pow(cl.y / 0.22, 2.0));
+ vec3 amber = vec3(1.0, 0.42, 0.07);
+ float fall = mix(1.0, 0.45, along);
+ outgoingLight *= 1.0 - mask * 0.35;
+ outgoingLight += amber * uCauI * mask * (0.025 + c * 1.1 * fall + focus * (0.35 + c * 1.2));
+ // Soft pool of the key light around the bottle.
+ float pool = exp(-dot(vReflW.xz - uPool.xz, vReflW.xz - uPool.xz) / 5.5);
+ outgoingLight *= mix(0.55, 1.0, pool * uPoolI);
+ outgoingLight *= smoothstep(uFade.y, uFade.x, length(vReflW.xz - uPool.xz));
+ }
+ #include <opaque_fragment>`);
+ };
+ mat.customProgramCacheKey = () => 'nocturne-floor';
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(40, 40), mat);
+ mesh.rotation.x = -Math.PI / 2;
+ mesh.receiveShadow = true;
+ mesh.renderOrder = -20;
+ reflection.hidden.push(mesh);
+ return { mesh, mat, U };
+}
diff --git a/examples/nocturne/index.html b/examples/nocturne/index.html
new file mode 100644
index 0000000..2ca356d
--- /dev/null
+++ b/examples/nocturne/index.html
@@ -0,0 +1,195 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Nocturne No. 9 — Iris &amp; Oud, extrait de parfum</title>
+ <meta name="description" content="Nocturne No. 9, an extrait de parfum from a small house in Grasse. Iris, bergamot, vanilla, oud. Poured by hand since 1911.">
+ <meta name="theme-color" content="#050404">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Bodoni+Moda:ital,opsz,wght@0,6..96,400;0,6..96,500;1,6..96,400;1,6..96,500&family=Hanken+Grotesk:wght@300;400;500;600&family=Italiana&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="ld-flacon" aria-hidden="true">
+ <svg viewBox="0 0 80 120">
+ <defs><clipPath id="ldClip"><path d="M12 44h56l4 4v60l-4 4H12l-4-4V48z"/></clipPath></defs>
+ <rect class="ld-liquid" x="0" y="112" width="80" height="0" clip-path="url(#ldClip)"/>
+ <path class="ld-glass" d="M12 44h56l4 4v60l-4 4H12l-4-4V48z M33 44v-8h14v8"/>
+ <path class="ld-cap" d="M31 36h18l3-10-4-9H32l-4 9z"/>
+ </svg>
+ </div>
+ <p class="ld-word">Nocturne</p>
+ <p class="ld-line">Decanting <span class="ld-pct">0</span>%</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Nocturne, home">
+ <svg viewBox="0 0 16 22" aria-hidden="true"><path d="M3 9h10l1 1v10l-1 1H3l-1-1V10z M6.5 9V7h3v2 M6 7h4l.8-2.6L9.8 2H6.2l-1 2.4z" fill="none" stroke="currentColor" stroke-width="1"/></svg>
+ <span>Nocturne</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#bergamot">The notes</a>
+ <a href="#house">The house</a>
+ <a href="#shop">Discovery set</a>
+ </nav>
+ <div class="nav-right">
+ <span class="bag" aria-live="polite">Bag <b class="bag-n">0</b></span>
+ <a class="btn btn-ghost" href="#shop" data-magnetic>Shop No. 9</a>
+ </div>
+ </header>
+
+ <aside class="gauge" aria-label="Maceration: notes poured into the flacon">
+ <p class="gauge-title">No. 9<br><em>maceration</em></p>
+ <div class="gauge-bar"><i class="gauge-fill"></i>
+ <span class="gauge-tick" style="--y:.57" data-n="0">Bergamot</span>
+ <span class="gauge-tick" style="--y:.69" data-n="1">Iris</span>
+ <span class="gauge-tick" style="--y:.81" data-n="2">Vanilla</span>
+ <span class="gauge-tick" style="--y:.93" data-n="3">Oud</span>
+ </div>
+ <p class="gauge-pct"><span class="gauge-v">0</span>%</p>
+ </aside>
+
+ <main id="top">
+ <section class="hero" data-stop="0">
+ <h1 class="sr">Nocturne No. 9 — iris, bergamot, vanilla, oud.</h1>
+ <p class="hero-eyebrow"><span>Extrait de parfum</span><span class="dot"></span><span>Maison Nocturne, Grasse — since 1911</span></p>
+ <div class="hero-foot">
+ <div class="hero-copy">
+ <p class="hero-line">No. 9 — <em>iris, bergamot, vanilla, oud.</em></p>
+ <p class="hero-sub">Four raw materials, eleven months in a cold cellar, one heavy flacon poured by hand. 32% concentration: it sits on the skin until morning.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#shop" data-magnetic>50 ml — €290</a>
+ <a class="btn btn-text" href="#bergamot">Meet the notes</a>
+ </div>
+ </div>
+ <div class="hint" aria-hidden="true">
+ <span class="hint-ico"><i></i></span>
+ <span><b>Drag the flacon.</b><br>Tilt it — the perfume follows.</span>
+ </div>
+ </div>
+ <p class="scroll-cue" aria-hidden="true">Scroll — the notes arrive</p>
+ </section>
+
+ <section class="note" id="bergamot" data-stop="1" data-side="left">
+ <div class="note-pin">
+ <article class="note-card">
+ <p class="note-kicker"><span class="roman">I</span><span>Top note</span><span class="rule"></span><span>the first fifteen minutes</span></p>
+ <h2>Bergamot <em>di Calabria</em></h2>
+ <p class="latin">Citrus bergamia · Reggio Calabria, Italy</p>
+ <p class="note-body">The first thing you notice, and the first thing to leave. We buy green December fruit from a single grove above the Strait of Messina and press the rind cold, so the oil keeps its bitterness — a flash of light before the dark comes in.</p>
+ <dl class="facts">
+ <div><dt>Share of formula</dt><dd>11%</dd></div>
+ <div><dt>Harvest</dt><dd>December, unripe</dd></div>
+ <div><dt>Extraction</dt><dd>Cold-pressed rind</dd></div>
+ </dl>
+ </article>
+ </div>
+ </section>
+
+ <section class="note" id="iris" data-stop="2" data-side="right">
+ <div class="note-pin">
+ <article class="note-card">
+ <p class="note-kicker"><span class="roman">II</span><span>Heart note</span><span class="rule"></span><span>hour one to five</span></p>
+ <h2>Iris <em>pallida</em></h2>
+ <p class="latin">Orris root · the hills above Florence</p>
+ <p class="note-body">Orris is not the flower but the root. The rhizomes are lifted by hand, peeled, and left to dry in the dark for three years before they give anything up. What comes out is cool and powdery — violets, suede, rain on a warm stone. It is the most expensive thing we own.</p>
+ <dl class="facts">
+ <div><dt>Resting time</dt><dd>3 years</dd></div>
+ <div><dt>Yield</dt><dd>2 kg butter / tonne</dd></div>
+ <div><dt>Share of formula</dt><dd>24%</dd></div>
+ </dl>
+ </article>
+ </div>
+ </section>
+
+ <section class="note" id="vanilla" data-stop="3" data-side="left">
+ <div class="note-pin">
+ <article class="note-card">
+ <p class="note-kicker"><span class="roman">III</span><span>Base note</span><span class="rule"></span><span>arrives late, stays close</span></p>
+ <h2>Vanilla <em>Bourbon</em></h2>
+ <p class="latin">Vanilla planifolia · Sava coast, Madagascar</p>
+ <p class="note-body">Pods sweated and sun-dried for six months, until the vanillin blooms on the skin in tiny crystals. We steep them in our own alcohol for a full year — the slow way — so the sweetness never shouts. It is warmth left in a coat.</p>
+ <dl class="facts">
+ <div><dt>Curing</dt><dd>6 months</dd></div>
+ <div><dt>Tincture</dt><dd>12 months</dd></div>
+ <div><dt>Pods per litre</dt><dd>140</dd></div>
+ </dl>
+ </article>
+ </div>
+ </section>
+
+ <section class="note" id="oud" data-stop="4" data-side="right">
+ <div class="note-pin">
+ <article class="note-card">
+ <p class="note-kicker"><span class="roman">IV</span><span>Base note</span><span class="rule"></span><span>until morning</span></p>
+ <h2>Oud <em>of Assam</em></h2>
+ <p class="latin">Aquilaria agallocha · resin wood, Hojai</p>
+ <p class="note-body">Agarwood from one plantation, where the resin took fifteen years to form. Smoke, leather, the inside of an old violin case. There is less than half a percent of it in every flacon — the heaviest half-percent in perfumery — and it holds the other three in place all night.</p>
+ <dl class="facts">
+ <div><dt>Resin age</dt><dd>15 years</dd></div>
+ <div><dt>Distillation</dt><dd>9 days, copper</dd></div>
+ <div><dt>Share of formula</dt><dd>0.4%</dd></div>
+ </dl>
+ </article>
+ </div>
+ </section>
+
+ <section class="house" id="house" data-stop="5">
+ <div class="house-inner">
+ <p class="kicker">The house</p>
+ <h2>Grasse, <em>since 1911.</em></h2>
+ <p class="lede">Nocturne began as a shop on the Rue de l’Oratoire, where Honorine Vey sold violet pastilles by day and blended for three private clients by night. Four generations later we are still eleven people, one copper still, and a cellar that holds fourteen degrees all year.</p>
+ <p class="lede lede-2">Every flacon of No. 9 is macerated for eleven months, chilled, filtered through paper, and poured by the same two hands. The number on the base is written in ink. So is the name of the person who poured it.</p>
+ <div class="stats">
+ <div><b>1911</b><span>The first night blend, for a singer at the Opéra de Monte-Carlo</span></div>
+ <div><b>2,400</b><span>Flacons a year, each one numbered by hand</span></div>
+ <div><b>11</b><span>Months from maceration to bottle</span></div>
+ <div><b>1</b><span>Perfumer. Her name is on the box.</span></div>
+ </div>
+ </div>
+ </section>
+
+ <section class="shop" id="shop" data-stop="6">
+ <div class="shop-inner">
+ <p class="kicker">Wear the night</p>
+ <h2>Begin with <em>a drop.</em></h2>
+ <div class="products">
+ <article class="product">
+ <header><h3>The Discovery Set</h3><p class="price">€38</p></header>
+ <p>The four raw notes alone — bergamot, iris, vanilla, oud — in 2 ml vials, and 5 ml of No. 9 where they meet. Credited in full against your first flacon.</p>
+ <ul><li>4 × 2 ml single-note accords</li><li>5 ml No. 9 extrait</li><li>A card that explains the pyramid</li></ul>
+ <button class="btn btn-ghost add" data-item="Discovery Set" data-magnetic>Add to bag</button>
+ </article>
+ <article class="product product-lit">
+ <header><h3>No. 9 Extrait, 50 ml</h3><p class="price">€290</p></header>
+ <p>Cut-crystal flacon, hand-gilt stopper set with onyx. Numbered and signed. Refills of the perfume alone are €210, forever.</p>
+ <ul><li>32% concentration · 10–12 h on skin</li><li>Complimentary engraving</li><li>Shipped from Grasse within 48 hours</li></ul>
+ <button class="btn btn-solid add" data-item="No. 9 Extrait, 50 ml" data-magnetic>Add to bag — €290</button>
+ </article>
+ </div>
+ <p class="fine">Returns within 30 days, even opened. We would rather you love it.</p>
+ </div>
+ </section>
+
+ <footer class="foot" id="visit">
+ <div class="foot-inner">
+ <p class="foot-word" aria-hidden="true">Nocturne</p>
+ <div class="foot-cols">
+ <p>Maison Nocturne<br>14 Rue de l’Oratoire<br>06130 Grasse, France</p>
+ <p>Boutique Tuesday – Saturday, 11:00 – 19:00.<br>Open until midnight on every full moon.</p>
+ <nav aria-label="Footer"><a href="#bergamot">The notes</a><a href="#house">The house</a><a href="#shop">Discovery set</a><a href="#top">Care &amp; refills</a></nav>
+ </div>
+ <p class="legal"><span>© 2026 Maison Nocturne</span><span>No. 9 contains natural materials; colour may vary with each harvest.</span></p>
+ </div>
+ </footer>
+ </main>
+
+ <div class="toast" role="status"></div>
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/nocturne/main.js b/examples/nocturne/main.js
new file mode 100644
index 0000000..c944f97
--- /dev/null
+++ b/examples/nocturne/main.js
@@ -0,0 +1,681 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, sampleSurface, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { createBottle, DIM } from './bottle.js';
+import { createFloor } from './floor.js';
+import { createStream, burnKey, BURN_GLSL, BURN_A, BURN_B, DUR } from './stream.js';
+
+const D2R = Math.PI / 180;
+const Q = new URLSearchParams(location.search);
+const P_END = 1 + DUR * 1.25 + 0.04; // stream progress at which every particle has landed
+const FILL0 = 0.42, FILL_STEP = 0.12; // hero level, and what each note adds
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 26, near: 0.05, far: 60, dpr: 1.5, background: 0x040303,
+ post: {
+ ao: { aoRadius: 0.45, intensity: 1.6, distanceFalloff: 0.5 },
+ bloom: { intensity: 0.85, luminanceThreshold: 0.78, luminanceSmoothing: 0.28, radius: 0.72 },
+ tone: 'aces',
+ vignette: { offset: 0.2, darkness: 0.8 },
+ noise: 0.045,
+ ca: 0.0007,
+ },
+});
+const { scene, camera, renderer } = engine;
+// The transmission pass clears to 50% white when the clear alpha is < 1 (the AO pass leaves it at 0): a real
+// background colour makes the glass refract the black studio instead of a white void.
+scene.background = new THREE.Color(0x040303);
+// The studio rig is defined relative to the camera (camera on +Z looking at the flacon) and rotated with the orbit,
+// the way a photographer moves the softboxes with the camera: the long strip highlights stay put on the glass.
+const RIG = [
+ { pos: [-0.42, 2.0, 7.6], size: [0.13, 11], intensity: 9, color: 0xfff4e6, glass: 5 }, // the long front strip
+ { pos: [0.9, 1.6, 7.6], size: [0.06, 11], intensity: 4, color: 0xfff0dc, glass: 5 }, // its thin twin
+ { pos: [-7.6, 2.2, 0.9], size: [0.7, 12], intensity: 10, color: 0xfff1e0, glass: 2.2 }, // left side strip -> chamfers
+ { pos: [7.6, 2.2, -0.6], size: [0.5, 12], intensity: 7, color: 0xffeedd, glass: 2.2 }, // right side strip
+ { pos: [-3.0, 2.8, -7.0], size: [0.45, 11], intensity: 6, color: 0xffd99c, glass: 2.5 }, // gold rim strips behind
+ { pos: [3.4, 2.8, -7.0], size: [0.4, 11], intensity: 5, color: 0xffcf8a, glass: 2.5 },
+ { pos: [0.6, 9, 0.4], size: [3.0, 0.35], intensity: 2.2, color: 0xfff4e6, glass: 1.5 }, // top bar -> shoulders
+ { pos: [-4.5, 1.0, 6.0], size: [2.4, 2.4], intensity: 0.35, color: 0xffe6c4, glass: 1 }, // soft front fill
+];
+const ENV = studioEnvironment(renderer, { top: 0x0a0807, bottom: 0x010101, blur: 0.012, panels: RIG });
+// Glass only reflects ~4% head-on, so it sees the same rig with the strips driven much hotter (metal would blow out).
+const ENV_GLASS = studioEnvironment(renderer, { top: 0x0a0807, bottom: 0x010101, blur: 0.006, panels: RIG.map(p => ({ ...p, intensity: p.intensity * p.glass })) });
+scene.environment = ENV;
+scene.environmentIntensity = 1;
+// r186 ignores material.envMapIntensity unless the material owns its envMap, so every lit material gets ENV explicitly
+// (and its rotation is driven with the orbit, like scene.environmentRotation would be).
+const envMats = new Set();
+function useEnv(root, env = ENV) {
+ root.traverse(o => {
+ if (!o.isMesh) return;
+ for (const m of [o.material].flat()) if (m && (m.isMeshStandardMaterial) && !envMats.has(m)) { m.envMap = env; m.needsUpdate = true; envMats.add(m); }
+ });
+}
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 6 });
+const loaderEl = document.querySelector('.loader');
+const ldLiquid = loaderEl.querySelector('.ld-liquid');
+const ldPct = loaderEl.querySelector('.ld-pct');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ ldPct.textContent = Math.round(v * 100);
+ const h = 68 * v;
+ ldLiquid.setAttribute('y', 112 - h); ldLiquid.setAttribute('height', h);
+ },
+});
+
+// Fonts must exist before we paint them into textures.
+const fontsReady = Promise.race([
+ Promise.all(['400 120px "Bodoni Moda"', 'italic 400 120px "Bodoni Moda"', '400 120px Italiana', '500 30px "Hanken Grotesk"'].map(f => document.fonts.load(f))),
+ new Promise(r => setTimeout(r, 3500)),
+]);
+
+// ─── Lights ────────────────────────────────────────────────────────────────────
+const KEY_POS = new THREE.Vector3(-3.3, 3.8, -3.1);
+const key = new THREE.SpotLight(0xffdfb2, 170, 20, 0.34, 0.6, 1.7);
+key.position.copy(KEY_POS);
+key.target.position.set(0, 0.55, 0);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+key.shadow.camera.near = 1; key.shadow.camera.far = 14;
+key.shadow.bias = -0.0002; key.shadow.normalBias = 0.02; key.shadow.radius = 4;
+scene.add(key, key.target);
+const fill = new THREE.SpotLight(0xffeedd, 26, 18, 0.15, 0.8, 1.6);
+fill.position.set(3.4, 1.05, 4.6); fill.target.position.set(0, 1.45, 0);
+scene.add(fill, fill.target);
+const noteKey = new THREE.SpotLight(0xfff0dc, 0, 12, 0.45, 0.8, 1.5);
+scene.add(noteKey, noteKey.target);
+const noteRim = new THREE.SpotLight(0xffc98a, 0, 12, 0.5, 0.8, 1.5);
+scene.add(noteRim, noteRim.target);
+for (const l of [key, fill, noteKey, noteRim]) l.layers.enable(1);
+
+// ─── Floor & reflection ────────────────────────────────────────────────────────
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+const floor = createFloor(renderer, reflection);
+scene.add(floor.mesh);
+floor.mesh.layers.enable(1);
+
+// Backlight haze behind the flacon (additive, drawn over the floor so there is no horizon line).
+const glow = (() => {
+ const m = new THREE.ShaderMaterial({
+ uniforms: { uCol: { value: new THREE.Color(0.42, 0.22, 0.08) }, uI: { value: 0.1 } },
+ blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false,
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `varying vec2 vUv; uniform vec3 uCol; uniform float uI;
+ void main(){ vec2 p = (vUv - 0.5) * 2.0; p.y -= 0.08;
+ float r = length(p * vec2(1.0, 1.6));
+ float g = exp(-r * r * 7.0) * 0.8 + exp(-r * r * 26.0) * 0.9;
+ float col = exp(-pow(p.x * 11.0, 2.0)) * exp(-pow((p.y - 0.05) * 2.6, 2.0)) * 0.55;
+ gl_FragColor = vec4(uCol * (g + col) * uI, 1.0); }`,
+ });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(16, 11), m);
+ mesh.renderOrder = -10;
+ mesh.frustumCulled = false;
+ mesh.layers.enable(1);
+ scene.add(mesh);
+ reflection.hidden.push(mesh);
+ return { mesh, m };
+})();
+
+// The title, in the scene, behind the glass — so the flacon refracts it.
+const title = { mesh: null, mat: null, v: 0 };
+function makeTitle() {
+ const c = document.createElement('canvas'); c.width = 4096; c.height = 1100;
+ const g = c.getContext('2d');
+ g.fillStyle = '#000'; g.fillRect(0, 0, c.width, c.height);
+ const grd = g.createLinearGradient(0, 180, 0, 900);
+ grd.addColorStop(0, '#fff2d2'); grd.addColorStop(0.55, '#e3c283'); grd.addColorStop(1, '#8e6630');
+ g.fillStyle = grd; g.textAlign = 'center'; g.textBaseline = 'alphabetic';
+ g.font = '400 900px "Bodoni Moda", Didot, serif';
+ if ('letterSpacing' in g) g.letterSpacing = '-24px';
+ g.fillText('Nocturne', 2048, 830);
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8;
+ const mat = new THREE.MeshBasicMaterial({ map: t, blending: THREE.AdditiveBlending, depthWrite: false, color: new THREE.Color(0, 0, 0) });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(7.4, 7.4 * 1100 / 4096), mat);
+ mesh.position.set(0, 0.98, -2.1);
+ mesh.renderOrder = -5;
+ mesh.layers.enable(1);
+ scene.add(mesh);
+ title.mesh = mesh; title.mat = mat;
+}
+
+// ─── The flacon ────────────────────────────────────────────────────────────────
+let bottle;
+const bgRT = new THREE.WebGLRenderTarget(2, 2, { type: THREE.HalfFloatType, colorSpace: THREE.LinearSRGBColorSpace, depthBuffer: true });
+const bgCam = new THREE.PerspectiveCamera();
+bgCam.layers.set(1);
+engine.onResize((w, h, dpr) => bgRT.setSize(Math.round(w * dpr * 0.5), Math.round(h * dpr * 0.5)));
+
+// ─── Notes ─────────────────────────────────────────────────────────────────────
+const NOTES = [
+ { key: 'bergamot', file: 'models/nocturne/bergamot.glb', size: 1.05, axis: 'max', yaw: -30, pitch: 8 },
+ { key: 'iris', file: 'models/nocturne/iris.glb', size: 1.45, axis: 'y', yaw: 20, pitch: 0 },
+ { key: 'vanilla', file: 'models/nocturne/vanilla.glb', size: 1.2, axis: 'max', yaw: 70, pitch: 10 },
+ { key: 'oud', file: 'models/nocturne/oud.glb', size: 1.15, axis: 'max', yaw: -25, pitch: 0 },
+];
+
+// Scroll stops: camera orbit around the flacon, where the flacon sits on screen (lx, ly in NDC) and where the note floats.
+const STOPS = [
+ { yaw: 0, elev: 4.5, dist: 6.9, look: [0, 0.93, 0], lx: 0, ly: 0 },
+ { yaw: 30, elev: 9, dist: 6.9, look: [0, 0.9, 0], lx: 0.12, ly: 0, note: { nx: 0.57, ny: 0.1, dz: 0.4, side: 1 } },
+ { yaw: -32, elev: 13, dist: 7.0, look: [0, 0.92, 0], lx: -0.16, ly: 0, note: { nx: -0.64, ny: 0.14, dz: 0.3, side: -1 } },
+ { yaw: 58, elev: 19, dist: 6.8, look: [0, 0.82, 0], lx: 0.1, ly: 0.03, note: { nx: 0.53, ny: -0.1, dz: 0.5, side: 1 } },
+ { yaw: -60, elev: 5, dist: 7.0, look: [0, 0.9, 0], lx: -0.16, ly: 0, note: { nx: -0.63, ny: 0.05, dz: 0.3, side: -1 } },
+ { yaw: 22, elev: 9, dist: 4.7, look: [0, 0.98, 0], lx: 0.3, ly: 0.0 },
+ { yaw: -18, elev: 7, dist: 7.0, look: [0, 0.92, 0], lx: 0.34, ly: 0 },
+ { yaw: -30, elev: 12, dist: 9.2, look: [0, 0.9, 0], lx: 0.0, ly: 0.12 },
+];
+const mobile = () => innerWidth / innerHeight < 0.8;
+function stopView(k) {
+ const s = STOPS[k];
+ if (!mobile()) return s;
+ // Portrait: the flacon rides high, the copy sits underneath, notes float above the cap.
+ const m = { ...s, lx: 0, ly: 0.47, dist: s.dist * (k === 5 ? 2.0 : 2.0) };
+ if (s.note) m.note = { ...s.note, nx: s.note.side * 0.5, ny: 0.64, dz: 0.5 };
+ if (k === 0) { m.ly = 0.18; m.dist = s.dist * 1.62; }
+ return m;
+}
+
+const notes = NOTES.map((n, i) => ({ ...n, i, stop: i + 1, P: 0, arrive: 0, group: new THREE.Group(), rest: new THREE.Vector3(), from: new THREE.Vector3(), mesh: null, stream: null, U: null }));
+const noteLoads = notes.map(n => assets.gltf(n.file).then(g => {
+ const m = g.scene;
+ normalize(m, n.size, { ground: false, axis: n.axis });
+ prepModel(m, renderer, { env: 0.75, metal: 0 });
+ const holder = new THREE.Group();
+ holder.rotation.set(n.pitch * D2R, n.yaw * D2R, 0);
+ holder.add(m);
+ n.group.add(holder);
+ n.holder = holder;
+ n.mesh = firstMesh(m);
+ useEnv(m);
+ n.group.visible = false;
+ n.group.traverse(o => o.layers.enable(1));
+ scene.add(n.group);
+}).catch(e => console.warn('note missing', n.key, e.message)));
+
+let capModel = null;
+const capLoad = assets.gltf('models/nocturne/cap.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 0.6, { axis: 'y' });
+ prepModel(m, renderer, { env: 1.9, onMat: mat => {
+ mat.color?.setRGB(1.0, 0.93, 0.8);
+ // Point lights on a mirror-smooth onyx make a blinding pin; keep a hair of roughness.
+ mat.onBeforeCompile = sh => { sh.fragmentShader = sh.fragmentShader.replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\n roughnessFactor = max(roughnessFactor, 0.2);'); };
+ } });
+ capModel = m;
+ useEnv(m);
+});
+
+// Burn-dissolve for the note models (discard below a moving threshold, glowing gold at the front).
+function burnMaterial(n, dir, mm, freq) {
+ const U = { uBurn: { value: -1 }, uDir: { value: dir }, uMM: { value: new THREE.Vector2(...mm) }, uFreq: { value: freq }, uEdge: { value: new THREE.Color(1.0, 0.62, 0.22) } };
+ n.mesh.material.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, U);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vLocalP;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvLocalP = position;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', `#include <common>
+ varying vec3 vLocalP; uniform float uBurn, uFreq; uniform vec3 uDir, uEdge; uniform vec2 uMM; ${BURN_GLSL}`)
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>
+ float bk = burnKey(vLocalP, uDir, uMM, uFreq);
+ if (bk < uBurn) discard;
+ float bEdge = (1.0 - smoothstep(0.0, 0.045, bk - uBurn)) * step(-0.05, uBurn);`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ totalEmissiveRadiance += uEdge * bEdge * 7.0;`);
+ };
+ n.mesh.material.customProgramCacheKey = () => 'burn-' + n.key;
+ n.mesh.material.needsUpdate = true;
+ n.U = U;
+}
+
+// ─── Particles: dust, intro pour ─────────────────────────────────────────────
+const dust = (() => {
+ const N = 700;
+ const pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const a = Math.random() * Math.PI * 2, r = 0.5 + Math.pow(Math.random(), 0.7) * 4.5;
+ pos.set([Math.cos(a) * r, Math.random() * 3.2, Math.sin(a) * r], i * 3);
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uDpr: { value: 1 }, uI: { value: 1 } },
+ vertexShader: `attribute float seed; uniform float uTime, uDpr; varying float vA;
+ void main(){ vec3 p = position; float t = uTime * (0.03 + seed * 0.04);
+ p += vec3(sin(t * 3.1 + seed * 40.), 0.0, cos(t * 2.7 + seed * 27.)) * 0.4; p.y = mod(p.y + t * 0.6, 3.2);
+ vec4 mv = modelViewMatrix * vec4(p, 1.); gl_Position = projectionMatrix * mv;
+ vA = (0.25 + 0.75 * fract(seed * 91.7)) * smoothstep(0.0, 0.4, p.y) * smoothstep(3.2, 2.4, p.y);
+ gl_PointSize = (1.0 + seed * 2.2) * uDpr * (4.0 / -mv.z); }`,
+ fragmentShader: `varying float vA; uniform float uI; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .0, d); gl_FragColor = vec4(vec3(1.0, .8, .52) * a * vA * 0.5 * uI, 1.); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false; pts.renderOrder = 9;
+ scene.add(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ return mat;
+})();
+
+// Six spiral ribbons of gold that unwind into the flacon, inner ends first.
+function introCloud(N) {
+ const local = new Float32Array(N * 3), normal = new Float32Array(N * 3), color = new Float32Array(N * 3), key = new Float32Array(N);
+ const R = 6;
+ for (let i = 0; i < N; i++) {
+ const r = i % R, u = Math.pow(Math.random(), 0.85);
+ const a = r * Math.PI * 2 / R + u * 2.8 + (Math.random() - 0.5) * 0.12;
+ const rad = 0.95 + u * 2.6 + (Math.random() - 0.5) * 0.12 * (1 + u);
+ const y = 0.35 + u * 2.3 + Math.sin(u * 7 + r) * 0.18 + (Math.random() - 0.5) * 0.1;
+ local.set([Math.cos(a) * rad, y, Math.sin(a) * rad * 0.75 - 0.2], i * 3);
+ normal.set([-Math.sin(a) * 0.5, 0.35, Math.cos(a) * 0.5], i * 3);
+ const g = Math.random();
+ color.set([1.0, 0.62 + g * 0.2, 0.22 + g * 0.2], i * 3);
+ key[i] = Math.min(0.92, u * 0.86 + Math.random() * 0.05);
+ }
+ return { local, normal, color, key };
+}
+const intro = { P: 0, stream: null };
+
+// ─── Interaction: drag to tilt ─────────────────────────────────────────────────
+const drag = { on: false, x0: 0, y0: 0, lx: 0, dx: 0, dy: 0, used: false, id: null };
+const phys = { roll: 0, rollV: 0, pitch: 0, pitchV: 0, yaw: 0, yawV: 0, lift: 0, liftV: 0, demo: 0 };
+const cur = cursor({ color: '#e8cf95', blend: 'normal', size: 34 });
+cur?.set('hidden');
+let overBottle = false, cursorState = '';
+const bottleRect = { x0: 0, y0: 0, x1: 0, y1: 0 };
+function setCursor(s, label) { if (!cur || cursorState === s + label) return; cursorState = s + label; cur.set(s, label); }
+function isUi(t) { return !!t.closest?.('a,button,.product,.nav,.tw-nav'); }
+addEventListener('pointerdown', e => {
+ if (!bottle || (e.pointerType === 'mouse' && e.button !== 0) || isUi(e.target)) return;
+ const x = e.clientX, y = e.clientY;
+ if (x < bottleRect.x0 || x > bottleRect.x1 || y < bottleRect.y0 || y > bottleRect.y1) return;
+ drag.on = true; drag.x0 = drag.lx = x; drag.y0 = y; drag.dx = drag.dy = 0; drag.id = e.pointerId; drag.touch = e.pointerType !== 'mouse';
+ if (!drag.used) { drag.used = true; document.body.classList.add('has-tilted'); }
+ phys.demo = 0;
+ if (e.pointerType === 'mouse') e.preventDefault();
+}, { passive: false });
+addEventListener('pointermove', e => {
+ if (drag.on && e.pointerId === drag.id) {
+ drag.dx = e.clientX - drag.x0; drag.dy = e.clientY - drag.y0;
+ phys.yawV += (e.clientX - drag.lx) * 0.02;
+ drag.lx = e.clientX;
+ }
+ overBottle = e.clientX > bottleRect.x0 && e.clientX < bottleRect.x1 && e.clientY > bottleRect.y0 && e.clientY < bottleRect.y1 && !isUi(e.target);
+}, { passive: true });
+const release = e => { if (drag.on && (!e || e.pointerId === drag.id)) drag.on = false; };
+addEventListener('pointerup', release);
+addEventListener('pointercancel', release);
+
+// ─── Story (scroll) ────────────────────────────────────────────────────────────
+const stopEls = [...document.querySelectorAll('[data-stop]')];
+const footEl = document.querySelector('.foot');
+const cards = [...document.querySelectorAll('.note-card')];
+const heroEls = document.querySelectorAll('.hero-eyebrow, .hero-foot, .scroll-cue');
+let anchors = [];
+function measure() {
+ anchors = stopEls.map(el => el.offsetTop);
+ anchors.push(footEl.offsetTop - innerHeight * 0.2);
+}
+addEventListener('resize', measure);
+function storyAt(y) {
+ if (y <= anchors[0]) return 0;
+ for (let k = 0; k < anchors.length - 1; k++) {
+ if (y < anchors[k + 1]) return k + (y - anchors[k]) / (anchors[k + 1] - anchors[k]);
+ }
+ return anchors.length - 1;
+}
+
+// ─── Camera ────────────────────────────────────────────────────────────────────
+const camLook = new THREE.Vector3(), camPos = new THREE.Vector3();
+const v1 = new THREE.Vector3(), v2 = new THREE.Vector3(), v3 = new THREE.Vector3(), v4 = new THREE.Vector3();
+const qA = new THREE.Quaternion(), qB = new THREE.Quaternion(), qC = new THREE.Quaternion();
+const cs = { yaw: 0, elev: 5, dist: 7.4, lx: 0, ly: 0, look: new THREE.Vector3() };
+function blendStops(S, out) {
+ const n = STOPS.length - 1;
+ const i = Math.min(n - 1, Math.max(0, Math.floor(S)));
+ const a = stopView(i), b = stopView(i + 1);
+ const hold = a.note ? 0.24 : 0.05;
+ const f = smooth(hold, 0.96, S - i);
+ out.yaw = lerp(a.yaw, b.yaw, f); out.elev = lerp(a.elev, b.elev, f); out.dist = lerp(a.dist, b.dist, f);
+ out.lx = lerp(a.lx, b.lx, f); out.ly = lerp(a.ly, b.ly, f);
+ out.look.set(lerp(a.look[0], b.look[0], f), lerp(a.look[1], b.look[1], f), lerp(a.look[2], b.look[2], f));
+ // Arc the orbit slightly upwards mid-transition.
+ out.elev += Math.sin(f * Math.PI) * 3;
+ return out;
+}
+function placeCamera(c, cam, extraYaw = 0, extraElev = 0) {
+ const yaw = (c.yaw + extraYaw) * D2R, el = (c.elev + extraElev) * D2R;
+ cam.position.set(Math.sin(yaw) * Math.cos(el), Math.sin(el), Math.cos(yaw) * Math.cos(el)).multiplyScalar(c.dist).add(c.look);
+ cam.lookAt(c.look);
+ // Lens shift instead of re-aiming: the flacon moves on screen without changing the perspective.
+ const t = Math.tan(cam.fov * D2R / 2);
+ cam.filmOffset = -c.lx * cam.getFilmWidth() * cam.aspect * t;
+ cam.updateProjectionMatrix();
+ // Vertical placement: nudge the aim so the look point lands at NDC y = ly.
+ if (c.ly) {
+ const dy = c.ly * t * c.dist;
+ v1.set(0, 1, 0).applyQuaternion(cam.quaternion);
+ cam.lookAt(v2.copy(c.look).addScaledVector(v1, -dy));
+ }
+ cam.updateMatrixWorld();
+}
+// Note rest positions for a given stop, computed from that stop's camera so they land where the layout wants them.
+const stopCam = new THREE.PerspectiveCamera(26, 1, 0.05, 60);
+function notePose(n, out) {
+ const s = stopView(n.stop);
+ stopCam.aspect = camera.aspect; stopCam.fov = camera.fov;
+ const c = { ...s, look: new THREE.Vector3(...s.look) };
+ placeCamera(c, stopCam);
+ const z = s.dist - s.note.dz;
+ const t = Math.tan(stopCam.fov * D2R / 2);
+ const fwd = v1.set(0, 0, -1).applyQuaternion(stopCam.quaternion);
+ const right = v2.set(1, 0, 0).applyQuaternion(stopCam.quaternion);
+ const up = v3.set(0, 1, 0).applyQuaternion(stopCam.quaternion);
+ // Account for the lens shift: NDC x of the look point is lx.
+ const ndcX = s.note.nx - s.lx * 0, ndcY = s.note.ny;
+ v4.set(ndcX, ndcY, 0.5).unproject(stopCam).sub(stopCam.position).normalize();
+ const cosA = v4.dot(fwd);
+ out.rest.copy(stopCam.position).addScaledVector(v4, z / cosA);
+ out.from.copy(out.rest).addScaledVector(right, s.note.side * 2.6).addScaledVector(up, 0.9).addScaledVector(fwd, 0.6);
+ out.camRight = right.clone(); out.camFwd = fwd.clone();
+}
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const toastEl = document.querySelector('.toast');
+const gaugeFill = document.querySelector('.gauge-fill');
+const gaugeV = document.querySelector('.gauge-v');
+const gaugeTicks = [...document.querySelectorAll('.gauge-tick')];
+const rootStyle = document.documentElement.style;
+let S = 0, Sraw = 0, frameN = 0;
+let introFill = 0;
+const heroIn = { v: 0 };
+const bottleWorld = new THREE.Vector3();
+const tmpM = new THREE.Matrix4();
+const box = new THREE.Box3();
+const corners = Array.from({ length: 8 }, () => new THREE.Vector3());
+
+function tick(dt, t) {
+ pointer.update(dt);
+ Sraw = storyAt(window.scrollY);
+ S = damp(S, Sraw, 5.5, dt);
+ document.body.classList.toggle('is-story', S > 0.55 && S < 5.4);
+
+ // Camera
+ blendStops(S, cs);
+ const par = drag.on ? 0 : 1;
+ placeCamera(cs, camera, pointer.sx * 2.2 * par + Math.sin(t * 0.21) * 0.6, pointer.sy * 1.2 * par + Math.sin(t * 0.33) * 0.25);
+ scene.environmentRotation.y = cs.yaw * D2R;
+ for (const m of envMats) m.envMapRotation.y = cs.yaw * D2R;
+
+ // ── Bottle physics
+ const held = drag.on;
+ const rollT = held ? clamp(-drag.dx * 0.0062, -2.05, 2.05) : phys.demo - pointer.sx * 0.05 * (S < 0.5 ? 1 : 0);
+ const pitchT = held && !drag.touch ? clamp(drag.dy * 0.0045, -0.85, 0.85) : 0;
+ const K = held ? 70 : 34, C = held ? 13 : 5.2;
+ phys.rollV += (K * (rollT - phys.roll) - C * phys.rollV) * dt; phys.roll += phys.rollV * dt;
+ phys.pitchV += (K * (pitchT - phys.pitch) - C * phys.pitchV) * dt; phys.pitch += phys.pitchV * dt;
+ phys.yawV *= Math.exp(-(held ? 6 : 1.6) * dt);
+ phys.yaw += phys.yawV * dt;
+ const idleYaw = Math.sin(t * 0.23) * 0.06;
+ const tilt = Math.max(Math.abs(Math.sin(phys.roll)), Math.abs(Math.sin(phys.pitch)));
+ const liftT = held ? 0.26 + 0.34 * tilt : Math.max(0, 0.34 * tilt - 0.02);
+ phys.liftV += (46 * (liftT - phys.lift) - 10 * phys.liftV) * dt; phys.lift += phys.liftV * dt;
+ if (phys.lift < 0) { if (phys.liftV < -0.6) { bottle.state.wobV.x += phys.liftV * 0.6 * (Math.random() - 0.5); bottle.state.wobV.y += phys.liftV * 0.8; } phys.lift = 0; phys.liftV = -phys.liftV * 0.18; }
+ // Tilt axes follow the camera: horizontal drag = lean left/right on screen; vertical = toward/away.
+ const fwdFlat = v1.set(-Math.sin(cs.yaw * D2R), 0, -Math.cos(cs.yaw * D2R));
+ const rightFlat = v2.set(Math.cos(cs.yaw * D2R), 0, -Math.sin(cs.yaw * D2R));
+ qA.setFromAxisAngle(fwdFlat, -phys.roll);
+ qB.setFromAxisAngle(rightFlat, phys.pitch);
+ qC.setFromAxisAngle(v3.set(0, 1, 0), phys.yaw + idleYaw);
+ bottle.pivot.quaternion.copy(qA).multiply(qB).multiply(qC);
+ bottle.root.position.y = phys.lift;
+
+ // ── Notes: arrive with scroll, dissolve on a timer once you have read about them
+ let absorb = 0, noteFill = 0;
+ for (const n of notes) {
+ if (!n.mesh) continue;
+ const k = n.stop;
+ n.arrive = smooth(k - 0.62, k - 0.06, S);
+ const want = S > k + 0.14 ? P_END : 0;
+ const rate = want > n.P ? P_END / 3.6 : P_END / 1.8;
+ n.P = want > n.P ? Math.min(want, n.P + rate * dt) : Math.max(want, n.P - rate * dt);
+ const e = 1 - Math.pow(1 - n.arrive, 3);
+ n.group.position.lerpVectors(n.from, n.rest, e);
+ const calm = 1 - clamp(n.P * 2);
+ n.group.position.y += Math.sin(t * 0.9 + n.i * 2) * 0.035 * calm;
+ n.group.rotation.set(Math.sin(t * 0.5 + n.i) * 0.05 * calm, (1 - e) * n.side * -1.6 + Math.sin(t * 0.35 + n.i) * 0.2 * calm, (1 - e) * 0.4 * (n.i % 2 ? 1 : -1));
+ const sc = 0.55 + 0.45 * e;
+ n.group.scale.setScalar(sc);
+ n.U.uBurn.value = n.P > 0 ? Math.min(n.P, 1) * BURN_A - BURN_B : -1;
+ n.group.visible = n.arrive > 0.001 && n.P < 1.0;
+ const su = n.stream.uniforms;
+ su.uP.value = n.P;
+ n.stream.points.visible = n.P > 0.001 && n.P < P_END;
+ const arrived = clamp((n.P - 0.45) / (P_END - 0.45));
+ noteFill += arrived;
+ absorb += n.P > 0.3 && n.P < P_END ? Math.sin(clamp((n.P - 0.3) / (P_END - 0.3)) * Math.PI) : 0;
+ }
+ intro.stream.uniforms.uP.value = intro.P;
+ intro.stream.points.visible = intro.P > 0.001 && intro.P < P_END;
+ introFill = FILL0 * clamp((intro.P - 0.42) / (P_END - 0.42 - 0.05));
+ absorb += intro.P > 0.3 && intro.P < P_END ? Math.sin(clamp((intro.P - 0.3) / (P_END - 0.3)) * Math.PI) * 0.8 : 0;
+ bottle.state.fill = introFill + noteFill * FILL_STEP;
+ bottle.U.uAbsorb.value = damp(bottle.U.uAbsorb.value, Math.min(absorb, 1.2), 4, dt);
+ bottle.GU.uBaseGlow.value.setRGB(0.9, 0.36, 0.05).multiplyScalar(0.3 * clamp(bottle.state.fill * 4) * (1 + bottle.U.uAbsorb.value * 0.6));
+
+ bottle.solve(dt);
+ bottle.U.uTime.value = t;
+ bottle.body.updateWorldMatrix(true, true);
+
+ // Streams need the flacon's pose.
+ bottle.root.getWorldPosition(bottleWorld);
+ const axisC = v4.set(0, 1.25 + phys.lift, 0).add(bottleWorld);
+ for (const st of [intro.stream, ...notes.map(n => n.stream)]) {
+ if (!st || !st.points.visible) continue;
+ const u = st.uniforms;
+ u.uTime.value = t;
+ u.uBottleM.value.copy(bottle.body.matrixWorld);
+ u.uSurf.value.copy(bottle.state.surf);
+ u.uAxisC.value.copy(axisC);
+ }
+ for (const n of notes) if (n.mesh && n.stream.points.visible) n.stream.uniforms.uNoteM.value.copy(n.mesh.matrixWorld);
+
+ // Note lighting follows whichever note is on stage.
+ let best = null, bw = 0;
+ for (const n of notes) { if (!n.mesh || !n.group.visible) continue; const w = n.arrive * (1 - clamp(n.P)); if (w > bw) { bw = w; best = n; } }
+ if (best) {
+ const p = best.group.position;
+ noteKey.position.copy(p).addScaledVector(best.camRight, -best.side * 1.2).add(v1.set(0, 2.6, 0)).addScaledVector(best.camFwd, -1.8);
+ noteKey.target.position.copy(p);
+ noteRim.position.copy(p).addScaledVector(best.camRight, best.side * 1.6).add(v1.set(0, 1.4, 0)).addScaledVector(best.camFwd, 2.2);
+ noteRim.target.position.copy(p);
+ }
+ noteKey.intensity = damp(noteKey.intensity, 34 * bw, 6, dt);
+ noteRim.intensity = damp(noteRim.intensity, 40 * bw, 6, dt);
+
+ // ── Floor: contact, caustic pool projected from the key light through the liquid
+ const fu = floor.U;
+ fu.uTime.value = t;
+ fu.uBase.value.set(bottleWorld.x, phys.lift, bottleWorld.z);
+ fu.uYaw.value.set(Math.cos(phys.yaw), Math.sin(phys.yaw));
+ const cen = bottle.state.centroid;
+ const L = v1.copy(cen).sub(KEY_POS);
+ const hit = v2.copy(cen).addScaledVector(L, cen.y / Math.max(-L.y, 0.2));
+ const dir = v3.set(L.x, 0, L.z).normalize();
+ fu.uCauC.value.copy(bottleWorld).setY(0).addScaledVector(dir, 0.12).lerp(v2.set(hit.x, 0, hit.z), 0.35);
+ fu.uCauDir.value.set(dir.x, dir.z);
+ fu.uCauLen.value = 1.05 + tilt * 0.25 + Math.min(phys.lift, 0.3) * 0.5;
+ const fillVis = clamp(bottle.state.fill * 2.2);
+ fu.uCauI.value = fillVis * (0.85 + bottle.U.uAbsorb.value * 0.5) * (1 - clamp(phys.lift * 1.6) * 0.75);
+ fu.uWob.value = bottle.state.energy;
+ fu.uPool.value.set(0, 0, 0);
+
+ // Glow plane sits behind the flacon, facing the camera.
+ v1.copy(camera.position).sub(cs.look).setY(0).normalize();
+ glow.mesh.position.set(-v1.x * 5.5, 1.1, -v1.z * 5.5);
+ glow.mesh.lookAt(camera.position.x, 1.1, camera.position.z);
+ glow.m.uniforms.uI.value = 0.1 + bottle.U.uAbsorb.value * 0.04;
+
+ // Title: only in the hero.
+ if (title.mat) {
+ const tv = heroIn.v * (1 - smooth(0.02, 0.4, S));
+ title.mat.color.setScalar(tv * 0.6);
+ title.mesh.visible = tv > 0.002;
+ title.mesh.position.y = 0.98 + S * 0.6;
+ // Fit the word to the visible width at its depth (portrait screens).
+ const dz = camera.position.distanceTo(title.mesh.position);
+ const visW = 2 * dz * Math.tan(camera.fov * D2R / 2) * camera.aspect;
+ title.mesh.scale.setScalar(Math.min(1, visW * 0.94 / 7.4));
+ }
+ dust.uniforms.uTime.value = t;
+
+ // ── Screen-space box for grabbing the flacon
+ box.set(v1.set(-0.6, 0, -0.4), v2.set(0.6, 1.95, 0.4));
+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9;
+ for (let i = 0; i < 8; i++) {
+ corners[i].set(i & 1 ? box.max.x : box.min.x, i & 2 ? box.max.y : box.min.y, i & 4 ? box.max.z : box.min.z).add(bottleWorld).project(camera);
+ const sx = (corners[i].x + 1) / 2 * innerWidth, sy = (1 - corners[i].y) / 2 * innerHeight;
+ x0 = Math.min(x0, sx); x1 = Math.max(x1, sx); y0 = Math.min(y0, sy); y1 = Math.max(y1, sy);
+ }
+ const padX = (x1 - x0) * 0.12;
+ Object.assign(bottleRect, { x0: x0 - padX, x1: x1 + padX, y0: y0 - 10, y1: y1 + 10 });
+ if (drag.on) setCursor('drag', 'Tilt');
+ else if (overBottle) setCursor('drag', 'Drag');
+ else if (cursorState === 'dragDrag' || cursorState === 'dragTilt') setCursor('', '');
+
+ // ── HTML
+ for (let i = 0; i < cards.length; i++) {
+ const k = i + 1;
+ const vis = smooth(k - 0.42, k - 0.04, S) * (1 - smooth(k + 0.42, k + 0.6, S));
+ cards[i].style.opacity = vis.toFixed(3);
+ cards[i].style.transform = `translate3d(0, ${((1 - vis) * (S < k ? 30 : -30)).toFixed(1)}px, 0)`;
+ }
+ const hv = 1 - smooth(0.05, 0.3, S);
+ for (const el of heroEls) el.style.opacity = (hv * heroIn.v).toFixed(3);
+ const lvl = bottle.state.fill;
+ gaugeFill.style.setProperty('--fill', clamp(lvl).toFixed(4));
+ gaugeV.textContent = Math.round(clamp(lvl) * 100);
+ for (let i = 0; i < gaugeTicks.length; i++) gaugeTicks[i].classList.toggle('on', notes[i].P > P_END * 0.7);
+
+ // ── Offscreen passes
+ if (!Q.has('norefl')) reflection.update(scene, camera);
+ bgCam.position.copy(camera.position); bgCam.quaternion.copy(camera.quaternion);
+ bgCam.projectionMatrix.copy(camera.projectionMatrix); bgCam.projectionMatrixInverse.copy(camera.projectionMatrixInverse);
+ bgCam.updateMatrixWorld();
+ // (not before the first main frames: shadow maps don't exist yet and an empty shadow sampler would be bound)
+ if ((frameN = frameN + 1) > 3) {
+ const prevRT = renderer.getRenderTarget(), prevAuto = renderer.shadowMap.autoUpdate;
+ renderer.shadowMap.autoUpdate = false;
+ renderer.setRenderTarget(bgRT); renderer.clear(); renderer.render(scene, bgCam);
+ renderer.setRenderTarget(prevRT); renderer.shadowMap.autoUpdate = prevAuto;
+ }
+ bottle.U.uMainVP.value.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
+
+ engine.paused = footEl.getBoundingClientRect().top < -innerHeight * 0.3;
+}
+
+// ─── Shop ──────────────────────────────────────────────────────────────────────
+let bagN = 0, toastT;
+document.querySelectorAll('.add').forEach(b => b.addEventListener('click', () => {
+ bagN++;
+ document.querySelector('.bag-n').textContent = bagN;
+ toastEl.textContent = `${b.dataset.item} — added. Poured and shipped from Grasse within 48 h.`;
+ toastEl.classList.add('on');
+ clearTimeout(toastT); toastT = setTimeout(() => toastEl.classList.remove('on'), 3200);
+}));
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('nocturne', { theme: 'dark', corner: 'bl' });
+magnetic();
+smoothScroll({ lerp: 0.08 });
+reveal('.house h2, .shop h2', { type: 'lines', stagger: 0.1 });
+reveal('.lede', { type: 'lines', stagger: 0.05, y: '100%' });
+
+await fontsReady;
+bottle = createBottle({ renderer });
+scene.add(bottle.root);
+for (const m of [bottle.glassMesh, bottle.backMesh, bottle.liqMesh]) useEnv(m, ENV_GLASS);
+useEnv(bottle.root);
+bottle.U.uBg.value = bgRT.texture;
+makeTitle();
+await Promise.all([...noteLoads, capLoad]);
+if (capModel) {
+ capModel.position.y += DIM.neckTop - 0.085;
+ bottle.setCap(capModel);
+}
+
+// Sample every note into a stream (in mesh-local space, keyed by the same burn function the shader uses).
+function buildStreams() {
+ measure();
+ for (const n of notes) {
+ if (!n.mesh) continue;
+ notePose(n, n);
+ n.side = STOPS[n.stop].note.side;
+ n.group.position.copy(n.rest); n.group.rotation.set(0, 0, 0); n.group.scale.setScalar(1);
+ n.group.updateMatrixWorld(true);
+ }
+}
+buildStreams();
+const invM = new THREE.Matrix4(), nm = new THREE.Matrix3();
+for (const n of notes) {
+ if (!n.mesh) continue;
+ const COUNT = 15000;
+ const smp = sampleSurface(n.mesh, COUNT);
+ invM.copy(n.mesh.matrixWorld).invert();
+ nm.getNormalMatrix(invM);
+ const local = new Float32Array(COUNT * 3), normal = new Float32Array(COUNT * 3), keyA = new Float32Array(COUNT);
+ // Direction toward the flacon, in mesh space: the side facing the bottle burns first.
+ const toB = v1.set(0, 0.8, 0).sub(n.rest).transformDirection(invM).normalize();
+ let mn = 1e9, mx = -1e9;
+ for (let i = 0; i < COUNT; i++) {
+ v2.fromArray(smp.position, i * 3).applyMatrix4(invM);
+ local.set([v2.x, v2.y, v2.z], i * 3);
+ v3.fromArray(smp.normal, i * 3).applyMatrix3(nm).normalize();
+ normal.set([v3.x, v3.y, v3.z], i * 3);
+ const d = v2.dot(toB); mn = Math.min(mn, d); mx = Math.max(mx, d);
+ }
+ const freq = 2.4;
+ for (let i = 0; i < COUNT; i++) keyA[i] = burnKey(local[i * 3], local[i * 3 + 1], local[i * 3 + 2], toB, [mn, mx], freq);
+ n.stream = createStream({ local, normal, color: smp.color, key: keyA }, { size: 20 });
+ n.stream.uniforms.uSpin.value = n.side * 0.6;
+ n.stream.points.visible = false;
+ n.stream.points.layers.enable(1);
+ scene.add(n.stream.points);
+ burnMaterial(n, toB.clone(), [mn, mx], freq);
+ engine.onResize((w, h, dpr) => { n.stream.uniforms.uDpr.value = dpr * h / 900; });
+}
+intro.stream = createStream(introCloud(12000), { size: 20 });
+intro.stream.points.visible = false;
+scene.add(intro.stream.points);
+engine.onResize((w, h, dpr) => { intro.stream.uniforms.uDpr.value = dpr * h / 900; });
+addEventListener('resize', () => buildStreams());
+
+engine.onTick(tick);
+// Warm every program: show everything once, compile, hide again.
+for (const n of notes) { if (n.mesh) { n.group.visible = true; n.stream.points.visible = true; } }
+intro.stream.points.visible = true;
+bottle.state.fill = 0.5;
+renderer.compile(scene, camera);
+engine.start();
+await loader.finish();
+if (cursorState === '') cur?.set('');
+
+// Intro: an empty flacon; gold gathers from the dark and pours itself in. Then a nudge that says "you can tilt this".
+if (Q.has('skip')) { heroIn.v = 1; intro.P = P_END; } else {
+ gsap.to(heroIn, { v: 1, duration: 2.6, ease: 'power2.inOut', delay: 0.3 });
+ gsap.to(intro, { P: P_END, duration: 4.4, ease: 'power1.inOut', delay: 0.1 });
+}
+gsap.from('.nav', { opacity: 0, y: -10, duration: 1.4, ease: 'power3.out', delay: 1.2 });
+if (!Q.has('still')) gsap.timeline({ delay: 4.6 }).to(phys, { demo: 0.32, duration: 0.7, ease: 'power2.inOut' }).to(phys, { demo: -0.2, duration: 0.8, ease: 'power2.inOut' }).to(phys, { demo: 0, duration: 0.9, ease: 'power2.inOut' });
+
+const scrollForS = v => { const k = Math.min(Math.floor(v), anchors.length - 1), f = v - k; const a = anchors[k], b = anchors[k + 1] ?? a; return a + (b - a) * f; };
+window.__noct = { studioEnvironment, renderer, ENV, ENV_GLASS, envMats, key, fill, noteKey, noteRim, go: v => window.__lenis.scrollTo(scrollForS(v), { immediate: true }), anchors: () => anchors, S: () => S, notes, bottle, phys, drag, intro, scene, engine, floor, glow, title, reflection, bgRT, THREE };
diff --git a/examples/nocturne/stream.js b/examples/nocturne/stream.js
new file mode 100644
index 0000000..15e6f70
--- /dev/null
+++ b/examples/nocturne/stream.js
@@ -0,0 +1,97 @@
+// Golden particle streams: a note's surface burns away point by point and each point flies, on its own curve,
+// around the flacon and into the liquid surface. One draw call per note; everything is computed in the vertex shader
+// from a single progress uniform, so it can play forwards and backwards.
+import { THREE } from '../../src/core/engine.js';
+
+export const BURN_GLSL = /* glsl */`
+ float burnNoise(vec3 p){
+ return 0.5 + 0.25 * sin(p.x * 1.7 + sin(p.y * 2.3 + p.z * 0.7)) * sin(p.z * 1.9 + p.y * 1.3)
+ + 0.25 * sin(p.y * 3.1 + sin(p.x * 2.9 - p.z * 1.1) * 1.4);
+ }
+ float burnKey(vec3 p, vec3 dir, vec2 mm, float freq){
+ float a = 1.0 - clamp((dot(p, dir) - mm.x) / (mm.y - mm.x), 0.0, 1.0);
+ return clamp(0.7 * a + 0.3 * burnNoise(p * freq), 0.0, 1.0);
+ }
+`;
+const fract = v => v - Math.floor(v);
+export function burnNoise(x, y, z) {
+ return 0.5 + 0.25 * Math.sin(x * 1.7 + Math.sin(y * 2.3 + z * 0.7)) * Math.sin(z * 1.9 + y * 1.3)
+ + 0.25 * Math.sin(y * 3.1 + Math.sin(x * 2.9 - z * 1.1) * 1.4);
+}
+export function burnKey(x, y, z, dir, mm, freq) {
+ const a = 1 - Math.min(1, Math.max(0, ((x * dir.x + y * dir.y + z * dir.z) - mm[0]) / (mm[1] - mm[0])));
+ return Math.min(1, Math.max(0, 0.7 * a + 0.3 * burnNoise(x * freq, y * freq, z * freq)));
+}
+// uBurn(P) = P * BURN_A - BURN_B, P in [0, 1 + DUR]
+export const BURN_A = 1.12, BURN_B = 0.08, DUR = 0.62;
+
+const VERT = /* glsl */`
+ attribute vec3 aLocal; attribute vec3 aNormal; attribute vec3 aColor; attribute float aKey; attribute vec4 aRand;
+ uniform mat4 uNoteM; uniform mat4 uBottleM; uniform vec3 uSurf; uniform vec3 uAxisC; uniform float uAxisR;
+ uniform float uP, uTime, uDpr, uSize, uDur, uBurnA, uBurnB, uSpin;
+ varying vec3 vCol; varying float vA;
+ vec3 bez(vec3 a, vec3 b, vec3 c, vec3 d, float t){ float s = 1.0 - t; return s*s*s*a + 3.0*s*s*t*b + 3.0*s*t*t*c + t*t*t*d; }
+ void main(){
+ float rel = (aKey + uBurnB) / uBurnA;
+ float t = clamp((uP - rel) / (uDur * (0.75 + aRand.w * 0.5)), 0.0, 1.0);
+ if (t <= 0.0 || t >= 1.0) { gl_Position = vec4(0.0, 0.0, -2.0, 1.0); gl_PointSize = 0.0; vA = 0.0; vCol = vec3(0.0); return; }
+ vec3 s = (uNoteM * vec4(aLocal, 1.0)).xyz;
+ vec3 nW = normalize(mat3(uNoteM) * aNormal);
+ vec3 e = uSurf + mat3(uBottleM) * vec3((aRand.x - 0.5) * 0.5, 0.0, (aRand.y - 0.5) * 0.28);
+ // Around the flacon on the way in.
+ vec3 toS = s - uAxisC; toS.y = 0.0;
+ float a0 = atan(toS.z, toS.x) + (aRand.z - 0.5) * 1.6 + uSpin;
+ vec3 ring = uAxisC + vec3(cos(a0), 0.0, sin(a0)) * uAxisR * (0.8 + aRand.x * 0.5) + vec3(0.0, 0.25 + aRand.y * 0.55, 0.0);
+ vec3 p1 = s + nW * (0.18 + aRand.z * 0.35) + vec3(0.0, 0.12 + aRand.w * 0.2, 0.0);
+ float te = t < 0.5 ? 4.0 * t * t * t : 1.0 - pow(-2.0 * t + 2.0, 3.0) / 2.0;
+ te = mix(t, te, 0.6);
+ vec3 p = bez(s, p1, ring, e, te);
+ // Curl-ish drift so a paused stream still breathes.
+ float w = sin(t * 3.14159);
+ p += vec3(sin(uTime * 1.3 + aRand.x * 40.0 + t * 7.0), sin(uTime * 1.1 + aRand.y * 30.0 + t * 5.0), cos(uTime * 1.2 + aRand.z * 20.0 + t * 6.0)) * 0.035 * w;
+ // Swirl about the bottle axis in the second half.
+ vec3 r = p - uAxisC; float sw = (1.0 - t) * t * 2.2 * (aRand.x > 0.5 ? 1.0 : -1.0);
+ float cs = cos(sw), sn = sin(sw);
+ p = uAxisC + vec3(r.x * cs - r.z * sn, r.y, r.x * sn + r.z * cs);
+ vec3 gold = mix(vec3(1.0, 0.5, 0.12), vec3(1.0, 0.72, 0.36), aRand.z * aRand.z);
+ float burn = exp(-t * 22.0);
+ vCol = mix(aColor * 1.4 + gold * 0.35, gold * 1.7, smoothstep(0.02, 0.32, t)) * (1.0 + burn * 3.0);
+ vA = smoothstep(1.0, 0.86, t) * (0.35 + 0.65 * aRand.w) * 0.6;
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = uSize * (0.6 + aRand.y * 0.9) * (1.0 + burn * 1.5) * uDpr / -mv.z;
+ }
+`;
+const FRAG = /* glsl */`
+ varying vec3 vCol; varying float vA;
+ void main(){ vec2 d = gl_PointCoord - 0.5; float r = dot(d, d); float a = exp(-r * 18.0);
+ gl_FragColor = vec4(vCol * a * vA, 1.0); }
+`;
+
+/**
+ * pts: { local: Float32Array(3N), normal: Float32Array(3N), color: Float32Array(3N), key: Float32Array(N) }
+ */
+export function createStream(pts, { size = 9 } = {}) {
+ const N = pts.key.length;
+ const g = new THREE.BufferGeometry();
+ const rand = new Float32Array(N * 4);
+ for (let i = 0; i < N * 4; i++) rand[i] = Math.random();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(N * 3), 3));
+ g.setAttribute('aLocal', new THREE.BufferAttribute(pts.local, 3));
+ g.setAttribute('aNormal', new THREE.BufferAttribute(pts.normal, 3));
+ g.setAttribute('aColor', new THREE.BufferAttribute(pts.color, 3));
+ g.setAttribute('aKey', new THREE.BufferAttribute(pts.key, 1));
+ g.setAttribute('aRand', new THREE.BufferAttribute(rand, 4));
+ const uniforms = {
+ uNoteM: { value: new THREE.Matrix4() }, uBottleM: { value: new THREE.Matrix4() }, uSurf: { value: new THREE.Vector3() },
+ uAxisC: { value: new THREE.Vector3() }, uAxisR: { value: 0.85 }, uP: { value: 0 }, uTime: { value: 0 }, uDpr: { value: 1 },
+ uSize: { value: size }, uDur: { value: DUR }, uBurnA: { value: BURN_A }, uBurnB: { value: BURN_B }, uSpin: { value: 0 },
+ };
+ const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: VERT, fragmentShader: FRAG, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending });
+ const points = new THREE.Points(g, mat);
+ points.frustumCulled = false;
+ points.renderOrder = 8;
+ return { points, uniforms, count: N };
+}
+
+export { fract };
diff --git a/examples/nocturne/style.css b/examples/nocturne/style.css
new file mode 100644
index 0000000..519681c
--- /dev/null
+++ b/examples/nocturne/style.css
@@ -0,0 +1,190 @@
+:root {
+ --bg: #050404;
+ --ink: #efe6d5;
+ --muted: #9a8f7e;
+ --dim: #6d6457;
+ --gold: #d8b56a;
+ --gold-hi: #f1d79c;
+ --amber: #c06a1f;
+ --line: rgba(216, 181, 106, .18);
+ --faint: rgba(239, 230, 213, .1);
+ --display: 'Bodoni Moda', 'Didot', 'Times New Roman', serif;
+ --label: 'Italiana', 'Bodoni Moda', serif;
+ --sans: 'Hanken Grotesk', system-ui, sans-serif;
+ --pad: clamp(18px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 16px/1.6 var(--sans); background: var(--bg); overflow-x: hidden; touch-action: pan-y; }
+a { color: inherit; }
+button { font: inherit; color: inherit; border: 0; background: none; cursor: pointer; }
+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
+em { font-style: italic; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+
+/* loader */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--bg); display: grid; place-content: center; justify-items: center; gap: 18px; }
+.ld-flacon svg { width: 64px; height: 96px; overflow: visible; }
+.ld-glass { fill: none; stroke: rgba(239,230,213,.45); stroke-width: 1; }
+.ld-cap { fill: none; stroke: var(--gold); stroke-width: 1; }
+.ld-liquid { fill: #b0621d; }
+.ld-word { font: 400 30px/1 var(--label); letter-spacing: .42em; text-transform: uppercase; margin-right: -.42em; color: var(--ink); margin-top: 10px; }
+.ld-line { font: 400 italic 15px/1 var(--display); color: var(--muted); letter-spacing: .02em; }
+.ld-pct { font-variant-numeric: tabular-nums; }
+
+/* nav */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 20; display: grid; grid-template-columns: 1fr auto 1fr; align-items: center;
+ padding: 22px var(--pad); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; font: 400 17px/1 var(--label); letter-spacing: .38em; text-transform: uppercase; justify-self: start; }
+.brand svg { width: 14px; height: 20px; color: var(--gold); }
+.links { display: flex; gap: 40px; }
+.links a { text-decoration: none; font: 500 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); transition: color .3s; }
+.links a:hover { color: var(--gold-hi); }
+.nav-right { justify-self: end; display: flex; align-items: center; gap: 22px; }
+.bag { font: 500 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.bag b { color: var(--gold); font-weight: 500; margin-left: 4px; }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 999px;
+ text-decoration: none; font: 500 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; white-space: nowrap;
+ transition: background .4s, color .4s, box-shadow .4s; }
+.btn-ghost { box-shadow: inset 0 0 0 1px rgba(216,181,106,.4); color: var(--ink); background: rgba(8,7,6,.35); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--gold); color: var(--gold-hi); }
+.btn-solid { background: linear-gradient(180deg, #e7c985, #c9a258); color: #1a1208; box-shadow: 0 10px 40px -12px rgba(216,181,106,.5), inset 0 1px 0 rgba(255,255,255,.35); }
+.btn-solid:hover { background: linear-gradient(180deg, #f3d99c, #d6ae62); box-shadow: 0 10px 50px -8px rgba(216,181,106,.7), inset 0 1px 0 rgba(255,255,255,.45); }
+.btn-text { padding: 0 6px; color: var(--ink); height: 46px; }
+.btn-text::after { content: ''; width: 26px; height: 1px; background: var(--gold); transition: width .4s; }
+.btn-text:hover::after { width: 42px; }
+
+/* gauge */
+.gauge { position: fixed; right: var(--pad); top: 50%; transform: translateY(-50%); z-index: 8; display: grid; justify-items: end; gap: 14px;
+ opacity: 0; transition: opacity .8s; pointer-events: none; }
+.is-story .gauge { opacity: 1; }
+.gauge-title { font: 400 13px/1.25 var(--label); letter-spacing: .24em; text-transform: uppercase; text-align: right; color: var(--muted); }
+.gauge-title em { font: italic 400 14px/1 var(--display); letter-spacing: .02em; text-transform: none; color: var(--gold); }
+.gauge-bar { position: relative; width: 1px; height: 34vh; background: rgba(239,230,213,.14); }
+.gauge-fill { position: absolute; left: -1px; right: -1px; bottom: 0; height: calc(var(--fill, 0) * 100%); background: linear-gradient(0deg, #8a3e0c, var(--gold)); box-shadow: 0 0 12px rgba(216,140,60,.6); }
+.gauge-tick { position: absolute; right: 12px; bottom: calc(var(--y) * 100% - 6px); font: 500 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase;
+ color: var(--dim); white-space: nowrap; transition: color .6s; }
+.gauge-tick::after { content: ''; position: absolute; right: -16px; top: 50%; width: 7px; height: 1px; background: currentColor; }
+.gauge-tick.on { color: var(--gold-hi); }
+.gauge-pct { font: 400 italic 20px/1 var(--display); color: var(--ink); font-variant-numeric: tabular-nums; }
+
+/* hero */
+.hero { position: relative; height: 100vh; min-height: 620px; z-index: 2; pointer-events: none; }
+.hero-eyebrow { position: absolute; left: var(--pad); top: calc(88px + 4vh); display: flex; align-items: center; gap: 14px;
+ font: 500 11px/1 var(--sans); letter-spacing: .24em; text-transform: uppercase; color: var(--muted); }
+.hero-eyebrow .dot { width: 4px; height: 4px; border-radius: 50%; background: var(--gold); }
+.hero-foot { position: absolute; left: var(--pad); right: var(--pad); bottom: 7vh; display: flex; justify-content: space-between; align-items: flex-end; gap: 40px; }
+.hero-copy { max-width: 470px; pointer-events: auto; }
+.hero-line { font: 400 clamp(24px, 2.3vw, 36px)/1.12 var(--display); letter-spacing: -.01em; color: var(--ink); }
+.hero-line em { color: var(--gold-hi); }
+.hero-sub { margin-top: 16px; font-size: 15px; line-height: 1.6; color: var(--muted); max-width: 30em; }
+.hero-cta { display: flex; gap: 14px; align-items: center; margin-top: 26px; }
+.hint { display: flex; align-items: center; gap: 16px; font: 400 13px/1.45 var(--sans); color: var(--muted); text-align: left; transition: opacity .8s; }
+.hint b { color: var(--ink); font-weight: 500; }
+.hint-ico { width: 46px; height: 46px; border-radius: 50%; box-shadow: inset 0 0 0 1px rgba(216,181,106,.45); position: relative; flex: none; }
+.hint-ico i { position: absolute; left: 50%; top: 50%; width: 8px; height: 8px; margin: -4px; border-radius: 50%; background: var(--gold); animation: nudge 2.6s cubic-bezier(.6,0,.3,1) infinite; box-shadow: 0 0 14px var(--gold); }
+@keyframes nudge { 0%, 100% { transform: translateX(-9px); } 50% { transform: translateX(9px); } }
+.has-tilted .hint { opacity: .35; }
+.scroll-cue { position: absolute; left: 50%; bottom: 2.6vh; transform: translateX(-50%); font: 400 italic 13px/1 var(--display); color: var(--dim); letter-spacing: .04em; white-space: nowrap; }
+.scroll-cue::before { content: ''; position: absolute; left: 50%; bottom: calc(100% + 10px); width: 1px; height: 26px; background: linear-gradient(transparent, var(--gold)); animation: drip 2.4s ease-in-out infinite; transform-origin: top; }
+@keyframes drip { 0% { transform: scaleY(0); opacity: 1; } 60% { transform: scaleY(1); opacity: 1; } 100% { transform: scaleY(1); opacity: 0; } }
+
+/* note sections */
+.note { position: relative; height: 240vh; z-index: 2; pointer-events: none; }
+.note-pin { position: sticky; top: 0; height: 100vh; display: flex; align-items: center; padding: 0 var(--pad); }
+.note[data-side="right"] .note-pin { justify-content: flex-end; padding-right: calc(var(--pad) + 108px); }
+.note-card { width: min(450px, 38vw); opacity: 0; will-change: opacity, transform; }
+.note-kicker { display: flex; align-items: center; gap: 12px; font: 500 10.5px/1 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--muted); margin-bottom: 26px; }
+.note-kicker .roman { font: 400 22px/1 var(--label); letter-spacing: .1em; color: var(--gold); margin-right: 4px; }
+.note-kicker .rule { width: 28px; height: 1px; background: var(--line); }
+.note h2 { font: 400 clamp(52px, 6.2vw, 104px)/.92 var(--display); letter-spacing: -.03em; }
+.note h2 em { display: block; font-size: .5em; letter-spacing: -.01em; color: var(--gold-hi); margin-top: .18em; }
+.latin { margin-top: 18px; font: 400 italic 15px/1.4 var(--display); color: var(--muted); }
+.note-body { margin-top: 24px; font-size: 16px; line-height: 1.7; color: #cdc2b0; max-width: 29em; }
+.facts { display: grid; grid-template-columns: repeat(3, auto); gap: 0 30px; margin-top: 34px; padding-top: 22px; border-top: 1px solid var(--line); justify-content: start; }
+.facts dt { font: 500 9.5px/1.3 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--dim); }
+.facts dd { margin-top: 8px; font: 400 18px/1.2 var(--display); color: var(--ink); }
+
+/* house */
+.kicker { font: 500 11px/1 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: var(--gold); margin-bottom: 26px; }
+.house { position: relative; z-index: 2; min-height: 190vh; padding: 26vh var(--pad) 22vh; pointer-events: none; }
+.house-inner { max-width: 1320px; margin: 0 auto; }
+.house h2, .shop h2 { font: 400 clamp(56px, 7.4vw, 124px)/.9 var(--display); letter-spacing: -.035em; max-width: 7.5em; }
+.house h2 em, .shop h2 em { color: var(--gold-hi); }
+.lede { max-width: 31em; margin-top: 40px; font: 400 clamp(17px, 1.35vw, 20px)/1.65 var(--sans); color: #cabfad; }
+.lede-2 { margin-top: 20px; color: var(--muted); }
+.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 36px; margin-top: 44vh; padding-top: 34px; border-top: 1px solid var(--line); }
+.stats b { display: block; font: 400 clamp(46px, 4.6vw, 76px)/1 var(--display); letter-spacing: -.03em; color: var(--gold-hi); font-variant-numeric: lining-nums; }
+.stats span { display: block; margin-top: 14px; font-size: 14px; line-height: 1.5; color: var(--muted); max-width: 17em; }
+
+/* shop */
+.shop { position: relative; z-index: 2; min-height: 150vh; padding: 22vh var(--pad) 20vh; pointer-events: none; }
+.shop-inner { max-width: 1320px; margin: 0 auto; }
+.products { display: grid; grid-template-columns: repeat(2, minmax(0, 330px)); gap: 20px; margin-top: 60px; }
+.product { pointer-events: auto; padding: 30px 28px 28px; border-radius: 3px; display: grid; gap: 18px; align-content: start;
+ background: linear-gradient(180deg, rgba(20,16,12,.72), rgba(10,8,7,.55)); backdrop-filter: blur(14px) saturate(1.2); -webkit-backdrop-filter: blur(14px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px var(--faint), 0 40px 80px -30px rgba(0,0,0,.9); }
+.product-lit { box-shadow: inset 0 0 0 1px rgba(216,181,106,.45), 0 40px 80px -30px rgba(0,0,0,.9);
+ background: radial-gradient(130% 80% at 50% -10%, rgba(216,160,80,.16), transparent 60%), linear-gradient(180deg, rgba(20,16,12,.78), rgba(10,8,7,.6)); }
+.product header { display: flex; justify-content: space-between; align-items: baseline; gap: 16px; }
+.product h3 { font: 400 25px/1.1 var(--display); letter-spacing: -.01em; }
+.price { font: 400 italic 26px/1 var(--display); color: var(--gold-hi); }
+.product > p { font-size: 14.5px; line-height: 1.6; color: #bfb4a2; }
+.product ul { list-style: none; display: grid; gap: 8px; font-size: 13.5px; color: var(--muted); }
+.product li::before { content: ''; display: inline-block; width: 12px; height: 1px; background: var(--gold); vertical-align: middle; margin-right: 12px; }
+.product .btn { justify-self: start; margin-top: 6px; }
+.fine { margin-top: 28px; font: 400 italic 15px/1.5 var(--display); color: var(--dim); }
+
+/* footer */
+.foot { position: relative; z-index: 4; background: linear-gradient(180deg, rgba(5,4,4,0), var(--bg) 26vh); padding: 34vh var(--pad) 40px; }
+.foot-inner { max-width: 1320px; margin: 0 auto; }
+.foot-word { font: 400 clamp(80px, 17vw, 300px)/.8 var(--display); letter-spacing: -.05em; color: transparent;
+ background: linear-gradient(180deg, #f1d79c 0%, #b88a45 55%, #3a2410 100%); -webkit-background-clip: text; background-clip: text; margin-left: -.04em; }
+.foot-cols { display: grid; grid-template-columns: 1fr 1fr auto; gap: 40px; margin-top: 70px; padding-top: 34px; border-top: 1px solid var(--line); font-size: 14px; line-height: 1.8; color: var(--muted); }
+.foot-cols nav { display: grid; gap: 4px; justify-items: end; }
+.foot-cols a { text-decoration: none; color: var(--ink); transition: color .3s; }
+.foot-cols a:hover { color: var(--gold-hi); }
+.legal { display: flex; justify-content: space-between; gap: 20px; margin-top: 60px; padding-bottom: 50px; font-size: 12px; color: var(--dim); }
+
+.toast { position: fixed; left: 50%; bottom: 5vh; transform: translate(-50%, 16px); z-index: 30; padding: 14px 24px; border-radius: 999px;
+ background: rgba(16,12,9,.86); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px rgba(216,181,106,.35); font-size: 13px; letter-spacing: .04em;
+ opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; white-space: nowrap; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+@media (max-width: 900px) {
+ .links, .bag { display: none; }
+ .nav { grid-template-columns: 1fr auto; padding: 16px 18px; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 10.5px; }
+ .brand { font-size: 15px; letter-spacing: .3em; }
+ .hero-eyebrow { top: 76px; font-size: 9.5px; letter-spacing: .18em; flex-wrap: wrap; gap: 8px; max-width: 80vw; }
+ .hero-foot { bottom: 9vh; flex-direction: column; align-items: stretch; gap: 22px; }
+ .hero-sub { display: none; }
+ .hero-cta { margin-top: 18px; }
+ .hint { display: none; }
+ .scroll-cue { display: none; }
+ .note { height: 220vh; }
+ .note-pin, .note[data-side="right"] .note-pin { align-items: flex-end; justify-content: flex-start; padding: 0 18px 10vh; }
+ .note-card { width: 100%; padding: 18px 18px 16px; border-radius: 3px; background: linear-gradient(180deg, rgba(8,6,5,.55), rgba(8,6,5,.85)); backdrop-filter: blur(10px); -webkit-backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px var(--faint); }
+ .note-kicker { margin-bottom: 16px; font-size: 9.5px; }
+ .note-kicker span:last-child, .note-kicker .rule { display: none; }
+ .note h2 { font-size: 40px; }
+ .note h2 em { font-size: .52em; }
+ .note-body { font-size: 13.5px; line-height: 1.6; margin-top: 12px; }
+ .facts { grid-template-columns: repeat(3, 1fr); gap: 0 12px; margin-top: 18px; padding-top: 14px; }
+ .facts dd { font-size: 15px; }
+ .latin { display: none; }
+ .note-pin, .note[data-side="right"] .note-pin { padding-bottom: 7vh; }
+ .gauge { right: 12px; top: 96px; transform: none; gap: 8px; }
+ .gauge-bar { height: 18vh; }
+ .gauge-title, .gauge-tick { display: none; }
+ .gauge-pct { font-size: 15px; }
+ .house { padding-top: 58vh; min-height: 0; }
+ .house-inner { background: linear-gradient(180deg, rgba(5,4,4,0), rgba(5,4,4,.8) 18%); padding-top: 20px; }
+ .stats { grid-template-columns: 1fr 1fr; margin-top: 60px; }
+ .shop { padding-top: 60vh; }
+ .products { grid-template-columns: 1fr; }
+ .foot-cols { grid-template-columns: 1fr; }
+ .foot-cols nav { justify-items: start; }
+ .legal { flex-direction: column; }
+}
diff --git a/examples/racer/audio.js b/examples/racer/audio.js
new file mode 100644
index 0000000..c89fc0c
--- /dev/null
+++ b/examples/racer/audio.js
@@ -0,0 +1,189 @@
+// Nightshift — everything you hear is synthesised here. Nothing plays until the visitor turns sound on.
+// Engine: a 270° parallel twin. One PeriodicWave cycle = two crank revolutions (720°), with two exhaust
+// pulses at 0° and 270° — the uneven gap is what makes it lope. Pulses are AM'd onto band-passed noise,
+// driven through a soft clipper and a low-pass that opens with RPM. Overrun pops are one-shot bursts.
+// Ambience: pre-rendered stereo rain loop and a 100 Hz neon transformer buzz (Dutch mains are 50 Hz).
+
+function twinWave(ctx, H = 180) {
+ const N = 4096, s = new Float32Array(N);
+ const pulse = (ph, amp) => {
+ for (let i = 0; i < N; i++) {
+ const x = (i / N - ph + 1) % 1; // cycle fraction since this cylinder fired
+ s[i] += amp * (Math.exp(-x / 0.018) * 1.0 - Math.exp(-x / 0.05) * 0.55 + Math.exp(-x / 0.12) * Math.sin(2 * Math.PI * x / 0.21) * 0.25);
+ }
+ };
+ pulse(0, 1);
+ pulse(0.375, 0.9);
+ let mean = 0; for (let i = 0; i < N; i++) mean += s[i] / N;
+ const real = new Float32Array(H + 1), imag = new Float32Array(H + 1);
+ for (let k = 1; k <= H; k++) {
+ let re = 0, im = 0;
+ const w = 2 * Math.PI * k / N;
+ for (let i = 0; i < N; i++) { const v = s[i] - mean; re += v * Math.cos(w * i); im += v * Math.sin(w * i); }
+ // gentle roll-off so the top harmonics don't fizz
+ const roll = 1 / (1 + Math.pow(k / 90, 2));
+ real[k] = re / N * 2 * roll; imag[k] = im / N * 2 * roll;
+ }
+ return ctx.createPeriodicWave(real, imag);
+}
+
+function softClip(k = 2.2, n = 2048) {
+ const c = new Float32Array(n);
+ const norm = Math.tanh(k);
+ for (let i = 0; i < n; i++) { const x = i / (n - 1) * 2 - 1; c[i] = Math.tanh(k * x) / norm; }
+ return c;
+}
+
+function noiseBuffer(ctx, seconds = 2) {
+ const b = ctx.createBuffer(1, ctx.sampleRate * seconds, ctx.sampleRate);
+ const d = b.getChannelData(0);
+ for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
+ return b;
+}
+
+function rainBuffer(ctx, seconds = 6) {
+ const sr = ctx.sampleRate, n = sr * seconds;
+ const b = ctx.createBuffer(2, n, sr);
+ for (let ch = 0; ch < 2; ch++) {
+ const d = b.getChannelData(ch);
+ // pink-ish noise (Paul Kellet) for the wash
+ let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;
+ for (let i = 0; i < n; i++) {
+ const w = Math.random() * 2 - 1;
+ b0 = 0.99886 * b0 + w * 0.0555179; b1 = 0.99332 * b1 + w * 0.0750759; b2 = 0.969 * b2 + w * 0.153852;
+ b3 = 0.8665 * b3 + w * 0.3104856; b4 = 0.55 * b4 + w * 0.5329522; b5 = -0.7616 * b5 - w * 0.016898;
+ d[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362) * 0.05; b6 = w * 0.115926;
+ }
+ // individual drops on metal and puddles
+ for (let k = 0; k < seconds * 140; k++) {
+ const at = Math.floor(Math.random() * (n - 800)), amp = Math.random() ** 3 * 0.35, f = 2500 + Math.random() * 5000, len = 60 + Math.random() * 500;
+ for (let j = 0; j < len; j++) d[at + j] += Math.sin(j * f * 2 * Math.PI / sr) * amp * Math.exp(-j / (len * 0.25));
+ }
+ // seamless loop: crossfade the tail into the head
+ const fade = sr * 0.25;
+ for (let i = 0; i < fade; i++) { const t = i / fade; d[i] = d[i] * t + d[n - fade + i] * (1 - t); }
+ }
+ return b;
+}
+
+export class EngineAudio {
+ constructor() { this.ctx = null; this.on = false; this.rpm = 1100; }
+
+ async enable() {
+ if (!this.ctx) this._build();
+ await this.ctx.resume();
+ this.on = true;
+ const t = this.ctx.currentTime;
+ this.master.gain.cancelScheduledValues(t);
+ this.master.gain.setTargetAtTime(0.8, t, 0.35);
+ }
+
+ disable() {
+ this.on = false;
+ if (!this.ctx) return;
+ const t = this.ctx.currentTime;
+ this.master.gain.cancelScheduledValues(t);
+ this.master.gain.setTargetAtTime(0, t, 0.12);
+ clearTimeout(this._susp);
+ this._susp = setTimeout(() => { if (!this.on) this.ctx.suspend(); }, 700);
+ }
+
+ _build() {
+ const ctx = this.ctx = new (window.AudioContext || window.webkitAudioContext)();
+ const master = this.master = ctx.createGain(); master.gain.value = 0;
+ const comp = ctx.createDynamicsCompressor();
+ comp.threshold.value = -16; comp.knee.value = 14; comp.ratio.value = 5; comp.attack.value = 0.004; comp.release.value = 0.22;
+ master.connect(comp).connect(ctx.destination);
+
+ // ── engine ──
+ const osc = this.osc = ctx.createOscillator();
+ osc.setPeriodicWave(twinWave(ctx));
+ osc.frequency.value = 1100 / 120;
+ const drive = this.drive = ctx.createGain(); drive.gain.value = 0.8;
+ const shaper = ctx.createWaveShaper(); shaper.curve = softClip(2.4); shaper.oversample = '2x';
+ const lp = this.lp = ctx.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 700; lp.Q.value = 0.8;
+ const chest = ctx.createBiquadFilter(); chest.type = 'peaking'; chest.frequency.value = 110; chest.Q.value = 1.1; chest.gain.value = 6;
+ const pipe = ctx.createBiquadFilter(); pipe.type = 'peaking'; pipe.frequency.value = 460; pipe.Q.value = 1.8; pipe.gain.value = 4;
+ const hp = ctx.createBiquadFilter(); hp.type = 'highpass'; hp.frequency.value = 32;
+ const eng = this.engGain = ctx.createGain(); eng.gain.value = 0.32;
+ osc.connect(drive);
+ // exhaust roar: noise gated by the pulse train, so the hiss arrives with each firing
+ const nsrc = ctx.createBufferSource(); nsrc.buffer = noiseBuffer(ctx); nsrc.loop = true;
+ const nbp = this.nbp = ctx.createBiquadFilter(); nbp.type = 'bandpass'; nbp.frequency.value = 900; nbp.Q.value = 0.7;
+ const nam = ctx.createGain(); nam.gain.value = 0;
+ const namDepth = this.namDepth = ctx.createGain(); namDepth.gain.value = 0.25;
+ osc.connect(namDepth).connect(nam.gain);
+ nsrc.connect(nbp).connect(nam).connect(drive);
+ drive.connect(shaper).connect(chest).connect(pipe).connect(lp).connect(hp).connect(eng).connect(master);
+ // intake / valve-train rasp on top, only with throttle
+ const isrc = ctx.createBufferSource(); isrc.buffer = noiseBuffer(ctx, 1.3); isrc.loop = true;
+ const ihp = ctx.createBiquadFilter(); ihp.type = 'bandpass'; ihp.frequency.value = 2600; ihp.Q.value = 0.9;
+ const ig = this.intake = ctx.createGain(); ig.gain.value = 0;
+ isrc.connect(ihp).connect(ig).connect(master);
+
+ // ── overrun pops bus ──
+ this.popBus = ctx.createGain(); this.popBus.gain.value = 0.9;
+ const pshaper = ctx.createWaveShaper(); pshaper.curve = softClip(3);
+ this.popBus.connect(pshaper).connect(master);
+ this.popNoise = noiseBuffer(ctx, 0.5);
+
+ // ── rain ──
+ const rsrc = ctx.createBufferSource(); rsrc.buffer = rainBuffer(ctx); rsrc.loop = true;
+ const rlp = ctx.createBiquadFilter(); rlp.type = 'lowpass'; rlp.frequency.value = 6500;
+ const rg = this.rainGain = ctx.createGain(); rg.gain.value = 0.55;
+ rsrc.connect(rlp).connect(rg).connect(master);
+
+ // ── neon buzz ──
+ const buzz = ctx.createOscillator(); buzz.type = 'sawtooth'; buzz.frequency.value = 100;
+ const bbp = ctx.createBiquadFilter(); bbp.type = 'bandpass'; bbp.frequency.value = 1400; bbp.Q.value = 2.5;
+ const bg = this.buzzGain = ctx.createGain(); bg.gain.value = 0.004;
+ buzz.connect(bbp).connect(bg).connect(master);
+
+ const t = ctx.currentTime + 0.02;
+ for (const s of [osc, nsrc, isrc, rsrc, buzz]) s.start(t);
+ }
+
+ /** Called every frame. rpm in r/min, throttle 0..1, neon 0..1 (current brightness), crackle 0..1 (flicker spikes). */
+ update(rpm, throttle, neon = 1, crackle = 0) {
+ if (!this.ctx || !this.on) return;
+ const t = this.ctx.currentTime;
+ const rn = Math.min(1, Math.max(0, (rpm - 1100) / 7400));
+ const wobble = 1 + (Math.random() - 0.5) * 0.012 * (1 - rn);
+ this.osc.frequency.setTargetAtTime(rpm / 120 * wobble, t, 0.015);
+ this.lp.frequency.setTargetAtTime(420 + rpm * 0.38 + throttle * 900, t, 0.03);
+ this.nbp.frequency.setTargetAtTime(700 + rpm * 0.28, t, 0.05);
+ this.drive.gain.setTargetAtTime(0.7 + throttle * 1.3 + rn * 0.5, t, 0.03);
+ this.namDepth.gain.setTargetAtTime(0.18 + throttle * 0.35, t, 0.05);
+ this.engGain.gain.setTargetAtTime(0.26 + rn * 0.16 + throttle * 0.12, t, 0.04);
+ this.intake.gain.setTargetAtTime(throttle * (0.012 + rn * 0.03), t, 0.05);
+ this.buzzGain.gain.setTargetAtTime(0.0025 + neon * 0.004 + crackle * 0.02, t, 0.02);
+ }
+
+ /** One overrun crackle. */
+ pop(strength = 1) {
+ if (!this.ctx || !this.on) return;
+ const ctx = this.ctx, t = ctx.currentTime + 0.005;
+ const src = ctx.createBufferSource(); src.buffer = this.popNoise;
+ const bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 500 + Math.random() * 900; bp.Q.value = 0.9;
+ const g = ctx.createGain();
+ const a = 0.5 * strength * (0.5 + Math.random() * 0.6);
+ g.gain.setValueAtTime(0, t); g.gain.linearRampToValueAtTime(a, t + 0.002); g.gain.exponentialRampToValueAtTime(0.001, t + 0.05 + Math.random() * 0.05);
+ src.connect(bp).connect(g).connect(this.popBus);
+ src.start(t, Math.random() * 0.3, 0.12);
+ const th = ctx.createOscillator(); th.type = 'sine';
+ th.frequency.setValueAtTime(95 + Math.random() * 40, t); th.frequency.exponentialRampToValueAtTime(42, t + 0.09);
+ const tg = ctx.createGain(); tg.gain.setValueAtTime(0, t); tg.gain.linearRampToValueAtTime(a * 0.9, t + 0.003); tg.gain.exponentialRampToValueAtTime(0.001, t + 0.1);
+ th.connect(tg).connect(this.popBus);
+ th.start(t); th.stop(t + 0.12);
+ }
+
+ /** Headlight relay clunk. */
+ click() {
+ if (!this.ctx || !this.on) return;
+ const ctx = this.ctx, t = ctx.currentTime + 0.003;
+ const src = ctx.createBufferSource(); src.buffer = this.popNoise;
+ const bp = ctx.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 3200; bp.Q.value = 3;
+ const g = ctx.createGain(); g.gain.setValueAtTime(0.18, t); g.gain.exponentialRampToValueAtTime(0.001, t + 0.03);
+ src.connect(bp).connect(g).connect(this.master); src.start(t, 0, 0.04);
+ }
+}
diff --git a/examples/racer/fx.js b/examples/racer/fx.js
new file mode 100644
index 0000000..b935970
--- /dev/null
+++ b/examples/racer/fx.js
@@ -0,0 +1,556 @@
+// Nightshift — page-local rendering pieces: wet asphalt, rain, splashes, heat haze, neon, wet paint.
+import { THREE } from '../../src/core/engine.js';
+import { Effect } from 'postprocessing';
+
+// ─── Shared GLSL ──────────────────────────────────────────────────────────────
+const HASH = /* glsl */`
+ vec2 nsHash2(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
+ float nsHash1(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+`;
+
+// Rain-drop rings on standing water: gradient of a field of expanding, decaying ring waves.
+const RIPPLES = /* glsl */`
+ vec2 nsRipples(vec2 uv, float t){
+ vec2 g = vec2(0.0);
+ vec2 id0 = floor(uv);
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
+ vec2 id = id0 + vec2(float(i), float(j));
+ vec2 h = nsHash2(id);
+ float tt = t * (0.75 + h.x * 0.6) + h.y * 11.0;
+ float cyc = floor(tt);
+ float ph = fract(tt);
+ vec2 c = id + 0.5 + (nsHash2(id + cyc * 1.37) - 0.5) * 0.9;
+ vec2 d = uv - c;
+ float r = length(d);
+ float x = (r - ph * 0.95) * 11.0;
+ float env = (1.0 - ph) * (1.0 - ph) * exp(-x * x);
+ g += (d / max(r, 1e-3)) * cos(x * 2.6) * env;
+ }
+ return g;
+ }
+`;
+
+// ─── Wet asphalt ─────────────────────────────────────────────────────────────
+// Planar reflection sampled with a vertical streak kernel (wet roads smear lights downward),
+// puddles that turn to mirrors, and rain rings that distort both the surface and the reflection.
+export function patchWetFloor(material, reflection, shared) {
+ const u = {
+ uPuddle: { value: shared.puddle },
+ uReflStrength: { value: 1.7 },
+ uStreak: { value: 0.09 },
+ uRipple: { value: 0.55 },
+ uTime: shared.uTime,
+ };
+ material.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, reflection.uniforms, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vW;
+ uniform sampler2D uRefl; uniform mat4 uReflMat; uniform sampler2D uPuddle;
+ uniform float uTime, uReflStrength, uStreak, uRipple;
+ ${HASH}
+ ${RIPPLES}`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+ float pudA = texture2D(uPuddle, vW.xz * 0.075).r;
+ float pudB = texture2D(uPuddle, vW.xz * 0.31 + 0.37).r;
+ float puddle = smoothstep(0.53, 0.6, pudA + (pudB - 0.5) * 0.18);
+ diffuseColor.rgb *= mix(0.8, 0.28, puddle);`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = mix(roughnessFactor, 0.03, puddle);`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ {
+ vec3 upV = normalize((viewMatrix * vec4(0.0, 1.0, 0.0, 0.0)).xyz);
+ normal = normalize(mix(normal, upV, puddle * 0.9));
+ vec2 rg = nsRipples(vW.xz * 5.5, uTime) + nsRipples(vW.xz * 8.3 + 17.3, uTime * 1.21) * 0.7;
+ rg *= uRipple * mix(0.28, 1.0, puddle);
+ normal = normalize(normal + (viewMatrix * vec4(rg.x, 0.0, rg.y, 0.0)).xyz * 0.6);
+ }`)
+ .replace('#include <opaque_fragment>', `
+ {
+ vec3 nW = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ vec4 rp = uReflMat * vec4(vW, 1.0);
+ vec2 ruv = rp.xy / rp.w + nW.xz * vec2(0.05, 0.08);
+ float rough = roughnessFactor;
+ float lod = 0.2 + rough * 5.5;
+ vec3 acc = vec3(0.0); float ws = 0.0;
+ for (int i = -5; i <= 5; i++) {
+ float fi = float(i) / 5.0;
+ float w = exp(-fi * fi * 2.2);
+ vec2 o = vec2(fi * rough * 0.006, fi * (0.002 + rough * uStreak));
+ acc += textureLod(uRefl, ruv + o, lod * 0.75).rgb * w; ws += w;
+ }
+ vec3 refl = acc / ws;
+ float ndv = clamp(dot(normal, normalize(vViewPosition)), 0.0, 1.0);
+ float fres = 0.02 + 0.98 * pow(1.0 - ndv, 5.0);
+ float edge = smoothstep(0.0, 0.03, ruv.x) * smoothstep(1.0, 0.97, ruv.x) * smoothstep(0.0, 0.02, ruv.y) * smoothstep(1.0, 0.98, ruv.y);
+ outgoingLight += refl * uReflStrength * mix(0.25, 1.0, fres) * (1.0 - rough * 0.55) * edge;
+ }
+ #include <opaque_fragment>`);
+ };
+ material.customProgramCacheKey = () => 'ns-wetfloor';
+ material.needsUpdate = true;
+ return u;
+}
+
+// ─── Wall wash: neon light falling on the bricks (respects albedo) ────────────
+export function patchWallWash(material, washes) {
+ // washes: [{ tex, rect: Vector4(x0, y0, w, h), color: Color, level: {value} }]
+ const u = {};
+ washes.forEach((w, i) => {
+ u[`uWashTex${i}`] = { value: w.tex };
+ u[`uWashRect${i}`] = { value: w.rect };
+ u[`uWashCol${i}`] = { value: w.color };
+ u[`uWashLvl${i}`] = w.level;
+ u[`uWashPos${i}`] = { value: w.pos };
+ });
+ const decl = washes.map((_, i) => `uniform sampler2D uWashTex${i}; uniform vec4 uWashRect${i}; uniform vec3 uWashCol${i}; uniform float uWashLvl${i}; uniform vec3 uWashPos${i};`).join('\n');
+ const body = washes.map((_, i) => `{
+ vec2 wuv = (vWW.xy - uWashRect${i}.xy) / uWashRect${i}.zw;
+ float inside = step(0.0, wuv.x) * step(wuv.x, 1.0) * step(0.0, wuv.y) * step(wuv.y, 1.0);
+ float h = texture2D(uWashTex${i}, clamp(wuv, 0.0, 1.0)).r * inside;
+ // grazing light from tubes that sit a hand's width off the bricks: relief facing the sign lights up
+ vec3 Lw = normalize(uWashPos${i} - vWW);
+ float ndl = max(dot(normal, normalize((viewMatrix * vec4(Lw, 0.0)).xyz)), 0.0);
+ totalEmissiveRadiance += diffuseColor.rgb * uWashCol${i} * h * uWashLvl${i} * (0.2 + ndl * 2.6);
+ }`).join('\n');
+ const prev = material.onBeforeCompile;
+ material.onBeforeCompile = (sh, r) => {
+ prev?.call(material, sh, r);
+ Object.assign(sh.uniforms, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvWW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 vWW;\n${decl}`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>\n${body}`);
+ };
+ material.customProgramCacheKey = () => 'ns-wash-' + washes.length + (material.name || '');
+ material.needsUpdate = true;
+}
+
+// ─── Wet paint: clearcoat on smooth parts + beaded rain drops ─────────────────
+export function wetMaterial(src, { drops = 1, dropScale = 70, clearcoat = 1, env = 1 } = {}) {
+ const p = {
+ map: src.map, normalMap: src.normalMap, normalScale: src.normalScale?.clone(),
+ roughnessMap: src.roughnessMap, metalnessMap: src.metalnessMap, roughness: src.roughness, metalness: src.metalness,
+ aoMap: src.aoMap, emissive: src.emissive?.clone(), emissiveMap: src.emissiveMap, side: THREE.FrontSide,
+ clearcoat, clearcoatRoughness: 0.06, envMapIntensity: env,
+ };
+ for (const k of Object.keys(p)) if (p[k] === undefined) delete p[k];
+ const m = new THREE.MeshPhysicalMaterial(p);
+ const u = { uDrops: { value: drops }, uDropScale: { value: dropScale } };
+ m.userData.wet = u;
+ m.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, u);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vOP; varying vec3 vWN;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvOP = transformed; vWN = normalize(mat3(modelMatrix) * objectNormal);');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vOP; varying vec3 vWN; uniform float uDrops, uDropScale;
+ ${HASH}
+ // one bead per cell (some cells empty): spherical cap height gradient
+ vec3 nsDrop(vec2 p){
+ vec2 id = floor(p); vec2 f = fract(p) - 0.5;
+ vec2 h = nsHash2(id);
+ vec2 c = (h - 0.5) * 0.45;
+ float r = 0.16 + 0.24 * nsHash1(id + 7.1);
+ float keep = step(0.62, nsHash1(id * 1.7 + 3.3));
+ vec2 d = f - c;
+ float q = 1.0 - dot(d, d) / (r * r);
+ if (q <= 0.0 || keep < 0.5) return vec3(0.0);
+ float hgt = sqrt(q);
+ return vec3(-d / (r * r * max(hgt, 0.25)) * 0.12, 1.0);
+ }`)
+ .replace('#include <lights_physical_fragment>', `#include <lights_physical_fragment>
+ {
+ // smooth surfaces (paint, chrome, polished cases) get the wet clearcoat; rubber and fabric do not
+ float gloss = 1.0 - smoothstep(0.28, 0.72, roughnessFactor);
+ vec3 wn = normalize(vWN);
+ vec3 an = abs(wn);
+ vec2 pp = an.y > max(an.x, an.z) ? vOP.xz : (an.x > an.z ? vOP.zy : vOP.xy);
+ vec3 dA = nsDrop(pp * uDropScale);
+ vec3 dB = nsDrop(pp * uDropScale * 0.47 + 11.7);
+ float up = smoothstep(-0.2, 0.75, wn.y);
+ float dm = max(dA.z, dB.z * 0.8) * uDrops * up * mix(0.4, 1.0, gloss);
+ vec2 gr = (dA.xy + dB.xy * 0.7) * uDrops * up;
+ // perturb the coat normal in world space along the projection plane, then back to view space
+ vec3 gW = an.y > max(an.x, an.z) ? vec3(gr.x, 0.0, gr.y) : (an.x > an.z ? vec3(0.0, gr.y, gr.x) : vec3(gr.x, gr.y, 0.0));
+ clearcoatNormal = normalize(clearcoatNormal + (viewMatrix * vec4(gW, 0.0)).xyz * 0.9);
+ material.clearcoat = clamp(material.clearcoat * gloss + dm * 0.5, 0.0, 1.0);
+ material.clearcoatRoughness = mix(material.clearcoatRoughness, 0.0525, dm);
+ }`);
+ };
+ m.customProgramCacheKey = () => 'ns-wet';
+ return m;
+}
+
+// ─── Rain: instanced streaks lit by the scene's lights (forward-scattering) ───
+export const MAX_RAIN_LIGHTS = 6;
+export function createRain({ count = 16000, box = new THREE.Vector3(16, 9, 16) } = {}) {
+ const base = new THREE.PlaneGeometry(1, 1);
+ const geo = new THREE.InstancedBufferGeometry();
+ geo.index = new THREE.BufferAttribute(new Uint16Array([0, 2, 1, 2, 3, 1]), 1);
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array([-1, 1, 0, 1, 1, 0, -1, 0, 0, 1, 0, 0]), 3));
+ base.dispose();
+ const seed = new Float32Array(count * 4);
+ for (let i = 0; i < count * 4; i++) seed[i] = Math.random();
+ geo.setAttribute('aSeed', new THREE.InstancedBufferAttribute(seed, 4));
+ geo.instanceCount = count;
+ const L = MAX_RAIN_LIGHTS;
+ const uniforms = {
+ uTime: { value: 0 }, uCenter: { value: new THREE.Vector3() }, uBox: { value: box }, uWind: { value: new THREE.Vector3(0.6, 0, 0.25) },
+ uWindOff: { value: new THREE.Vector3() }, uLen: { value: 0.3 }, uWidth: { value: 0.85 }, uRes: { value: new THREE.Vector2(1, 1) },
+ uBike: { value: new THREE.Vector3(0, 0.5, 0) }, uRev: { value: 0 }, uAlpha: { value: 1 }, uAmbient: { value: new THREE.Color(0.0015, 0.0015, 0.0022) },
+ uLPos: { value: Array.from({ length: L }, () => new THREE.Vector3()) },
+ uLCol: { value: Array.from({ length: L }, () => new THREE.Vector3()) },
+ uLDir: { value: Array.from({ length: L }, () => new THREE.Vector4(0, -1, 0, -2)) },
+ };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ vertexShader: /* glsl */`
+ attribute vec4 aSeed;
+ uniform float uTime, uLen, uWidth, uRev, uAlpha;
+ uniform vec3 uCenter, uBox, uWind, uWindOff, uBike, uAmbient;
+ uniform vec2 uRes;
+ uniform vec3 uLPos[${L}]; uniform vec3 uLCol[${L}]; uniform vec4 uLDir[${L}];
+ varying vec3 vC; varying vec2 vQ; varying float vA;
+ void main(){
+ float speed = 7.5 + aSeed.w * 3.5;
+ vec3 p;
+ vec3 lo = uCenter - uBox * 0.5;
+ p.xz = mod(aSeed.xz * uBox.xz + uWindOff.xz - lo.xz, uBox.xz) + lo.xz;
+ p.y = mod(aSeed.y * uBox.y - uTime * speed, uBox.y) - 0.05;
+ vec3 vel = vec3(uWind.x, -speed, uWind.z);
+ // hot air off the engine and exhaust bends the rain when the throttle is open
+ vec3 d = p - uBike;
+ float near = exp(-dot(d * vec3(0.7, 0.9, 1.0), d) * 0.55);
+ vel.xz += normalize(d.xz + 1e-4) * near * uRev * 6.5;
+ vel.y += near * uRev * 5.0;
+ vel.x -= uRev * 1.6;
+ p += normalize(vel) * near * uRev * 0.25;
+ vec3 dir = normalize(vel);
+ float len = uLen * clamp(length(vel) / 9.0, 0.35, 1.2);
+ vec3 tail = p - dir * len;
+ vec4 ch = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ vec4 ct = projectionMatrix * viewMatrix * vec4(tail, 1.0);
+ vec2 sd = (ch.xy / ch.w - ct.xy / ct.w) * uRes;
+ float sl = length(sd);
+ vec2 sn = sl > 1e-4 ? sd / sl : vec2(0.0, 1.0);
+ vec2 perp = vec2(-sn.y, sn.x);
+ vec4 c = mix(ct, ch, position.y);
+ float camD = max(c.w, 0.01);
+ float w = uWidth * (1.0 + 1.5 / camD);
+ c.xy += perp * position.x * w * 2.0 / uRes * c.w;
+ gl_Position = c;
+ vec3 V = normalize(p - cameraPosition);
+ vec3 lit = uAmbient;
+ for (int i = 0; i < ${L}; i++) {
+ vec3 ld = p - uLPos[i];
+ float dist = max(length(ld), 0.05);
+ vec3 ln = ld / dist;
+ float cone = uLDir[i].w < -1.5 ? 1.0 : smoothstep(uLDir[i].w, uLDir[i].w + 0.05, dot(ln, uLDir[i].xyz));
+ float fwd = pow(max(dot(ln, -V), 0.0), 4.0);
+ lit += uLCol[i] * cone / (1.0 + dist * dist) * (0.12 + 2.4 * fwd);
+ }
+ vC = lit;
+ vQ = position.xy;
+ vA = smoothstep(1.2, 2.6, camD) * (1.0 - smoothstep(9.0, 15.0, camD)) * uAlpha * (0.55 + aSeed.w * 0.6);
+ }`,
+ fragmentShader: /* glsl */`
+ varying vec3 vC; varying vec2 vQ; varying float vA;
+ void main(){
+ float across = 1.0 - abs(vQ.x);
+ float along = smoothstep(0.0, 0.55, vQ.y) * smoothstep(1.0, 0.86, vQ.y);
+ float a = across * across * along * vA;
+ gl_FragColor = vec4(vC * a, 1.0);
+ }`,
+ });
+ const mesh = new THREE.Mesh(geo, mat);
+ mesh.frustumCulled = false;
+ mesh.renderOrder = 5;
+ return { mesh, uniforms };
+}
+
+// Crown splashes on the ground: short-lived bright ticks that re-seed every cycle.
+export function createSplashes(rainUniforms, { count = 5000, radius = 7 } = {}) {
+ const seed = new Float32Array(count * 3);
+ for (let i = 0; i < count * 3; i++) seed[i] = Math.random();
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3));
+ geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 3));
+ const L = MAX_RAIN_LIGHTS;
+ const uniforms = { ...rainUniforms, uRadius: { value: radius }, uDpr: { value: 1 } };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: /* glsl */`
+ attribute vec3 aSeed;
+ uniform float uTime, uRadius, uDpr, uAlpha;
+ uniform vec3 uCenter, uAmbient;
+ uniform vec3 uLPos[${L}]; uniform vec3 uLCol[${L}]; uniform vec4 uLDir[${L}];
+ varying vec3 vC; varying float vLife;
+ ${HASH}
+ void main(){
+ float period = 0.55 + aSeed.z * 0.9;
+ float tt = uTime / period + aSeed.x * 17.0;
+ float cyc = floor(tt);
+ vLife = fract(tt);
+ vec2 h = nsHash2(vec2(cyc, aSeed.y * 311.0));
+ float ang = h.x * 6.2831853, rad = sqrt(h.y) * uRadius;
+ vec3 p = vec3(uCenter.x + cos(ang) * rad, 0.012, uCenter.z + sin(ang) * rad);
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ float life = smoothstep(0.0, 0.05, vLife) * (1.0 - smoothstep(0.05, 0.16, vLife));
+ gl_PointSize = (2.0 + vLife * 26.0) * uDpr * (1.0 / max(-mv.z, 0.6));
+ vec3 V = normalize(p - cameraPosition);
+ vec3 lit = uAmbient * 2.0;
+ for (int i = 0; i < ${L}; i++) {
+ vec3 ld = p - uLPos[i];
+ float dist = max(length(ld), 0.05);
+ vec3 ln = ld / dist;
+ float cone = uLDir[i].w < -1.5 ? 1.0 : smoothstep(uLDir[i].w, uLDir[i].w + 0.05, dot(ln, uLDir[i].xyz));
+ float fwd = pow(max(dot(ln, -V), 0.0), 4.0);
+ lit += uLCol[i] * cone / (1.0 + dist * dist) * (0.5 + 2.5 * fwd);
+ }
+ vC = lit * life * uAlpha * 0.4 * step(vLife, 0.18) * (1.0 - smoothstep(6.0, 11.0, -mv.z));
+ }`,
+ fragmentShader: /* glsl */`
+ varying vec3 vC; varying float vLife;
+ void main(){
+ vec2 q = gl_PointCoord - 0.5;
+ q.y *= 2.6;
+ float r = length(q);
+ float ring = smoothstep(0.5, 0.36, r) * smoothstep(0.12, 0.3, r) + smoothstep(0.18, 0.0, r) * 0.6;
+ gl_FragColor = vec4(vC * ring, 1.0);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 4;
+ return { points: pts, uniforms };
+}
+
+// ─── Heat haze: screen-space refraction plumes (exhaust tip + cylinder head) ──
+const hazeFrag = /* glsl */`
+ uniform vec2 uA0; uniform vec2 uB0; uniform vec2 uA1; uniform vec2 uB1;
+ uniform float uS0; uniform float uS1; uniform float uW0; uniform float uW1; uniform float uHTime;
+ float hzH(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453); }
+ float hzN(vec2 p){ vec2 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(hzH(i), hzH(i + vec2(1.0, 0.0)), f.x), mix(hzH(i + vec2(0.0, 1.0)), hzH(i + vec2(1.0, 1.0)), f.x), f.y); }
+ float hzPlume(vec2 uv, vec2 a, vec2 b, float w){
+ vec2 asp = vec2(aspect, 1.0);
+ vec2 pa = (uv - a) * asp, ba = (b - a) * asp;
+ float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6), 0.0, 1.0);
+ float d = length(pa - ba * h);
+ float ww = w * (0.35 + h * 1.6);
+ return exp(-d * d / (ww * ww)) * smoothstep(0.0, 0.1, h) * (1.0 - smoothstep(0.55, 1.0, h));
+ }
+ void mainUv(inout vec2 uv){
+ float m = hzPlume(uv, uA0, uB0, uW0) * uS0 + hzPlume(uv, uA1, uB1, uW1) * uS1;
+ if (m > 0.0005) {
+ vec2 q = uv * vec2(aspect, 1.0) * 70.0;
+ vec2 n = vec2(hzN(q + vec2(0.0, -uHTime * 7.0)), hzN(q * 1.37 + vec2(13.1, -uHTime * 9.0))) - 0.5;
+ n += (vec2(hzN(q * 2.9 + vec2(3.0, -uHTime * 15.0)), hzN(q * 3.3 + vec2(7.0, -uHTime * 17.0))) - 0.5) * 0.5;
+ uv += n * m * 0.011;
+ }
+ }
+`;
+export class HeatHazeEffect extends Effect {
+ constructor() {
+ super('HeatHazeEffect', hazeFrag, {
+ uniforms: new Map([
+ ['uA0', new THREE.Uniform(new THREE.Vector2(0.5, 0.5))], ['uB0', new THREE.Uniform(new THREE.Vector2(0.5, 0.6))],
+ ['uA1', new THREE.Uniform(new THREE.Vector2(0.5, 0.5))], ['uB1', new THREE.Uniform(new THREE.Vector2(0.5, 0.6))],
+ ['uS0', new THREE.Uniform(0)], ['uS1', new THREE.Uniform(0)], ['uW0', new THREE.Uniform(0.04)], ['uW1', new THREE.Uniform(0.05)],
+ ['uHTime', new THREE.Uniform(0)],
+ ]),
+ });
+ }
+ update(renderer, input, dt) { this.uniforms.get('uHTime').value += dt; }
+}
+
+// ─── Canvas textures ──────────────────────────────────────────────────────────
+export function canvasTex(w, h, draw, { srgb = true } = {}) {
+ const c = document.createElement('canvas'); c.width = w; c.height = h;
+ draw(c.getContext('2d'), w, h);
+ const t = new THREE.CanvasTexture(c);
+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;
+ t.anisotropy = 8;
+ return t;
+}
+
+/**
+ * Neon sign drawn as glass tubes. Returns the lit-tube texture, a dim "unlit glass" texture,
+ * and a soft wash texture for the wall. `flickerIndex` splits one letter into its own texture.
+ */
+export function neonTextures({ word = 'Nightshift', sub = 'MOTOR CO.', W = 2048, H = 768, flickerIndex = 6 } = {}) {
+ const probe = document.createElement('canvas').getContext('2d');
+ probe.font = '400 100px Neonderthaw';
+ const fontPx = Math.min(H * 0.56, 100 * W * 0.84 / Math.max(1, probe.measureText(word).width));
+ const font = `400 ${Math.round(fontPx)}px Neonderthaw`;
+ const subFont = `500 ${Math.round(H * 0.075)}px Inter`;
+ const layout = g => {
+ g.font = font;
+ const tw = g.measureText(word).width;
+ const x0 = (W - tw) / 2, y0 = H * 0.46;
+ return { x0, y0 };
+ };
+ const drawWord = (g, range, stroke) => {
+ const { x0, y0 } = layout(g);
+ g.font = font; g.textBaseline = 'middle'; g.textAlign = 'left';
+ for (let i = 0; i < word.length; i++) {
+ if (!range(i)) continue;
+ const x = x0 + g.measureText(word.slice(0, i)).width;
+ stroke(g, word[i], x, y0);
+ }
+ };
+ const drawSub = (g, stroke) => {
+ g.font = subFont; g.textAlign = 'center'; g.textBaseline = 'middle';
+ if ('letterSpacing' in g) g.letterSpacing = `${Math.round(H * 0.035)}px`;
+ stroke(g, sub, W / 2 + H * 0.02, H * 0.86);
+ if ('letterSpacing' in g) g.letterSpacing = '0px';
+ // tube underline swash with a gap for the text
+ g.beginPath(); g.moveTo(W * 0.2, H * 0.86); g.lineTo(W * 0.32, H * 0.86); g.moveTo(W * 0.68, H * 0.86); g.lineTo(W * 0.8, H * 0.86);
+ };
+ const tube = (core, edge, w) => (g, s, x, y) => {
+ g.lineJoin = 'round'; g.lineCap = 'round';
+ g.strokeStyle = edge; g.lineWidth = w; g.strokeText(s, x, y);
+ g.fillStyle = edge; g.fillText(s, x, y);
+ g.strokeStyle = core; g.lineWidth = w * 0.28; g.strokeText(s, x, y);
+ };
+ const tw = H * 0.017;
+ const lit = (range, withSub) => canvasTex(W, H, g => {
+ g.clearRect(0, 0, W, H);
+ g.shadowColor = 'rgba(255,40,80,0.9)'; g.shadowBlur = H * 0.012;
+ drawWord(g, range, tube('#ffe2e8', '#ff2e57', tw));
+ if (withSub) {
+ drawSub(g, tube('#ffe2e8', '#ff2e57', tw * 0.55));
+ g.strokeStyle = '#ff2e57'; g.lineWidth = tw * 0.9; g.stroke();
+ g.strokeStyle = '#ffe2e8'; g.lineWidth = tw * 0.25; g.stroke();
+ }
+ });
+ const main = lit(i => i !== flickerIndex, true);
+ const flick = lit(i => i === flickerIndex, false);
+ const glass = canvasTex(W, H, g => {
+ drawWord(g, () => true, tube('rgba(255,210,220,0.5)', 'rgba(120,90,100,0.55)', tw));
+ drawSub(g, tube('rgba(255,210,220,0.5)', 'rgba(120,90,100,0.55)', tw * 0.55));
+ g.strokeStyle = 'rgba(120,90,100,0.55)'; g.lineWidth = tw * 0.9; g.stroke();
+ });
+ // Wall wash: the glyphs blurred wide, over a broad soft falloff. Canvas is 2x the sign in each direction.
+ const wash = canvasTex(1024, 768, (g, w, h) => {
+ g.fillStyle = '#000'; g.fillRect(0, 0, w, h);
+ const grd = g.createRadialGradient(w / 2, h * 0.5, 0, w / 2, h * 0.5, w * 0.5);
+ grd.addColorStop(0, 'rgba(255,255,255,0.55)'); grd.addColorStop(0.35, 'rgba(255,255,255,0.22)'); grd.addColorStop(1, 'rgba(255,255,255,0)');
+ g.fillStyle = grd; g.fillRect(0, 0, w, h);
+ const src = main.image;
+ g.filter = 'blur(26px)'; g.globalCompositeOperation = 'lighter';
+ g.drawImage(src, w * 0.25, h * 0.25, w * 0.5, h * 0.5);
+ g.filter = 'blur(8px)';
+ g.globalAlpha = 0.8; g.drawImage(src, w * 0.25, h * 0.25, w * 0.5, h * 0.5);
+ }, { srgb: false });
+ return { main, flick, glass, wash, aspect: W / H };
+}
+
+/** Soft radial sprite (for lens glows, embers, flames). */
+export function glowTexture(stops = [[0, 'rgba(255,255,255,1)'], [0.08, 'rgba(255,255,255,0.7)'], [0.25, 'rgba(255,255,255,0.12)'], [1, 'rgba(255,255,255,0)']], size = 256) {
+ return canvasTex(size, size, (g, w, h) => {
+ const grd = g.createRadialGradient(w / 2, h / 2, 0, w / 2, h / 2, w / 2);
+ for (const [o, c] of stops) grd.addColorStop(o, c);
+ g.fillStyle = grd; g.fillRect(0, 0, w, h);
+ });
+}
+
+/** Backfire flame: a hot core with ragged tongues, drawn once. */
+export function flameTexture() {
+ return canvasTex(256, 256, (g, w, h) => {
+ g.translate(w / 2, h / 2);
+ g.globalCompositeOperation = 'lighter';
+ for (let i = 0; i < 26; i++) {
+ const a = (Math.random() - 0.5) * 1.3, len = 40 + Math.random() * 80;
+ g.save(); g.rotate(a);
+ const grd = g.createLinearGradient(0, 0, len, 0);
+ grd.addColorStop(0, 'rgba(255,240,210,0.55)'); grd.addColorStop(0.4, 'rgba(255,120,30,0.28)'); grd.addColorStop(1, 'rgba(120,20,0,0)');
+ g.fillStyle = grd;
+ g.beginPath(); g.ellipse(len * 0.45, 0, len * 0.55, 6 + Math.random() * 10, 0, 0, Math.PI * 2); g.fill();
+ g.restore();
+ }
+ const core = g.createRadialGradient(0, 0, 0, 0, 0, 40);
+ core.addColorStop(0, 'rgba(210,225,255,1)'); core.addColorStop(0.4, 'rgba(255,200,140,0.8)'); core.addColorStop(1, 'rgba(255,100,20,0)');
+ g.fillStyle = core; g.beginPath(); g.arc(0, 0, 40, 0, Math.PI * 2); g.fill();
+ });
+}
+
+// ─── Steam: rain flashing off hot exhaust pipes, rising in soft wisps ────────
+export function createSteam(rainUniforms, path, { count = 420 } = {}) {
+ // path: array of Vector3 (bike-local) along the pipes; particles are born along it
+ const seed = new Float32Array(count * 4);
+ for (let i = 0; i < count * 4; i++) seed[i] = Math.random();
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count * 3), 3));
+ geo.setAttribute('aSeed', new THREE.BufferAttribute(seed, 4));
+ const L = MAX_RAIN_LIGHTS;
+ const P = path.length;
+ const tex = glowTexture([[0, 'rgba(255,255,255,0.9)'], [0.35, 'rgba(255,255,255,0.35)'], [1, 'rgba(255,255,255,0)']], 128);
+ const uniforms = {
+ uTime: rainUniforms.uTime, uLPos: rainUniforms.uLPos, uLCol: rainUniforms.uLCol, uLDir: rainUniforms.uLDir, uAmbient: rainUniforms.uAmbient,
+ uWind: rainUniforms.uWind, uHeat: { value: 0 }, uBikeMat: { value: new THREE.Matrix4() }, uDpr: { value: 1 }, uTex: { value: tex },
+ uPath: { value: path },
+ };
+ const mat = new THREE.ShaderMaterial({
+ uniforms, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: /* glsl */`
+ attribute vec4 aSeed;
+ uniform float uTime, uHeat, uDpr;
+ uniform mat4 uBikeMat;
+ uniform vec3 uPath[${P}];
+ uniform vec3 uWind, uAmbient;
+ uniform vec3 uLPos[${L}]; uniform vec3 uLCol[${L}]; uniform vec4 uLDir[${L}];
+ varying vec3 vC; varying float vRot;
+ void main(){
+ float life = 1.6 + aSeed.z * 1.6;
+ float age = fract(uTime / life + aSeed.x);
+ // where on the pipe this puff was born
+ float s = aSeed.y * float(${P - 1});
+ int k = int(floor(s));
+ vec3 a = uPath[0], b = uPath[1];
+ for (int i = 0; i < ${P - 1}; i++) if (i == k) { a = uPath[i]; b = uPath[i + 1]; }
+ vec3 born = (uBikeMat * vec4(mix(a, b, fract(s)), 1.0)).xyz;
+ float t = age * life;
+ vec3 p = born + vec3(uWind.x * 0.35 * t + sin(t * 1.7 + aSeed.w * 9.0) * 0.05 * t, 0.32 * t - 0.03 * t * t, uWind.z * 0.3 * t + cos(t * 1.3 + aSeed.x * 7.0) * 0.05 * t);
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ float size = 0.03 + age * 0.2;
+ gl_PointSize = size * uDpr * 900.0 / max(-mv.z, 0.2) * projectionMatrix[1][1] * 0.5;
+ vec3 V = normalize(p - cameraPosition);
+ vec3 lit = uAmbient * 6.0;
+ for (int i = 0; i < ${L}; i++) {
+ vec3 ld = p - uLPos[i];
+ float dist = max(length(ld), 0.05);
+ vec3 ln = ld / dist;
+ float cone = uLDir[i].w < -1.5 ? 1.0 : smoothstep(uLDir[i].w, uLDir[i].w + 0.08, dot(ln, uLDir[i].xyz));
+ float fwd = pow(max(dot(ln, -V), 0.0), 3.0);
+ lit += uLCol[i] * cone / (1.0 + dist * dist) * (0.3 + 1.2 * fwd);
+ }
+ float fade = smoothstep(0.0, 0.12, age) * (1.0 - smoothstep(0.35, 1.0, age));
+ vC = lit * fade * uHeat * 0.018;
+ vRot = aSeed.w * 6.2831;
+ }`,
+ fragmentShader: /* glsl */`
+ uniform sampler2D uTex;
+ varying vec3 vC; varying float vRot;
+ void main(){
+ vec2 q = gl_PointCoord - 0.5;
+ float c = cos(vRot), s = sin(vRot);
+ q = mat2(c, -s, s, c) * q * vec2(1.0, 1.35);
+ float a = texture2D(uTex, q + 0.5).r;
+ gl_FragColor = vec4(vC * a, 1.0);
+ }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.renderOrder = 7;
+ return { points: pts, uniforms };
+}
diff --git a/examples/racer/index.html b/examples/racer/index.html
new file mode 100644
index 0000000..7086427
--- /dev/null
+++ b/examples/racer/index.html
@@ -0,0 +1,232 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Nightshift Motor Co. — Twelve bikes a year</title>
+ <meta name="description" content="Hand-built café racers from a two-bay garage in Rotterdam that only opens after dark. Twelve bikes a year. This is number seven.">
+ <meta name="theme-color" content="#050507">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Anton&family=Inter:wght@300;400;500;600&family=Neonderthaw&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="redline-flash" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <p class="loader-sign" aria-hidden="true"><span>Nightshift</span></p>
+ <div class="loader-bar"><i></i></div>
+ <p class="loader-line"><span>Warming the engine</span><b class="loader-pct">0</b></p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Nightshift Motor Co. home">
+ <b>Nightshift</b><span>Motor Co.</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#rev">Rev it</a>
+ <a href="#build">The build</a>
+ <a href="#waitlist">2027 slots</a>
+ <a href="#garage">The garage</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" data-magnetic>
+ <span class="sound-bars" aria-hidden="true"><i></i><i></i><i></i><i></i></span>
+ <span class="sound-label">Sound off</span>
+ </button>
+ <a class="btn btn-neon" href="#waitlist" data-magnetic>Reserve a slot</a>
+ </div>
+ </header>
+
+ <main id="top">
+ <!-- HERO -->
+ <section class="hero" data-station="hero">
+ <p class="eyebrow"><span class="dot"></span>Build 07 / 12 &nbsp;·&nbsp; Rotterdam, 01:40, raining</p>
+ <div class="hero-bottom">
+ <div class="hero-row">
+ <p class="sub">Hand-built café racers from a two-bay garage under the Maas bridge. We open when the city closes, and we finish one bike a month.</p>
+ <div class="hold-hint" aria-hidden="true">
+ <span class="hold-ring"><svg viewBox="0 0 44 44"><circle cx="22" cy="22" r="20"/><circle class="p" cx="22" cy="22" r="20"/></svg><i></i></span>
+ <span><b>Hold</b> anywhere to rev <em>or press space</em></span>
+ </div>
+ </div>
+ <h1 aria-label="Twelve bikes a year. This is number seven.">
+ <span class="h-line"><span>Twelve bikes a year.</span></span>
+ </h1>
+ <p class="script" aria-hidden="true">This is number seven.</p>
+ </div>
+ </section>
+
+ <!-- REV -->
+ <section class="rev" id="rev" data-station="rev">
+ <div class="rev-copy">
+ <p class="kicker"><b>01</b> Rev it</p>
+ <h2>Wake her <em>up.</em></h2>
+ <p class="lede">A 1968 air-cooled parallel twin, bored to 790cc and rebuilt from the crank out. We re-phased it to a 270° firing order, so it lopes like a V-twin at idle and pulls clean to 8,500.</p>
+ <ul class="rev-notes">
+ <li><span>Hold</span> mouse, space or the button to open the throttle.</li>
+ <li><span>Let go</span> above five thousand for the crackle on the overrun.</li>
+ <li><span>Watch</span> the headlight — on a 1968 charging system it brightens with the revs.</li>
+ </ul>
+ <button class="rev-btn" type="button" aria-label="Hold to rev the engine">
+ <span class="rev-btn-ring"></span><span class="rev-btn-label">Hold to rev</span>
+ </button>
+ </div>
+ </section>
+
+ <!-- BUILD -->
+ <section class="build" id="build">
+ <header class="build-head" data-station="buildhead">
+ <p class="kicker"><b>02</b> The build</p>
+ <h2>Nine hundred hours, <em>four pairs of hands.</em></h2>
+ </header>
+
+ <article class="part part-r" data-station="tank">
+ <p class="part-num">01 / 04 · Tank</p>
+ <h3>Twelve coats of black, <br>one brush of gold.</h3>
+ <p>Hand-beaten from 1.2&nbsp;mm aluminium over a wooden buck, then twelve coats of piano black, wet-sanded between each. The pinstripe is 23-carat gold leaf laid by one brush — Marit's — in a single breath per side.</p>
+ <dl class="specs">
+ <div><dt>Capacity</dt><dd>14<small>L</small></dd></div>
+ <div><dt>Paint coats</dt><dd>12</dd></div>
+ <div><dt>Pinstripe</dt><dd>0.8<small>mm</small></dd></div>
+ </dl>
+ </article>
+
+ <article class="part part-l" data-station="engine">
+ <p class="part-num">02 / 04 · Engine</p>
+ <h3>Fins you could <br>shave with.</h3>
+ <p>Every cooling fin is hand-dressed with a file, the cases vapour-blasted then polished to a mirror. Brass unions and fuel taps are turned on a 1954 lathe in the back bay. It idles at 1,100 and never leaks. We check.</p>
+ <dl class="specs">
+ <div><dt>Displacement</dt><dd>790<small>cc</small></dd></div>
+ <div><dt>Power</dt><dd>58<small>hp</small></dd></div>
+ <div><dt>Torque</dt><dd>64<small>Nm</small></dd></div>
+ </dl>
+ </article>
+
+ <article class="part part-r" data-station="seat">
+ <p class="part-num">03 / 04 · Seat</p>
+ <h3>Leather that <br>remembers you.</h3>
+ <p>Vegetable-tanned Tuscan hide, 3&nbsp;mm thick, quilted in a diagonal stitch that takes eleven hours at the bench. It will darken where you sit and crease where you tuck in. That is the point.</p>
+ <dl class="specs">
+ <div><dt>Stitching</dt><dd>11<small>h</small></dd></div>
+ <div><dt>Hide</dt><dd>3<small>mm</small></dd></div>
+ <div><dt>Riders</dt><dd>1</dd></div>
+ </dl>
+ </article>
+
+ <article class="part part-l" data-station="wheel">
+ <p class="part-num">04 / 04 · Wheels</p>
+ <h3>Forty spokes, <br>trued by ear.</h3>
+ <p>Eighteen-inch alloy rims laced to polished hubs with forty stainless spokes each, tensioned by tapping and listening until every one rings the same note. Up front, a 320&nbsp;mm floating disc that looks nothing like 1968 and stops like it isn't.</p>
+ <dl class="specs">
+ <div><dt>Rims</dt><dd>18<small>in</small></dd></div>
+ <div><dt>Spokes</dt><dd>40</dd></div>
+ <div><dt>Disc</dt><dd>320<small>mm</small></dd></div>
+ </dl>
+ </article>
+ </section>
+
+ <!-- WAITLIST -->
+ <section class="waitlist" id="waitlist" data-station="waitlist">
+ <div class="wl-panel">
+ <p class="kicker"><b>03</b> The 2027 waitlist</p>
+ <h2>Twelve slots. <em>Nine are gone.</em></h2>
+ <p class="lede">Each build takes fourteen weeks and starts with a night in the garage: you, us, a donor engine and a lot of coffee. A €5,000 deposit holds your month. It is refundable until we cut the first tube.</p>
+ <ol class="slots" aria-label="2027 build slots">
+ <li class="taken"><b>01</b><span>Jan</span></li>
+ <li class="taken"><b>02</b><span>Feb</span></li>
+ <li class="taken"><b>03</b><span>Mar</span></li>
+ <li class="taken"><b>04</b><span>Apr</span></li>
+ <li class="open" data-slot="05"><b>05</b><span>May</span></li>
+ <li class="taken"><b>06</b><span>Jun</span></li>
+ <li class="taken"><b>07</b><span>Jul</span></li>
+ <li class="taken"><b>08</b><span>Aug</span></li>
+ <li class="open" data-slot="09"><b>09</b><span>Sep</span></li>
+ <li class="taken"><b>10</b><span>Oct</span></li>
+ <li class="open" data-slot="11"><b>11</b><span>Nov</span></li>
+ <li class="taken"><b>12</b><span>Dec</span></li>
+ </ol>
+ <form class="wl-form" novalidate>
+ <label><span>Name</span><input name="name" autocomplete="off" placeholder="Who's riding"></label>
+ <label><span>Email</span><input name="email" type="email" autocomplete="off" placeholder="Where we write back"></label>
+ <label class="wide"><span>Slot</span>
+ <select name="slot"><option value="05">No. 05 — May 2027</option><option value="09">No. 09 — September 2027</option><option value="11">No. 11 — November 2027</option></select>
+ </label>
+ <button class="btn btn-neon wide" type="submit" data-magnetic>Hold my month · €5,000 deposit</button>
+ <p class="wl-fine wide">From €38,000 complete. We reply within one night shift. Nothing is charged until we have spoken.</p>
+ </form>
+ <p class="wl-done" role="status" hidden>You're on the list for <b>No. 05</b>. We'll call after midnight — keep the phone on.</p>
+ </div>
+ </section>
+
+ <!-- GARAGE -->
+ <section class="garage" id="garage" data-station="garage">
+ <div class="garage-copy">
+ <p class="kicker"><b>04</b> The garage</p>
+ <h2>We open when <br>the city <em>closes.</em></h2>
+ <p class="lede">Nightshift started in 2011 as two dock mechanics working the hours nobody wanted — ten at night to six in the morning, in a borrowed bay under the Maas bridge. The hours stuck. So did the rain.</p>
+ <p>Fifteen years later there are four of us, two bays and a neon sign that has buzzed since the night we hung it. Nobody answers the phone before dark. Everybody answers it after.</p>
+ <dl class="garage-stats">
+ <div><dt>Since</dt><dd>2011</dd></div>
+ <div><dt>Bikes delivered</dt><dd>147</dd></div>
+ <div><dt>Builders</dt><dd>4</dd></div>
+ <div><dt>Built in daylight</dt><dd>0</dd></div>
+ </dl>
+ </div>
+ <blockquote class="garage-quote" data-station="quote">
+ <p>“I asked for a motorbike. They gave me a reason to ride at three in the morning.”</p>
+ <cite>— Joris V., owner of No. 112</cite>
+ </blockquote>
+ </section>
+
+ <!-- FOOTER -->
+ <footer class="foot" id="visit" data-station="foot">
+ <p class="script foot-script" aria-hidden="true">see you after midnight</p>
+ <h2 class="foot-title">Come by <br>after dark.</h2>
+ <div class="foot-cols">
+ <p><b>Nightshift Motor Co.</b><br>Kadewerf 14, Bay 2<br>3072 Rotterdam, NL</p>
+ <p><b>Open</b><br>Tuesday — Saturday<br>22:00 — 06:00</p>
+ <p><b>Write</b><br><a href="#waitlist">[email protected]</a><br><a href="#top">Instagram</a> · <a href="#top">Journal</a></p>
+ <a class="btn btn-neon" href="#waitlist" data-magnetic>Reserve a 2027 slot</a>
+ </div>
+ <p class="foot-legal"><span>© 2026 Nightshift Motor Co. — a fictional workshop.</span><span>Photographed in the rain. Nothing was harmed except sleep.</span></p>
+ </footer>
+ </main>
+
+ <button class="rev-btn rev-fab" type="button" aria-label="Hold to rev the engine"><span class="rev-btn-ring"></span><span class="rev-btn-label">Hold<br>to rev</span></button>
+
+ <!-- Tachometer (big in the rev section, mini while revving elsewhere) -->
+ <div class="tacho" aria-hidden="true">
+ <svg viewBox="-160 -160 320 320" class="tacho-svg">
+ <defs>
+ <radialGradient id="tFace" cx="50%" cy="38%" r="70%"><stop offset="0" stop-color="#16151a"/><stop offset=".7" stop-color="#08080a"/><stop offset="1" stop-color="#020203"/></radialGradient>
+ <linearGradient id="tBezel" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#f3dca0"/><stop offset=".35" stop-color="#9c7a3c"/><stop offset=".6" stop-color="#5a4320"/><stop offset=".85" stop-color="#d8b872"/><stop offset="1" stop-color="#6d5329"/></linearGradient>
+ <linearGradient id="tGlass" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#fff" stop-opacity=".09"/><stop offset=".45" stop-color="#fff" stop-opacity="0"/></linearGradient>
+ <filter id="tGlow" x="-50%" y="-50%" width="200%" height="200%"><feGaussianBlur stdDeviation="3.2" result="b"/><feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge></filter>
+ </defs>
+ <circle r="156" fill="url(#tBezel)"/>
+ <circle r="147" fill="#050506"/>
+ <circle r="144" fill="url(#tFace)"/>
+ <g class="tacho-ticks"></g>
+ <path class="tacho-red" fill="none" stroke="#ff3b5c" stroke-width="7" filter="url(#tGlow)"/>
+ <path class="tacho-arc" fill="none" stroke="#ff3b5c" stroke-width="2.4" stroke-linecap="round" filter="url(#tGlow)"/>
+ <text class="tacho-unit" y="-52" text-anchor="middle">×1000 r/min</text>
+ <text class="tacho-brand" y="-34" text-anchor="middle">Nightshift</text>
+ <text class="tacho-rpm" y="70" text-anchor="middle">1,100</text>
+ <text class="tacho-gear" y="96" text-anchor="middle">N · 07</text>
+ <circle class="tacho-shift" cx="0" cy="-92" r="6"/>
+ <g class="tacho-needle">
+ <path d="M -3.2 18 L -1.1 -128 L 1.1 -128 L 3.2 18 Z" fill="#ff3b5c" filter="url(#tGlow)"/>
+ <path d="M -0.6 10 L -0.3 -124 L 0.3 -124 L 0.6 10 Z" fill="#ffd6de"/>
+ </g>
+ <circle r="15" fill="url(#tBezel)"/>
+ <circle r="7" fill="#0c0b0d"/>
+ <circle r="144" fill="url(#tGlass)"/>
+ </svg>
+ </div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/racer/main.js b/examples/racer/main.js
new file mode 100644
index 0000000..ea34593
--- /dev/null
+++ b/examples/racer/main.js
@@ -0,0 +1,848 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { bakeTexture } from '../../src/core/textures.js';
+import { RectAreaLightUniformsLib } from 'three/examples/jsm/lights/RectAreaLightUniformsLib.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { DepthOfFieldEffect, BloomEffect, HueSaturationEffect } from 'postprocessing';
+import {
+ patchWetFloor, patchWallWash, wetMaterial, createRain, createSplashes, HeatHazeEffect,
+ neonTextures, glowTexture, flameTexture, canvasTex, MAX_RAIN_LIGHTS, createSteam,
+} from './fx.js';
+import { EngineAudio } from './audio.js';
+import { Tacho } from './tacho.js';
+
+const D = Math.PI / 180;
+const Q = new URLSearchParams(location.search);
+const TOUCH = matchMedia('(pointer: coarse)').matches;
+const MOBILE = innerWidth < 760;
+
+// ─── World layout (metres). Bike nose points +X, exhaust side faces the street (+Z). ──
+const WALL_Z = -2.3;
+const SHUTTER = { x0: -9.8, x1: -5.6, top: 3.1, gap: 0.42 };
+const SIGN = { x: 2.0, y: 1.52, w: 2.5 };
+const BIKE_YAW = -22 * D;
+const LAMP = new THREE.Vector3(-0.35, 3.75, WALL_Z + 0.26);
+const CRATE = new THREE.Vector3(2.45, 0, -1.62);
+// Cold fluorescent batten on the wall behind the tail: the cool counter-light to the neon.
+const TUBE = new THREE.Vector3(-2.3, 2.35, WALL_Z + 0.1);
+const TUBE_LEN = 1.5;
+const BIKE_LEN = 2.05;
+// Points on the bike, in the bike group's local space.
+const HEAD_L = new THREE.Vector3(0.62, 0.915, 0);
+const TIP_L = new THREE.Vector3(-0.74, 0.47, 0.19);
+const TIP_DIR = new THREE.Vector3(-0.9, 0.42, 0).normalize();
+const HEADS_L = new THREE.Vector3(0.1, 0.66, 0.12);
+
+// Camera stations: orbit around a point of interest. az: 0 = street side (+Z), 90 = nose-on.
+const STATIONS = {
+ hero: { poi: [0.08, 0.52, 0], az: 6, el: -3.5, dist: 3.75, fov: 31, shift: [-0.14, 0.2], bokeh: 1.8, range: 1.4, vol: 1, mag: 0.9, sat: -0.06, fill: 1.1 },
+ rev: { poi: [0.0, 0.55, 0], az: -45, el: 2, dist: 4.8, fov: 30, shift: [0.22, 0.12], bokeh: 1.6, range: 1.6, vol: 1, mag: 0.8, sat: -0.1 },
+ buildhead: { poi: [0, 0.5, 0], az: -12, el: 9, dist: 5.6, fov: 30, shift: [0.52, 0.36], bokeh: 1.4, range: 2, vol: 0.8 },
+ tank: { poi: [0.26, 0.84, 0.1], local: true, az: 22, el: 9, dist: 0.85, fov: 26, shift: [-0.3, 0.02], bokeh: 4, range: 0.22, vol: 0.1, mag: 0.4, sat: -0.3, fill: 1.6 },
+ engine: { poi: [0.1, 0.56, 0.12], local: true, az: 10, el: 4, dist: 0.8, fov: 28, shift: [0.3, 0], bokeh: 4, range: 0.22, vol: 0.1, mag: 0.4, sat: -0.32, fill: 1.6 },
+ seat: { poi: [-0.42, 0.82, 0.0], local: true, az: -35, el: 30, dist: 1.0, fov: 26, shift: [-0.3, 0], bokeh: 4, range: 0.25, vol: 0.1, mag: 0.4, sat: -0.28, fill: 1.6 },
+ wheel: { poi: [0.68, 0.34, 0.06], local: true, az: 32, el: 3, dist: 1.2, fov: 28, shift: [0.3, 0], bokeh: 3.5, range: 0.3, vol: 0.14, mag: 0.45, sat: -0.28, fill: 1.5 },
+ waitlist: { poi: [0.0, 0.55, 0], az: -52, el: 15, dist: 5.6, fov: 30, shift: [-0.36, 0], bokeh: 1.5, range: 2, vol: 0.8 },
+ garage: { poi: [2.45, 0.66, -1.62], az: -8, el: 4, dist: 2.1, fov: 30, shift: [0.3, -0.05], bokeh: 3, range: 0.45, vol: 0.6 },
+ quote: { poi: [2.0, 1.35, -2.2], az: 24, el: 3, dist: 5.2, fov: 30, shift: [-0.42, 0.22], bokeh: 2, range: 1, vol: 0.3 },
+ foot: { poi: [0.4, 0.7, -0.6], az: 14, el: 9, dist: 11, fov: 32, shift: [0.2, 0.56], bokeh: 0.6, range: 4, vol: 1 },
+};
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let vol, dof, bloom, haze, hueSat;
+const engine = new Engine({
+ canvas, fov: 30, near: 0.05, far: 140, dpr: MOBILE ? 1.25 : 1.5, background: 0x030304,
+ post: {
+ ao: { aoRadius: 0.55, intensity: 2.4, distanceFalloff: 0.6 },
+ bloom: false,
+ pre: cam => [
+ (dof = new DepthOfFieldEffect(cam, { focusDistance: 5, focusRange: 1.8, bokehScale: 1.5, resolutionScale: 0.5 })),
+ (bloom = new BloomEffect({ intensity: 1.2, luminanceThreshold: 0.62, luminanceSmoothing: 0.3, mipmapBlur: true, radius: 0.8, levels: 8 })),
+ (vol = new VolumetricSpotEffect(cam, { density: 0.032, noise: 0.8, noiseScale: 2.2, maxDist: 24, floorY: 0, wind: new THREE.Vector3(0.15, -0.9, 0.05) })),
+ (haze = new HeatHazeEffect()),
+ ],
+ tone: 'agx',
+ extra: () => [(hueSat = new HueSaturationEffect({ saturation: 0 }))],
+ vignette: { offset: 0.26, darkness: 0.74 },
+ noise: 0.055,
+ ca: false,
+ },
+});
+const { scene, camera, renderer } = engine;
+RectAreaLightUniformsLib.init();
+scene.fog = new THREE.FogExp2(0x030305, 0.035);
+
+scene.environment = studioEnvironment(renderer, {
+ top: 0x0d0b14, bottom: 0x020203, blur: 0.03,
+ panels: [
+ { pos: [SIGN.x, SIGN.y, WALL_Z], size: [3, 0.9], intensity: 2.4, color: 0xff3b5c },
+ { pos: [TUBE.x, TUBE.y, TUBE.z], size: [TUBE_LEN, 0.14], intensity: 9, color: 0xd6f2ff },
+ { pos: [-5, 1.6, 3], size: [0.3, 2.6], intensity: 1.2, color: 0x9fe6ff },
+ { pos: [LAMP.x, LAMP.y, LAMP.z], size: [0.7, 0.25], intensity: 14, color: 0xd6e2ff },
+ { pos: [(SHUTTER.x0 + SHUTTER.x1) / 2, 0.22, WALL_Z], size: [4, 0.45], intensity: 3.5, color: 0xffa050 },
+ { pos: [2.5, 3.4, 5.5], size: [6, 0.3], intensity: 2.2, color: 0xdfe6ff },
+ { pos: [7, 2.2, 1], size: [0.35, 3.5], intensity: 1.1, color: 0x9fb0ff },
+ { pos: [0, 12, 0], size: [16, 16], intensity: 0.1, color: 0x6b5a8e },
+ ],
+});
+scene.environmentIntensity = 0.4;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 5 });
+
+// ─── Loader ────────────────────────────────────────────────────────────────────
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', (v * v * (Math.random() < 0.08 ? 0.5 : 1)).toFixed(3));
+ },
+ exit: async () => {
+ loaderEl.style.setProperty('--p', 1);
+ loaderEl.classList.add('buzz');
+ await new Promise(r => setTimeout(r, 850));
+ await gsap.to(loaderEl, { autoAlpha: 0, duration: 1.0, ease: 'power2.inOut' });
+ },
+});
+
+// ─── Textures ──────────────────────────────────────────────────────────────────
+const shared = { uTime: { value: 0 } };
+const texP = Promise.all([
+ assets.texture('img/racer/asphalt.webp'), assets.texture('img/racer/brick.webp'), assets.texture('img/racer/shutter.webp'),
+ assets.texture('img/racer/workshop.webp'), assets.texture('img/racer/city.webp'),
+]);
+const fontP = Promise.race([
+ Promise.all([document.fonts.load('300px Neonderthaw'), document.fonts.load('500 60px Inter'), document.fonts.load('40px Anton')]),
+ new Promise(r => setTimeout(r, 4000)),
+]);
+const modelP = Promise.all([assets.gltf('models/racer/bike.glb'), assets.gltf('models/racer/helmet.glb')]);
+
+/** Height-from-luminance normal map + roughness, baked on the GPU from a photo texture. */
+function derive(src, { size = 1024, strength = 3, rough = '0.5' } = {}) {
+ const u = { uSrc: { value: src }, uStr: { value: strength } };
+ const lum = 'float L(vec2 uv){ return dot(texture2D(uSrc, uv).rgb, vec3(0.299, 0.587, 0.114)); }';
+ const normal = bakeTexture(renderer, size, `
+ uniform sampler2D uSrc; uniform float uStr; ${lum}
+ void main(){
+ float e = 1.0 / ${size.toFixed(1)};
+ float hx = L(vUv + vec2(e, 0.)) - L(vUv - vec2(e, 0.));
+ float hy = L(vUv + vec2(0., e)) - L(vUv - vec2(0., e));
+ vec3 n = normalize(vec3(-hx * uStr, -hy * uStr, 1.0));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);
+ }`, u);
+ const roughness = bakeTexture(renderer, size, `
+ uniform sampler2D uSrc; ${lum}
+ void main(){ vec3 c = texture2D(uSrc, vUv).rgb; float l = L(vUv); float r = ${rough}; gl_FragColor = vec4(1.0, clamp(r, 0.03, 1.0), 0.0, 1.0); }`, u);
+ return { normal, roughness };
+}
+const tile = (t, rx, ry, mirror = true) => {
+ t.wrapS = t.wrapT = mirror ? THREE.MirroredRepeatWrapping : THREE.RepeatWrapping;
+ t.repeat.set(rx, ry); t.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return t;
+};
+
+// ─── Build the street ─────────────────────────────────────────────────────────
+const reflection = new PlanarReflection(renderer, { resolution: MOBILE ? 0.4 : 0.5 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+const neon = { level: 0, flick: 0, crackle: 0, target: 1 };
+const washLevel = { value: 0 };
+const garageWash = { value: 0.9 };
+let floor, floorU, neonMats = {}, splashes, rain, steam;
+const lights = {};
+
+async function buildWorld() {
+ const [asphalt, brick, shutterTex, workshop, city] = await texP;
+ await fontP;
+
+ // Wet asphalt with puddles.
+ const puddle = bakeTexture(renderer, 512, `void main(){ float n = fbm(vUv * 5.0, 5.0, 6, 0.55) * 0.5 + 0.5; gl_FragColor = vec4(vec3(n), 1.0); }`);
+ puddle.wrapS = puddle.wrapT = THREE.RepeatWrapping;
+ shared.puddle = puddle;
+ const ad = derive(asphalt, { size: 1024, strength: 2.2, rough: '0.14 + smoothstep(0.02, 0.2, l) * 0.34 + (fbm(vUv * 6.0, 6.0, 4, 0.5)) * 0.12' });
+ const AR = 1 / 2.6; // one asphalt tile per 2.6 m
+ const floorMat = new THREE.MeshStandardMaterial({
+ map: tile(asphalt, 90 * AR, 44 * AR), normalMap: tile(ad.normal, 90 * AR, 44 * AR), roughnessMap: tile(ad.roughness, 90 * AR, 44 * AR),
+ normalScale: new THREE.Vector2(0.9, 0.9), roughness: 1, metalness: 0, envMapIntensity: 0.14, color: 0x5a5a60,
+ });
+ floor = new THREE.Mesh(new THREE.PlaneGeometry(90, 44), floorMat);
+ floor.rotation.x = -Math.PI / 2;
+ floor.position.set(-15, 0, WALL_Z + 22);
+ floor.receiveShadow = true;
+ scene.add(floor);
+ reflection.hidden.push(floor);
+ floorU = patchWetFloor(floorMat, reflection, shared);
+
+ // Brick wall with an opening for the shutter.
+ const bd = derive(brick, { size: 1024, strength: 4.5, rough: '0.62 - smoothstep(0.02, 0.12, l) * 0.2 - smoothstep(0.35, 0.9, fbm(vec2(vUv.x * 18.0, vUv.y * 1.5), 18.0, 4, 0.5) + 0.5) * 0.35' });
+ const BR = 1 / 3.4;
+ const wallShape = new THREE.Shape();
+ wallShape.moveTo(-42, 0); wallShape.lineTo(9, 0); wallShape.lineTo(9, 12); wallShape.lineTo(-42, 12); wallShape.lineTo(-42, 0);
+ const hole = new THREE.Path();
+ hole.moveTo(SHUTTER.x0, 0); hole.lineTo(SHUTTER.x1, 0); hole.lineTo(SHUTTER.x1, SHUTTER.top); hole.lineTo(SHUTTER.x0, SHUTTER.top); hole.lineTo(SHUTTER.x0, 0);
+ wallShape.holes.push(hole);
+ const wallMat = new THREE.MeshStandardMaterial({
+ map: tile(brick, BR, BR), normalMap: tile(bd.normal, BR, BR), roughnessMap: tile(bd.roughness, BR, BR), roughness: 1,
+ normalScale: new THREE.Vector2(1.2, 1.2), envMapIntensity: 0.5, color: 0xb8aeb0, name: 'wall',
+ });
+ const wall = new THREE.Mesh(new THREE.ShapeGeometry(wallShape), wallMat);
+ wall.position.z = WALL_Z;
+ wall.receiveShadow = true;
+ scene.add(wall);
+
+ // Concrete plinth along the base of the wall.
+ const plinthMat = new THREE.MeshStandardMaterial({ color: 0x1b1a1c, roughness: 0.55, envMapIntensity: 0.4 });
+ for (const [a, b] of [[-42, SHUTTER.x0 - 0.12], [SHUTTER.x1 + 0.12, 9]]) {
+ const p = new THREE.Mesh(new THREE.BoxGeometry(b - a, 0.22, 0.12), plinthMat);
+ p.position.set((a + b) / 2, 0.11, WALL_Z + 0.06);
+ p.receiveShadow = p.castShadow = true;
+ scene.add(p);
+ }
+
+ // Roll-up shutter, lifted a hand's width: the workshop light leaks out underneath.
+ const sd = derive(shutterTex, { size: 1024, strength: 5, rough: '0.3 + (1.0 - l) * 0.45 + max(c.r - c.b, 0.0) * 1.2' });
+ const sw = SHUTTER.x1 - SHUTTER.x0, sh = SHUTTER.top - SHUTTER.gap;
+ const shutterMat = new THREE.MeshStandardMaterial({
+ map: shutterTex, normalMap: sd.normal, roughnessMap: sd.roughness, roughness: 1, metalness: 0.65, normalScale: new THREE.Vector2(1.6, 1.6),
+ envMapIntensity: 0.9, color: 0x9b9ba4,
+ });
+ shutterTex.repeat.set(1, 1);
+ const shutter = new THREE.Mesh(new THREE.PlaneGeometry(sw, sh), shutterMat);
+ shutter.position.set((SHUTTER.x0 + SHUTTER.x1) / 2, SHUTTER.gap + sh / 2, WALL_Z - 0.06);
+ shutter.receiveShadow = true;
+ scene.add(shutter);
+ const steel = new THREE.MeshStandardMaterial({ color: 0x2a2a2e, roughness: 0.38, metalness: 0.85, envMapIntensity: 1.1 });
+ const bar = new THREE.Mesh(new THREE.BoxGeometry(sw, 0.06, 0.07), steel);
+ bar.position.set(shutter.position.x, SHUTTER.gap + 0.03, WALL_Z - 0.03);
+ bar.castShadow = true;
+ scene.add(bar);
+ for (const x of [SHUTTER.x0 - 0.05, SHUTTER.x1 + 0.05]) {
+ const rail = new THREE.Mesh(new THREE.BoxGeometry(0.1, SHUTTER.top + 0.2, 0.14), steel);
+ rail.position.set(x, (SHUTTER.top + 0.2) / 2, WALL_Z + 0.02);
+ rail.castShadow = rail.receiveShadow = true;
+ scene.add(rail);
+ }
+ const housing = new THREE.Mesh(new RoundedBoxGeometry(sw + 0.4, 0.46, 0.4, 2, 0.03), steel);
+ housing.position.set(shutter.position.x, SHUTTER.top + 0.25, WALL_Z + 0.12);
+ housing.castShadow = housing.receiveShadow = true;
+ scene.add(housing);
+
+ // The workshop behind it: a warm plate and floor, only ever seen through the gap.
+ const inside = new THREE.Mesh(new THREE.PlaneGeometry(8.4, 3.6), new THREE.MeshBasicMaterial({ map: workshop, color: new THREE.Color(1.3, 0.95, 0.65), fog: false }));
+ inside.position.set(shutter.position.x, 1.2, WALL_Z - 4.2);
+ scene.add(inside);
+ const inFloor = new THREE.Mesh(new THREE.PlaneGeometry(sw + 1, 4.2), new THREE.MeshStandardMaterial({ color: 0x2a2018, roughness: 0.25, metalness: 0, envMapIntensity: 0 }));
+ inFloor.rotation.x = -Math.PI / 2; inFloor.position.set(shutter.position.x, 0.002, WALL_Z - 2.1);
+ scene.add(inFloor);
+ const inLight = new THREE.PointLight(0xffa458, 12, 7, 1.6);
+ inLight.position.set(shutter.position.x, 1.6, WALL_Z - 2.4);
+ scene.add(inLight);
+ const garageRect = new THREE.RectAreaLight(0xffa050, 2.5, sw, SHUTTER.gap);
+ garageRect.position.set(shutter.position.x, SHUTTER.gap / 2, WALL_Z + 0.02);
+ garageRect.lookAt(shutter.position.x, SHUTTER.gap / 2, 10);
+ scene.add(garageRect);
+ lights.garage = garageRect;
+ // A low warm spot to haze the air just outside the gap.
+ const garageSpot = new THREE.SpotLight(0xffa050, 9, 6, 0.9, 0.9, 1.8);
+ garageSpot.position.set(shutter.position.x, 0.3, WALL_Z - 0.3);
+ garageSpot.target.position.set(shutter.position.x, 0.0, WALL_Z + 4);
+ scene.add(garageSpot, garageSpot.target);
+ lights.garageSpot = garageSpot;
+
+ // Neon sign.
+ const nt = neonTextures({});
+ const signH = SIGN.w / nt.aspect;
+ const mk = (map, blending, color, z) => {
+ const m = new THREE.MeshBasicMaterial({ map, transparent: true, depthWrite: false, blending, color, fog: false, toneMapped: false });
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(SIGN.w, signH), m);
+ mesh.position.set(SIGN.x, SIGN.y, WALL_Z + z);
+ mesh.renderOrder = 6;
+ scene.add(mesh);
+ return m;
+ };
+ neonMats.glass = mk(nt.glass, THREE.NormalBlending, new THREE.Color(0.08, 0.06, 0.07), 0.055);
+ neonMats.main = mk(nt.main, THREE.AdditiveBlending, new THREE.Color(0, 0, 0), 0.06);
+ neonMats.flick = mk(nt.flick, THREE.AdditiveBlending, new THREE.Color(0, 0, 0), 0.061);
+ // standoffs
+ const standoffMat = new THREE.MeshStandardMaterial({ color: 0x777777, metalness: 1, roughness: 0.3 });
+ for (const [dx, dy] of [[-1.2, 0.25], [1.2, 0.25], [-1.2, -0.3], [1.2, -0.3], [0, 0.34]]) {
+ const s = new THREE.Mesh(new THREE.CylinderGeometry(0.008, 0.008, 0.06, 8), standoffMat);
+ s.rotation.x = Math.PI / 2; s.position.set(SIGN.x + dx, SIGN.y + dy, WALL_Z + 0.03);
+ scene.add(s);
+ }
+ patchWallWash(wallMat, [{ tex: nt.wash, rect: new THREE.Vector4(SIGN.x - SIGN.w, SIGN.y - signH, SIGN.w * 2, signH * 2), pos: new THREE.Vector3(SIGN.x, SIGN.y, WALL_Z + 0.1), color: new THREE.Color(1.0, 0.16, 0.3), level: washLevel }]);
+ const neonRect = new THREE.RectAreaLight(0xff3b5c, 0, SIGN.w * 0.9, signH * 0.7);
+ neonRect.position.set(SIGN.x, SIGN.y, WALL_Z + 0.08);
+ neonRect.lookAt(SIGN.x, SIGN.y - 0.6, 10);
+ scene.add(neonRect);
+ lights.neon = neonRect;
+ const neonSpot = new THREE.SpotLight(0xff3b5c, 0, 9, 0.62, 1, 1.6);
+ neonSpot.position.set(SIGN.x, SIGN.y + 0.2, WALL_Z + 0.2);
+ neonSpot.target.position.set(SIGN.x, 0, WALL_Z + 1.5);
+ scene.add(neonSpot, neonSpot.target);
+ lights.neonSpot = neonSpot;
+
+ // Caged bulkhead lamp over the shutter: the cold key from above and behind.
+ const lampHousing = new THREE.Mesh(new THREE.CylinderGeometry(0.13, 0.16, 0.14, 24), steel);
+ lampHousing.position.copy(LAMP).add(new THREE.Vector3(0, 0.06, 0));
+ scene.add(lampHousing);
+ const arm = new THREE.Mesh(new THREE.BoxGeometry(0.05, 0.05, 0.3), steel);
+ arm.position.set(LAMP.x, LAMP.y + 0.1, WALL_Z + 0.13);
+ scene.add(arm);
+ const lens = new THREE.Mesh(new THREE.CircleGeometry(0.12, 32), new THREE.MeshBasicMaterial({ color: new THREE.Color(9, 10, 12), fog: false }));
+ lens.rotation.x = Math.PI / 2; lens.position.copy(LAMP).add(new THREE.Vector3(0, -0.012, 0));
+ scene.add(lens);
+ lights.lampLens = lens.material;
+ const lamp = new THREE.SpotLight(0xd4e0ff, 70, 16, 0.37, 0.5, 1.5);
+ lamp.position.copy(LAMP).add(new THREE.Vector3(0, -0.05, 0));
+ lamp.target.position.set(0.05, 0, 0.15);
+ lamp.castShadow = true;
+ lamp.shadow.mapSize.set(2048, 2048);
+ lamp.shadow.camera.near = 0.3; lamp.shadow.camera.far = 12;
+ lamp.shadow.bias = -0.0002; lamp.shadow.normalBias = 0.02; lamp.shadow.radius = 3;
+ scene.add(lamp, lamp.target);
+ lights.lamp = lamp;
+ vol.add(lamp, { scale: 0.022, range: 0.06, softness: 0.25 });
+ vol.add(neonSpot, { scale: 0.012, range: 0.12, softness: 0.9 });
+ // Fluorescent batten: emissive tube, a long area light for reflections, a spot for the rim + haze.
+ const tubeMesh = new THREE.Mesh(new THREE.CylinderGeometry(0.018, 0.018, TUBE_LEN, 12), new THREE.MeshBasicMaterial({ color: new THREE.Color(5, 7, 8), fog: false }));
+ tubeMesh.rotation.z = Math.PI / 2; tubeMesh.position.copy(TUBE).add(new THREE.Vector3(0, 0, 0.04));
+ scene.add(tubeMesh);
+ const batten = new THREE.Mesh(new RoundedBoxGeometry(TUBE_LEN + 0.12, 0.07, 0.06, 2, 0.01), steel);
+ batten.position.copy(TUBE).add(new THREE.Vector3(0, 0.035, -0.01));
+ scene.add(batten);
+ const tubeRect = new THREE.RectAreaLight(0xd6f2ff, 0, TUBE_LEN, 0.1);
+ tubeRect.position.copy(TUBE).add(new THREE.Vector3(0, 0, 0.06));
+ tubeRect.lookAt(0.2, 0.55, 0.3);
+ scene.add(tubeRect);
+ const tubeSpot = new THREE.SpotLight(0xc8ecff, 0, 9, 0.42, 0.6, 1.6);
+ tubeSpot.position.copy(TUBE).add(new THREE.Vector3(0, -0.02, 0.1));
+ tubeSpot.target.position.set(0.25, 0.45, 0.2);
+ scene.add(tubeSpot, tubeSpot.target);
+ lights.tube = { mesh: tubeMesh.material, rect: tubeRect, spot: tubeSpot };
+ vol.add(tubeSpot, { scale: 0.004, range: 0.12, softness: 0.5 });
+
+ // Soft cold fill from across the street (a shop window we never see).
+ const fill = new THREE.RectAreaLight(0xc4d0ff, 2.2, 6, 0.35);
+ fill.position.set(2.5, 3.0, 6.5);
+ fill.lookAt(0, 0.6, 0);
+ scene.add(fill);
+ lights.fill = fill;
+ scene.add(new THREE.HemisphereLight(0x1c1c30, 0x060505, 0.12));
+
+ // Drainpipe, left of the shutter.
+ const pipeMat = new THREE.MeshStandardMaterial({ color: 0x1a1b1d, metalness: 0.7, roughness: 0.35, envMapIntensity: 1 });
+ const pipe = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.055, 9.6, 16), pipeMat);
+ pipe.position.set(SHUTTER.x1 + 0.55, 4.8 + 0.12, WALL_Z + 0.1);
+ pipe.castShadow = pipe.receiveShadow = true;
+ scene.add(pipe);
+ const shoe = new THREE.Mesh(new THREE.CylinderGeometry(0.055, 0.075, 0.2, 16, 1, true), pipeMat);
+ shoe.position.set(pipe.position.x, 0.1, WALL_Z + 0.12); shoe.rotation.x = 0.5;
+ scene.add(shoe);
+
+ // Crate with a stencil, for the helmet.
+ const crateTex = canvasTex(1024, 1024, (g, w, h) => {
+ g.fillStyle = '#2b1d14'; g.fillRect(0, 0, w, h);
+ for (let i = 0; i < 4; i++) {
+ const y0 = i * h / 4;
+ g.fillStyle = `hsl(24, 32%, ${12 + Math.random() * 5}%)`; g.fillRect(0, y0 + 4, w, h / 4 - 8);
+ for (let k = 0; k < 90; k++) {
+ g.strokeStyle = `rgba(${Math.random() < 0.5 ? '0,0,0' : '120,80,50'},${Math.random() * 0.18})`; g.lineWidth = 1 + Math.random() * 2;
+ const yy = y0 + 8 + Math.random() * (h / 4 - 16);
+ g.beginPath(); g.moveTo(0, yy); g.bezierCurveTo(w * 0.3, yy + (Math.random() - 0.5) * 12, w * 0.7, yy + (Math.random() - 0.5) * 12, w, yy + (Math.random() - 0.5) * 6); g.stroke();
+ }
+ g.fillStyle = 'rgba(0,0,0,0.85)'; g.fillRect(0, y0, w, 5);
+ }
+ g.globalAlpha = 0.55; g.fillStyle = '#d9cdb4'; g.textAlign = 'center';
+ g.font = '400 118px Anton'; g.fillText('NIGHTSHIFT', w / 2, h * 0.44);
+ g.font = '600 44px Inter'; if ('letterSpacing' in g) g.letterSpacing = '14px'; g.fillText('MOTOR CO. · ROTTERDAM', w / 2, h * 0.58);
+ g.font = '400 70px Anton'; g.fillText('No. 07', w / 2, h * 0.76);
+ });
+ const crateMat = new THREE.MeshStandardMaterial({ map: crateTex, roughness: 0.55, metalness: 0, envMapIntensity: 0.6 });
+ const crate = new THREE.Mesh(new RoundedBoxGeometry(0.64, 0.44, 0.46, 2, 0.012), crateMat);
+ crate.position.copy(CRATE).add(new THREE.Vector3(0, 0.22, 0));
+ crate.rotation.y = 0.2;
+ crate.castShadow = crate.receiveShadow = true;
+ scene.add(crate);
+ lights.crateTop = crate.position.y + 0.22;
+
+ // The street beyond the wall's end.
+ const cityMat = new THREE.MeshBasicMaterial({ map: city, color: new THREE.Color(0.5, 0.46, 0.55), fog: false, depthWrite: false });
+ const cityPlane = new THREE.Mesh(new THREE.PlaneGeometry(46, 19.7), cityMat);
+ cityPlane.position.set(-44, 6.2, 5);
+ cityPlane.rotation.y = Math.PI / 2;
+ scene.add(cityPlane);
+
+ // Rain + splashes.
+ rain = createRain({ count: MOBILE ? 14000 : 36000, box: new THREE.Vector3(13, 8, 13) });
+ scene.add(rain.mesh);
+ splashes = createSplashes(rain.uniforms, { count: MOBILE ? 2500 : 5000, radius: 7 });
+ scene.add(splashes.points);
+ reflection.hidden.push(splashes.points);
+ // steam off the pipes: headers down from the head, under the engine, back along the muffler
+ steam = createSteam(rain.uniforms, [
+ new THREE.Vector3(0.26, 0.5, 0.16), new THREE.Vector3(0.2, 0.3, 0.2), new THREE.Vector3(0.05, 0.17, 0.2),
+ new THREE.Vector3(-0.3, 0.24, 0.2), new THREE.Vector3(-0.55, 0.36, 0.2), new THREE.Vector3(-0.74, 0.47, 0.19),
+ ], { count: MOBILE ? 200 : 420 });
+ scene.add(steam.points);
+ reflection.hidden.push(steam.points);
+ engine.onResize((w, h, dpr) => { rain.uniforms.uRes.value.set(w * dpr, h * dpr); splashes.uniforms.uDpr.value = dpr * (h / 900); steam.uniforms.uDpr.value = dpr * (h / 900); });
+}
+
+// ─── Bike, helmet, headlight, exhaust ─────────────────────────────────────────
+const bike = new THREE.Group(); // vibrates
+const bikeRoot = new THREE.Group(); // leans on its stand
+bikeRoot.add(bike);
+bikeRoot.rotation.set(-4.5 * D, BIKE_YAW, 0, 'YXZ');
+scene.add(bikeRoot);
+const glowTex = glowTexture();
+const streakTex = glowTexture([[0, 'rgba(255,255,255,1)'], [0.1, 'rgba(255,255,255,0.35)'], [0.4, 'rgba(255,255,255,0.05)'], [1, 'rgba(255,255,255,0)']]);
+const head = new THREE.SpotLight(0xfff2de, 0, 32, 0.36, 0.5, 1.25);
+head.target.position.set(10, 0.2, 0.4);
+scene.add(head, head.target);
+vol.add(head, { scale: 0.05, range: 0.035, softness: 0.22 });
+const headLens = new THREE.Mesh(new THREE.CircleGeometry(0.083, 40), new THREE.MeshBasicMaterial({ map: glowTex, color: 0x000000, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, fog: false }));
+headLens.rotation.y = Math.PI / 2;
+headLens.position.copy(HEAD_L).add(new THREE.Vector3(0.012, 0, 0));
+bike.add(headLens);
+const flare = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: 0x000000, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: true, fog: false }));
+const streak = new THREE.Sprite(new THREE.SpriteMaterial({ map: streakTex, color: 0x000000, blending: THREE.AdditiveBlending, depthWrite: false, depthTest: false, fog: false }));
+scene.add(flare, streak);
+const flame = new THREE.Sprite(new THREE.SpriteMaterial({ map: flameTexture(), color: 0x000000, blending: THREE.AdditiveBlending, depthWrite: false, fog: false }));
+scene.add(flame);
+const tipGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: glowTex, color: 0x000000, blending: THREE.AdditiveBlending, depthWrite: false, fog: false }));
+scene.add(tipGlow);
+const popLight = new THREE.PointLight(0xff7a2a, 0, 5, 2);
+scene.add(popLight);
+let bikeModel, helmetModel;
+
+async function buildBike() {
+ const [bikeG, helmetG] = await modelP;
+ const m = bikeG.scene;
+ normalize(m, BIKE_LEN, { axis: 'x' });
+ m.rotation.y = Math.PI;
+ prepModel(m, renderer, {
+ env: 1,
+ onMat: (mat, mesh) => { mesh.material = wetMaterial(mat, { drops: 0.5, dropScale: 110, env: 1.15 }); },
+ });
+ bike.add(m);
+ bikeModel = m;
+ if (Q.has('dbg')) for (const [p, c] of [[HEAD_L, 0x00ff00], [TIP_L, 0xff0000], [HEADS_L, 0x0088ff]]) {
+ const s = new THREE.Mesh(new THREE.SphereGeometry(0.015, 12, 8), new THREE.MeshBasicMaterial({ color: c, depthTest: false }));
+ s.position.copy(p); s.renderOrder = 99; bike.add(s);
+ }
+ const h = helmetG.scene;
+ normalize(h, 0.3, { axis: 'max' });
+ prepModel(h, renderer, { env: 1, onMat: (mat, mesh) => { mesh.material = wetMaterial(mat, { drops: 0.6, dropScale: 16, env: 1.1 }); } });
+ const hg = new THREE.Group();
+ hg.add(h);
+ hg.position.set(CRATE.x + 0.02, lights.crateTop ?? 0.44, CRATE.z + 0.02);
+ hg.rotation.y = 0.75;
+ scene.add(hg);
+ helmetModel = hg;
+}
+
+// ─── Throttle, RPM and everything it drives ───────────────────────────────────
+const IDLE = 1100, RED = 8500;
+const rev = { held: false, throttle: 0, rpm: IDLE, rn: 0, heat: 0, limiter: 0, lastHeld: -10, pops: 0, beam: 0, highUntil: 0, used: false };
+const audio = new EngineAudio();
+const tacho = new Tacho(document.querySelector('.tacho'));
+const tachoEl = document.querySelector('.tacho');
+const flashEl = document.querySelector('.redline-flash');
+const root = document.documentElement;
+const body = document.body;
+let beamPower = 0; // 0 dark, 1 low beam, >1 high beam
+
+function setHeld(v) {
+ if (v === rev.held) return;
+ rev.held = v;
+ if (v) {
+ rev.used = true;
+ if (rev.beam < 2 && beamPower > 0.5) { rev.beam = 2; audio.click(); snapBeam(); }
+ } else rev.lastHeld = engine.time;
+ body.classList.toggle('is-revving', v);
+ document.querySelectorAll('.rev-btn').forEach(b => b.classList.toggle('on', v));
+}
+function snapBeam() {
+ // relay chatter on the switch to high beam
+ gsap.timeline().to(beam, { k: 0.2, duration: 0.03 }).to(beam, { k: 1.25, duration: 0.03, delay: 0.04 }).to(beam, { k: 0.6, duration: 0.03, delay: 0.03 }).to(beam, { k: 1, duration: 0.15 });
+}
+const beam = { k: 1 };
+const interactive = t => t.closest?.('a, button, input, select, textarea, label, .wl-panel, .nav, .tw-nav');
+addEventListener('pointerdown', e => {
+ if (e.button !== 0) return;
+ const btn = e.target.closest?.('.rev-btn');
+ if (btn) { e.preventDefault(); try { btn.setPointerCapture?.(e.pointerId); } catch { /* synthetic pointers */ } setHeld(true); return; }
+ if (e.pointerType === 'touch' || interactive(e.target)) return;
+ setHeld(true);
+});
+addEventListener('pointerup', () => setHeld(false));
+addEventListener('pointercancel', () => setHeld(false));
+addEventListener('blur', () => setHeld(false));
+addEventListener('contextmenu', e => { if (e.target.closest?.('.rev-btn')) e.preventDefault(); });
+addEventListener('keydown', e => {
+ if (e.code !== 'Space' || e.target.closest?.('input, textarea, select, button')) return;
+ e.preventDefault();
+ setHeld(true);
+});
+addEventListener('keyup', e => { if (e.code === 'Space') setHeld(false); });
+
+function popFlash(s) {
+ audio.pop(s);
+ const k = 0.6 + Math.random() * 0.8;
+ gsap.killTweensOf(fx);
+ gsap.fromTo(fx, { flame: k * s }, { flame: 0, duration: 0.09 + Math.random() * 0.08, ease: 'power2.out' });
+ fx.flameRot = Math.random() * Math.PI * 2;
+}
+const fx = { flame: 0, flameRot: 0 };
+
+function updateRev(dt, t) {
+ rev.throttle = damp(rev.throttle, rev.held ? 1 : 0, rev.held ? 16 : 11, dt);
+ const rn0 = (rev.rpm - IDLE) / (RED - IDLE);
+ let acc = rev.throttle * (2600 + 5600 * Math.sin(Math.PI * clamp(rn0 * 0.9 + 0.08)));
+ acc -= (rev.rpm - IDLE) * (rev.held ? 0.28 : 2.2);
+ rev.rpm += acc * dt;
+ rev.limiter = Math.max(0, rev.limiter - dt);
+ if (rev.rpm >= RED) { rev.rpm = RED - 260 - Math.random() * 180; rev.limiter = 0.12; }
+ rev.rpm = Math.max(IDLE * 0.96, rev.rpm);
+ // the idle lope
+ const idleWob = (Math.sin(t * 7.1) * 0.6 + Math.sin(t * 12.7 + 1.3) * 0.4) * 28 * (1 - rev.throttle);
+ rev.shown = rev.rpm + idleWob;
+ rev.rn = clamp((rev.rpm - IDLE) / (RED - IDLE));
+ rev.heat = damp(rev.heat, rev.rn, rev.rn > rev.heat ? 0.9 : 0.25, dt);
+ // overrun crackle after letting go from high revs
+ if (!rev.held && rev.rpm > 3200 && t - rev.lastHeld < 1.6) {
+ const rate = 11 * clamp((rev.rpm - 3200) / 4500) * (1 - (t - rev.lastHeld) / 1.6);
+ if (Math.random() < rate * dt) popFlash(0.6 + rev.rn * 0.6);
+ }
+ // high beam drops back to low a while after the last blip
+ if (rev.held) rev.highUntil = t + 3;
+ if (rev.beam === 2 && t > rev.highUntil) { rev.beam = 1; audio.click(); }
+}
+
+// ─── Fluorescent tube: steady 100 Hz shimmer, and a tired starter every so often ─
+let tubeNext = 7, tubeEnd = 0;
+function tubeLevel(t) {
+ if (t > tubeNext) { tubeEnd = t + 0.5 + Math.random() * 0.7; tubeNext = t + 9 + Math.random() * 12; }
+ let v = 0.97 + Math.sin(t * 628) * 0.03;
+ if (t < tubeEnd) { const k = Math.sin(t * 47) * Math.sin(t * 13.3); v *= k > 0.15 ? 1 : k > -0.3 ? 0.35 : 0.05; }
+ return v;
+}
+
+// ─── Neon behaviour ───────────────────────────────────────────────────────────
+let nextStutter = 4, stutterEnd = 0, stutterSeed = 0, nextBlink = 18;
+function updateNeon(dt, t) {
+ let lv = neon.target;
+ let letter = 1;
+ if (t > nextStutter) { stutterEnd = t + 0.35 + Math.random() * 0.5; nextStutter = t + 4 + Math.random() * 6; stutterSeed = Math.random() * 100; }
+ if (t < stutterEnd) letter = Math.sin(t * 90 + stutterSeed) > 0.1 ? 1 : 0.06;
+ if (t > nextBlink) { nextBlink = t + 16 + Math.random() * 14; gsap.timeline().to(neon, { blink: 0.25, duration: 0.03 }).to(neon, { blink: 1, duration: 0.05, delay: 0.06 }).to(neon, { blink: 0.4, duration: 0.03, delay: 0.1 }).to(neon, { blink: 1, duration: 0.2 }); }
+ lv *= neon.blink ?? 1;
+ // revving sags the supply, then the transformer sings
+ const sag = rev.rn > 0.2 && Math.random() < rev.rn * 0.08 ? 0.55 : 1;
+ const boost = 1 + rev.rn * 0.45 + Math.sin(t * 120) * 0.02 * rev.rn;
+ neon.level = damp(neon.level, lv * sag * boost, 30, dt) * neon.power;
+ neon.letter = neon.level * letter;
+ neon.crackle = (sag < 1 ? 1 : 0) + (letter < 1 ? 0.6 : 0);
+}
+neon.power = 0; neon.blink = 1;
+
+// ─── Scroll → camera stations ─────────────────────────────────────────────────
+let anchors = [];
+function measure() {
+ const max = document.documentElement.scrollHeight - innerHeight;
+ anchors = [...document.querySelectorAll('[data-station]')].map(el => {
+ const r = el.getBoundingClientRect();
+ const key = el.dataset.station;
+ let y = r.top + scrollY + r.height / 2 - innerHeight / 2;
+ if (key === 'hero') y = 0;
+ if (key === 'foot') y = max;
+ return { y: clamp(y, 0, max), key, st: STATIONS[key] };
+ }).sort((a, b) => a.y - b.y);
+}
+addEventListener('resize', () => requestAnimationFrame(measure));
+const cur = { poi: new THREE.Vector3(), az: 0, el: 0, dist: 5, fov: 30, sx: 0, sy: 0, bokeh: 1, range: 2, vol: 1, mag: 1, sat: 0, fill: 1 };
+const va = new THREE.Vector3(), vb = new THREE.Vector3();
+function stationAt(sy) {
+ let i = 0;
+ while (i < anchors.length - 2 && sy >= anchors[i + 1].y) i++;
+ const a = anchors[i], b = anchors[i + 1] ?? a;
+ const f = b.y > a.y ? clamp((sy - a.y) / (b.y - a.y)) : 0;
+ const e = smooth(0.1, 0.9, f);
+ const A = a.st, B = b.st;
+ cur.poi.set(...A.poi).lerp(vb.set(...B.poi), e);
+ cur.az = lerp(A.az, B.az, e); cur.el = lerp(A.el, B.el, e);
+ // pull back a little mid-transition so macro-to-macro moves feel like a dolly, not a cut
+ cur.dist = lerp(A.dist, B.dist, e) + Math.sin(e * Math.PI) * Math.min(A.dist, B.dist) * 0.35;
+ cur.fov = lerp(A.fov, B.fov, e);
+ cur.sx = lerp(A.shift[0], B.shift[0], e); cur.sy = lerp(A.shift[1], B.shift[1], e);
+ cur.bokeh = lerp(A.bokeh, B.bokeh, e); cur.range = lerp(A.range, B.range, e); cur.vol = lerp(A.vol ?? 0.6, B.vol ?? 0.6, e);
+ cur.mag = lerp(A.mag ?? 0.8, B.mag ?? 0.8, e); cur.sat = lerp(A.sat ?? -0.1, B.sat ?? -0.1, e); cur.fill = lerp(A.fill ?? 1, B.fill ?? 1, e);
+ return { i, f, key: f < 0.5 ? a.key : b.key };
+}
+const cam = { poi: new THREE.Vector3(0.1, 0.6, 0), az: 44, el: 3, dist: 5, fov: 30, sx: 0.2, sy: 0, bokeh: 1.5, range: 1.8, vol: 1, mag: 1, sat: 0, fill: 1 };
+if (MOBILE) for (const s of Object.values(STATIONS)) { s.shift = [0, s.shift[1] + 0.2]; s.dist *= 1.35; s.fov += 6; }
+if (MOBILE) { STATIONS.hero.dist *= 1.3; STATIONS.hero.poi = [0.15, 0.55, 0]; }
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const tmp = new THREE.Vector3(), tmp2 = new THREE.Vector3(), tmp3 = new THREE.Vector3();
+const SIGN_P = new THREE.Vector3(SIGN.x, SIGN.y, WALL_Z + 0.2);
+const headW = new THREE.Vector3(), tipW = new THREE.Vector3(), headsW = new THREE.Vector3();
+const hazeU = () => haze.uniforms;
+const toUv = (v, out) => { tmp3.copy(v).project(camera); out.set((tmp3.x + 1) / 2, (tmp3.y + 1) / 2); return tmp3.z < 1; };
+const heroEl = document.querySelector('.hero');
+const revEl = document.querySelector('.rev');
+let lastCursor = '', stationKey = 'hero';
+let cursorApi, ready = false;
+
+function frame(dt, t) {
+ pointer.update(dt);
+ shared.uTime.value = t;
+ updateRev(dt, t);
+ updateNeon(dt, t);
+ const rn = rev.rn;
+
+ // Camera
+ const st = stationAt(scrollY);
+ stationKey = st.key;
+ const k = 1 - Math.exp(-4.5 * dt);
+ cam.poi.lerp(cur.poi, k);
+ for (const p of ['az', 'el', 'dist', 'fov', 'sx', 'sy', 'bokeh', 'range', 'vol', 'mag', 'sat', 'fill']) cam[p] += (cur[p] - cam[p]) * k;
+ hueSat.saturation = cam.sat;
+ vol.uniforms.get('uDensity').value = 0.028 * cam.vol;
+ const az = (cam.az + pointer.sx * 3 + Math.sin(t * 0.13) * 1.2) * D;
+ const el = (cam.el + pointer.sy * 1.6 + Math.sin(t * 0.21) * 0.4) * D;
+ const dist = cam.dist * (1 - rn * 0.035);
+ camera.position.set(Math.sin(az) * Math.cos(el), Math.sin(el), Math.cos(az) * Math.cos(el)).multiplyScalar(dist).add(cam.poi);
+ // engine shake reaches the camera at high revs
+ const shake = (0.0006 + rn * rn * 0.004) * Math.min(dist, 5);
+ camera.position.x += (Math.random() - 0.5) * shake; camera.position.y += (Math.random() - 0.5) * shake;
+ camera.position.y = Math.max(0.12, camera.position.y);
+ camera.lookAt(cam.poi);
+ camera.fov = cam.fov - rn * 1.2;
+ camera.updateProjectionMatrix();
+ camera.projectionMatrix.elements[8] -= cam.sx;
+ camera.projectionMatrix.elements[9] -= cam.sy;
+ camera.projectionMatrixInverse.copy(camera.projectionMatrix).invert();
+ camera.updateMatrixWorld();
+
+ // Depth of field on the point of interest.
+ const fd = camera.position.distanceTo(cam.poi);
+ dof.cocMaterial.focusDistance = fd;
+ dof.cocMaterial.focusRange = cam.range;
+ dof.bokehScale = cam.bokeh * (MOBILE ? 0.7 : 1);
+
+ // Bike vibration: a lope at idle, a buzz at revs.
+ const lope = Math.sin(t * 2 * Math.PI * 4.6) * (Math.sin(t * 2 * Math.PI * 9.2 + 0.7) > 0 ? 1 : 0.4);
+ const amp = 0.0005 * (1 - rn) + rn * 0.0024;
+ bike.position.set((Math.random() - 0.5) * amp * 0.6, lope * amp * 0.5 + (Math.random() - 0.5) * amp, (Math.random() - 0.5) * amp * 0.5);
+ bike.rotation.x = (Math.random() - 0.5) * amp * 1.6 + lope * 0.0004;
+ bike.rotation.z = rev.throttle * 0.006 + (Math.random() - 0.5) * amp * 0.8;
+ bikeRoot.updateMatrixWorld(true);
+ headW.copy(HEAD_L).applyMatrix4(bike.matrixWorld);
+ tipW.copy(TIP_L).applyMatrix4(bike.matrixWorld);
+ headsW.copy(HEADS_L).applyMatrix4(bike.matrixWorld);
+
+ // Headlight: alternator-fed, so it brightens with the revs.
+ const baseBeam = rev.beam === 2 ? 1 : 0.75;
+ beamPower = damp(beamPower, rev.beam ? baseBeam : 0, 30, dt);
+ const volt = 0.72 + rn * 0.38 + Math.sin(t * 4.6 * 2 * Math.PI) * 0.03 * (1 - rn);
+ const hb = beamPower * volt * beam.k;
+ head.position.copy(headW);
+ head.target.position.copy(headW).add(tmp.set(8, rev.beam === 2 ? -0.15 : -0.6, 0).applyQuaternion(bikeRoot.quaternion));
+ head.angle = rev.beam === 2 ? 0.3 : 0.38;
+ head.intensity = 150 * hb;
+ headLens.material.color.setScalar(9 * hb);
+ // flare: only when we can see into the lens
+ const toCam = tmp.copy(camera.position).sub(headW).normalize();
+ const facing = Math.pow(clamp(toCam.dot(tmp2.set(1, 0, 0).applyQuaternion(bikeRoot.quaternion))), 3);
+ flare.position.copy(headW).add(tmp2.set(0.02, 0, 0).applyQuaternion(bikeRoot.quaternion));
+ flare.scale.setScalar(0.16 + hb * 0.22);
+ flare.material.color.setRGB(1, 0.93, 0.85).multiplyScalar(hb * facing * 4);
+ streak.position.copy(flare.position);
+ streak.scale.set(2.6 * hb, 0.022, 1);
+ streak.material.color.setRGB(0.55, 0.7, 1).multiplyScalar(hb * facing * 1.1);
+
+ // Exhaust: backfire flame, glow, heat haze.
+ flame.position.copy(tipW).addScaledVector(TIP_DIR, 0.06 + fx.flame * 0.08);
+ flame.scale.setScalar(0.08 + fx.flame * 0.34);
+ flame.material.rotation = fx.flameRot;
+ flame.material.color.setRGB(1, 0.75, 0.55).multiplyScalar(fx.flame * 6);
+ popLight.position.copy(tipW).addScaledVector(TIP_DIR, 0.2).add(tmp.set(0, 0, 0.12));
+ popLight.intensity = fx.flame * 26;
+ tipGlow.position.copy(tipW);
+ tipGlow.scale.setScalar(0.12);
+ tipGlow.material.color.setRGB(1, 0.25, 0.08).multiplyScalar(rev.heat * rev.heat * 0.5);
+ const hu = hazeU();
+ const onA = toUv(tipW, hu.get('uA0').value);
+ toUv(tmp.copy(tipW).addScaledVector(TIP_DIR, 0.35).add(tmp2.set(0, 0.45, 0)), hu.get('uB0').value);
+ const tipD = camera.position.distanceTo(tipW);
+ hu.get('uW0').value = 0.11 / tipD;
+ hu.get('uS0').value = onA ? (0.18 + rev.heat * 1.1 + rev.throttle * 0.4) : 0;
+ toUv(headsW, hu.get('uA1').value);
+ toUv(tmp.copy(headsW).add(tmp2.set(-0.05, 0.6, 0)), hu.get('uB1').value);
+ hu.get('uW1').value = 0.16 / camera.position.distanceTo(headsW);
+ hu.get('uS1').value = 0.12 + rev.heat * 0.7;
+
+ // Neon.
+ const nl = neon.level;
+ neonMats.main?.color.setRGB(3.2, 1.0, 1.3).multiplyScalar(nl);
+ neonMats.flick?.color.setRGB(3.2, 1.0, 1.3).multiplyScalar(neon.letter);
+ if (lights.neon) {
+ lights.neon.intensity = 7 * nl * cam.mag;
+ lights.neonSpot.intensity = 18 * nl * cam.mag;
+ lights.fill.intensity = 2.2 * cam.fill;
+ const tb = neon.lamp * tubeLevel(t);
+ lights.tube.rect.intensity = 16 * tb;
+ lights.tube.spot.intensity = 16 * tb;
+ lights.tube.mesh.color.setRGB(5, 7, 8).multiplyScalar(0.08 + tb * 0.92);
+ washLevel.value = 2.4 * nl;
+ }
+ if (lights.lamp) {
+ // the bulkhead has a tired starter: it hums along, then occasionally hiccups
+ const hic = (t % 23) > 22.6 ? (Math.sin(t * 70) > 0 ? 0.3 : 1) : 1;
+ lights.lamp.intensity = 70 * neon.lamp * hic;
+ lights.lampLens.color.setRGB(9, 10, 12).multiplyScalar(neon.lamp * hic);
+ }
+
+ // Rain: follows the camera, bends in the hot air, lit by what is actually shining.
+ if (rain) {
+ const u = rain.uniforms;
+ u.uTime.value = t;
+ camera.getWorldDirection(tmp);
+ u.uCenter.value.copy(camera.position).addScaledVector(tmp, 6);
+ u.uRev.value = damp(u.uRev.value, rn * rev.throttle + rev.heat * 0.2, 4, dt);
+ const wind = u.uWind.value;
+ wind.set(0.5 + Math.sin(t * 0.3) * 0.25, 0, 0.22);
+ u.uWindOff.value.addScaledVector(wind, dt);
+ u.uBike.value.copy(headsW);
+ const L = [
+ [head, head.color, head.intensity * 0.06, true],
+ [lights.lamp, lights.lamp.color, lights.lamp.intensity * 0.02, true],
+ [lights.neonSpot, lights.neonSpot.color, 0.5 * nl, false, SIGN_P],
+ [lights.tube.spot, lights.tube.spot.color, lights.tube.spot.intensity * 0.03, true],
+ [popLight, popLight.color, popLight.intensity * 0.05, false],
+ [lights.fill, lights.fill.color, 0.02, false],
+ ];
+ for (let i = 0; i < MAX_RAIN_LIGHTS; i++) {
+ const [l, c, s, spot, at] = L[i];
+ const p = u.uLPos.value[i];
+ if (at) p.copy(at); else l.getWorldPosition(p);
+ u.uLCol.value[i].set(c.r * s, c.g * s, c.b * s);
+ if (spot) {
+ const d = tmp.copy(l.target.position).sub(p).normalize();
+ u.uLDir.value[i].set(d.x, d.y, d.z, Math.cos(l.angle));
+ } else u.uLDir.value[i].set(0, -1, 0, -2);
+ }
+ splashes.uniforms.uCenter.value.copy(cam.poi);
+ steam.uniforms.uBikeMat.value.copy(bike.matrixWorld);
+ steam.uniforms.uHeat.value = damp(steam.uniforms.uHeat.value, 0.15 + rev.heat * rev.heat * 1.4, 2, dt);
+ }
+
+ // UI state
+ root.style.setProperty('--rev', rn.toFixed(3));
+ const rr = revEl.getBoundingClientRect();
+ const inRev = rr.top < innerHeight * 0.45 && rr.bottom > innerHeight * 0.75;
+ tachoEl.classList.toggle('big', inRev);
+ body.classList.toggle('in-rev', inRev);
+ tachoEl.classList.toggle('mini', !inRev && (rev.held || rev.rpm > 1500));
+ tacho.update(rev.shown, dt, rev.limiter > 0);
+ flashEl.style.opacity = (rev.limiter > 0 ? 0.9 : 0) + rn * rn * 0.25;
+ heroEl.style.opacity = 1 - smooth(0.05, 0.5, scrollY / innerHeight);
+ body.classList.toggle('past-hero', scrollY > innerHeight * 0.3);
+ if (cursorApi && ready) {
+ const label = rev.held ? rev.shown.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ',') : 'Hold';
+ const over = document.elementFromPoint(pointer.px, pointer.py);
+ const want = over && !interactive(over) && !TOUCH ? label : '';
+ if (want !== lastCursor) { lastCursor = want; cursorApi.set(want ? 'label' : '', want); }
+ }
+
+ audio.update(rev.rpm, rev.throttle, nl, neon.crackle);
+ if (floor) reflection.update(scene, camera);
+}
+
+// ─── Sound toggle, waitlist, reveals ──────────────────────────────────────────
+const soundBtn = document.querySelector('.sound');
+soundBtn.addEventListener('click', async () => {
+ const on = soundBtn.getAttribute('aria-pressed') !== 'true';
+ soundBtn.setAttribute('aria-pressed', String(on));
+ soundBtn.querySelector('.sound-label').textContent = on ? 'Sound on' : 'Sound off';
+ if (on) await audio.enable(); else audio.disable();
+});
+const form = document.querySelector('.wl-form');
+const slotSel = form.querySelector('select');
+document.querySelectorAll('.slots li.open').forEach(li => li.addEventListener('click', () => {
+ document.querySelectorAll('.slots li').forEach(x => x.classList.remove('sel'));
+ li.classList.add('sel');
+ slotSel.value = li.dataset.slot;
+}));
+slotSel.addEventListener('change', () => {
+ document.querySelectorAll('.slots li').forEach(x => x.classList.toggle('sel', x.dataset.slot === slotSel.value));
+});
+form.addEventListener('submit', e => {
+ e.preventDefault();
+ const name = form.elements.name, email = form.elements.email;
+ let ok = true;
+ for (const [el, good] of [[name, name.value.trim().length > 1], [email, /.+@.+\..+/.test(email.value)]]) { el.classList.toggle('bad', !good); ok &&= good; }
+ if (!ok) return;
+ const done = document.querySelector('.wl-done');
+ done.querySelector('b').textContent = `No. ${slotSel.value}`;
+ done.hidden = false;
+ form.hidden = true;
+ gsap.from(done, { opacity: 0, y: 12, duration: 0.8, ease: 'power3.out' });
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('racer', { theme: 'dark', corner: 'bl' });
+cursorApi = cursor({ color: '#ffd7df', blend: 'normal', size: 34 });
+magnetic();
+smoothScroll({ lerp: 0.08 });
+reveal('section h2, .foot-title', { type: 'lines', stagger: 0.08 });
+reveal('.lede, .part h3', { type: 'lines', stagger: 0.06, y: '100%' });
+if (Q.has('notext')) document.body.classList.add('dbg-notext');
+if (TOUCH) document.querySelector('.hold-hint span:last-child').innerHTML = '<b>Hold</b> the rev button <em>bottom right</em>';
+
+await Promise.all([buildWorld(), buildBike()]);
+// Macro stations are authored in the bike's own frame.
+bikeRoot.updateMatrixWorld(true);
+for (const st of Object.values(STATIONS)) if (st.local) {
+ st.poi = tmp.set(...st.poi).applyMatrix4(bikeRoot.matrixWorld).toArray();
+ st.az += BIKE_YAW / D;
+}
+measure();
+setTimeout(measure, 1500);
+stationAt(0);
+cam.poi.copy(cur.poi);
+Object.assign(cam, { az: cur.az + 14, el: cur.el + 3, dist: cur.dist * 1.25, fov: cur.fov, sx: cur.sx, sy: cur.sy, mag: cur.mag, sat: cur.sat, fill: cur.fill });
+engine.onTick(frame);
+// Warm every program with every light on before the reveal.
+neon.power = 1; neon.lamp = 1; rev.beam = 1;
+frame(1 / 60, 0);
+renderer.compile(scene, camera);
+neon.power = 0; neon.lamp = 0; rev.beam = 0;
+engine.start();
+await loader.finish();
+ready = true;
+
+// Ignition: the lamp stutters, the sign buzzes on, then the headlight.
+neon.lamp = 0;
+gsap.timeline({ delay: 0.15 })
+ .to(neon, { lamp: 0.7, duration: 0.04 }).to(neon, { lamp: 0.05, duration: 0.05, delay: 0.08 })
+ .to(neon, { lamp: 1, duration: 0.05, delay: 0.22 }).to(neon, { lamp: 0.2, duration: 0.03, delay: 0.05 }).to(neon, { lamp: 1, duration: 0.3 })
+ .to(neon, { power: 1, duration: 0.03 }, 0.7).to(neon, { power: 0.1, duration: 0.04, delay: 0.05 })
+ .to(neon, { power: 1, duration: 0.03, delay: 0.12 }).to(neon, { power: 0.3, duration: 0.03, delay: 0.06 }).to(neon, { power: 1, duration: 0.4 })
+ .call(() => { rev.beam = 1; snapBeam(); }, null, 1.75)
+ .call(() => { window.__racerIntro = true; }, null, 2.6);
+gsap.from('.h-line > span', { yPercent: 110, duration: 1.6, ease: 'expo.out', stagger: 0.1, delay: 0.9 });
+gsap.set('.hero .script', { opacity: 0 });
+gsap.timeline({ delay: 1.9 }).to('.hero .script', { opacity: 1, duration: 0.04 }).to('.hero .script', { opacity: 0.1, duration: 0.04, delay: 0.06 })
+ .to('.hero .script', { opacity: 1, duration: 0.04, delay: 0.14 }).to('.hero .script', { opacity: 0.3, duration: 0.03, delay: 0.05 }).to('.hero .script', { opacity: 1, duration: 0.3 });
+gsap.from('.eyebrow, .hero-row, .nav', { opacity: 0, y: 14, duration: 1.2, ease: 'power3.out', stagger: 0.08, delay: 1.3 });
+
+window.__racer = { rev, setHeld, cam, STATIONS, bike, bikeRoot, neon, audio, popFlash, reflection, rain, splashes, vol, dof, haze, bloom, engine, lights, head, scene, renderer, floor };
diff --git a/examples/racer/style.css b/examples/racer/style.css
new file mode 100644
index 0000000..fe864f9
--- /dev/null
+++ b/examples/racer/style.css
@@ -0,0 +1,288 @@
+:root {
+ --bg: #050507;
+ --ink: #f2eee9;
+ --ink2: #c9c4cc;
+ --muted: #86828d;
+ --line: rgba(242, 238, 233, .12);
+ --neon: #ff3b5c;
+ --neon-soft: #ff8aa0;
+ --brass: #c9a35c;
+ --brass-hi: #ecd29a;
+ --display: 'Anton', 'Impact', sans-serif;
+ --sans: 'Inter', system-ui, sans-serif;
+ --script: 'Neonderthaw', cursive;
+ --gut: clamp(18px, 4vw, 56px);
+ --rev: 0;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; }
+body { font: 400 16px/1.6 var(--sans); background: var(--bg); overflow-x: hidden; }
+main { overflow-x: clip; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+::selection { background: var(--neon); color: #0b0306; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+.redline-flash { position: fixed; inset: 0; z-index: 1; pointer-events: none; opacity: 0;
+ background: radial-gradient(120% 90% at 50% 50%, transparent 45%, rgba(255, 30, 70, .32) 100%); mix-blend-mode: screen; }
+
+/* ── loader ─────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: #030304; display: grid; place-content: center; justify-items: center; gap: 26px; --p: 0; }
+.loader-sign { font: 400 clamp(84px, 13vw, 190px)/1 var(--script); color: #2a1219; position: relative; padding: 0 .2em; }
+.loader-sign span { display: block; color: rgba(255, 90, 120, calc(.08 + var(--p) * .92));
+ text-shadow: 0 0 calc(var(--p) * 4px) #fff, 0 0 calc(var(--p) * 18px) var(--neon), 0 0 calc(var(--p) * 54px) var(--neon), 0 0 calc(var(--p) * 110px) rgba(255, 59, 92, .6);
+ -webkit-text-stroke: 1px rgba(255, 59, 92, .25); }
+.loader.buzz .loader-sign span { animation: buzz .9s steps(1) 1; }
+@keyframes buzz { 0% { opacity: 1 } 8% { opacity: .2 } 12% { opacity: 1 } 30% { opacity: .35 } 34% { opacity: 1 } 60% { opacity: .7 } 64% { opacity: 1 } }
+.loader-bar { margin-top: 30px; width: min(300px, 60vw); height: 1px; background: rgba(255, 255, 255, .1); position: relative; overflow: hidden; }
+.loader-bar i { position: absolute; inset: 0; background: linear-gradient(90deg, var(--brass), var(--neon)); transform-origin: 0 50%; transform: scaleX(var(--p)); }
+.loader-line { display: flex; gap: 14px; font: 500 11px/1 var(--sans); letter-spacing: .28em; text-transform: uppercase; color: var(--muted); }
+.loader-line b { color: var(--ink); font-weight: 500; font-variant-numeric: tabular-nums; min-width: 3ch; text-align: right; }
+.loader-line b::after { content: '%'; color: var(--muted); }
+
+/* ── nav ────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between; gap: 24px;
+ padding: 22px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav::before { content: ''; position: absolute; inset: 0 0 -40px; z-index: -1; pointer-events: none; background: linear-gradient(180deg, rgba(5,5,7,.82), rgba(5,5,7,.45) 55%, rgba(5,5,7,0)); opacity: 0; transition: opacity .6s; }
+.past-hero .nav::before { opacity: 1; }
+.brand { display: flex; align-items: baseline; gap: 10px; text-decoration: none; }
+.brand b { font: 400 22px/1 var(--display); letter-spacing: .04em; text-transform: uppercase; }
+.brand span { font: 400 26px/1 var(--script); color: var(--neon); text-shadow: 0 0 10px rgba(255, 59, 92, .7); transform: translateY(2px); }
+.links { display: flex; gap: clamp(18px, 2.6vw, 38px); }
+.links a { text-decoration: none; font: 500 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--ink2); position: relative; padding: 6px 0; transition: color .3s; }
+.links a::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: var(--neon); transform: scaleX(0); transform-origin: 0 50%; transition: transform .45s cubic-bezier(.2, .8, .2, 1); box-shadow: 0 0 8px var(--neon); }
+.links a:hover { color: var(--ink); }
+.links a:hover::after { transform: scaleX(1); }
+.nav-right { display: flex; align-items: center; gap: 12px; }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 46px; padding: 0 24px; border-radius: 2px;
+ text-decoration: none; font: 600 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; white-space: nowrap;
+ transition: background .35s, color .35s, box-shadow .35s; }
+.btn-neon { color: #fff; background: rgba(255, 59, 92, .08); box-shadow: inset 0 0 0 1px var(--neon), 0 0 18px rgba(255, 59, 92, .25), inset 0 0 14px rgba(255, 59, 92, .2);
+ text-shadow: 0 0 8px rgba(255, 59, 92, .8); backdrop-filter: blur(6px); }
+.btn-neon:hover { background: var(--neon); color: #12030a; text-shadow: none; box-shadow: 0 0 40px rgba(255, 59, 92, .6); }
+.sound { height: 46px; padding: 0 16px; display: inline-flex; align-items: center; gap: 10px; border-radius: 2px;
+ box-shadow: inset 0 0 0 1px var(--line); background: rgba(8, 8, 10, .35); backdrop-filter: blur(6px);
+ font: 500 11px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink2); transition: box-shadow .3s, color .3s; }
+.sound:hover { box-shadow: inset 0 0 0 1px rgba(242, 238, 233, .4); color: var(--ink); }
+.sound-bars { display: flex; align-items: flex-end; gap: 2px; height: 12px; }
+.sound-bars i { width: 2px; height: 4px; background: currentColor; transition: height .3s; }
+.sound-bars i:nth-child(2) { height: 9px; } .sound-bars i:nth-child(3) { height: 6px; } .sound-bars i:nth-child(4) { height: 11px; }
+.sound[aria-pressed="false"] .sound-bars { opacity: .55; }
+.sound[aria-pressed="true"] { color: var(--ink); box-shadow: inset 0 0 0 1px rgba(201, 163, 92, .6); }
+.sound[aria-pressed="true"] .sound-bars i { background: var(--brass-hi); animation: eq 1s ease-in-out infinite; }
+.sound[aria-pressed="true"] .sound-bars i:nth-child(2) { animation-delay: -.3s; }
+.sound[aria-pressed="true"] .sound-bars i:nth-child(3) { animation-delay: -.6s; }
+.sound[aria-pressed="true"] .sound-bars i:nth-child(4) { animation-delay: -.15s; }
+@keyframes eq { 0%, 100% { height: 3px } 50% { height: 12px } }
+
+/* ── shared type ────────────────────────────────────────── */
+section, footer { position: relative; z-index: 4; }
+h2 { font: 400 clamp(52px, 7.2vw, 128px)/.9 var(--display); text-transform: uppercase; letter-spacing: -.005em; }
+h2 em { font-style: normal; color: transparent; -webkit-text-stroke: 1.2px var(--ink); }
+.kicker { display: flex; align-items: center; gap: 14px; margin-bottom: 26px; font: 500 11px/1 var(--sans); letter-spacing: .3em; text-transform: uppercase; color: var(--muted); }
+.kicker b { font: 400 14px/1 var(--display); letter-spacing: .06em; color: var(--neon); text-shadow: 0 0 10px rgba(255, 59, 92, .6); }
+.kicker::after { content: ''; width: 48px; height: 1px; background: var(--line); }
+.lede { max-width: 31em; margin-top: 28px; font: 300 clamp(17px, 1.35vw, 20px)/1.55 var(--sans); color: var(--ink2); }
+.script { font: 400 clamp(54px, 6.4vw, 108px)/1 var(--script); color: #ffe3e9;
+ text-shadow: 0 0 2px #fff, 0 0 10px var(--neon), 0 0 28px var(--neon), 0 0 70px rgba(255, 59, 92, .55); }
+
+/* ── hero ───────────────────────────────────────────────── */
+.hero { height: 100vh; min-height: 620px; display: grid; grid-template-rows: auto 1fr; padding: 104px var(--gut) 74px; pointer-events: none; }
+.eyebrow { justify-self: start; align-self: start; display: inline-flex; align-items: center; gap: 12px; font: 500 11px/1 var(--sans); letter-spacing: .26em; text-transform: uppercase; color: var(--ink2); }
+.eyebrow .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--neon); box-shadow: 0 0 10px var(--neon), 0 0 20px var(--neon); animation: blink 2.4s steps(1) infinite; }
+@keyframes blink { 0%, 86% { opacity: 1 } 88% { opacity: .2 } 90% { opacity: 1 } 93% { opacity: .3 } 95% { opacity: 1 } }
+.hero-bottom { align-self: end; position: relative; }
+.hero-row { display: flex; align-items: end; gap: clamp(28px, 4vw, 64px); margin-bottom: 26px; max-width: 60vw; }
+.hero h1 { font: 400 clamp(56px, 7.9vw, 156px)/.84 var(--display); text-transform: uppercase; letter-spacing: -.004em; white-space: nowrap; }
+.h-line { display: block; overflow: hidden; padding-bottom: .02em; }
+.h-line > span { display: inline-block; }
+.hero .script { position: absolute; right: 0; bottom: 7.4vw; transform: rotate(-5deg); transform-origin: 100% 50%; font-size: clamp(38px, 4.1vw, 84px); white-space: nowrap; }
+.sub { max-width: 27em; font: 300 clamp(15px, 1.12vw, 18px)/1.6 var(--sans); color: var(--ink2); }
+.hold-hint { display: flex; align-items: center; gap: 16px; font: 500 12px/1.3 var(--sans); letter-spacing: .14em; text-transform: uppercase; color: var(--ink2); }
+.hold-hint b { color: var(--ink); font-weight: 600; }
+.hold-hint em { display: block; font-style: normal; color: var(--muted); letter-spacing: .12em; margin-top: 4px; font-size: 10.5px; }
+.hold-ring { position: relative; width: 44px; height: 44px; flex: none; }
+.hold-ring svg { width: 100%; height: 100%; transform: rotate(-90deg); }
+.hold-ring circle { fill: none; stroke: rgba(242, 238, 233, .2); stroke-width: 1.2; }
+.hold-ring circle.p { stroke: var(--neon); stroke-width: 2; stroke-dasharray: 125.7; stroke-dashoffset: calc(125.7 * (1 - var(--rev))); filter: drop-shadow(0 0 4px var(--neon)); }
+.hold-ring i { position: absolute; left: 50%; top: 50%; width: 8px; height: 8px; margin: -4px; border-radius: 50%; background: var(--ink); animation: press 2.2s ease-in-out infinite; }
+@keyframes press { 0%, 100% { transform: scale(1); opacity: .9 } 45% { transform: scale(.55); opacity: 1 } 60% { transform: scale(1.8); opacity: 0 } 61% { transform: scale(.3); opacity: 0 } }
+.hero-specs { list-style: none; display: flex; gap: clamp(20px, 2.6vw, 44px); }
+.hero-specs li { display: grid; gap: 6px; }
+.hero-specs b { font: 400 clamp(26px, 2.2vw, 38px)/1 var(--display); letter-spacing: .02em; }
+.hero-specs span { font: 500 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.scroll-cue { position: absolute; right: var(--gut); bottom: 30px; display: none; transform: translateX(-50%); display: grid; justify-items: center; gap: 10px;
+ font: 500 10px/1 var(--sans); letter-spacing: .3em; text-transform: uppercase; color: var(--muted); }
+.scroll-cue i { width: 1px; height: 38px; background: linear-gradient(var(--ink), transparent); animation: drip 2.2s cubic-bezier(.6, 0, .3, 1) infinite; transform-origin: 50% 0; }
+@keyframes drip { 0% { transform: scaleY(0); opacity: 1 } 60% { transform: scaleY(1); opacity: 1 } 100% { transform: scaleY(1); opacity: 0 } }
+
+/* ── rev ────────────────────────────────────────────────── */
+.rev { min-height: 150vh; padding: 30vh var(--gut) 20vh; pointer-events: none; }
+.rev-copy { position: sticky; top: 16vh; max-width: 520px; }
+.rev-copy h2 { font-size: clamp(60px, 8vw, 140px); }
+.rev-notes { list-style: none; margin-top: 34px; display: grid; gap: 12px; max-width: 28em; }
+.rev-notes li { display: grid; grid-template-columns: 76px 1fr; gap: 12px; font-size: 14px; color: var(--ink2); padding-top: 12px; border-top: 1px solid var(--line); }
+.rev-notes span { font: 600 11px/1.9 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--brass-hi); }
+.rev-btn { pointer-events: auto; margin-top: 34px; position: relative; width: 132px; height: 132px; border-radius: 50%; display: none; place-items: center;
+ box-shadow: inset 0 0 0 1px rgba(255, 59, 92, .6), 0 0 30px rgba(255, 59, 92, .2); background: radial-gradient(circle, rgba(255, 59, 92, .18), rgba(8, 8, 10, .5) 70%);
+ backdrop-filter: blur(6px); touch-action: none; user-select: none; -webkit-user-select: none; -webkit-touch-callout: none; }
+.rev-btn-label { font: 600 11px/1.2 var(--sans); letter-spacing: .2em; text-transform: uppercase; }
+.rev-btn-ring { position: absolute; inset: -8px; border-radius: 50%; border: 1px solid rgba(255, 59, 92, .35); transform: scale(calc(1 + var(--rev) * .18)); opacity: calc(.4 + var(--rev) * .6); }
+.rev-fab { display: none; position: fixed; z-index: 7; right: 16px; bottom: 18px; width: 84px; height: 84px; margin: 0; transition: opacity .5s; }
+.rev-fab .rev-btn-label { font-size: 9.5px; text-align: center; }
+.rev-btn.on { background: radial-gradient(circle, rgba(255, 59, 92, .55), rgba(40, 6, 14, .6) 70%); }
+
+/* ── tachometer ─────────────────────────────────────────── */
+.tacho { position: fixed; z-index: 6; right: var(--gut); bottom: 7vh; width: min(34vh, 330px); aspect-ratio: 1; pointer-events: none;
+ opacity: 0; transform: translateY(30px) scale(.9); transition: opacity .6s, transform .8s cubic-bezier(.2, .8, .2, 1), width .8s cubic-bezier(.2, .8, .2, 1);
+ filter: drop-shadow(0 30px 60px rgba(0, 0, 0, .8)); }
+.tacho.big { opacity: 1; transform: none; }
+.tacho.mini { opacity: 1; transform: none; width: 150px; bottom: auto; top: 96px; }
+.tacho-svg { width: 100%; height: 100%; overflow: visible; }
+.tacho-ticks line { stroke: #d9d3cc; }
+.tacho-ticks line.minor { stroke: rgba(217, 211, 204, .45); }
+.tacho-ticks line.red { stroke: var(--neon); }
+.tacho-ticks text { font: 400 19px/1 var(--display); fill: #e8e2da; text-anchor: middle; dominant-baseline: central; }
+.tacho-ticks text.red { fill: var(--neon); }
+.tacho-unit { font: 500 7.5px/1 var(--sans); letter-spacing: .24em; fill: #8b8690; text-transform: uppercase; }
+.tacho-brand { font: 400 22px/1 var(--script); fill: #ffb3c1; }
+.tacho-rpm { font: 400 30px/1 var(--display); fill: #f2eee9; letter-spacing: .04em; font-variant-numeric: tabular-nums; }
+.tacho-gear { font: 600 8px/1 var(--sans); letter-spacing: .3em; fill: var(--brass); }
+.tacho-shift { fill: #2a0d13; transition: fill .05s; }
+.tacho.limit .tacho-shift { fill: #ff4a68; filter: drop-shadow(0 0 6px #ff3b5c); }
+.tacho-arc { opacity: .9; }
+
+/* ── build ──────────────────────────────────────────────── */
+.build { padding: 10vh var(--gut) 0; pointer-events: none; }
+.build-head { max-width: 780px; min-height: 100vh; display: flex; flex-direction: column; justify-content: flex-end; padding-bottom: 14vh; }
+.build-head h2 { font-size: clamp(52px, 6.6vw, 120px); }
+.build-head h2 em { display: block; }
+.part { position: relative; min-height: 115vh; display: flex; flex-direction: column; justify-content: center; max-width: 440px; padding: 12vh 0; }
+.part-r { margin-left: auto; }
+.part > * { position: relative; }
+.part::before { content: ''; position: absolute; inset: 8vh -12vw 8vh -8vw; background: radial-gradient(closest-side, rgba(4,4,6,.62), rgba(4,4,6,0)); pointer-events: none; }
+.part-l::before { inset: 8vh -8vw 8vh -14vw; }
+.part-num { font: 500 11px/1 var(--sans); letter-spacing: .3em; text-transform: uppercase; color: var(--brass-hi); margin-bottom: 22px; display: flex; gap: 12px; align-items: center; }
+.part-num::before { content: ''; width: 28px; height: 1px; background: var(--brass); }
+.part h3 { font: 400 clamp(38px, 3.8vw, 64px)/.95 var(--display); text-transform: uppercase; }
+.part > p:not(.part-num) { margin-top: 22px; color: var(--ink2); font-size: 15.5px; line-height: 1.65; max-width: 30em; }
+.specs { display: grid; grid-template-columns: repeat(3, 1fr); margin-top: 34px; border-top: 1px solid var(--line); }
+.specs div { padding: 16px 12px 0 0; }
+.specs div + div { padding-left: 16px; border-left: 1px solid var(--line); }
+.specs dt { font: 500 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.specs dd { margin-top: 12px; font: 400 clamp(34px, 3vw, 50px)/1 var(--display); letter-spacing: .01em; }
+.specs dd small { font: 500 12px/1 var(--sans); letter-spacing: .1em; color: var(--brass-hi); margin-left: 4px; vertical-align: 4px; text-transform: uppercase; }
+.part, .rev-copy, .garage-copy, .wl-panel { text-shadow: 0 1px 24px rgba(0, 0, 0, .7); }
+
+/* ── waitlist ───────────────────────────────────────────── */
+.waitlist { min-height: 130vh; padding: 18vh var(--gut); display: flex; align-items: center; justify-content: flex-end; }
+.wl-panel { width: min(600px, 100%); padding: clamp(28px, 3.4vw, 52px); background: linear-gradient(160deg, rgba(14, 12, 16, .78), rgba(6, 6, 8, .62));
+ backdrop-filter: blur(18px) saturate(1.2); -webkit-backdrop-filter: blur(18px) saturate(1.2); box-shadow: inset 0 0 0 1px var(--line), 0 40px 90px -30px rgba(0, 0, 0, .9); border-radius: 3px; }
+.wl-panel h2 { font-size: clamp(44px, 4.8vw, 82px); }
+.wl-panel h2 em { display: block; }
+.wl-panel .lede { font-size: 16px; }
+.slots { list-style: none; display: grid; grid-template-columns: repeat(6, 1fr); gap: 6px; margin: 32px 0 30px; }
+.slots li { position: relative; aspect-ratio: 1 / 1.08; display: grid; align-content: space-between; padding: 9px 9px 8px; border-radius: 2px; box-shadow: inset 0 0 0 1px var(--line); transition: box-shadow .3s, background .3s; }
+.slots b { font: 400 22px/1 var(--display); }
+.slots span { font: 500 9.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--muted); }
+.slots li.taken { background: repeating-linear-gradient(-45deg, rgba(255, 255, 255, .025) 0 4px, transparent 4px 8px); }
+.slots li.taken b { color: rgba(242, 238, 233, .28); }
+.slots li.taken::after { content: 'Taken'; position: absolute; right: 8px; top: 10px; font: 500 8px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: rgba(242, 238, 233, .28); }
+.slots li.open { cursor: pointer; box-shadow: inset 0 0 0 1px rgba(255, 59, 92, .55); }
+.slots li.open b { color: var(--ink); }
+.slots li.open span { color: var(--neon-soft); }
+.slots li.open:hover, .slots li.sel { background: rgba(255, 59, 92, .14); box-shadow: inset 0 0 0 1px var(--neon), 0 0 20px rgba(255, 59, 92, .3); }
+.slots li.sel::after { content: ''; position: absolute; right: 9px; top: 10px; width: 6px; height: 6px; border-radius: 50%; background: var(--neon); box-shadow: 0 0 8px var(--neon); }
+.wl-form { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+.wl-form .wide { grid-column: 1 / -1; }
+.wl-form[hidden] { display: none; }
+.wl-form label { display: grid; gap: 8px; }
+.wl-form label span { font: 500 10px/1 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--muted); }
+.wl-form input, .wl-form select { height: 46px; width: 100%; padding: 0 14px; border: 0; border-radius: 2px; background: rgba(255, 255, 255, .04); color: var(--ink);
+ box-shadow: inset 0 0 0 1px var(--line); font: 400 15px/1 var(--sans); outline: none; transition: box-shadow .3s; appearance: none; }
+.wl-form select { background-image: linear-gradient(45deg, transparent 50%, var(--ink2) 50%), linear-gradient(-45deg, transparent 50%, var(--ink2) 50%); background-size: 5px 5px; background-position: calc(100% - 20px) 50%, calc(100% - 15px) 50%; background-repeat: no-repeat; }
+.wl-form select option { background: #111; }
+.wl-form input:focus, .wl-form select:focus { box-shadow: inset 0 0 0 1px var(--brass); }
+.wl-form input.bad { box-shadow: inset 0 0 0 1px var(--neon); }
+.wl-form .btn { height: 54px; margin-top: 6px; }
+.wl-fine { font-size: 12.5px; color: var(--muted); }
+.wl-done { margin-top: 26px; padding: 18px 20px; font-size: 15px; color: var(--ink); box-shadow: inset 0 0 0 1px rgba(201, 163, 92, .5); background: rgba(201, 163, 92, .07); }
+.wl-done b { color: var(--brass-hi); font-weight: 500; }
+
+/* ── garage ─────────────────────────────────────────────── */
+.garage { min-height: 170vh; padding: 20vh var(--gut) 24vh; display: grid; align-content: space-between; gap: 30vh; pointer-events: none; }
+.garage-copy { max-width: 540px; }
+.garage-copy > p:not(.kicker):not(.lede) { margin-top: 18px; max-width: 31em; color: var(--ink2); font-size: 15.5px; }
+.garage-stats { display: grid; grid-template-columns: repeat(4, auto); justify-content: start; gap: 0; margin-top: 40px; border-top: 1px solid var(--line); }
+.garage-stats div { padding: 16px 26px 0 0; }
+.garage-stats div + div { padding-left: 22px; border-left: 1px solid var(--line); }
+.garage-stats dt { font: 500 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--muted); }
+.garage-stats dd { margin-top: 12px; font: 400 clamp(32px, 3vw, 48px)/1 var(--display); }
+.garage-quote { justify-self: end; max-width: 620px; text-align: right; }
+.garage-quote p { font: 400 clamp(42px, 4.4vw, 76px)/1.02 var(--script); color: #ffe7ec; text-shadow: 0 0 2px #fff, 0 0 12px var(--neon), 0 0 40px rgba(255, 59, 92, .6); }
+.garage-quote cite { display: block; margin-top: 18px; font: 500 11px/1 var(--sans); letter-spacing: .24em; text-transform: uppercase; font-style: normal; color: var(--muted); }
+
+/* ── footer ─────────────────────────────────────────────── */
+.foot { min-height: 100vh; padding: 22vh var(--gut) 34px; display: grid; align-content: end;
+ background: linear-gradient(180deg, transparent 0%, rgba(5, 5, 7, .25) 45%, rgba(5, 5, 7, .88) 100%); }
+.foot-script { font-size: clamp(40px, 4.6vw, 80px); transform: rotate(-4deg); transform-origin: 0 50%; margin-left: .3em; margin-bottom: -.18em; position: relative; z-index: 1; }
+.foot-title { font-size: clamp(80px, 11.5vw, 210px); line-height: .82; }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr) auto; gap: 32px; align-items: end; margin-top: 64px; padding-top: 28px; border-top: 1px solid var(--line); font-size: 14px; color: var(--ink2); line-height: 1.8; }
+.foot-cols b { font: 500 10.5px/2.4 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--muted); }
+.foot-cols a { text-decoration: none; border-bottom: 1px solid var(--line); transition: border-color .3s, color .3s; }
+.foot-cols a:hover { color: #fff; border-color: var(--neon); }
+.foot-cols a.btn { border: 0; }
+.foot-legal { display: flex; justify-content: space-between; gap: 20px; margin-top: 48px; padding-left: 150px; font-size: 11.5px; color: var(--muted); }
+
+/* ── states ─────────────────────────────────────────────── */
+.is-revving .scroll-cue { opacity: 0; }
+.scroll-cue, .hold-hint { transition: opacity .6s; }
+.past-hero .scroll-cue { opacity: 0; }
+
+@media (pointer: coarse) {
+ .rev-fab { display: grid; }
+ html .hero { padding-bottom: 116px; }
+ .tacho.mini { width: 120px; right: 12px; top: 80px; }
+ .past-hero .rev-fab { opacity: 0; pointer-events: none; }
+}
+@media (max-width: 900px) {
+ .links { display: none; }
+ .sound-label { display: none; }
+ .nav { padding: 16px var(--gut); }
+ .nav .btn { height: 40px; padding: 0 14px; font-size: 10.5px; letter-spacing: .12em; }
+ .sound { height: 40px; padding: 0 12px; }
+ .brand b { font-size: 18px; }
+ .brand span { display: none; }
+ .hero { padding: 84px var(--gut) 70px; }
+ .eyebrow { justify-self: start; font-size: 10px; letter-spacing: .2em; }
+ .hero h1 { font-size: clamp(58px, 16.5vw, 110px); white-space: normal; }
+ .hero .script { position: relative; right: auto; bottom: auto; margin: -.1em 0 0 .3em; transform: rotate(-5deg); transform-origin: 0 50%; font-size: clamp(38px, 10.5vw, 64px); }
+ .hero-row { grid-template-columns: 1fr; gap: 18px; margin-bottom: 20px; }
+ .hero-row { max-width: none; flex-direction: column; align-items: start; }
+ .scroll-cue { display: none; }
+ .hold-hint em { display: none; }
+ .rev { min-height: 170vh; padding-top: 50vh; }
+ .rev-copy { top: 10vh; }
+ .rev-btn { display: grid; }
+ .rev-notes { display: none; }
+ .tacho { width: 160px; right: 14px; bottom: 14px; }
+ .tacho.mini { width: 140px; }
+ .part { max-width: 100%; min-height: 130vh; justify-content: flex-end; padding-bottom: 8vh; }
+ .part::before, .part-l::before { inset: 40vh -6vw 2vh -6vw; background: linear-gradient(180deg, rgba(4,4,6,0), rgba(4,4,6,.72) 45%); }
+ .part h3 { font-size: 40px; }
+ .specs dd { font-size: 32px; }
+ .waitlist { padding: 12vh 12px; }
+ .wl-panel { padding: 24px 18px; }
+ .slots { grid-template-columns: repeat(4, 1fr); }
+ .wl-form { grid-template-columns: 1fr; }
+ .garage-stats { grid-template-columns: repeat(2, auto); row-gap: 20px; }
+ .garage-stats div:nth-child(3) { padding-left: 0; border-left: 0; }
+ .garage-quote { text-align: left; justify-self: start; }
+ .foot-cols { grid-template-columns: 1fr 1fr; gap: 18px; margin-top: 40px; }
+ .foot-cols .btn { grid-column: 1 / -1; }
+ .foot-title { font-size: clamp(60px, 16vw, 100px) !important; }
+ .foot { padding-top: 16vh; }
+ .foot-legal { flex-direction: column; padding-left: 0; padding-bottom: 60px; }
+}
+
+.dbg-notext main > *, .dbg-notext .nav, .dbg-notext .tacho { visibility: hidden; }
diff --git a/examples/racer/tacho.js b/examples/racer/tacho.js
new file mode 100644
index 0000000..9cb5b81
--- /dev/null
+++ b/examples/racer/tacho.js
@@ -0,0 +1,53 @@
+// Brass-bezel tachometer drawn in SVG; the needle has a little mass and overshoot.
+const A0 = -130, SWEEP = 260, MAX = 10000;
+const polar = (r, deg) => { const a = deg * Math.PI / 180; return [r * Math.sin(a), -r * Math.cos(a)]; };
+const arc = (r, d0, d1) => {
+ const [x0, y0] = polar(r, d0), [x1, y1] = polar(r, d1);
+ return `M ${x0.toFixed(2)} ${y0.toFixed(2)} A ${r} ${r} 0 ${d1 - d0 > 180 ? 1 : 0} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}`;
+};
+const angleOf = rpm => A0 + Math.min(Math.max(rpm, 0), MAX * 1.02) / MAX * SWEEP;
+
+export class Tacho {
+ constructor(el) {
+ this.el = el;
+ this.needle = el.querySelector('.tacho-needle');
+ this.rpmText = el.querySelector('.tacho-rpm');
+ this.lit = el.querySelector('.tacho-arc');
+ const ticks = el.querySelector('.tacho-ticks');
+ const ns = 'http://www.w3.org/2000/svg';
+ let html = '';
+ for (let v = 0; v <= 10.001; v += 0.25) {
+ const major = Math.abs(v - Math.round(v)) < 1e-3;
+ const half = !major && Math.abs(v * 2 - Math.round(v * 2)) < 1e-3;
+ const a = A0 + v / 10 * SWEEP;
+ const r0 = 131, r1 = major ? 111 : half ? 119 : 123;
+ const [x0, y0] = polar(r0, a), [x1, y1] = polar(r1, a);
+ const cls = v >= 8.5 ? 'red' : major ? '' : 'minor';
+ html += `<line x1="${x0.toFixed(2)}" y1="${y0.toFixed(2)}" x2="${x1.toFixed(2)}" y2="${y1.toFixed(2)}" class="${cls}" stroke-width="${major ? 2.6 : 1.2}"/>`;
+ if (major) {
+ const [tx, ty] = polar(93, a);
+ html += `<text x="${tx.toFixed(2)}" y="${ty.toFixed(2)}" class="${v >= 9 ? 'red' : ''}">${Math.round(v)}</text>`;
+ }
+ }
+ ticks.innerHTML = html;
+ void ns;
+ el.querySelector('.tacho-red').setAttribute('d', arc(137, angleOf(8500), angleOf(10000)));
+ this.a = angleOf(0); this.v = 0;
+ this.shown = -1;
+ }
+
+ /** Spring the needle toward the rpm; dt in seconds. */
+ update(rpm, dt, limit) {
+ const target = angleOf(rpm);
+ // under-damped spring: fast, with a hint of overshoot on blips
+ const k = 520, c = 30;
+ this.v += ((target - this.a) * k - this.v * c) * dt;
+ this.a += this.v * dt;
+ this.needle.setAttribute('transform', `rotate(${this.a.toFixed(2)})`);
+ const lit = Math.max(this.a, A0 + 0.5);
+ this.lit.setAttribute('d', arc(141, A0, lit));
+ const shownRpm = Math.round(rpm / 50) * 50;
+ if (shownRpm !== this.shown) { this.shown = shownRpm; this.rpmText.textContent = shownRpm.toLocaleString('en-US'); }
+ this.el.classList.toggle('limit', !!limit);
+ }
+}
diff --git a/examples/reliquary/index.html b/examples/reliquary/index.html
new file mode 100644
index 0000000..6b273dd
--- /dev/null
+++ b/examples/reliquary/index.html
@@ -0,0 +1,134 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Reliquary — The Museum of the Unlit</title>
+ <meta name="description" content="An after-hours museum. Six objects, two thousand years, one small light.">
+ <meta name="theme-color" content="#070605">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Cormorant+Garamond:ital,wght@0,300;0,400;0,500;1,300;1,400&family=Instrument+Sans:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <div class="flash" aria-hidden="true"></div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-wick"><i></i></div>
+ <p class="loader-line">Lighting the lantern <span class="loader-pct">0</span>%</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Reliquary home">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2c2.6 3.4 4 6.2 4 8.6a4 4 0 0 1-8 0C8 8.2 9.4 5.4 12 2Z" fill="none" stroke="currentColor" stroke-width="1.2"/><path d="M6 21h12M8 21l1-6h6l1 6" fill="none" stroke="currentColor" stroke-width="1.2"/></svg>
+ <span>Reliquary</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#collection">Collection</a>
+ <a href="#hours">Night hours</a>
+ <a href="#membership">Membership</a>
+ </nav>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Book a night visit</a>
+ </header>
+
+ <main id="top">
+ <section class="walk" id="collection">
+ <div class="hero">
+ <p class="eyebrow mono">Open 21:00 — 04:00 &nbsp;·&nbsp; Lanterns issued at the door</p>
+ <h1 class="title" aria-label="Reliquary"><span>Reli</span><span>quary</span></h1>
+ <p class="sub">An after-hours museum. Six objects, two thousand years,<br> and the small light in your hand.</p>
+ </div>
+ <div class="hint mono" aria-hidden="true">
+ <span><kbd>Move</kbd> to aim the lantern</span>
+ <span><kbd>Click</kbd> to photograph a relic</span>
+ <span><kbd>Scroll</kbd> to walk the hall</span>
+ </div>
+ </section>
+
+ <section class="panel hours" id="hours">
+ <div class="panel-inner">
+ <p class="eyebrow mono">The night hours</p>
+ <h2>We turned the lights off <em>on purpose.</em></h2>
+ <p class="lede">Under museum floodlight, every object looks the same: flat, catalogued, finished. By a single moving light they look the way their makers saw them — by lamp, by fire, by moon. Relief comes back. Gold wakes up. You notice the chisel.</p>
+ <div class="grid3">
+ <article>
+ <span class="num mono">01</span>
+ <h3>One lantern each</h3>
+ <p>A warm 2,700 K beam, weighted for the hand. There are no other lights in the building until you earn them.</p>
+ </article>
+ <article>
+ <span class="num mono">02</span>
+ <h3>Photograph to illuminate</h3>
+ <p>Each relic you document switches on its own exhibit lamp. By dawn, the hall is lit by the people who walked it.</p>
+ </article>
+ <article>
+ <span class="num mono">03</span>
+ <h3>Silence after midnight</h3>
+ <p>Conversation stops at twelve. What remains is footsteps, the tick of the building cooling, and the objects.</p>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <section class="panel quotes">
+ <div class="panel-inner">
+ <blockquote>
+ <p>“I have walked past that helmet a hundred times in daylight. At two in the morning it looked back.”</p>
+ <cite class="mono">— Member since 2019</cite>
+ </blockquote>
+ <div class="stats">
+ <div><b>6</b><span class="mono">relics on the night floor</span></div>
+ <div><b>2,300</b><span class="mono">years between the oldest and youngest</span></div>
+ <div><b>40</b><span class="mono">visitors admitted per night</span></div>
+ </div>
+ </div>
+ </section>
+
+ <section class="panel membership" id="membership">
+ <div class="panel-inner">
+ <p class="eyebrow mono">Membership</p>
+ <h2>Keep a key to <em>the dark.</em></h2>
+ <div class="tiers">
+ <article class="tier">
+ <header><h3>Night Visitor</h3><p class="price">€18 <span class="mono">/ night</span></p></header>
+ <ul><li>One lantern, one evening</li><li>Entry until 01:00</li><li>Your photographs, printed at the door</li></ul>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Reserve a night</a>
+ </article>
+ <article class="tier tier-lit">
+ <header><h3>Keeper</h3><p class="price">€240 <span class="mono">/ year</span></p></header>
+ <ul><li>Unlimited nights, any hour</li><li>Your own engraved brass lantern</li><li>Quarterly new-moon openings</li><li>Bring one guest, always</li></ul>
+ <a class="btn btn-solid" href="#visit" data-magnetic>Become a Keeper</a>
+ </article>
+ <article class="tier">
+ <header><h3>Patron</h3><p class="price">€1,200 <span class="mono">/ year</span></p></header>
+ <ul><li>Everything a Keeper has</li><li>A private hour with a curator</li><li>Name on the lamp you light first</li></ul>
+ <a class="btn btn-ghost" href="#visit" data-magnetic>Speak to us</a>
+ </article>
+ </div>
+ </div>
+ </section>
+
+ <footer class="panel foot" id="visit">
+ <div class="panel-inner">
+ <h2 class="foot-title">See you <em>after dark.</em></h2>
+ <div class="foot-cols">
+ <p class="mono">Reliquary<br>14 Rue des Lanternes<br>Doors 21:00 — Dawn</p>
+ <p class="mono">Nights: Thursday to Sunday<br>New moon: every hall open</p>
+ <a class="btn btn-solid" href="#top" data-magnetic>Book a night visit</a>
+ </div>
+ </div>
+ </footer>
+ </main>
+
+ <div class="cards" aria-live="polite"></div>
+ <aside class="journal" aria-label="Your field journal">
+ <p class="journal-title mono"><span class="journal-count">0</span>/6 documented</p>
+ <ol class="journal-slots"></ol>
+ </aside>
+ <div class="toast mono" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/reliquary/main.js b/examples/reliquary/main.js
new file mode 100644
index 0000000..e1edd18
--- /dev/null
+++ b/examples/reliquary/main.js
@@ -0,0 +1,556 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal, elementProgress } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { VolumetricSpotEffect } from '../../src/core/volumetric.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+
+// ─── The collection ────────────────────────────────────────────────────────────
+const D = Math.PI / 180;
+const DBG = new URLSearchParams(location.search);
+const RELICS = [
+ { key: 'guardian', file: 'models/reliquary/guardian.glb', num: 'I', name: 'Guardian Lion', meta: 'Granite · Fujian, Ming dynasty · c. 1520',
+ desc: 'One of a pair that flanked a temple gate for four centuries. The ball beneath its paw is the world; the lichen is its own.',
+ pos: [0.95, 0, 0], plinth: [1.75, 0.34, 1.35], h: 1.75, yaw: 22 * D, lampPower: 30, view: [0.05, 1.08, 4.35], look: [0.55, 1.28, 0] },
+ { key: 'helmet', file: 'models/reliquary/helmet.glb', num: 'II', name: 'Corinthian Helmet', meta: 'Bronze · Argos, Greece · c. 480 BC',
+ desc: 'Beaten from a single sheet. The dent above the left eye was made by a spear, not by time. Whoever wore it survived the blow.',
+ pos: [-2.4, 0, -8], plinth: [0.9, 1.12, 0.9], h: 0.44, yaw: 56 * D, view: [-0.85, 1.5, -6.55], look: [-2.4, 1.33, -8] },
+ { key: 'mask', file: 'models/reliquary/mask.glb', num: 'III', name: 'Jade Funerary Mask', meta: 'Jade, shell, obsidian · Palenque · 7th c.',
+ desc: 'Three hundred and forty tesserae, fitted without a pattern book. It was made to be seen by one person, once, in the dark.',
+ pos: [2.4, 0, -15], plinth: [0.9, 1.04, 0.9], h: 0.56, yaw: -56 * D, view: [0.85, 1.5, -13.55], look: [2.4, 1.32, -15] },
+ { key: 'bust', file: 'models/reliquary/bust.glb', num: 'IV', name: 'Portrait of a Young Woman', meta: 'Carrara marble · Rome · c. AD 120',
+ desc: 'Her braids were fashionable for about eleven years. The sculptor left one chisel stroke in her hair unpolished. Find it.',
+ pos: [-2.4, 0, -22], plinth: [0.9, 1.0, 0.9], h: 0.74, yaw: 50 * D, view: [-0.85, 1.52, -20.5], look: [-2.4, 1.36, -22] },
+ { key: 'amphora', file: 'models/reliquary/amphora.glb', num: 'V', name: 'Black-figure Amphora', meta: 'Terracotta · Athens · c. 530 BC',
+ desc: 'A prize for the footrace. It held forty litres of olive oil from the sacred trees. The runners have not stopped running since.',
+ pos: [2.4, 0, -29], plinth: [0.9, 0.62, 0.9], h: 0.98, yaw: -40 * D, view: [0.85, 1.45, -27.4], look: [2.4, 1.1, -29] },
+ { key: 'astrolabe', file: 'models/reliquary/astrolabe.glb', num: 'VI', name: 'Planispheric Astrolabe', meta: 'Brass, walnut · Toledo · 1068',
+ desc: 'A computer for the sky, accurate to a few minutes of arc. Set the rete to tonight and it will still tell you when dawn comes.',
+ pos: [0, 0, -37], plinth: [1.0, 0.98, 0.8], h: 0.74, yaw: 0, rough: 1.5, env: 0.8, lampPower: 7, view: [0, 1.5, -34.75], look: [0, 1.34, -37] },
+];
+const END = { view: [0, 1.66, -38.2], look: [0, 2.35, -47] };
+const HALL = { x: 5.2, len: 66, z0: 9, z1: -48, h: 10.5 };
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let vol;
+const engine = new Engine({
+ canvas, fov: 38, near: 0.05, far: 80, dpr: 1.6, background: 0x050404,
+ post: {
+ ao: { aoRadius: 0.9, intensity: 2.6, distanceFalloff: 0.8 },
+ bloom: { intensity: 0.85, luminanceThreshold: 0.55, luminanceSmoothing: 0.35, radius: 0.78 },
+ pre: cam => [(vol = new VolumetricSpotEffect(cam, { density: 0.024, noise: 0.95, noiseScale: 0.9, maxDist: 22, floorY: 0 }))],
+ vignette: { offset: 0.22, darkness: 0.78 },
+ noise: 0.085,
+ ca: 0.0011,
+ },
+});
+const { scene, camera, renderer } = engine;
+scene.fog = new THREE.FogExp2(0x050404, 0.034);
+scene.environment = studioEnvironment(renderer, { top: 0x2a2622, bottom: 0x060505 });
+scene.environmentIntensity = 0.035;
+scene.add(new THREE.HemisphereLight(0x2a3040, 0x0b0907, 0.05));
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 7 });
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1300,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', 0.15 + v * 0.85);
+ },
+});
+
+// ─── Materials & procedural textures ──────────────────────────────────────────
+// Stone slab floor: per-slab tone and roughness variation, darker seams.
+const floorAlbedo = bakeTexture(renderer, 1024, `
+ void main(){
+ vec2 g = vUv * vec2(4.0, 4.0);
+ vec2 id = floor(g); vec2 f = fract(g);
+ float slab = fract(sin(dot(id, vec2(12.9898, 78.233))) * 43758.5453);
+ float seam = smoothstep(0.0, 0.012, f.x) * smoothstep(0.0, 0.012, f.y) * smoothstep(1.0, 0.988, f.x) * smoothstep(1.0, 0.988, f.y);
+ float n = fbm(vUv * 18.0, 18.0, 6, 0.55);
+ float veins = smoothstep(0.02, 0.0, abs(fbm(vUv * 5.0 + slab, 5.0, 5, 0.6) + 0.05)) * 0.35;
+ vec3 base = mix(vec3(0.050, 0.044, 0.038), vec3(0.085, 0.074, 0.062), slab);
+ base *= 0.85 + n * 0.5;
+ base += veins * vec3(0.05, 0.045, 0.04);
+ gl_FragColor = vec4(base * mix(0.25, 1.0, seam), 1.0);
+ }`);
+const floorRough = bakeTexture(renderer, 1024, `
+ void main(){
+ vec2 g = vUv * vec2(4.0, 4.0);
+ vec2 id = floor(g); vec2 f = fract(g);
+ float slab = fract(sin(dot(id, vec2(41.3, 17.7))) * 43758.5453);
+ float seam = smoothstep(0.0, 0.015, f.x) * smoothstep(0.0, 0.015, f.y) * smoothstep(1.0, 0.985, f.x) * smoothstep(1.0, 0.985, f.y);
+ float wear = fbm(vUv * 7.0, 7.0, 5, 0.5);
+ float r = 0.16 + slab * 0.14 + wear * 0.22 + fbm(vUv * 40.0, 40.0, 3, 0.5) * 0.06;
+ r = mix(0.95, r, seam);
+ gl_FragColor = vec4(1.0, clamp(r, 0.05, 1.0), 0.0, 1.0);
+ }`);
+const plasterN = fbmNormal(renderer, { size: 512, scale: 8, octaves: 6, strength: 1.6 });
+const stoneN = fbmNormal(renderer, { size: 512, scale: 5, octaves: 6, strength: 1.2 });
+
+const floorMat = new THREE.MeshStandardMaterial({ map: floorAlbedo, roughnessMap: floorRough, roughness: 1, metalness: 0, envMapIntensity: 0.2 });
+floorAlbedo.repeat.set(3, 14); floorRough.repeat.set(3, 14);
+const wallMat = new THREE.MeshStandardMaterial({ color: 0x1f1b17, roughness: 0.93, normalMap: plasterN, normalScale: new THREE.Vector2(0.9, 0.9) });
+plasterN.repeat.set(10, 3);
+const trimMat = new THREE.MeshStandardMaterial({ color: 0x2a2520, roughness: 0.78, normalMap: stoneN, normalScale: new THREE.Vector2(0.5, 0.5) });
+const plinthRough = bakeTexture(renderer, 512, `void main(){ float r = 0.42 + fbm(vUv * 3.0, 3.0, 5, 0.55) * 0.35 + fbm(vUv * 24.0, 24.0, 3, 0.5) * 0.08; gl_FragColor = vec4(1., clamp(r, .1, 1.), 0., 1.); }`);
+const lipMat = new THREE.MeshStandardMaterial({ color: 0x1b1814, roughness: 0.55, metalness: 0, envMapIntensity: 0.6 });
+const plinthMat = new THREE.MeshStandardMaterial({ color: 0x0f0d0b, roughness: 1, roughnessMap: plinthRough, metalness: 0, envMapIntensity: 0.6 });
+function placardTexture(num) {
+ const c = document.createElement('canvas'); c.width = 256; c.height = 80;
+ const g = c.getContext('2d');
+ g.fillStyle = '#4a3820'; g.fillRect(0, 0, 256, 80);
+ g.strokeStyle = '#21180c'; g.lineWidth = 3; g.strokeRect(8, 8, 240, 64);
+ g.fillStyle = '#140e06'; g.font = 'italic 44px Georgia, serif'; g.textAlign = 'center'; g.textBaseline = 'middle'; g.fillText(num, 128, 42);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 8; return t;
+}
+
+// ─── The hall ──────────────────────────────────────────────────────────────────
+const hall = new THREE.Group();
+scene.add(hall);
+const floor = new THREE.Mesh(new THREE.PlaneGeometry(HALL.x * 2, HALL.len), floorMat);
+floor.rotation.x = -Math.PI / 2;
+floor.position.z = (HALL.z0 + HALL.z1) / 2;
+floor.receiveShadow = true;
+hall.add(floor);
+
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+reflection.hidden.push(floor);
+if (!DBG.has('norefl')) reflection.patch(floorMat, { strength: 1.25, distort: 0.012, lodScale: 7.5, lodBias: 0.3, f0: 0.06 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+
+for (const s of [-1, 1]) {
+ const wall = new THREE.Mesh(new THREE.BoxGeometry(0.4, HALL.h, HALL.len), wallMat);
+ wall.position.set(s * (HALL.x + 0.2), HALL.h / 2, floor.position.z);
+ wall.receiveShadow = true;
+ hall.add(wall);
+ const skirting = new THREE.Mesh(new THREE.BoxGeometry(0.12, 0.34, HALL.len), trimMat);
+ skirting.position.set(s * (HALL.x - 0.04), 0.17, floor.position.z);
+ skirting.receiveShadow = true;
+ hall.add(skirting);
+}
+const ceiling = new THREE.Mesh(new THREE.PlaneGeometry(HALL.x * 2, HALL.len), new THREE.MeshStandardMaterial({ color: 0x0d0b0a, roughness: 1 }));
+ceiling.rotation.x = Math.PI / 2; ceiling.position.set(0, HALL.h, floor.position.z);
+hall.add(ceiling);
+
+// Pilasters and transverse arches every bay.
+const bays = [4.2, -4.5, -11.5, -18.5, -25.5, -32.5, -41];
+const pilGeo = new RoundedBoxGeometry(0.62, HALL.h, 0.7, 2, 0.03);
+const capGeo = new RoundedBoxGeometry(0.86, 0.26, 0.9, 2, 0.03);
+const archGeo = new THREE.TorusGeometry(HALL.x - 0.3, 0.26, 10, 72, Math.PI);
+for (const z of bays) {
+ for (const s of [-1, 1]) {
+ const p = new THREE.Mesh(pilGeo, trimMat);
+ p.position.set(s * (HALL.x - 0.3), HALL.h / 2, z);
+ p.castShadow = p.receiveShadow = true;
+ hall.add(p);
+ const c = new THREE.Mesh(capGeo, trimMat);
+ c.position.set(s * (HALL.x - 0.36), 4.9, z);
+ c.castShadow = c.receiveShadow = true;
+ hall.add(c);
+ }
+ const a = new THREE.Mesh(archGeo, trimMat);
+ a.position.set(0, 5.0, z);
+ a.receiveShadow = true;
+ hall.add(a);
+}
+
+// End wall with an arched doorway onto a moonlit court.
+{
+ const w = HALL.x * 2, h = HALL.h;
+ const shape = new THREE.Shape();
+ shape.moveTo(-w / 2, 0); shape.lineTo(w / 2, 0); shape.lineTo(w / 2, h); shape.lineTo(-w / 2, h); shape.lineTo(-w / 2, 0);
+ const door = new THREE.Path();
+ const dw = 1.3, dh = 3.3;
+ door.moveTo(-dw, 0); door.lineTo(-dw, dh); door.absarc(0, dh, dw, Math.PI, 0, true); door.lineTo(dw, 0); door.lineTo(-dw, 0);
+ shape.holes.push(door);
+ const end = new THREE.Mesh(new THREE.ExtrudeGeometry(shape, { depth: 0.6, bevelEnabled: false }), wallMat);
+ end.position.set(0, 0, HALL.z1 + 1.6);
+ end.receiveShadow = true;
+ hall.add(end);
+ // The court beyond: a moonlit cloister plate, lifted slightly so the bloom catches the moon.
+ const courtTex = new THREE.TextureLoader().load(`${import.meta.env.BASE_URL}img/reliquary/court.webp`);
+ courtTex.colorSpace = THREE.SRGBColorSpace;
+ const court = new THREE.Mesh(new THREE.PlaneGeometry(4.4, 4.4 * 2200 / 1160), new THREE.MeshBasicMaterial({ map: courtTex, fog: false, color: new THREE.Color(0.62, 0.72, 0.95) }));
+ court.position.set(0, 2.5, HALL.z1 - 0.6);
+ hall.add(court);
+ const moonSpot = new THREE.SpotLight(0x9fb4ff, 60, 20, 0.5, 0.8, 1.6);
+ moonSpot.position.set(0, 4.5, HALL.z1 + 0.5);
+ moonSpot.target.position.set(0, 0, HALL.z1 + 7);
+ hall.add(moonSpot, moonSpot.target);
+}
+
+// ─── Lantern ──────────────────────────────────────────────────────────────────
+function cookieTexture() {
+ const c = document.createElement('canvas'); c.width = c.height = 256;
+ const g = c.getContext('2d');
+ const grd = g.createRadialGradient(128, 128, 0, 128, 128, 128);
+ grd.addColorStop(0, '#fff'); grd.addColorStop(0.18, '#fff6e6'); grd.addColorStop(0.3, '#d9c7aa');
+ grd.addColorStop(0.36, '#fff3de'); grd.addColorStop(0.55, '#8c7a62'); grd.addColorStop(0.8, '#2b241b'); grd.addColorStop(1, '#000');
+ g.fillStyle = grd; g.fillRect(0, 0, 256, 256);
+ // Imperfections in the reflector.
+ g.globalCompositeOperation = 'multiply';
+ g.filter = 'blur(10px)';
+ for (let i = 0; i < 14; i++) {
+ const a = Math.random() * Math.PI * 2, r = 50 + Math.random() * 60;
+ g.fillStyle = `rgba(0,0,0,${0.04 + Math.random() * 0.05})`;
+ g.beginPath(); g.arc(128 + Math.cos(a) * r, 128 + Math.sin(a) * r, 14 + Math.random() * 20, 0, Math.PI * 2); g.fill();
+ }
+ g.filter = 'none';
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace;
+ return t;
+}
+const lantern = new THREE.SpotLight(0xffd8a6, 0, 26, 0.29, 0.42, 1.7);
+if (!DBG.has('nomap')) lantern.map = cookieTexture();
+lantern.castShadow = !DBG.has('noshadow');
+lantern.shadow.mapSize.set(2048, 2048);
+lantern.shadow.camera.near = 0.15; lantern.shadow.camera.far = 24;
+lantern.shadow.bias = -0.0004; lantern.shadow.normalBias = 0.06;
+scene.add(lantern, lantern.target);
+vol.add(lantern, { scale: 0.0028, range: 0.09, softness: 0.35 });
+const LANTERN_ON = 95;
+const lanternState = { power: 0 };
+
+// Moonlight from the court door rims the guardian and the hall's silhouettes.
+const moonRim = new THREE.SpotLight(0x8ea6ff, 16, 14, 0.42, 0.9, 1.4);
+moonRim.position.set(-2.6, 4.2, -5.5);
+moonRim.target.position.set(0.95, 1.1, 0);
+scene.add(moonRim, moonRim.target);
+const flash = new THREE.PointLight(0xfff1e0, 0, 30, 1.6);
+scene.add(flash);
+
+// Dust that only exists where the lantern falls.
+const dust = (() => {
+ const N = 7000;
+ const pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ pos[i * 3] = (Math.random() * 2 - 1) * HALL.x;
+ pos[i * 3 + 1] = Math.random() * 5.5 + 0.1;
+ pos[i * 3 + 2] = lerp(HALL.z0, HALL.z1 + 4, Math.random());
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uLPos: { value: new THREE.Vector3() }, uLDir: { value: new THREE.Vector3(0, 0, -1) }, uCos: { value: 0.93 }, uPower: { value: 0 }, uDpr: { value: 1 } },
+ vertexShader: `
+ attribute float seed; uniform float uTime, uCos, uPower, uDpr; uniform vec3 uLPos, uLDir; varying float vA;
+ void main(){
+ vec3 p = position;
+ float t = uTime * (0.05 + seed * 0.06);
+ p += vec3(sin(t * 3.1 + seed * 40.), sin(t * 2.3 + seed * 13.) * 0.6 - t * 0.1, cos(t * 2.7 + seed * 27.)) * 0.35;
+ p.y = mod(p.y, 5.6) + 0.1;
+ vec3 d = p - uLPos; float dist = length(d);
+ float cone = smoothstep(uCos, uCos + 0.03, dot(d / dist, uLDir));
+ vA = cone * uPower / (1.0 + dist * dist * 0.12) * (0.4 + 0.6 * fract(seed * 91.7));
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (1.2 + seed * 2.6) * uDpr * (5.0 / -mv.z);
+ }`,
+ fragmentShader: `varying float vA; void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .0, d); gl_FragColor = vec4(vec3(1.0, .86, .66) * a * vA * 2.2, 1.); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false;
+ scene.add(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ return mat;
+})();
+
+// ─── Relics ────────────────────────────────────────────────────────────────────
+const cardsEl = document.querySelector('.cards');
+const slotsEl = document.querySelector('.journal-slots');
+const relics = RELICS.map((r, i) => {
+ const group = new THREE.Group();
+ group.position.set(...r.pos);
+ scene.add(group);
+ const [pw, ph, pd] = r.plinth;
+ const plinth = new THREE.Mesh(new RoundedBoxGeometry(pw, ph, pd, 3, 0.025), plinthMat);
+ plinth.position.y = ph / 2;
+ plinth.castShadow = plinth.receiveShadow = true;
+ group.add(plinth);
+ const lip = new THREE.Mesh(new RoundedBoxGeometry(pw + 0.06, 0.05, pd + 0.06, 2, 0.015), lipMat);
+ lip.position.y = ph + 0.025; lip.receiveShadow = true; lip.castShadow = true;
+ group.add(lip);
+ // Brass placard facing the visitor.
+ const plate = new THREE.Mesh(new THREE.PlaneGeometry(0.2, 0.0625), new THREE.MeshStandardMaterial({ map: placardTexture(r.num), metalness: 0.9, roughness: 0.42, envMapIntensity: 1.5 }));
+ plate.position.set(0, Math.max(ph - 0.16, ph * 0.72), pd / 2 + 0.002);
+ group.add(plate);
+ const holder = new THREE.Group();
+ holder.position.y = ph + 0.05;
+ holder.rotation.y = r.yaw;
+ group.add(holder);
+ // Exhibit lamp, earned by documenting the relic.
+ const lamp = new THREE.SpotLight(0xffd4a0, 0, 9, 0.3, 0.75, 1.5);
+ const worldPos = new THREE.Vector3(...r.pos);
+ lamp.position.copy(worldPos).add(new THREE.Vector3(0, ph + 2.8, 0.9));
+ lamp.target.position.copy(worldPos).add(new THREE.Vector3(0, ph + r.h * 0.45, 0));
+ scene.add(lamp, lamp.target);
+
+ const card = document.createElement('article');
+ card.className = 'card right';
+ card.innerHTML = `<p class="num mono"><span>Relic ${r.num}</span><span class="status">Undocumented</span></p>
+ <h3>${r.name}</h3><p class="meta mono">${r.meta}</p><p class="desc">${r.desc}</p>`;
+ cardsEl.appendChild(card);
+ const li = document.createElement('li');
+ li.textContent = r.num;
+ slotsEl.appendChild(li);
+ return {
+ ...r, i, group, holder, lamp, card, li, lit: 0, shot: false, lampPower: r.lampPower ?? 14,
+ center: worldPos.clone().add(new THREE.Vector3(0, ph + 0.05 + r.h * 0.5, 0)),
+ view: new THREE.Vector3(...r.view), look: new THREE.Vector3(...r.look),
+ };
+});
+const stations = [...relics.map(r => ({ view: r.view.clone(), look: r.look.clone(), desk: { view: r.view.clone(), look: r.look.clone() }, r })),
+ { view: new THREE.Vector3(...END.view), look: new THREE.Vector3(...END.look) }];
+// Portrait screens: widen the lens and aim each station straight at its relic.
+engine.onResize((w, h) => {
+ const portrait = w / h < 0.8;
+ camera.fov = portrait ? 62 : 38;
+ camera.updateProjectionMatrix();
+ for (const st of stations) {
+ if (!st.r) continue;
+ st.view.copy(st.desk.view); st.look.copy(st.desk.look);
+ if (portrait) { st.look.x = st.r.center.x; st.look.z = st.r.center.z; st.view.lerp(st.r.center, -0.12); st.view.y = st.desk.view.y; }
+ }
+});
+
+const loads = relics.map(r => assets.gltf(r.file).then(g => {
+ const m = g.scene;
+ normalize(m, r.h, { axis: 'y' });
+ prepModel(m, renderer, { env: r.env ?? 1.2, onMat: mat => { if (r.rough) mat.roughness = r.rough; } });
+ r.holder.add(m);
+ r.model = m;
+}).catch(e => console.warn('relic missing', r.key, e.message)));
+
+// ─── Camera choreography ──────────────────────────────────────────────────────
+const walkEl = document.querySelector('.walk');
+const camPos = new THREE.Vector3().copy(stations[0].view);
+const camLook = new THREE.Vector3().copy(stations[0].look);
+const tmpA = new THREE.Vector3(), tmpB = new THREE.Vector3();
+let walkT = 0;
+let exposureDist = 5;
+const idleC = { x: 0.2, y: 0.05 };
+function stationAt(t, outPos, outLook) {
+ const n = stations.length - 1;
+ const i = Math.min(n - 1, Math.floor(t));
+ const f = smooth(0.18, 0.82, t - i);
+ const a = stations[i], b = stations[i + 1];
+ outPos.lerpVectors(a.view, b.view, f);
+ outLook.lerpVectors(a.look, b.look, f);
+ // Drift toward the hall's centre line mid-walk so we never clip a plinth.
+ outPos.x *= 1 - Math.sin(f * Math.PI) * 0.7;
+ outPos.y += Math.sin(f * Math.PI) * 0.08;
+}
+
+// ─── Aim, lantern and hero mask ───────────────────────────────────────────────
+const ray = new THREE.Raycaster();
+const aimNdc = new THREE.Vector2();
+const aimDir = new THREE.Vector3();
+const lightDir = new THREE.Vector3();
+let lastMove = -10;
+pointer.on('move', () => { lastMove = engine.time; });
+const heroTitle = document.querySelector('.title');
+const heroEl = document.querySelector('.hero');
+const rootStyle = document.documentElement.style;
+
+// ─── Photography ──────────────────────────────────────────────────────────────
+const flashEl = document.querySelector('.flash');
+const toastEl = document.querySelector('.toast');
+let captureAt = null;
+let toastTimer;
+function toast(msg, ms = 2600) {
+ toastEl.textContent = msg;
+ toastEl.classList.add('on');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+let audio;
+function shutterSound() {
+ try {
+ audio ??= new AudioContext();
+ const t = audio.currentTime;
+ const len = 0.12, buf = audio.createBuffer(1, audio.sampleRate * len, audio.sampleRate);
+ const d = buf.getChannelData(0);
+ for (let i = 0; i < d.length; i++) { const k = i / d.length; d[i] = (Math.random() * 2 - 1) * (k < 0.08 ? 1 : Math.exp(-k * 22)) * (k > 0.45 && k < 0.5 ? 2 : 1); }
+ const src = audio.createBufferSource(); src.buffer = buf;
+ const bp = audio.createBiquadFilter(); bp.type = 'bandpass'; bp.frequency.value = 2400; bp.Q.value = 0.9;
+ const g = audio.createGain(); g.gain.setValueAtTime(0.35, t); g.gain.exponentialRampToValueAtTime(0.001, t + len);
+ src.connect(bp).connect(g).connect(audio.destination); src.start(t);
+ } catch { /* audio is a nicety */ }
+}
+function photograph() {
+ if (lanternState.power < 0.5) return;
+ shutterSound();
+ gsap.fromTo(flash, { intensity: 42 }, { intensity: 0, duration: 0.7, ease: 'power3.out' });
+ gsap.fromTo(flashEl, { opacity: 0.5 }, { opacity: 0, duration: 0.8, ease: 'expo.out', delay: 0.05 });
+ captureAt = { x: pointer.px, y: pointer.py, frames: 3 };
+}
+addEventListener('pointerdown', e => {
+ if (e.button !== 0 || e.target.closest('a,button,.tier,.panel')) return;
+ photograph();
+});
+
+function finishCapture(cap) {
+ // Which relic sits in the beam?
+ let best = null, bestA = 0.16;
+ const cp = camera.position;
+ for (const r of relics) {
+ if (!r.model) continue;
+ tmpA.copy(r.center).sub(cp);
+ const dist = tmpA.length();
+ if (dist > 9.5) continue;
+ const a = tmpA.normalize().angleTo(aimDir);
+ if (a < bestA) { bestA = a; best = r; }
+ }
+ const src = renderer.domElement;
+ const sw = src.width, sh = src.height, s = sw / innerWidth;
+ const cw = Math.min(sw, 520 * s), ch = cw / 1.5;
+ const sx = clamp(cap.x * s - cw / 2, 0, sw - cw), sy = clamp(cap.y * s - ch / 2, 0, sh - ch);
+ const c2 = document.createElement('canvas'); c2.width = 420; c2.height = 280;
+ c2.getContext('2d').drawImage(src, sx, sy, cw, ch, 0, 0, 420, 280);
+ const url = c2.toDataURL('image/jpeg', 0.85);
+
+ if (!best) { toast('Only darkness. Aim the lantern at a relic.'); return; }
+ if (best.shot) { toast(`${best.name} is already in your journal.`); return; }
+ best.shot = true;
+ best.card.classList.add('shot');
+ best.card.querySelector('.status').textContent = 'Documented ✓';
+ gsap.to(best.lamp, { intensity: best.lampPower, duration: 2.8, ease: 'power2.inOut', delay: 0.9 });
+ // Polaroid flies into the journal.
+ const pol = document.createElement('div');
+ pol.className = 'polaroid';
+ pol.innerHTML = `<img alt=""><span>${best.num}. ${best.name}</span>`;
+ pol.firstElementChild.src = url;
+ document.body.appendChild(pol);
+ document.body.classList.add('has-photos');
+ const slot = best.li.getBoundingClientRect();
+ gsap.set(pol, { x: cap.x - 107, y: cap.y - 81, rotation: gsap.utils.random(-8, 8), scale: 0.7, opacity: 0 });
+ gsap.timeline()
+ .to(pol, { scale: 1, opacity: 1, duration: 0.45, ease: 'back.out(1.6)' })
+ .to(pol, { x: slot.left - 107 + slot.width / 2, y: slot.top - 81 + slot.height / 2, scale: 0.3, rotation: 0, duration: 0.9, ease: 'power3.inOut', delay: 0.55 })
+ .to(pol, { opacity: 0, duration: 0.25, onComplete: () => {
+ pol.remove();
+ const img = new Image(); img.src = url; img.alt = best.name;
+ best.li.appendChild(img); best.li.classList.add('filled');
+ const n = relics.filter(r => r.shot).length;
+ document.querySelector('.journal-count').textContent = n;
+ if (n === relics.length) {
+ toast('Every relic is documented. The hall is yours tonight.', 4200);
+ for (const r of relics) gsap.to(r.lamp, { intensity: r.lampPower * 1.25, duration: 3 });
+ } else toast(`${best.name} documented — its lamp is waking up.`);
+ } }, '-=0.1');
+}
+
+engine.onAfterRender(() => {
+ if (!captureAt) return;
+ if (captureAt.frames-- > 0) return; // capture on the frame after the flash peaks
+ const c = captureAt; captureAt = null;
+ finishCapture(c);
+});
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const quotesEl = document.querySelector('.quotes');
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ walkT = damp(walkT, elementProgress(walkEl) * (stations.length - 1), 5, dt);
+ document.body.classList.toggle('is-walking', walkT > 0.08 && walkT < stations.length - 1.4);
+
+ stationAt(walkT, tmpA, tmpB);
+ camPos.copy(tmpA); camLook.copy(tmpB);
+ // Breath and hand-held drift.
+ camera.position.copy(camPos).add(tmpA.set(pointer.sx * 0.12 + Math.sin(t * 0.37) * 0.02, pointer.sy * 0.06 + Math.sin(t * 0.61) * 0.012, 0));
+ camera.lookAt(camLook);
+
+ // Aim: the pointer when it is being used, otherwise a slow searching sweep.
+ const user = clamp(1 - (t - lastMove - 3.5) / 2.5);
+ // Idle sweep circles the relic at the current station so it is never left in the dark.
+ const cur = relics[clamp(Math.round(walkT), 0, relics.length - 1)];
+ tmpB.copy(cur.center).project(camera);
+ if (Math.abs(walkT - cur.i) < 0.45) { idleC.x = damp(idleC.x, clamp(tmpB.x, -0.8, 0.8), 2, dt); idleC.y = damp(idleC.y, clamp(tmpB.y, -0.6, 0.6), 2, dt); }
+ else { idleC.x = damp(idleC.x, 0, 2, dt); idleC.y = damp(idleC.y, 0.05, 2, dt); }
+ const wx = idleC.x + Math.sin(t * 0.33) * 0.3 + Math.sin(t * 0.71) * 0.08, wy = idleC.y + Math.cos(t * 0.47) * 0.14;
+ aimNdc.set(lerp(wx, pointer.sx, user), lerp(wy, pointer.sy, user));
+ ray.setFromCamera(aimNdc, camera);
+ aimDir.copy(ray.ray.direction);
+
+ // Lantern hangs from the right hand, lags slightly behind the aim.
+ const hand = tmpA.set(0.2, -0.2, -0.05).applyQuaternion(camera.quaternion).add(camera.position);
+ lantern.position.copy(hand);
+ lightDir.lerp(aimDir, 1 - Math.exp(-12 * dt)).normalize();
+ lantern.target.position.copy(camera.position).addScaledVector(lightDir, 6);
+ const flicker = 1 + Math.sin(t * 41) * Math.sin(t * 17.3) * 0.025;
+ // Keep the pool of light at a steady exposure: a real torch blows out close objects, this one is kind.
+ let hit = 6;
+ for (const r of relics) { tmpB.copy(r.center).sub(camera.position); const d = tmpB.length(); if (d < hit && tmpB.normalize().angleTo(lightDir) < 0.35) hit = d; }
+ exposureDist = damp(exposureDist, hit, 3, dt);
+ lantern.intensity = LANTERN_ON * lanternState.power * flicker * clamp(Math.pow(exposureDist / 4.6, 1.6), 0.4, 1.25);
+ flash.position.copy(camera.position);
+
+ dust.uniforms.uTime.value = t;
+ dust.uniforms.uLPos.value.copy(lantern.position);
+ dust.uniforms.uLDir.value.copy(lightDir);
+ dust.uniforms.uCos.value = Math.cos(lantern.angle * 0.95);
+ dust.uniforms.uPower.value = lanternState.power;
+
+ // Hero title is lit only where the lantern falls.
+ rootStyle.setProperty('--mx', ((aimNdc.x + 1) / 2 * 100).toFixed(2) + 'vw');
+ rootStyle.setProperty('--my', ((1 - aimNdc.y) / 2 * 100).toFixed(2) + 'vh');
+ rootStyle.setProperty('--beam', (0.2 + lanternState.power * 0.8).toFixed(3));
+ heroEl.style.opacity = 1 - smooth(0.04, 0.2, walkT);
+
+ // Relic cards: visible at their station while the lantern (or their lamp) is on them.
+ const right = tmpB.set(1, 0, 0).applyQuaternion(camera.quaternion);
+ for (const r of relics) {
+ tmpA.copy(r.center).sub(lantern.position).normalize();
+ const inBeam = tmpA.angleTo(lightDir) < lantern.angle * 1.05 ? 1 : 0;
+ r.lit = damp(r.lit, Math.max(inBeam * lanternState.power, r.shot ? 1 : 0), inBeam ? 5 : 1.4, dt);
+ const near = Math.abs(walkT - r.i) < 0.34 && (r.i > 0 || walkT > 0.12);
+ const on = near && r.lit > 0.45 && !!r.model;
+ r.card.classList.toggle('on', on);
+ if (near && innerWidth / innerHeight < 0.8) {
+ r.card.style.transform = `translate3d(16px, ${(innerHeight - r.card.offsetHeight - 150).toFixed(0)}px, 0)`;
+ } else if (near) {
+ tmpA.copy(r.center).addScaledVector(right, r.h * 0.55 + 0.32).project(camera);
+ const x = (tmpA.x + 1) / 2 * innerWidth, y = (1 - tmpA.y) / 2 * innerHeight - 60;
+ r.card.style.transform = `translate3d(${Math.min(x + 20, innerWidth - r.card.offsetWidth - 150).toFixed(1)}px, ${clamp(y, 90, innerHeight - 320).toFixed(1)}px, 0)`;
+ }
+ }
+
+ if (!DBG.has('norefl')) reflection.update(scene, camera);
+ // Nothing to draw once the content panels fully cover the canvas.
+ engine.paused = quotesEl.getBoundingClientRect().top < 0;
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('reliquary', { theme: 'dark' });
+cursor({ color: '#ffe9c4', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.075 });
+reveal('.panel h2', { type: 'lines', stagger: 0.1 });
+reveal('.lede, blockquote p', { type: 'lines', stagger: 0.06, y: '100%' });
+
+await Promise.all(loads);
+// Warm the GPU before revealing: compile every program with the lantern at full power.
+lanternState.power = 1;
+renderer.compile(scene, camera);
+lanternState.power = 0;
+engine.start();
+await loader.finish();
+// The lantern stutters on.
+gsap.timeline({ delay: 0.25 })
+ .to(lanternState, { power: 0.7, duration: 0.05 })
+ .to(lanternState, { power: 0.05, duration: 0.08, delay: 0.07 })
+ .to(lanternState, { power: 0.9, duration: 0.05, delay: 0.18 })
+ .to(lanternState, { power: 0.3, duration: 0.06, delay: 0.05 })
+ .to(lanternState, { power: 1, duration: 0.6, ease: 'power2.out', delay: 0.12 });
+gsap.from('.title span', { yPercent: 40, opacity: 0, duration: 2.2, ease: 'expo.out', stagger: 0.12, delay: 0.3 });
+gsap.from('.eyebrow, .sub, .hint, .nav', { opacity: 0, y: 14, duration: 1.4, ease: 'power3.out', stagger: 0.08, delay: 0.9 });
diff --git a/examples/reliquary/style.css b/examples/reliquary/style.css
new file mode 100644
index 0000000..2eceb3d
--- /dev/null
+++ b/examples/reliquary/style.css
@@ -0,0 +1,150 @@
+:root {
+ --bg: #070605;
+ --ink: #ece4d6;
+ --muted: #8f8577;
+ --faint: rgba(236, 228, 214, .12);
+ --accent: #d6ad6e;
+ --serif: 'Cormorant Garamond', 'Times New Roman', serif;
+ --sans: 'Instrument Sans', system-ui, sans-serif;
+ --mono: 'JetBrains Mono', ui-monospace, monospace;
+ --mx: 50vw; --my: 50vh;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; }
+body { font: 400 16px/1.6 var(--sans); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+.mono { font-family: var(--mono); font-size: 11px; letter-spacing: .12em; text-transform: uppercase; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+.flash { position: fixed; inset: 0; background: #fff8ec; opacity: 0; pointer-events: none; z-index: 50; mix-blend-mode: screen; }
+
+/* loader */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--bg); display: grid; place-content: center; justify-items: center; gap: 22px; }
+.loader-wick { width: 2px; height: 46px; background: linear-gradient(#0000, #3a3128); position: relative; }
+.loader-wick i { position: absolute; left: 50%; top: -14px; width: 10px; height: 16px; margin-left: -5px; border-radius: 50% 50% 45% 45%;
+ background: radial-gradient(circle at 50% 70%, #fff5d8, #ffb65a 45%, #ff7a1a00 72%); filter: blur(.4px);
+ transform-origin: 50% 100%; animation: flame 1.6s ease-in-out infinite; opacity: var(--p, .15); }
+@keyframes flame { 0%,100% { transform: scale(1, 1) rotate(-2deg); } 50% { transform: scale(.92, 1.08) rotate(2deg); } }
+.loader-line { font: 400 italic 20px/1 var(--serif); color: var(--muted); letter-spacing: .02em; }
+.loader-pct { font-variant-numeric: tabular-nums; }
+
+/* nav */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 20; display: flex; align-items: center; justify-content: space-between;
+ padding: 22px clamp(16px, 4vw, 48px); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font: 500 13px/1 var(--mono); letter-spacing: .3em; text-transform: uppercase; }
+.brand svg { width: 20px; height: 20px; color: var(--accent); }
+.links { display: flex; gap: 34px; }
+.links a { text-decoration: none; font: 500 13px/1 var(--sans); color: var(--muted); transition: color .3s; }
+.links a:hover { color: var(--ink); }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 44px; padding: 0 22px; border-radius: 999px;
+ text-decoration: none; font: 500 13px/1 var(--sans); letter-spacing: .02em; transition: background .35s, color .35s, box-shadow .35s; white-space: nowrap; }
+.btn-ghost { box-shadow: inset 0 0 0 1px rgba(236,228,214,.28); color: var(--ink); background: rgba(10,9,8,.3); backdrop-filter: blur(8px); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--accent); color: #fff; }
+.btn-solid { background: var(--accent); color: #140f09; }
+.btn-solid:hover { background: #f0c887; box-shadow: 0 0 40px rgba(214,173,110,.35); }
+
+/* walk / hero */
+.walk { position: relative; height: 760vh; z-index: 2; pointer-events: none; }
+.hero { position: sticky; top: 0; height: 100vh; display: grid; align-content: end; padding: 0 clamp(16px, 4vw, 48px) 13vh; }
+.eyebrow { color: var(--accent); margin-bottom: 18px; }
+.title { font: 300 clamp(76px, 15.5vw, 250px)/.82 var(--serif); letter-spacing: -.035em; display: flex; flex-wrap: wrap;
+ color: #fff3dc;
+ /* only visible where the lantern falls */
+ -webkit-mask-image: radial-gradient(circle calc(var(--beam, 1) * 36vmin) at var(--mx) var(--my), #000 0%, rgba(0,0,0,.7) 40%, rgba(0,0,0,.34) 100%);
+ mask-image: radial-gradient(circle calc(var(--beam, 1) * 36vmin) at var(--mx) var(--my), #000 0%, rgba(0,0,0,.7) 40%, rgba(0,0,0,.34) 100%);
+ text-shadow: 0 0 60px rgba(255, 190, 120, .18); }
+.title span:last-child { font-style: italic; margin-left: .04em; }
+.sub { max-width: 30em; margin-top: 26px; font: 400 clamp(17px, 1.5vw, 21px)/1.45 var(--serif); color: #c9bfb0; }
+.hint { position: fixed; right: clamp(16px, 4vw, 48px); bottom: 5.5vh; z-index: 3; display: grid; gap: 10px; justify-items: end; color: var(--muted); transition: opacity .6s; }
+.hint kbd { font: inherit; color: var(--ink); padding: 3px 7px; border-radius: 4px; box-shadow: inset 0 0 0 1px var(--faint); margin-right: 8px; }
+.is-walking .hint { opacity: 0; }
+
+/* relic cards (positioned from 3D) */
+.cards { position: fixed; inset: 0; z-index: 5; pointer-events: none; }
+.card { position: absolute; left: 0; top: 0; width: 290px; padding: 20px 22px 22px; border-radius: 2px;
+ background: linear-gradient(180deg, rgba(20,17,14,.72), rgba(12,10,9,.5)); backdrop-filter: blur(10px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(214,173,110,.16), 0 30px 60px -20px rgba(0,0,0,.8);
+ opacity: 0; transform: translate3d(-9999px, 0, 0); transition: opacity .7s ease; will-change: transform, opacity; }
+.card.on { opacity: 1; }
+.card .num { display: flex; justify-content: space-between; color: var(--accent); margin-bottom: 14px; }
+.card .num .status { color: var(--muted); }
+.card.shot .num .status { color: #9fd49a; }
+.card h3 { font: 400 28px/1.02 var(--serif); letter-spacing: -.01em; margin-bottom: 6px; }
+.card .meta { color: var(--muted); margin-bottom: 12px; font-size: 10px; }
+.card p.desc { font-size: 13.5px; line-height: 1.55; color: #cfc5b6; }
+.card::before { content: ''; position: absolute; top: 38px; width: 46px; height: 1px; background: linear-gradient(90deg, #0000, rgba(214,173,110,.6)); }
+.card.left::before { right: -46px; transform: scaleX(-1); }
+.card.right::before { left: -46px; }
+
+/* journal */
+.journal { position: fixed; right: clamp(16px, 3vw, 36px); top: 50%; transform: translateY(-50%); z-index: 8; display: grid; gap: 10px; justify-items: end;
+ opacity: 0; transition: opacity .8s; }
+.is-walking .journal { opacity: 1; }
+.journal-title { color: var(--muted); font-size: 10px; }
+.journal-count { color: var(--ink); }
+.journal-slots { list-style: none; display: grid; gap: 8px; }
+.journal-slots li { width: 74px; height: 50px; border-radius: 2px; box-shadow: inset 0 0 0 1px rgba(236,228,214,.14); position: relative;
+ display: grid; place-items: center; font: 400 italic 15px/1 var(--serif); color: rgba(236,228,214,.28); overflow: hidden; background: rgba(8,7,6,.4); }
+.journal-slots li img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.journal-slots li.filled { box-shadow: inset 0 0 0 1px rgba(214,173,110,.55); }
+.polaroid { position: fixed; z-index: 60; left: 0; top: 0; padding: 7px 7px 22px; background: #efe8da; box-shadow: 0 20px 50px rgba(0,0,0,.6); pointer-events: none; }
+.polaroid img { display: block; width: 200px; height: 134px; object-fit: cover; }
+.polaroid span { position: absolute; left: 9px; bottom: 5px; font: 400 italic 13px/1 var(--serif); color: #3b3127; }
+.toast { position: fixed; left: 50%; bottom: 6vh; transform: translate(-50%, 20px); z-index: 30; padding: 14px 22px; border-radius: 999px;
+ background: rgba(20,17,14,.8); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(214,173,110,.3); color: var(--ink);
+ opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; text-align: center; }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+/* content panels */
+.panel { position: relative; z-index: 4; padding: 18vh clamp(16px, 6vw, 96px); }
+.panel-inner { max-width: 1180px; margin: 0 auto; }
+.hours { background: linear-gradient(180deg, #07060500 0%, rgba(7,6,5,.86) 22%, var(--bg) 60%); padding-top: 34vh; }
+.panel h2 { font: 300 clamp(44px, 6.4vw, 104px)/.95 var(--serif); letter-spacing: -.025em; max-width: 12em; }
+.panel h2 em { color: var(--accent); }
+.lede { max-width: 36em; margin: 34px 0 80px; font: 400 clamp(18px, 1.6vw, 23px)/1.5 var(--serif); color: #cabfae; }
+.grid3 { display: grid; grid-template-columns: repeat(3, 1fr); gap: 1px; background: var(--faint); box-shadow: 0 0 0 1px var(--faint); }
+.grid3 article { background: var(--bg); padding: 34px 30px 40px; }
+.grid3 .num { color: var(--accent); }
+.grid3 h3 { font: 400 30px/1.1 var(--serif); margin: 26px 0 12px; }
+.grid3 p { color: #b3a898; font-size: 15px; }
+.quotes { background: var(--bg); }
+blockquote p { font: 300 italic clamp(32px, 4.2vw, 64px)/1.12 var(--serif); letter-spacing: -.015em; max-width: 18em; }
+blockquote cite { display: block; margin-top: 28px; color: var(--muted); font-style: normal; }
+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 40px; margin-top: 110px; border-top: 1px solid var(--faint); padding-top: 40px; }
+.stats b { display: block; font: 300 clamp(56px, 6vw, 96px)/1 var(--serif); color: var(--accent); }
+.stats span { color: var(--muted); display: block; margin-top: 12px; max-width: 18em; }
+.membership { background: var(--bg); }
+.tiers { display: grid; grid-template-columns: repeat(3, 1fr); gap: 22px; margin-top: 70px; }
+.tier { padding: 34px 30px; display: grid; gap: 28px; align-content: start; box-shadow: inset 0 0 0 1px var(--faint); border-radius: 2px;
+ background: radial-gradient(120% 90% at 50% -10%, rgba(214,173,110,.07), transparent 60%); }
+.tier-lit { box-shadow: inset 0 0 0 1px rgba(214,173,110,.5); background: radial-gradient(120% 90% at 50% -10%, rgba(214,173,110,.2), transparent 70%); }
+.tier h3 { font: 400 32px/1 var(--serif); }
+.price { margin-top: 12px; font: 300 44px/1 var(--serif); color: var(--accent); }
+.price span { color: var(--muted); }
+.tier ul { list-style: none; display: grid; gap: 10px; color: #bdb2a2; font-size: 15px; }
+.tier li::before { content: '—'; color: var(--accent); margin-right: 10px; }
+.tier .btn { justify-self: start; }
+.foot { background: var(--bg); padding-bottom: 12vh; border-top: 1px solid var(--faint); }
+.foot-title { font-size: clamp(56px, 9vw, 150px) !important; }
+.foot-cols { display: grid; grid-template-columns: 1fr 1fr auto; gap: 40px; align-items: end; margin-top: 80px; color: var(--muted); line-height: 2; }
+
+@media (max-width: 900px) {
+ .links { display: none; }
+ .grid3, .tiers, .stats { grid-template-columns: 1fr; }
+ .foot-cols { grid-template-columns: 1fr; }
+ .card { width: 230px; padding: 16px; }
+ .card h3 { font-size: 22px; }
+ .card p.desc { display: none; }
+ .journal { top: auto; bottom: 70px; transform: none; }
+ .journal-slots { grid-auto-flow: column; }
+ .journal-slots li { width: 42px; height: 30px; font-size: 11px; }
+ .hint { display: none; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 12px; }
+}
+@media (max-width: 640px) {
+ .title { font-size: 21vw; }
+ .sub br { display: none; }
+ .hero { padding-bottom: 16vh; }
+ .eyebrow { font-size: 10px; }
+}
+@media (max-aspect-ratio: 4/5) { .card::before { display: none; } }
diff --git a/examples/sucre/coffret.js b/examples/sucre/coffret.js
new file mode 100644
index 0000000..7837d11
--- /dev/null
+++ b/examples/sucre/coffret.js
@@ -0,0 +1,375 @@
+// "Coffret de six": a pistachio gift box with six slots. Macarons dropped in snap to a slot;
+// when the sixth lands the lid swings shut and a satin ribbon ties itself.
+import { THREE, clamp, lerp } from '../../src/core/engine.js';
+import { fbmNormal } from '../../src/core/textures.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+import { gsap } from '../../src/core/scroll.js';
+import { RAPIER } from './pastry.js';
+
+const W = 2.24, D = 1.52, H = 0.46, T = 0.045, LID_H = 0.17;
+const SLOTS = [];
+for (let j = 0; j < 2; j++) for (let i = 0; i < 3; i++) SLOTS.push(new THREE.Vector3((i - 1) * 0.69, 0, (j - 0.5) * 0.7));
+const _v = new THREE.Vector3(), _q = new THREE.Quaternion(), _q2 = new THREE.Quaternion(), _e = new THREE.Euler();
+
+// Ribbon crossing point on the lid (off-centre, so the gold lettering stays readable).
+const RX = 0.6, RZ = 0.36;
+
+function lidTexture(aspect) {
+ const S = 1024, SH = Math.round(S / aspect);
+ const c = document.createElement('canvas'); c.width = S; c.height = SH;
+ const g = c.getContext('2d');
+ const m = document.createElement('canvas'); m.width = S; m.height = SH;
+ const mg = m.getContext('2d');
+ g.fillStyle = '#b9c796'; g.fillRect(0, 0, S, SH);
+ const n = g.createRadialGradient(S * 0.4, SH * 0.35, 0, S * 0.5, SH * 0.5, S * 0.75);
+ n.addColorStop(0, 'rgba(255,255,240,.16)'); n.addColorStop(1, 'rgba(60,70,30,.1)');
+ g.fillStyle = n; g.fillRect(0, 0, S, SH);
+ mg.fillStyle = 'rgb(0,190,0)'; mg.fillRect(0, 0, S, SH); // G = roughness, B = metalness
+ const cx = S * 0.36;
+ const foil = (ctx, isMat) => {
+ ctx.strokeStyle = ctx.fillStyle = isMat ? 'rgb(0,70,255)' : '#d9b866';
+ ctx.lineWidth = 6; ctx.strokeRect(34, 34, S - 68, SH - 68);
+ ctx.lineWidth = 2; ctx.strokeRect(52, 52, S - 104, SH - 104);
+ ctx.textAlign = 'center'; ctx.textBaseline = 'alphabetic';
+ ctx.font = '600 22px "DM Sans", sans-serif';
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '9px';
+ ctx.fillText('PÂTISSERIE · PARIS', cx, SH * 0.2);
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '0px';
+ ctx.font = 'italic 500 132px "Playfair Display", Georgia, serif';
+ ctx.fillText('Maison', cx, SH * 0.43);
+ ctx.fillText('Sucre', cx + 38, SH * 0.63);
+ ctx.font = '600 22px "DM Sans", sans-serif';
+ if ('letterSpacing' in ctx) ctx.letterSpacing = '9px';
+ ctx.fillText('DEPUIS 1962', cx, SH * 0.9);
+ };
+ foil(g, false); foil(mg, true);
+ const map = new THREE.CanvasTexture(c); map.colorSpace = THREE.SRGBColorSpace; map.anisotropy = 8;
+ const mr = new THREE.CanvasTexture(m); mr.anisotropy = 8;
+ return { map, mr };
+}
+
+/** A flat satin strip swept along a curve; `up(t)` gives the direction across the ribbon's width. */
+function ribbonStrip(curve, width, segs, up) {
+ const pos = [], nor = [], uv = [], idx = [];
+ const p = new THREE.Vector3(), tan = new THREE.Vector3(), side = new THREE.Vector3(), n = new THREE.Vector3();
+ for (let i = 0; i <= segs; i++) {
+ const t = i / segs;
+ curve.getPointAt(t, p); curve.getTangentAt(t, tan);
+ side.copy(up(t, p)).normalize();
+ n.crossVectors(tan, side).normalize();
+ for (const s of [-0.5, 0.5]) {
+ pos.push(p.x + side.x * width * s, p.y + side.y * width * s, p.z + side.z * width * s);
+ nor.push(n.x, n.y, n.z);
+ uv.push(s + 0.5, t);
+ }
+ if (i < segs) { const k = i * 2; idx.push(k, k + 1, k + 2, k + 1, k + 3, k + 2); }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ g.setIndex(idx);
+ return g;
+}
+
+export class Coffret {
+ constructor({ scene, renderer, pat, pos, onChange, toast }) {
+ this.pat = pat; this.onChange = onChange; this.toast = toast;
+ this.pos = pos.clone();
+ this.slots = SLOTS.map(() => null);
+ this.closed = false;
+ this.busy = false;
+ this.flying = [];
+
+ const g = this.group = new THREE.Group();
+ g.position.copy(pos);
+ g.rotation.y = -0.08;
+ scene.add(g);
+ this.inv = new THREE.Matrix4();
+
+ const paperN = fbmNormal(renderer, { size: 512, scale: 24, octaves: 4, strength: 0.35 });
+ paperN.repeat.set(2, 2);
+ const outer = new THREE.MeshStandardMaterial({ color: 0xb9c796, roughness: 0.72, normalMap: paperN, normalScale: new THREE.Vector2(0.4, 0.4), envMapIntensity: 0.8 });
+ const inner = new THREE.MeshStandardMaterial({ color: 0xf7eee2, roughness: 0.85, normalMap: paperN, normalScale: new THREE.Vector2(0.3, 0.3), envMapIntensity: 0.6 });
+ const gold = new THREE.MeshStandardMaterial({ color: 0xe0c07a, metalness: 1, roughness: 0.3, envMapIntensity: 1.5 });
+ const add = (geo, mat, x, y, z, parent = g) => { const m = new THREE.Mesh(geo, mat); m.position.set(x, y, z); m.castShadow = m.receiveShadow = true; parent.add(m); return m; };
+
+ add(new RoundedBoxGeometry(W, 0.05, D, 2, 0.015), outer, 0, 0.025, 0);
+ add(new THREE.BoxGeometry(W - 2 * T, 0.012, D - 2 * T), inner, 0, 0.056, 0);
+ for (const s of [-1, 1]) {
+ add(new RoundedBoxGeometry(W, H, T, 2, 0.012), outer, 0, H / 2, s * (D / 2 - T / 2));
+ add(new RoundedBoxGeometry(T, H, D - 2 * T, 2, 0.012), outer, s * (W / 2 - T / 2), H / 2, 0);
+ add(new THREE.BoxGeometry(W - 2 * T - 0.004, H - 0.06, 0.008), inner, 0, H / 2 + 0.02, s * (D / 2 - T - 0.004));
+ add(new THREE.BoxGeometry(0.008, H - 0.06, D - 2 * T - 0.004), inner, s * (W / 2 - T - 0.004), H / 2 + 0.02, 0);
+ // gold foil band around the outside
+ add(new THREE.BoxGeometry(W + 0.006, 0.05, 0.004), gold, 0, H * 0.52, s * (D / 2 + 0.002));
+ add(new THREE.BoxGeometry(0.004, 0.05, D + 0.006), gold, s * (W / 2 + 0.002), H * 0.52, 0);
+ }
+ // cream dividers with gilded top edges
+ for (const x of [-0.345, 0.345]) { add(new THREE.BoxGeometry(0.018, 0.2, D - 2 * T - 0.02), inner, x, 0.16, 0); add(new THREE.BoxGeometry(0.02, 0.006, D - 2 * T - 0.02), gold, x, 0.262, 0); }
+ add(new THREE.BoxGeometry(W - 2 * T - 0.02, 0.2, 0.018), inner, 0, 0.16, 0);
+ add(new THREE.BoxGeometry(W - 2 * T - 0.02, 0.006, 0.02), gold, 0, 0.262, 0);
+
+ // Lid, hinged along the back top edge.
+ const { map, mr } = lidTexture((W + 0.05) / (D + 0.05));
+ const lidTop = new THREE.MeshStandardMaterial({ map, roughnessMap: mr, metalnessMap: mr, roughness: 1, metalness: 1, envMapIntensity: 2.2, normalMap: paperN, normalScale: new THREE.Vector2(0.25, 0.25),
+ emissiveMap: mr, emissive: new THREE.Color(0.0, 0.0, 0.0) });
+ // Foil catches a little light from every angle (the mask lives in the blue channel): tint the emissive gold.
+ lidTop.onBeforeCompile = sh => { sh.fragmentShader = sh.fragmentShader.replace('#include <emissivemap_fragment>', 'totalEmissiveRadiance += vec3(0.30, 0.22, 0.09) * texture2D(emissiveMap, vEmissiveMapUv).b;'); };
+ const lidMats = [outer, outer, lidTop, outer, outer, outer];
+ this.hinge = new THREE.Group();
+ this.hinge.position.set(0, H, -D / 2 - 0.02);
+ g.add(this.hinge);
+ const LW = W + 0.05, LD = D + 0.05;
+ const top = new THREE.Mesh(new THREE.BoxGeometry(LW, 0.04, LD), lidMats);
+ top.position.set(0, 0.02, LD / 2 - 0.005); top.castShadow = top.receiveShadow = true; this.hinge.add(top);
+ add(new RoundedBoxGeometry(LW, LID_H, 0.03, 2, 0.01), outer, 0, -LID_H / 2 + 0.04, LD - 0.02, this.hinge);
+ add(new RoundedBoxGeometry(LW, LID_H, 0.03, 2, 0.01), outer, 0, -LID_H / 2 + 0.04, 0.01, this.hinge);
+ for (const s of [-1, 1]) add(new RoundedBoxGeometry(0.03, LID_H, LD, 2, 0.01), outer, s * (LW / 2 - 0.015), -LID_H / 2 + 0.04, LD / 2 - 0.005, this.hinge);
+ this.lidOpen = -1.98;
+ this.hinge.rotation.x = this.lidOpen;
+
+ // Satin ribbon (hidden until the box is full): two bands crossing off-centre and a proper bow.
+ const satin = new THREE.MeshPhysicalMaterial({ color: 0xe48ea4, roughness: 0.4, sheen: 1, sheenColor: new THREE.Color(0xffdbe4), sheenRoughness: 0.28, envMapIntensity: 1.1, side: THREE.DoubleSide });
+ const bowSatin = satin.clone(); bowSatin.color.set(0xf6a9bc); bowSatin.sheenColor.set(0xffe6ec);
+ this.ribbon = new THREE.Group();
+ g.add(this.ribbon);
+ const RY = H + 0.062, RW = 0.16;
+ this.bandX = new THREE.Group(); this.bandZ = new THREE.Group();
+ this.bandX.position.z = RZ; this.bandZ.position.x = RX;
+ this.ribbon.add(this.bandX, this.bandZ);
+ const rb = (geo, x, y, z, parent) => { const m = new THREE.Mesh(geo, satin); m.position.set(x, y, z); m.castShadow = true; m.receiveShadow = true; parent.add(m); return m; };
+ rb(new THREE.BoxGeometry(LW + 0.02, 0.012, RW), 0, RY, 0, this.bandX);
+ for (const s of [-1, 1]) rb(new THREE.BoxGeometry(0.012, H + 0.06, RW), s * (LW / 2 + 0.007), (H + 0.06) / 2, 0, this.bandX);
+ rb(new THREE.BoxGeometry(RW, 0.013, LD + 0.02), 0, RY + 0.002, 0, this.bandZ);
+ for (const s of [-1, 1]) rb(new THREE.BoxGeometry(RW, H + 0.06, 0.012), 0, (H + 0.06) / 2, s * (LD / 2 + 0.007), this.bandZ);
+ this.bow = new THREE.Group();
+ this.bow.position.set(RX, RY + 0.008, RZ);
+ this.bow.rotation.y = 0.5;
+ this.ribbon.add(this.bow);
+ const V3 = (x, y, z) => new THREE.Vector3(x, y, z);
+ for (const s of [-1, 1]) {
+ // Loop: a teardrop that leaves the knot, swells outward and comes back underneath.
+ const loop = new THREE.CatmullRomCurve3([V3(0, 0.03, 0), V3(s * 0.12, 0.13, 0.02), V3(s * 0.28, 0.17, 0.03), V3(s * 0.36, 0.09, 0.02), V3(s * 0.3, 0.02, 0), V3(s * 0.14, 0.015, -0.01)], true, 'centripetal');
+ const l = rb(ribbonStrip(loop, 0.13, 72, () => V3(0.05 * s, 0.25, 1)), 0, 0, 0, this.bow);
+ l.rotation.set(0.12 * s, 0, 0);
+ // Tail: drops from the knot onto the lid and lies flat.
+ const tail = new THREE.CatmullRomCurve3([V3(0, 0.03, 0), V3(s * 0.06, 0.02, 0.1), V3(s * 0.12, 0.004, 0.26), V3(s * 0.2, 0.0, 0.44)]);
+ rb(ribbonStrip(tail, 0.12, 30, t => V3(1, 0.3 * (1 - t), -0.25 * s)), 0, 0, 0, this.bow);
+ }
+ this.bow.traverse(o => { if (o.isMesh) o.material = bowSatin; });
+ const knot = rb(new THREE.SphereGeometry(0.07, 20, 14), 0, 0.045, 0, this.bow);
+ knot.material = bowSatin;
+ knot.scale.set(1.15, 0.8, 1.2);
+ this.bandX.scale.set(0.001, 1, 1); this.bandZ.scale.set(1, 1, 0.001); this.bow.scale.setScalar(0.001);
+ this.ribbon.visible = false;
+
+ // Physics: the tray is fixed; the lid top becomes solid once closed.
+ const world = pat.world;
+ this.body = world.createRigidBody(RAPIER.RigidBodyDesc.fixed().setTranslation(pos.x, pos.y, pos.z).setRotation(new THREE.Quaternion().setFromEuler(g.rotation)));
+ const cd = (hx, hy, hz, x, y, z) => world.createCollider(RAPIER.ColliderDesc.cuboid(hx, hy, hz).setTranslation(x, y, z).setFriction(0.8).setRestitution(0.2), this.body);
+ cd(W / 2, 0.028, D / 2, 0, 0.028, 0);
+ cd(W / 2, H / 2, T / 2, 0, H / 2, D / 2 - T / 2); cd(W / 2, H / 2, T / 2, 0, H / 2, -D / 2 + T / 2);
+ cd(T / 2, H / 2, D / 2, W / 2 - T / 2, H / 2, 0); cd(T / 2, H / 2, D / 2, -W / 2 + T / 2, H / 2, 0);
+ this.lidCollider = null;
+ g.updateMatrixWorld(true);
+ this.inv.copy(g.matrixWorld).invert();
+ this.emit();
+ }
+
+ get filled() { return this.slots.filter(Boolean).length; }
+
+ local(p, out = _v) { return out.copy(p).applyMatrix4(this.inv); }
+ slotWorld(i, out = new THREE.Vector3()) { return out.copy(SLOTS[i]).applyMatrix4(this.group.matrixWorld); }
+
+ /** Is a world point over the open tray (with a margin)? */
+ over(p, margin = 0) {
+ const l = this.local(p);
+ return Math.abs(l.x) < W / 2 + margin && Math.abs(l.z) < D / 2 + margin;
+ }
+
+ freeSlotNear(p) {
+ const l = this.local(p);
+ let best = -1, bd = 1e9;
+ this.slots.forEach((s, i) => { if (s) return; const d = (SLOTS[i].x - l.x) ** 2 + (SLOTS[i].z - l.z) ** 2; if (d < bd) { bd = d; best = i; } });
+ return best;
+ }
+
+ /** Fly a macaron into a slot along an arc. */
+ capture(e, { apex = 0.9, dur = 0.55, slot = -1 } = {}) {
+ if (this.closed || this.busy) return false;
+ const pat = this.pat;
+ const p0 = pat.pos(e);
+ const i = slot >= 0 ? slot : this.freeSlotNear(p0);
+ if (i < 0) return false;
+ this.slots[i] = e;
+ if (pat.held === e) pat.release();
+ e.state = 'fly';
+ e.rb.setBodyType(RAPIER.RigidBodyType.KinematicPositionBased, true);
+ const r0 = e.rb.rotation();
+ const q0 = new THREE.Quaternion(r0.x, r0.y, r0.z, r0.w);
+ const q1 = new THREE.Quaternion().setFromEuler(_e.set(0, this.group.rotation.y + (Math.random() - 0.5) * 0.9, 0));
+ const p1 = this.slotWorld(i);
+ p1.y = this.pos.y + 0.056 + e.T.hy + 0.004;
+ const top = Math.max(p0.y, p1.y) + apex;
+ this.flying.push({ e, i, p0, p1, q0, q1, top, t: 0, dur });
+ this.emit();
+ return true;
+ }
+
+ update(dt) {
+ const pat = this.pat;
+ for (const f of this.flying) {
+ f.t += dt / f.dur;
+ const k = clamp(f.t), u = 1 - k;
+ const ease = k < 1 ? 1 - Math.pow(1 - k, 2.2) : 1;
+ // quadratic bezier with a lifted control point
+ const cx = (f.p0.x + f.p1.x) / 2, cz = (f.p0.z + f.p1.z) / 2, cy = f.top * 2 - (f.p0.y + f.p1.y) / 2;
+ const x = u * u * f.p0.x + 2 * u * k * cx + k * k * f.p1.x;
+ const y = u * u * f.p0.y + 2 * u * k * cy + k * k * f.p1.y;
+ const z = u * u * f.p0.z + 2 * u * k * cz + k * k * f.p1.z;
+ f.e.rb.setNextKinematicTranslation({ x, y, z });
+ _q.copy(f.q0).slerp(f.q1, ease);
+ f.e.rb.setNextKinematicRotation(_q);
+ if (f.t >= 1 && !f.done) {
+ f.done = true;
+ f.e.state = 'boxed';
+ f.e.sqv -= 0.35;
+ this.onLand?.(f.e, f.p1);
+ }
+ }
+ this.flying = this.flying.filter(f => !f.done);
+
+ if (this.closed || this.busy || pat.time < (this.cooldownUntil ?? 0)) return;
+ // Pastries that fall or roll into the open tray.
+ for (const e of pat.entries) {
+ if (e.state !== 'live') continue;
+ const t = e.rb.translation();
+ if (t.y > this.pos.y + H + 0.5 || t.y < this.pos.y) continue;
+ _v.set(t.x, t.y, t.z);
+ if (!this.over(_v, -0.06)) continue;
+ const isMac = e.T.def.key === 'macA' || e.T.def.key === 'macB';
+ const byHand = pat.time - (e.touchedAt ?? -99) < 4;
+ if (isMac && this.filled < 6 && (byHand || this.filled > 0 || pat.time - e.bornAt > 3)) this.capture(e, { apex: 0.35, dur: 0.35 });
+ else this.eject(e, !byHand ? null : isMac ? 'This one is full — six is the rule.' : 'Macarons only in the coffret, s’il vous plaît.');
+ }
+ if (this.filled === 6 && !this.flying.length && !this.closed) this.close();
+ }
+
+ eject(e, msg) {
+ const t = e.rb.translation();
+ const l = this.local(_v.set(t.x, t.y, t.z));
+ const dir = new THREE.Vector3(Math.sign(l.x || 1) * 0.6, 0, 1).applyQuaternion(this.group.quaternion).normalize();
+ e.rb.setLinvel({ x: dir.x * 5, y: 9, z: dir.z * 5 }, true);
+ e.rb.setAngvel({ x: 6, y: 0, z: -4 }, true);
+ if (msg && (!this._lastEject || pat_time() - this._lastEject > 2)) { this.toast?.(msg); this._lastEject = pat_time(); }
+ }
+
+ releasedOver(e) {
+ const p = this.pat.pos(e);
+ if (this.closed || this.busy || !this.over(p, 0.35) || p.y > this.pos.y + 4) return false;
+ const isMac = e.T.def.key === 'macA' || e.T.def.key === 'macB';
+ if (!isMac) return false;
+ if (this.filled >= 6) return false;
+ return this.capture(e, { apex: 0.4, dur: 0.4 });
+ }
+
+ /** Fly the nearest free macarons in, one after another, until the box is full (summoning more if needed). */
+ fillForMe() {
+ if (this.closed || this.busy || this._filling) return;
+ this._filling = true;
+ const isMac = e => e.T.def.key === 'macA' || e.T.def.key === 'macB';
+ let summoned = 0;
+ const step = () => {
+ const need = 6 - this.filled;
+ if (this.closed || this.busy || need <= 0) { this._filling = false; return; }
+ const inBox = new Set(this.slots.filter(Boolean).map(e => e.flavour));
+ const c = this.pos, pat = this.pat;
+ let best = null, bd = 1e9;
+ for (const e of pat.entries) {
+ if (e.state !== 'live' || e.queued || !isMac(e) || pat.held === e) continue;
+ const d = pat._dist2(e, c.x, c.z) + (inBox.has(e.flavour) ? 40 : 0); // prefer a flavour the box lacks
+ if (d < bd && d < 160 + (inBox.has(e.flavour) ? 40 : 0)) { bd = d; best = e; }
+ }
+ if (!best) {
+ if (summoned++ > 2) { this._filling = false; this.toast?.('The counter is out of macarons — hold the marble to make it rain.'); return; }
+ pat.rain({ x: c.x + 1.9, z: c.z + 0.9, rx: 0.9, rz: 0.5, count: need, over: 0.5, pick: isMac, height: [7, 9] });
+ setTimeout(step, 1300);
+ return;
+ }
+ this.capture(best, { apex: 2.4, dur: 0.85 });
+ setTimeout(step, 240);
+ };
+ step();
+ }
+
+ close() {
+ this.closed = true;
+ this.busy = true;
+ this.emit();
+ const tl = gsap.timeline({ delay: 0.35, onComplete: () => { this.busy = false; this.emit(); } });
+ tl.to(this.hinge.rotation, { x: 0.03, duration: 0.9, ease: 'power2.in' })
+ .to(this.hinge.rotation, { x: 0, duration: 0.35, ease: 'elastic.out(1, 0.5)' })
+ .add(() => {
+ this.onThud?.();
+ const w = this.pat.world;
+ const q = new THREE.Quaternion().setFromEuler(this.group.rotation);
+ this.lidCollider = w.createCollider(RAPIER.ColliderDesc.cuboid(W / 2 + 0.03, 0.05, D / 2 + 0.03).setTranslation(0, H + 0.05, 0).setFriction(0.8), this.body);
+ this.ribbon.visible = true;
+ }, '-=0.3')
+ .to(this.bandX.scale, { x: 1, duration: 0.55, ease: 'power3.out' })
+ .to(this.bandZ.scale, { z: 1, duration: 0.55, ease: 'power3.out' }, '-=0.25')
+ .to(this.bow.scale, { x: 1, y: 1, z: 1, duration: 0.8, ease: 'back.out(2.4)', onStart: () => this.onTied?.() }, '-=0.15')
+ .to(this.group.position, { y: this.pos.y + 0.35, duration: 0.22, ease: 'power2.out' }, '-=0.5')
+ .to(this.group.position, { y: this.pos.y, duration: 0.5, ease: 'bounce.out' });
+ }
+
+ reset() {
+ if (!this.closed || this.busy) return;
+ this.busy = true;
+ const tl = gsap.timeline({ onComplete: () => { this.busy = false; this.closed = false; this.emit(); } });
+ tl.to(this.bow.scale, { x: 0.001, y: 0.001, z: 0.001, duration: 0.3, ease: 'power2.in' })
+ .to([this.bandX.scale], { x: 0.001, duration: 0.3, ease: 'power2.in' }, '-=0.1')
+ .to([this.bandZ.scale], { z: 0.001, duration: 0.3, ease: 'power2.in' }, '-=0.2')
+ .add(() => {
+ this.ribbon.visible = false;
+ if (this.lidCollider) { this.pat.world.removeCollider(this.lidCollider, true); this.lidCollider = null; }
+ // Anything that was resting on the lid slides off rather than dropping into the tray.
+ for (const e of this.pat.entries) {
+ if (e.state !== 'live') continue;
+ const p = this.pat.pos(e);
+ if (!this.over(p, 0.1) || p.y < this.pos.y + H - 0.2) continue;
+ const l = this.local(p.clone());
+ const d = new THREE.Vector3(Math.sign(l.x || 1) * 0.7, 0, 1).applyQuaternion(this.group.quaternion).normalize();
+ e.rb.setLinvel({ x: d.x * 4.5, y: 6, z: d.z * 4.5 }, true);
+ }
+ this.cooldownUntil = this.pat.time + 3;
+ })
+ .to(this.hinge.rotation, { x: this.lidOpen, duration: 0.8, ease: 'power3.inOut' })
+ .add(() => {
+ // Everyone out: the macarons pop from their slots back onto the marble.
+ this.cooldownUntil = this.pat.time + 2.6;
+ this.slots.forEach((e, i) => {
+ if (!e) return;
+ e.rb.setBodyType(RAPIER.RigidBodyType.Dynamic, true);
+ e.state = 'live';
+ const t0 = e.rb.translation();
+ e.rb.setTranslation({ x: t0.x, y: this.pos.y + H + e.T.hy + 0.05, z: t0.z }, true); // clear of the tray walls
+ e.sqv += 0.4;
+ // Out and away from the tray: each one leaves in the direction of its own slot, toward the front.
+ const d = new THREE.Vector3(SLOTS[i].x * 2.2, 0, SLOTS[i].z + 0.45).applyQuaternion(this.group.quaternion).normalize();
+ e.rb.setLinvel({ x: d.x * 2.9, y: 9 + Math.random() * 2, z: d.z * 2.4 }, true);
+ e.rb.setAngvel({ x: (Math.random() - 0.5) * 16, y: 0, z: (Math.random() - 0.5) * 16 }, true);
+ });
+ this.slots = this.slots.map(() => null);
+ this.emit();
+ }, '-=0.35');
+ }
+
+ emit() {
+ this.onChange?.({ slots: this.slots.map(e => e?.flavour ?? null), filled: this.filled, closed: this.closed, busy: this.busy });
+ }
+}
+
+let _clock = 0;
+const pat_time = () => (_clock = performance.now() / 1000);
diff --git a/examples/sucre/fx.js b/examples/sucre/fx.js
new file mode 100644
index 0000000..27627f1
--- /dev/null
+++ b/examples/sucre/fx.js
@@ -0,0 +1,142 @@
+// Small tactile effects: icing-sugar puffs and gold-leaf flakes (one GPU particle pool),
+// ripples on the marble when you knock, and the fingertip mark that shows where the cursor touches the counter.
+import { THREE } from '../../src/core/engine.js';
+
+export class Dust {
+ constructor(scene, N = 4000) {
+ this.N = N; this.head = 0;
+ const geo = new THREE.BufferGeometry();
+ this.aOrigin = new THREE.BufferAttribute(new Float32Array(N * 3).fill(-999), 3);
+ this.aVel = new THREE.BufferAttribute(new Float32Array(N * 3), 3);
+ this.aInfo = new THREE.BufferAttribute(new Float32Array(N * 4).fill(-99), 4); // birth, life, size, seed
+ this.aCol = new THREE.BufferAttribute(new Float32Array(N * 4), 4); // rgb, gravity
+ for (const a of [this.aOrigin, this.aVel, this.aInfo, this.aCol]) a.setUsage(THREE.DynamicDrawUsage);
+ geo.setAttribute('position', this.aOrigin);
+ geo.setAttribute('aVel', this.aVel);
+ geo.setAttribute('aInfo', this.aInfo);
+ geo.setAttribute('aCol', this.aCol);
+ this.mat = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false,
+ uniforms: { uTime: { value: 0 }, uScale: { value: 800 } },
+ vertexShader: /* glsl */`
+ attribute vec3 aVel; attribute vec4 aInfo; attribute vec4 aCol;
+ uniform float uTime, uScale;
+ varying float vA; varying vec3 vC; varying float vSeed; varying float vFlake;
+ void main(){
+ float age = uTime - aInfo.x;
+ float life = aInfo.y;
+ float k = clamp(age / life, 0.0, 1.0);
+ vFlake = step(1.5, aCol.w);
+ float drag = mix(3.2, 1.3, vFlake);
+ vec3 p = position + aVel * (1.0 - exp(-drag * age)) / drag;
+ p.y -= aCol.w * age * age * 0.5;
+ p.y = max(p.y, 0.012);
+ if (vFlake > 0.5) { p.x += sin(age * 7.0 + aInfo.w * 30.0) * 0.08 * k; p.z += cos(age * 6.0 + aInfo.w * 17.0) * 0.08 * k; }
+ vA = (age < 0.0 || age > life) ? 0.0 : smoothstep(0.0, 0.06, k) * (1.0 - smoothstep(0.35, 1.0, k));
+ if (vFlake > 0.5) vA = (age < 0.0 || age > life) ? 0.0 : (1.0 - smoothstep(0.7, 1.0, k)) * (0.55 + 0.45 * sin(age * 18.0 + aInfo.w * 40.0));
+ vC = aCol.rgb; vSeed = aInfo.w;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ float sz = aInfo.z * mix(1.0, 2.6, vFlake > 0.5 ? 0.0 : sqrt(k));
+ gl_PointSize = vA > 0.0 ? sz * uScale / -mv.z : 0.0;
+ }`,
+ fragmentShader: /* glsl */`
+ varying float vA; varying vec3 vC; varying float vSeed; varying float vFlake;
+ void main(){
+ vec2 d = gl_PointCoord - 0.5;
+ float r = length(d);
+ float a;
+ if (vFlake > 0.5) { a = step(abs(d.x) + abs(d.y) * 1.6, 0.42); }
+ else { a = exp(-r * r * 16.0) * (0.75 + 0.25 * fract(sin(dot(floor(gl_PointCoord * 5.0), vec2(12.9, 78.2)) + vSeed) * 4375.5)); }
+ if (a * vA < 0.01) discard;
+ gl_FragColor = vec4(vC, a * vA * (vFlake > 0.5 ? 1.0 : 0.55));
+ }`,
+ });
+ this.points = new THREE.Points(geo, this.mat);
+ this.points.frustumCulled = false;
+ this.points.renderOrder = 5;
+ scene.add(this.points);
+ this.dirty = false;
+ }
+
+ emit(p, n, { spread = 0.25, speed = 2.2, up = 1.1, life = 1.4, size = 0.1, color = [1, 0.985, 0.975], gravity = 0.25, time }) {
+ for (let j = 0; j < n; j++) {
+ const i = this.head; this.head = (this.head + 1) % this.N;
+ const a = Math.random() * Math.PI * 2, r = Math.random() * spread;
+ this.aOrigin.setXYZ(i, p.x + Math.cos(a) * r, p.y + Math.random() * 0.05, p.z + Math.sin(a) * r);
+ const s = speed * (0.35 + Math.random() * 0.65);
+ this.aVel.setXYZ(i, Math.cos(a) * s, up * (0.3 + Math.random()), Math.sin(a) * s);
+ this.aInfo.setXYZW(i, time + Math.random() * 0.03, life * (0.6 + Math.random() * 0.6), size * (0.6 + Math.random() * 0.8), Math.random());
+ const c = Array.isArray(color[0]) ? color[(Math.random() * color.length) | 0] : color;
+ this.aCol.setXYZW(i, c[0], c[1], c[2], gravity);
+ }
+ this.dirty = true;
+ }
+
+ update(t, h, fov) {
+ this.mat.uniforms.uTime.value = t;
+ this.mat.uniforms.uScale.value = h / (2 * Math.tan(fov * Math.PI / 360));
+ if (this.dirty) {
+ for (const a of [this.aOrigin, this.aVel, this.aInfo, this.aCol]) a.needsUpdate = true;
+ this.dirty = false;
+ }
+ }
+}
+
+/** Flat marks on the marble: expanding knock ripples and the fingertip ring. */
+export class Marks {
+ constructor(scene) {
+ const ringMat = (color, mode) => new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2,
+ uniforms: { uR: { value: 0.3 }, uW: { value: 0.03 }, uA: { value: 0 }, uFill: { value: 0 }, uC: { value: new THREE.Color(color) } },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv * 2.0 - 1.0; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
+ fragmentShader: `uniform float uR, uW, uA, uFill; uniform vec3 uC; varying vec2 vUv;
+ void main(){ float r = length(vUv); float ring = exp(-pow((r - uR) / uW, 2.0)); float fill = smoothstep(uR, uR * 0.2, r) * uFill;
+ float a = (ring + fill) * uA * smoothstep(1.0, 0.92, r); if (a < 0.003) discard; gl_FragColor = vec4(uC, a); }`,
+ });
+ this.tip = new THREE.Mesh(new THREE.PlaneGeometry(1.6, 1.6), ringMat(0x45202b));
+ this.tip.rotation.x = -Math.PI / 2;
+ this.tip.renderOrder = 4;
+ this.tip.material.uniforms.uR.value = 0.26; // in uv units of the 0.8 half-size plane
+ scene.add(this.tip);
+ this.ripples = [];
+ for (let i = 0; i < 5; i++) {
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(10, 10), ringMat(0x6d3a47));
+ m.rotation.x = -Math.PI / 2; m.visible = false; m.renderOrder = 4;
+ scene.add(m);
+ this.ripples.push({ m, t: 1e9 });
+ }
+ this.k = 0;
+ this.tipA = 0; this.tipTarget = 0; this.tipPress = 0;
+ }
+
+ ripple(p, t) {
+ const r = this.ripples[this.k++ % this.ripples.length];
+ r.m.position.set(p.x, 0.006, p.z); r.m.visible = true; r.t = t;
+ }
+
+ tipAt(p, visible, pressed, dt) {
+ this.tipTarget = visible ? 1 : 0;
+ this.tipA += (this.tipTarget - this.tipA) * (1 - Math.exp(-10 * dt));
+ this.tipPress += ((pressed ? 1 : 0) - this.tipPress) * (1 - Math.exp(-14 * dt));
+ if (p) this.tip.position.set(p.x, 0.005, p.z);
+ const u = this.tip.material.uniforms;
+ u.uA.value = this.tipA * 0.42;
+ u.uR.value = 0.44 - this.tipPress * 0.1;
+ u.uW.value = 0.018 + this.tipPress * 0.01;
+ u.uFill.value = 0.12 + this.tipPress * 0.2;
+ this.tip.visible = this.tipA > 0.01;
+ }
+
+ update(t) {
+ for (const r of this.ripples) {
+ if (!r.m.visible) continue;
+ const age = t - r.t;
+ if (age > 0.6) { r.m.visible = false; continue; }
+ const u = r.m.material.uniforms;
+ u.uR.value = 0.02 + age * 1.6; // ≈ the speed of the impulse wave (8 units/s on a 10-unit plane)
+ u.uW.value = 0.012 + age * 0.05;
+ u.uA.value = 0.34 * (1 - age / 0.6) ** 1.3;
+ }
+ }
+}
diff --git a/examples/sucre/index.html b/examples/sucre/index.html
new file mode 100644
index 0000000..afa16e0
--- /dev/null
+++ b/examples/sucre/index.html
@@ -0,0 +1,170 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Maison Sucre — Pâtisserie, rue du Bac, Paris</title>
+ <meta name="description" content="Macarons piped by hand on rue du Bac since 1962. Sugar, almonds, and a little gravity.">
+ <meta name="theme-color" content="#f6d9df">
+ <link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Cellipse cx='16' cy='11' rx='13' ry='6' fill='%23eea9b6'/%3E%3Crect x='5' y='14' width='22' height='5' rx='2.5' fill='%23fbeee6'/%3E%3Cellipse cx='16' cy='22' rx='13' ry='5.5' fill='%23e39aa9'/%3E%3C/svg%3E">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=DM+Sans:ital,opsz,wght@0,9..40,400;0,9..40,500;0,9..40,600;1,9..40,400&family=Playfair+Display:ital,wght@0,400;0,500;1,400;1,500;1,600&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-mac" aria-hidden="true"><i class="shell top"></i><i class="fill"></i><i class="shell bot"></i></div>
+ <p class="loader-line">Weighing the almonds</p>
+ <p class="loader-g"><span class="loader-pct">0</span> g <em>of 100 g</em></p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Maison Sucre home">
+ <span class="brand-mark" aria-hidden="true">MS</span>
+ <span class="brand-name">Maison <em>Sucre</em></span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#carte">La Carte</a>
+ <a href="#coffret">Build a box</a>
+ <a href="#atelier">L'Atelier</a>
+ <a href="#visit">Visit</a>
+ </nav>
+ <div class="nav-right">
+ <button class="sound" type="button" aria-pressed="false" aria-label="Sound"><i></i><i></i><i></i><i></i><span>Sound</span></button>
+ <a class="btn btn-solid nav-cta" href="#coffret" data-magnetic><span>Order a box</span></a>
+ </div>
+ </header>
+
+ <main>
+ <!-- 01 · Hero -->
+ <section class="stage hero" id="top" data-cam="hero">
+ <div class="hero-copy">
+ <p class="eyebrow"><span>Pâtisserie</span><span class="dot"></span><span>44 rue du Bac, Paris 7<sup>e</sup></span><span class="dot"></span><span>Depuis 1962</span></p>
+ <h1 class="title" aria-label="Sugar, almonds, and a little gravity.">
+ <span class="line">Sugar, almonds,</span>
+ <span class="line">and <em class="grav">a little</em></span>
+ <span class="line"><em class="grav">gravity.</em></span>
+ </h1>
+ <p class="sub">Every shell is piped by hand, rested for a night and filled the next morning. Then, now and again, we let them fall — just to watch them land.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#coffret" data-magnetic><span>Build a box of six</span></a>
+ <a class="btn btn-ghost" href="#carte" data-magnetic><span>See La Carte</span></a>
+ </div>
+ </div>
+ <ul class="hint" aria-hidden="true">
+ <li><b>Move</b> nudge the pastries</li>
+ <li><b>Drag</b> pick one up &amp; toss it</li>
+ <li><b>Click</b> knock on the marble</li>
+ <li><b>Hold</b> make it rain</li>
+ <li class="hint-touch"><b>Tap</b> knock · <b>Hold</b> rain · <b>Drag</b> toss</li>
+ </ul>
+ </section>
+
+ <!-- 02 · La Carte -->
+ <section class="stage carte" id="carte" data-cam="carte">
+ <div class="menu-card">
+ <p class="eyebrow center">La Carte · Printemps</p>
+ <h2>Today, <em>behind the glass.</em></h2>
+ <p class="menu-note">Hover a line and it will stand up on the counter to be counted.</p>
+ <h3 class="menu-group">Les macarons <span>€2.60 each</span></h3>
+ <ul class="menu">
+ <li data-hop="rose"><span class="sw" style="--c:#e7aab4"></span><span class="nm">Rose &amp; Litchi</span><span class="ds">Rose-petal ganache, a lychee heart</span></li>
+ <li data-hop="pistache"><span class="sw" style="--c:#bfc79a"></span><span class="nm">Pistache de Bronte</span><span class="ds">Sicilian pistachio, a pinch of fleur de sel</span></li>
+ <li data-hop="citron"><span class="sw" style="--c:#efd98c"></span><span class="nm">Citron de Menton</span><span class="ds">Lemon curd, candied zest, no apologies</span></li>
+ <li data-hop="violette"><span class="sw" style="--c:#b6a2c9"></span><span class="nm">Violette-Cassis</span><span class="ds">Blackcurrant jam, crystallised violet</span></li>
+ <li data-hop="chocolat"><span class="sw" style="--c:#7a4b3a"></span><span class="nm">Chocolat Grand Cru</span><span class="ds">70% Venezuelan ganache, cocoa nib</span></li>
+ <li data-hop="vanille"><span class="sw" style="--c:#f1e6cf"></span><span class="nm">Vanille de Tahiti</span><span class="ds">Three pods per litre of cream</span></li>
+ </ul>
+ <h3 class="menu-group">Le reste de la vitrine</h3>
+ <ul class="menu menu-priced">
+ <li data-hop="tart"><span class="nm">Tartelette aux fraises</span><span class="ds">Gariguette strawberries, vanilla crème, sablé breton</span><b>€7.80</b></li>
+ <li data-hop="croissant"><span class="nm">Croissant au beurre</span><span class="ds">AOP Charentes butter, 27 layers, out every 40 minutes</span><b>€2.20</b></li>
+ <li data-hop="berry"><span class="nm">Fraises Gariguette</span><span class="ds">By the punnet, April to June, while they last</span><b>€9 / 250 g</b></li>
+ <li data-hop="cake"><span class="nm">Le Grand Gâteau</span><span class="ds">Three tiers, sugar roses, raspberries — on commission</span><b>from €280</b></li>
+ </ul>
+ </div>
+ </section>
+
+ <!-- 03 · Build a box -->
+ <section class="stage coffret" id="coffret" data-cam="box">
+ <div class="coffret-sticky">
+ <div class="box-panel">
+ <p class="eyebrow">Coffret de six · €24</p>
+ <h2>Build a box. <em>We'll tie the ribbon.</em></h2>
+ <p class="box-lede">Drag any six macarons into the coffret. Mix freely — the only house rule is that no two boxes should ever be the same.</p>
+ <ol class="slots" aria-label="Your box">
+ <li></li><li></li><li></li><li></li><li></li><li></li>
+ </ol>
+ <p class="box-count"><b class="n">0</b> of 6 <span class="box-status">— the box is waiting</span></p>
+ <p class="box-flavours" aria-live="polite"></p>
+ <div class="box-actions">
+ <button class="btn btn-ghost fill-btn" type="button" data-magnetic><span>Fill it for me</span></button>
+ <a class="btn btn-solid order-btn" href="#visit" data-magnetic aria-disabled="true"><span>Order this box — €24</span></a>
+ </div>
+ <button class="reset-btn" type="button">Untie &amp; start again</button>
+ </div>
+ </div>
+ </section>
+
+ <!-- 04 · L'Atelier -->
+ <section class="stage atelier" id="atelier" data-cam="atelier">
+ <div class="atelier-copy">
+ <p class="eyebrow">L'Atelier · since 1962</p>
+ <h2>Sixty years on <em>rue du Bac.</em></h2>
+ <p class="lede">Odile Marchand opened the shop in the spring of 1962 with one oven, a copper basin and a recipe she refused to write down. Her granddaughter Camille still whips the meringue in that basin.</p>
+ <p class="body">What changed: the ovens, and the length of the queue on Saturday mornings. What didn't: the whites are aged for three days, the almonds are ground before sunrise, and every shell is piped by hand — by five people who could do it with their eyes closed, and occasionally do.</p>
+ <dl class="stats">
+ <div><dt>3 days</dt><dd>egg whites aged before a single shell is piped</dd></div>
+ <div><dt>4,000</dt><dd>shells piped by hand, every working day</dd></div>
+ <div><dt>24 h</dt><dd>resting in the cold room before we fill them</dd></div>
+ </dl>
+ <p class="sig">— Camille Marchand, <em>troisième génération</em></p>
+ </div>
+ </section>
+
+ <!-- 05 · Visit -->
+ <section class="stage visit" id="visit" data-cam="visit">
+ <div class="visit-head">
+ <p class="eyebrow">Visit · 44 rue du Bac</p>
+ <h2>Come hungry. <em>Leave with a box.</em></h2>
+ </div>
+ <div class="visit-card">
+ <div>
+ <h3>The shop</h3>
+ <p>44 rue du Bac<br>75007 Paris<br><span class="muted">Métro Rue du Bac, ligne 12</span></p>
+ </div>
+ <div>
+ <h3>Hours</h3>
+ <p>Tuesday – Saturday &nbsp;8:00 – 19:30<br>Sunday &nbsp;8:00 – 13:00<br><span class="muted">Monday closed — the ovens rest</span></p>
+ </div>
+ <div>
+ <h3>Orders &amp; commissions</h3>
+ <p>[email protected]<br>+33 1 45 48 19 62<br><span class="muted">Cakes need ten days' notice</span></p>
+ </div>
+ <a class="btn btn-solid" href="#coffret" data-magnetic><span>Order a box for collection</span></a>
+ </div>
+ </section>
+ </main>
+
+ <footer class="foot">
+ <div class="foot-inner">
+ <p class="foot-mark">Maison <em>Sucre</em></p>
+ <form class="letter" onsubmit="return false">
+ <label for="lettre">La Lettre Sucrée — one letter a season, first taste of new flavours.</label>
+ <div class="letter-row"><input id="lettre" type="email" placeholder="[email protected]" autocomplete="email"><button class="btn btn-solid" type="button"><span>Subscribe</span></button></div>
+ </form>
+ <div class="foot-row">
+ <span>© 1962 – 2026 Maison Sucre, Paris</span>
+ <span class="foot-links"><a href="#carte">La Carte</a><a href="#coffret">Coffrets</a><a href="#atelier">L'Atelier</a><a href="#visit">Visit</a></span>
+ <span>Made with butter, not margarine.</span>
+ </div>
+ </div>
+ </footer>
+
+ <div class="toast" role="status"></div>
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/sucre/main.js b/examples/sucre/main.js
new file mode 100644
index 0000000..ec0551f
--- /dev/null
+++ b/examples/sucre/main.js
@@ -0,0 +1,571 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { DepthOfFieldEffect, BrightnessContrastEffect, HueSaturationEffect } from 'postprocessing';
+import { buildSet, windowCookie, COUNTER } from './set.js';
+import { Patisserie, TYPES, FLAVOURS } from './pastry.js';
+import { Coffret } from './coffret.js';
+import { Dust, Marks } from './fx.js';
+import { Foley } from './sound.js';
+
+const DBG = new URLSearchParams(location.search);
+const isTouch = matchMedia('(pointer: coarse)').matches;
+const CAKE_POS = new THREE.Vector3(2.7, 0, -0.9);
+const PILE = { x: 2.3, z: 1.75 };
+const BOX_POS = new THREE.Vector3(11.2, 0, 1.15);
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+let dof;
+const engine = new Engine({
+ canvas, fov: 30, near: 0.1, far: 120, dpr: 1.5, background: 0xf3d3da,
+ post: {
+ ao: { aoRadius: 0.55, intensity: 2.4, distanceFalloff: 0.6 },
+ bloom: { intensity: 0.32, luminanceThreshold: 0.92, luminanceSmoothing: 0.25, radius: 0.7 },
+ pre: cam => (DBG.has('nodof') ? [] : [(dof = new DepthOfFieldEffect(cam, { focusDistance: 12, focusRange: 6, bokehScale: 1.4, resolutionScale: 0.5 }))]),
+ tone: 'neutral',
+ extra: () => [new BrightnessContrastEffect({ brightness: 0.0, contrast: 0.09 }), new HueSaturationEffect({ saturation: -0.04 })],
+ vignette: { offset: 0.34, darkness: 0.36 },
+ noise: 0.035,
+ ca: 0.0005,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.shadowMap.type = THREE.PCFShadowMap;
+scene.environment = studioEnvironment(renderer, {
+ top: 0xf6e4e6, bottom: 0xb98f98,
+ panels: [
+ { pos: [-8, 7, 6], size: [5, 7], intensity: 5.5, color: 0xfff4e8 }, // the window
+ { pos: [0, 10, 2], size: [8, 3], intensity: 2.2, color: 0xffffff }, // ceiling bounce
+ { pos: [8, 4, -5], size: [2.5, 6], intensity: 2.6, color: 0xffe6ec }, // rim card
+ { pos: [4, 2, 9], size: [6, 3], intensity: 1.4, color: 0xffeef0 }, // front fill card
+ ],
+});
+scene.environmentIntensity = 0.36;
+scene.fog = new THREE.Fog(0xf3d3da, 40, 95);
+
+const assets = new Assets();
+const foley = new Foley();
+const soundBtn = document.querySelector('.sound');
+soundBtn.addEventListener('click', () => { foley.enable(!foley.on); soundBtn.setAttribute('aria-pressed', String(foley.on)); soundBtn.querySelector('span').textContent = foley.on ? 'Sound on' : 'Sound'; });
+const pointer = new Pointer({ lambda: 8 });
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1500,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ },
+ exit: async () => {
+ await gsap.timeline()
+ .to('.loader-mac, .loader-line, .loader-g', { y: -18, opacity: 0, duration: 0.5, ease: 'power2.in', stagger: 0.05 })
+ .to(loaderEl, { yPercent: -100, duration: 1.1, ease: 'expo.inOut' }, '-=0.1');
+ },
+});
+
+// ─── Lights: window key with a cookie, rim card, soft fill ────────────────────
+const key = new THREE.SpotLight(0xfff4ea, 5.6, 0, 0.5, 0.3, 0);
+key.position.set(-12, 17.5, 15.5);
+key.target.position.set(4.5, 0, -0.5);
+key.map = windowCookie();
+key.castShadow = true;
+key.shadow.mapSize.set(4096, 4096);
+key.shadow.camera.near = 12; key.shadow.camera.far = 60;
+key.shadow.bias = -0.00012; key.shadow.normalBias = 0.02;
+key.shadow.radius = 5;
+key.shadow.blurSamples = 16;
+scene.add(key, key.target);
+const rim = new THREE.SpotLight(0xffe4ea, 60, 26, 0.6, 0.8, 1.2);
+rim.position.set(7, 11, -2.6);
+rim.target.position.set(2, 1.5, 0.5);
+scene.add(rim, rim.target);
+const hemi = new THREE.HemisphereLight(0xfff3f1, 0xd8a9b3, 0.16);
+scene.add(hemi);
+// Beauty light: a soft warm pool on the cake, the way a cover shoot would flag the subject.
+const beauty = new THREE.SpotLight(0xfff0e4, 70, 30, 0.2, 0.9, 1.4);
+beauty.position.set(-1.5, 12, 9);
+beauty.target.position.set(2.7, 2.2, -0.9);
+scene.add(beauty, beauty.target);
+
+// ─── Set ───────────────────────────────────────────────────────────────────────
+const set = buildSet(renderer, scene);
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+reflection.hidden.push(set.top);
+if (!DBG.has('norefl')) reflection.patch(set.marble, { strength: 0.9, distort: 0.004, lodScale: 5.5, lodBias: 0.2, f0: 0.045 });
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+
+// ─── Physics & pastries ───────────────────────────────────────────────────────
+const pat = new Patisserie(scene);
+const physicsReady = pat.init();
+const dust = new Dust(scene);
+const marks = new Marks(scene);
+
+const typeLoads = TYPES.map(def => Promise.all([assets.gltf(def.file), assets.gltf(def.shadow).catch(() => null)]).then(([g, s]) => ({ def, g, s })));
+let cake, cakeSpin = { v: 0.14 };
+const cakeLoad = assets.gltf('models/sucre/cake.glb').then(g => {
+ const m = g.scene;
+ normalize(m, 4.3, { axis: 'y' });
+ prepModel(m, renderer, { env: 0.9, onMat: mat => warmFrosting(mat) });
+ cake = new THREE.Group();
+ cake.position.copy(CAKE_POS);
+ cake.add(m);
+ scene.add(cake);
+ m.updateMatrixWorld(true);
+ const bb = new THREE.Box3().setFromObject(m);
+ if (DBG.has('log')) console.log('cake bb', bb.min.toArray(), bb.max.toArray());
+});
+
+// The model's buttercream bakes out grey-beige; warm the pale, unsaturated texels (frosting, ruffles, sugar roses)
+// toward the pink cream of the reference plate. Berries, leaves and gold leaf are saturated and stay as they are;
+// the porcelain stand (below the first tier) stays white.
+function warmFrosting(mat) {
+ mat.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying float vCakeY;')
+ .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvCakeY = (modelMatrix * vec4(transformed, 1.0)).y;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying float vCakeY;')
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ {
+ vec3 s = pow(max(diffuseColor.rgb, 0.0), vec3(1.0 / 2.2));
+ float lum = dot(s, vec3(0.299, 0.587, 0.114));
+ float sat = max(s.r, max(s.g, s.b)) - min(s.r, min(s.g, s.b));
+ float m = smoothstep(0.24, 0.5, lum) * (1.0 - smoothstep(0.12, 0.28, sat)) * smoothstep(1.02, 1.2, vCakeY);
+ vec3 cream = vec3(1.0, 0.905, 0.865) * min(1.0, lum * 1.2 + 0.07);
+ diffuseColor.rgb = pow(mix(s, cream, m * 0.92), vec3(2.2));
+ }`);
+ };
+ mat.customProgramCacheKey = () => 'sucre-cake-cream';
+ mat.needsUpdate = true;
+}
+
+// ─── Coffret UI ───────────────────────────────────────────────────────────────
+const toastEl = document.querySelector('.toast');
+let toastTimer;
+function toast(msg, ms = 2600) {
+ toastEl.textContent = msg;
+ toastEl.classList.add('on');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+const slotsEl = [...document.querySelectorAll('.slots li')];
+const countEl = document.querySelector('.box-count .n');
+const statusEl = document.querySelector('.box-status');
+const flavEl = document.querySelector('.box-flavours');
+const orderBtn = document.querySelector('.order-btn');
+const coffretEl = document.querySelector('.coffret');
+let lastFilled = 0;
+function renderBox(s) {
+ slotsEl.forEach((li, i) => {
+ const f = s.slots[i];
+ li.classList.toggle('on', !!f);
+ li.style.setProperty('--c', f ? FLAVOURS[f].css : 'transparent');
+ li.title = f ? FLAVOURS[f].name : 'Empty';
+ });
+ countEl.textContent = s.filled;
+ statusEl.textContent = s.closed ? '— tied with a ribbon, ready for you' : s.filled === 0 ? '— the box is waiting' : s.filled < 6 ? `— ${6 - s.filled} more to go` : '— closing the lid…';
+ const tally = {};
+ s.slots.forEach(f => { if (f) tally[f] = (tally[f] || 0) + 1; });
+ flavEl.textContent = Object.entries(tally).map(([f, n]) => `${n} ${FLAVOURS[f].name}`).join(' · ') || 'Pick a flavour. Any flavour.';
+ const ready = s.closed && !s.busy;
+ orderBtn.setAttribute('aria-disabled', s.closed ? 'false' : 'true');
+ orderBtn.classList.toggle('ready', ready);
+ coffretEl.classList.toggle('is-closed', ready);
+ if (s.closed && !s.busy && lastFilled !== 7) { toast('Tied with a ribbon. Your coffret is ready — €24.', 3200); lastFilled = 7; }
+ else if (!s.closed) lastFilled = s.filled;
+}
+
+// ─── Camera choreography ──────────────────────────────────────────────────────
+const V = (x, y, z) => new THREE.Vector3(x, y, z);
+const KEYS = {
+ hero: { pos: V(0.3, 2.75, 13.2), look: V(1.05, 2.05, 0), fov: 30, focus: V(2.7, 1.8, 0), range: 7, bokeh: 1.2, subject: V(2.7, 1.6, 0), m: { pos: V(2.4, 5.6, 19.5), look: V(2.45, 4.25, 0) } },
+ carte: { pos: V(0.1, 1.2, 9.3), look: V(1.25, 0.85, 1.2), fov: 22, focus: V(2.0, 0.3, 2.1), range: 2.2, bokeh: 3.2, subject: V(2.3, 0.6, 1.6), m: { pos: V(2.2, 3.0, 15.5), look: V(2.35, -0.35, 1.5) } },
+ box: { pos: V(11.9, 7.5, 6.0), look: V(10.2, 0, 1.15), fov: 30, focus: V(11.2, 0.2, 1.2), range: 8, bokeh: 0.8, subject: V(11.2, 0.3, 1.2), m: { pos: V(11.2, 14.5, 10.4), look: V(11.2, 0, 3.7) } },
+ atelier: { pos: V(9.6, 2.5, 8.4), look: V(4.3, 2.3, -2.1), fov: 28, focus: V(2.7, 2.0, -0.9), range: 5, bokeh: 1.6, subject: V(2.7, 2.1, -0.9), m: { pos: V(7.4, 3.9, 15), look: V(2.8, 0.6, -0.9) } },
+ visit: { pos: V(9.2, 6.1, 19.5), look: V(7.2, 2.3, 0.4), fov: 30, focus: V(6.5, 0.8, 1), range: 14, bokeh: 0.8, subject: V(6, 0.8, 0.6) },
+};
+const stages = [...document.querySelectorAll('[data-cam]')].map(el => ({ el, key: KEYS[el.dataset.cam], name: el.dataset.cam, a: 0, b: 0 }));
+function measure() {
+ for (const s of stages) {
+ const r = s.el.getBoundingClientRect();
+ s.a = r.top + scrollY;
+ s.b = Math.max(s.a, s.a + r.height - innerHeight);
+ }
+}
+addEventListener('resize', measure);
+const easeIO = t => (t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2);
+const cam = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fov: 30, focus: 12, range: 6, bokeh: 1 };
+const tmpA = new THREE.Vector3(), tmpB = new THREE.Vector3(), tmpC = new THREE.Vector3();
+function keyFrame(k, out) {
+ // Portrait screens: back off along the view line and centre on the subject.
+ const asp = camera.aspect;
+ out.look.copy(k.look); out.pos.copy(k.pos);
+ if (asp < 0.8 && k.m) { out.look.copy(k.m.look); out.pos.copy(k.m.pos); }
+ else if (asp < 1) {
+ out.look.lerp(k.subject, 0.85);
+ tmpC.subVectors(k.pos, k.look);
+ out.pos.copy(out.look).addScaledVector(tmpC, Math.pow(1 / asp, 0.62));
+ }
+ out.fov = k.fov; out.range = k.range; out.bokeh = k.bokeh;
+ out.focus = out.pos.distanceTo(k.focus);
+ return out;
+}
+const kfA = { pos: new THREE.Vector3(), look: new THREE.Vector3() }, kfB = { pos: new THREE.Vector3(), look: new THREE.Vector3() };
+let stageIdx = 0, stageF = 0;
+function sampleCamera(y, out) {
+ let i = 0;
+ while (i < stages.length - 1 && y > stages[i].b) i++;
+ // y is in (stages[i-1].b, stages[i].a] → transition from i-1 to i; else holding at i
+ if (i > 0 && y < stages[i].a) {
+ const A = stages[i - 1], B = stages[i];
+ const f = easeIO(clamp((y - A.b) / (B.a - A.b)));
+ keyFrame(A.key, kfA); keyFrame(B.key, kfB);
+ out.pos.lerpVectors(kfA.pos, kfB.pos, f);
+ out.look.lerpVectors(kfA.look, kfB.look, f);
+ out.pos.y += Math.sin(f * Math.PI) * 0.9;
+ out.fov = lerp(kfA.fov, kfB.fov, f); out.focus = lerp(kfA.focus, kfB.focus, f);
+ out.range = lerp(kfA.range, kfB.range, f); out.bokeh = lerp(kfA.bokeh, kfB.bokeh, f);
+ stageIdx = f < 0.5 ? i - 1 : i; stageF = f;
+ } else {
+ keyFrame(stages[i].key, out);
+ stageIdx = i; stageF = 1;
+ }
+ return out;
+}
+const camTarget = { pos: new THREE.Vector3(), look: new THREE.Vector3(), fov: 30, focus: 12, range: 6, bokeh: 1 };
+
+// ─── Pointer: fingertip, pick-up & toss, knock ────────────────────────────────
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const plane = new THREE.Plane();
+const hit = new THREE.Vector3();
+const CURSOR_Y = 0.3;
+let overCanvas = false, dragging = null, downAt = null, hoverE = null;
+const dragPlane = new THREE.Plane();
+let cur = null;
+function rayFrom(px, py) {
+ ndc.set(px / innerWidth * 2 - 1, -(py / innerHeight) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ return ray.ray;
+}
+function counterHit(r, y = CURSOR_Y, out = hit) {
+ plane.set(tmpA.set(0, 1, 0), -y);
+ return r.intersectPlane(plane, out);
+}
+function pickAt(px, py) {
+ const r = rayFrom(px, py);
+ return pat.pick(r.origin, r.direction);
+}
+addEventListener('pointermove', e => { overCanvas = e.target === canvas; }, { passive: true });
+canvas.addEventListener('pointerleave', () => { overCanvas = false; });
+canvas.addEventListener('pointerdown', e => {
+ if (e.button !== 0 || !started) return;
+ const p = pickAt(e.clientX, e.clientY);
+ downAt = { x: e.clientX, y: e.clientY, t: performance.now(), pick: p };
+ if (p) startDrag(p.e);
+ else rainHold = { t0: engine.time, next: 0, n: 0 };
+});
+// Hold on the marble: pastries rain onto that spot, borrowed from wherever the camera is not looking.
+let rainHold = null;
+const frustum = new THREE.Frustum(), projM = new THREE.Matrix4(), sph = new THREE.Sphere();
+function inView(e) { sph.center.copy(pat.pos(e, sph.center)); sph.radius = 0.4; return frustum.intersectsSphere(sph); }
+function updateRainHold(t) {
+ if (!rainHold) return;
+ if (!pointer.down || !downAt || Math.hypot(pointer.px - downAt.x, pointer.py - downAt.y) > 14) { if (!pointer.down) rainHold = null; return; }
+ if (t - rainHold.t0 < 0.32 || t < rainHold.next) return;
+ if (!counterHit(ray.ray, 0, tmpC)) return;
+ const burst = rainHold.n < 3 ? 2 : 1;
+ rainHold.n++;
+ rainHold.next = t + 0.075;
+ projM.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse); frustum.setFromProjectionMatrix(projM);
+ pat.rain({ x: tmpC.x, z: tmpC.z, rx: 0.32, rz: 0.32, count: burst, over: 0.05, height: [6, 7.5], vy: -6,
+ pick: e => e.state === 'live' || e.state === 'parked', prefer: e => !inView(e) });
+ if (rainHold.n === 1) { document.body.classList.add('is-raining'); hintUsed(); }
+}
+// On touch screens, touching a pastry holds it instead of scrolling the page.
+canvas.addEventListener('touchstart', e => {
+ const t = e.touches[0];
+ if (t && started && pickAt(t.clientX, t.clientY)) e.preventDefault();
+}, { passive: false });
+const lift = { v: 0 };
+let dragT0 = 0;
+function startDrag(e) {
+ pat.grab(e);
+ pat.holdActive = false;
+ dragT0 = engine.time;
+ dragging = e;
+ const p = pat.pos(e);
+ const fwd = camera.getWorldDirection(tmpB);
+ // Looking down at the counter: drag on a raised horizontal plane. Looking across it: on an upright plane.
+ if (Math.abs(fwd.y) > 0.5) dragPlane.set(tmpA.set(0, 1, 0), -(Math.max(p.y, 0.3) + 1.1));
+ else { tmpA.set(-fwd.x, 0, -fwd.z).normalize(); dragPlane.setFromNormalAndCoplanarPoint(tmpA, p); }
+ lift.v = 0;
+ gsap.to(lift, { v: 1, duration: 0.35, ease: 'power2.out' });
+ cur?.set('drag', 'Toss');
+ document.body.classList.add('is-dragging');
+ hintUsed();
+}
+addEventListener('pointerup', e => {
+ const tap = downAt && Math.hypot(e.clientX - downAt.x, e.clientY - downAt.y) < 8 && performance.now() - downAt.t < 380;
+ if (rainHold) { rainHold = null; document.body.classList.remove('is-raining'); }
+ if (dragging) {
+ const e2 = pat.release();
+ if (e2 && coffret && !tap) coffret.releasedOver(e2);
+ dragging = null;
+ document.body.classList.remove('is-dragging');
+ cur?.set('');
+ }
+ if (tap && (e.target === canvas || downAt.pick)) {
+ // A tap is a knuckle on the marble; on a pastry, it knocks right beneath it.
+ const r = rayFrom(e.clientX, e.clientY);
+ if (downAt.pick) knockAt(pat.pos(downAt.pick.e, tmpC).setY(0).clone());
+ else if (counterHit(r, 0, tmpC)) knockAt(tmpC.clone());
+ }
+ downAt = null;
+});
+function knockAt(p) {
+ pat.knock(p);
+ foley.knock();
+ marks.ripple(p, engine.time);
+ dust.emit(p, 26, { spread: 0.12, speed: 2.6, up: 0.9, size: 0.09, life: 1.1, time: engine.time });
+ hintUsed();
+}
+let hintDone = false;
+function hintUsed() {
+ if (hintDone) return;
+ hintDone = true;
+ setTimeout(() => document.querySelector('.hint')?.classList.add('used'), 2500);
+}
+
+// ─── Menu hover: the line you hover stands up on the counter ──────────────────
+const hopPick = {
+ tart: e => e.T.def.key === 'tart', croissant: e => e.T.def.key === 'croissant', berry: e => e.T.def.key === 'berry',
+};
+let lastHop = {};
+document.querySelectorAll('[data-hop]').forEach(li => {
+ const k = li.dataset.hop;
+ li.addEventListener('pointerenter', () => {
+ if (!started || engine.time - (lastHop[k] ?? -9) < 0.9) return;
+ lastHop[k] = engine.time;
+ if (k === 'cake') {
+ gsap.timeline().to(cakeSpin, { v: 7, duration: 0.5, ease: 'power2.in' }).to(cakeSpin, { v: 0.14, duration: 1.6, ease: 'power3.out' });
+ pat.hop(() => true, { strength: 0.45, spread: 0.5 });
+ return;
+ }
+ const pick = hopPick[k] ?? (e => e.flavour === k);
+ const n = pat.hop(pick, { strength: 1, spread: 0.3 });
+ if (n === 0) {
+ const src = k in hopPick ? { tart: 'tart', croissant: 'croissant', berry: 'berry' }[k] : null;
+ pat.rain({ x: PILE.x - 0.5, z: PILE.z, rx: 1.4, rz: 0.8, count: 4, over: 0.6, height: [5, 7], pick: src ? e => e.T.def.key === src : e => e.flavour === k });
+ }
+ });
+});
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const footEl = document.querySelector('.foot');
+const navLinks = [...document.querySelectorAll('.links a')];
+let started = false, coffret = null;
+const visited = new Set();
+let impactsThisFrame = 0;
+pat.onImpact = (e, tr, sp) => {
+ const k = e.T.def.key;
+ foley.land(k, sp);
+ if (impactsThisFrame++ > 6 || sp < 7) return;
+ const n = Math.round(clamp((sp - 6) * 0.9, 2, 9));
+ const col = k === 'croissant' ? [[0.86, 0.6, 0.32], [0.95, 0.78, 0.5], [0.7, 0.44, 0.2]] : k === 'tart' ? [0.99, 0.975, 0.96] : [1, 0.985, 0.975];
+ dust.emit({ x: tr.x, y: Math.max(0.02, tr.y - e.T.hy), z: tr.z }, k === 'croissant' ? n * 2 : n, {
+ spread: 0.18, speed: 1.4 + sp * 0.08, up: 0.6, size: k === 'croissant' ? 0.035 : 0.06, life: k === 'croissant' ? 1.0 : 1.2,
+ color: k === 'croissant' ? col : [0.86, 0.84, 0.83], gravity: k === 'croissant' ? 9 : 0.2, time: engine.time,
+ });
+};
+pat.onLost = e => {
+ // A pastry fell off the counter: it comes back as rain where the camera is looking.
+ if (!started) return;
+ const z = stageZone();
+ pat.rain({ x: z.x, z: z.z, rx: z.rx, rz: z.rz, count: 1, over: 0, delay: 0.6 + Math.random(), pick: x => x === e, avoid: z.avoid });
+};
+function stageZone() {
+ const n = stages[stageIdx]?.name;
+ if (n === 'box') return { x: BOX_POS.x + 0.2, z: BOX_POS.z + 0.5, rx: 2.3, rz: 1.35, avoid: (x, z) => coffret?.over(tmpA.set(x, 0, z), 0.3) || x < BOX_POS.x - 2.2 };
+ if (n === 'visit') return { x: 6.5, z: 1.6, rx: 6, rz: 1.5 };
+ return { x: PILE.x, z: PILE.z, rx: 2.4, rz: 1.3 };
+}
+function onStage(name) {
+ if (!started) return;
+ navLinks.forEach(a => a.classList.toggle('on', a.getAttribute('href') === '#' + ({ hero: 'top', carte: 'carte', box: 'coffret', atelier: 'atelier', visit: 'visit' }[name])));
+ if (visited.has(name)) return;
+ visited.add(name);
+ if (name === 'box') {
+ const macs = e => (e.T.def.key === 'macA' || e.T.def.key === 'macB');
+ const z = stageZone();
+ pat.rain({ x: z.x, z: z.z, rx: 2.4, rz: 1.25, count: 16, over: 1.6, delay: 0.25, pick: e => macs(e) && e.state !== 'boxed', avoid: z.avoid, height: [9, 13] });
+ pat.rain({ x: z.x + 1.2, z: z.z, rx: 2.4, rz: 1.1, count: 5, over: 1.4, delay: 0.6, pick: e => e.T.def.key === 'berry', avoid: z.avoid, height: [9, 12] });
+ }
+ if (name === 'visit') {
+ pat.rain({ x: 6.2, z: 1.9, rx: 5.5, rz: 1.4, count: 26, over: 2.4, delay: 0.3, pick: e => e.state !== 'boxed', height: [10, 15], avoid: (x, z) => coffret?.over(tmpA.set(x, 0, z), 0.3) });
+ }
+}
+let lastStage = -1;
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ impactsThisFrame = 0;
+
+ // Camera from scroll, with a little hand-held float and pointer parallax.
+ sampleCamera(scrollY, camTarget);
+ const k = 1 - Math.exp(-6 * dt);
+ cam.pos.lerp(camTarget.pos, k); cam.look.lerp(camTarget.look, k);
+ cam.fov = lerp(cam.fov, camTarget.fov, k); cam.focus = lerp(cam.focus, camTarget.focus, k);
+ cam.range = lerp(cam.range, camTarget.range, k); cam.bokeh = lerp(cam.bokeh, camTarget.bokeh, k);
+ const par = dragging ? 0 : 1;
+ camera.position.copy(cam.pos).add(tmpA.set(pointer.sx * 0.22 * par + Math.sin(t * 0.3) * 0.03, pointer.sy * 0.1 * par + Math.sin(t * 0.47) * 0.02, 0));
+ camera.lookAt(cam.look);
+ if (Math.abs(camera.fov - cam.fov) > 0.01) { camera.fov = cam.fov; camera.updateProjectionMatrix(); }
+ if (dof) {
+ dof.cocMaterial.focusDistance = cam.focus;
+ dof.cocMaterial.focusRange = cam.range;
+ dof.bokehScale = cam.bokeh;
+ }
+ if (stageIdx !== lastStage) { lastStage = stageIdx; onStage(stages[stageIdx].name); }
+
+ // Pointer → fingertip on the counter, hover pick, drag target.
+ const r = ray.ray;
+ ndc.set(pointer.x, pointer.y);
+ ray.setFromCamera(ndc, camera);
+ let tipP = null;
+ if (started) {
+ if (dragging) {
+ if (!pat.holdActive && downAt && (Math.hypot(pointer.px - downAt.x, pointer.py - downAt.y) > 7 || t - dragT0 > 0.2)) pat.holdActive = true;
+ if (r.intersectPlane(dragPlane, tmpB)) {
+ if (dragPlane.normal.y < 0.5) tmpB.y += lift.v * 0.6;
+ tmpB.y = clamp(tmpB.y, 0.35, 7);
+ tmpB.x = clamp(tmpB.x, COUNTER.x0 + 0.5, COUNTER.x1 - 0.5);
+ tmpB.z = clamp(tmpB.z, COUNTER.z0 + 0.4, COUNTER.z1 + 0.6);
+ pat.holdTarget.copy(tmpB);
+ }
+ tipP = pat.pos(dragging, tmpC); tipP.y = 0;
+ marks.tipAt(tipP, true, true, dt);
+ } else {
+ const onC = overCanvas && pointer.active && !isTouch;
+ if (onC && counterHit(r)) {
+ pat.setCursor(hit, true);
+ tipP = hit;
+ } else pat.setCursor(null, false);
+ // Hover label over pastries (cheap Rapier ray).
+ const h = onC ? pat.pick(r.origin, r.direction) : null;
+ const he = h?.e ?? null;
+ if (he !== hoverE) { hoverE = he; cur?.set(he ? 'drag' : '', he ? 'Pick up' : ''); }
+ marks.tipAt(tipP, onC && !he, pointer.down, dt);
+ }
+ }
+
+ // Cake turns on its stand (kinematic, so anything resting on a tier turns with it).
+ if (pat.cake) {
+ pat.cake.setAngvel({ x: 0, y: cakeSpin.v, z: 0 }, true);
+ const q = pat.cake.rotation();
+ cake?.quaternion.set(q.x, q.y, q.z, q.w);
+ }
+ if (started) {
+ updateRainHold(t);
+ pat.update(dt);
+ coffret?.update(dt);
+ }
+ dust.update(t, engine.size.h * engine.size.dpr, camera.fov);
+ marks.update(t);
+
+ if (!DBG.has('norefl')) reflection.update(scene, camera);
+ engine.paused = footEl.getBoundingClientRect().top <= 0;
+});
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+worldNav('sucre', { theme: 'light', corner: 'bl' });
+cur = cursor({ color: '#45202b', blend: 'normal', size: 32 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.085 });
+// Split the gravity words into letters that will fall into place.
+document.querySelectorAll('.grav').forEach(el => {
+ el.innerHTML = el.textContent.split(' ').map(w => `<span class="w">${[...w].map(c => `<span class="ch">${c}</span>`).join('')}</span>`).join(' ');
+});
+reveal('.stage h2', { type: 'lines', stagger: 0.08 });
+reveal('.atelier .lede', { type: 'lines', stagger: 0.05, y: '100%' });
+
+document.querySelector('.fill-btn').addEventListener('click', () => coffret?.fillForMe());
+document.querySelector('.reset-btn').addEventListener('click', () => coffret?.reset());
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href');
+ const el = id === '#top' ? document.body : document.querySelector(id);
+ if (!el) return;
+ e.preventDefault();
+ lenis.scrollTo(id === '#top' ? 0 : el, { duration: 2.2, easing: t => 1 - Math.pow(1 - t, 4) });
+}));
+
+const [types] = await Promise.all([Promise.all(typeLoads), physicsReady, cakeLoad, document.fonts.ready]);
+await Promise.all([document.fonts.load('italic 500 80px "Playfair Display"'), document.fonts.load('600 20px "DM Sans"')]).catch(() => {});
+for (const { def, g, s } of types) pat.addType(def, g, s);
+if (DBG.has('log')) for (const k in pat.types) console.log(k, pat.types[k].dim.toArray().map(v => v.toFixed(3)).join(','), 'hy', pat.types[k].hy.toFixed(3));
+// Cake colliders: stand, plate and three tiers (measured from the model's proportions).
+pat.addCake(CAKE_POS, [
+ { y: 0, h: 0.7, r: 0.5 }, { y: 0.7, h: 0.4, r: 1.28 }, { y: 1.1, h: 0.82, r: 0.9 }, { y: 1.92, h: 0.84, r: 0.74 }, { y: 2.76, h: 0.9, r: 0.56 },
+]);
+coffret = new Coffret({ scene, renderer, pat, pos: BOX_POS, onChange: renderBox, toast });
+coffret.onTied = () => foley.chime();
+coffret.onLand = (e, p) => (foley.land('macA', 14), dust.emit({ x: p.x, y: 0.1, z: p.z }, 10, { spread: 0.2, speed: 1.2, up: 0.5, size: 0.06, life: 0.9, time: engine.time }));
+coffret.onThud = () => {
+ foley.paper();
+ const p = coffret.pos;
+ dust.emit({ x: p.x, y: 0.5, z: p.z }, 70, { spread: 1.1, speed: 3.2, up: 3.2, size: 0.05, life: 2.2, gravity: 2.5, color: [[0.93, 0.8, 0.48], [0.99, 0.9, 0.62], [0.8, 0.62, 0.3]], time: engine.time });
+ pat.knock(p, { radius: 3.2, strength: 0.55 });
+};
+measure();
+sampleCamera(scrollY, cam);
+camera.position.copy(cam.pos); camera.lookAt(cam.look);
+
+// Warm up every program (pastries visible, dust alive) before the first frame.
+for (const k in pat.types) { const T = pat.types[k]; for (const e of T.entries) T.im.setMatrixAt(e.i, new THREE.Matrix4().makeTranslation(PILE.x, 0.3, PILE.z)); T.im.instanceMatrix.needsUpdate = true; }
+dust.emit(new THREE.Vector3(0, -50, 0), 4, { time: -100 });
+renderer.compile(scene, camera);
+for (const k in pat.types) { const T = pat.types[k]; for (const e of T.entries) T.im.setMatrixAt(e.i, new THREE.Matrix4().makeScale(0, 0, 0)); T.im.instanceMatrix.needsUpdate = true; }
+engine.start();
+window.__sucre = {
+ pat, coffret, engine, knockAt, lenis,
+ // QA helpers: screen position (0..1) of the live pastry of a kind nearest the screen centre.
+ find(kind = 'macB') {
+ let best = null, bd = 9;
+ for (const e of pat.entries) {
+ if (e.state !== 'live' || (e.T.def.key !== kind && e.flavour !== kind)) continue;
+ const v = pat.pos(e).project(camera);
+ const d = Math.hypot(v.x - 0.2, v.y + 0.3);
+ if (Math.abs(v.x) < 0.95 && Math.abs(v.y) < 0.95 && d < bd) { bd = d; best = [(v.x + 1) / 2, (1 - v.y) / 2]; }
+ }
+ return best;
+ },
+ emptySpot(y = 0.82) {
+ for (let x = 0.5; x < 0.95; x += 0.02) {
+ const r = rayFrom(x * innerWidth, y * innerHeight);
+ if (!pat.pick(r.origin, r.direction) && !pickAt(x * innerWidth + 30, y * innerHeight) && !pickAt(x * innerWidth - 30, y * innerHeight)) return [x, y];
+ }
+ return [0.3, 0.92];
+ },
+};
+await loader.finish();
+started = true;
+lastStage = -1;
+setTimeout(measure, 300);
+
+// Intro: the title settles, then the pastries rain around the cake — a few land on its tiers.
+const heroRain = () => {
+ pat.rain({ x: PILE.x + 0.2, z: PILE.z, rx: 1.7, rz: 0.8, count: 30, over: 2.6, delay: 0.1, pick: e => e.T.def.key === 'macA' || e.T.def.key === 'macB', height: [7, 12] });
+ pat.rain({ x: PILE.x + 0.3, z: PILE.z + 0.2, rx: 2.9, rz: 1.1, count: 12, over: 2.4, delay: 0.4, pick: e => e.T.def.key === 'macA' || e.T.def.key === 'macB', height: [7, 11] });
+ pat.rain({ x: PILE.x + 0.4, z: PILE.z, rx: 2.0, rz: 0.9, count: 14, over: 2.2, delay: 0.3, pick: e => e.T.def.key === 'berry', height: [7, 11] });
+ pat.rain({ x: PILE.x, z: PILE.z - 0.2, rx: 3.2, rz: 0.8, count: 3, over: 1.6, delay: 0.7, pick: e => e.T.def.key === 'croissant', height: [8, 10] });
+ pat.rain({ x: PILE.x + 1.2, z: PILE.z + 0.3, rx: 2.4, rz: 0.6, count: 2, over: 1.2, delay: 1.1, pick: e => e.T.def.key === 'tart', height: [8, 10] });
+ pat.rain({ x: CAKE_POS.x, z: CAKE_POS.z, rx: 0.5, rz: 0.4, count: 3, over: 1.4, delay: 0.9, pick: e => e.T.def.key === 'macA' || e.T.def.key === 'berry', height: [9, 11] });
+};
+if (!DBG.has('norain')) heroRain();
+visited.add('hero');
+gsap.from('.title .line:first-child', { yPercent: 60, opacity: 0, duration: 1.6, ease: 'expo.out', delay: 0.1 });
+gsap.from('.grav .ch', { y: () => -innerHeight * (0.6 + Math.random() * 0.4), rotation: () => (Math.random() - 0.5) * 50, duration: 1.5, ease: 'bounce.out', stagger: { each: 0.045, from: 'random' }, delay: 0.5 });
+gsap.from('.hero .eyebrow, .sub, .hero-cta, .hint li, .nav', { opacity: 0, y: 16, duration: 1.2, ease: 'power3.out', stagger: 0.06, delay: 1.0 });
diff --git a/examples/sucre/pastry.js b/examples/sucre/pastry.js
new file mode 100644
index 0000000..79019b3
--- /dev/null
+++ b/examples/sucre/pastry.js
@@ -0,0 +1,417 @@
+// Pastries with real physics (Rapier): instanced meshes per type, simplified colliders, a kinematic fingertip,
+// spring pick-up and toss, knock waves, hops, rain, and texture-less proxies for the shadow pass.
+import RAPIER from '@dimforge/rapier3d-compat';
+import { THREE, clamp, lerp } from '../../src/core/engine.js';
+import { firstMesh } from '../../src/core/assets.js';
+import { COUNTER } from './set.js';
+
+export { RAPIER };
+export const GRAVITY = 40;
+
+// Macaron flavours. Everything except pistachio is the rose shell, hue-shifted per instance in the shader.
+export const FLAVOURS = {
+ rose: { model: 'macA', tint: [0.0, 1.0, 1.0], name: 'Rose & Litchi', css: '#e7aab4' },
+ citron: { model: 'macA', tint: [0.15, 1.45, 1.14], name: 'Citron', css: '#efd98c' },
+ violette: { model: 'macA', tint: [-0.16, 0.72, 0.93], name: 'Violette-Cassis', css: '#b6a2c9' },
+ chocolat: { model: 'macA', tint: [0.075, 1.25, 0.46], name: 'Chocolat', css: '#7a4b3a' },
+ vanille: { model: 'macA', tint: [0.13, 0.38, 1.16], name: 'Vanille', css: '#f1e6cf' },
+ pistache: { model: 'macB', tint: [0.0, 1.0, 1.0], name: 'Pistache', css: '#bfc79a' },
+};
+const MAC_A_MIX = ['rose', 'rose', 'rose', 'citron', 'violette', 'chocolat', 'vanille', 'rose', 'citron', 'vanille'];
+
+export const TYPES = [
+ { key: 'macA', file: 'models/sucre/macaron-lo.glb', shadow: 'models/sucre/macaron-shadow.glb', size: 0.54, count: 48, shape: 'macaron', rest: 0.16, fric: 1.0, dens: 1.0, adamp: 0.7 },
+ { key: 'macB', file: 'models/sucre/macaron2-lo.glb', shadow: 'models/sucre/macaron2-shadow.glb', size: 0.54, count: 16, shape: 'macaron', rest: 0.16, fric: 1.0, dens: 1.0, adamp: 0.7 },
+ { key: 'berry', file: 'models/sucre/strawberry-lo.glb', shadow: 'models/sucre/strawberry-shadow.glb', size: 0.46, count: 26, shape: 'ball', rest: 0.26, fric: 0.9, dens: 1.1, adamp: 1.6 },
+ { key: 'croissant', file: 'models/sucre/croissant-lo.glb', shadow: 'models/sucre/croissant-shadow.glb', size: 1.3, count: 7, shape: 'capsule', rest: 0.08, fric: 1.0, dens: 0.35, adamp: 1.2, upright: true },
+ { key: 'tart', file: 'models/sucre/tart-lo.glb', shadow: 'models/sucre/tart-shadow.glb', size: 0.98, count: 5, shape: 'cylinder', rest: 0.04, fric: 1.0, dens: 0.9, adamp: 2.5, upright: true },
+];
+
+const _m = new THREE.Matrix4(), _q = new THREE.Quaternion(), _p = new THREE.Vector3(), _s = new THREE.Vector3(1, 1, 1), _e = new THREE.Euler();
+const ZERO = new THREE.Matrix4().makeScale(0, 0, 0);
+
+/** Copy a (possibly quantised) glTF mesh into a float geometry in the model's own space. */
+function bakeGeometry(root) {
+ const mesh = firstMesh(root);
+ root.updateMatrixWorld(true);
+ const src = mesh.geometry, geo = new THREE.BufferGeometry();
+ for (const name of ['position', 'normal', 'uv']) {
+ const a = src.getAttribute(name);
+ if (!a) continue;
+ const arr = new Float32Array(a.count * a.itemSize);
+ for (let i = 0; i < a.count; i++) for (let k = 0; k < a.itemSize; k++) arr[i * a.itemSize + k] = a.getComponent(i, k);
+ geo.setAttribute(name, new THREE.BufferAttribute(arr, a.itemSize));
+ }
+ if (src.index) geo.setIndex(new THREE.BufferAttribute(Uint32Array.from(src.index.array), 1));
+ geo.applyMatrix4(mesh.matrixWorld);
+ if (!geo.getAttribute('normal')) geo.computeVertexNormals();
+ return { geo, material: mesh.material };
+}
+
+// Hue/saturation/value shift per instance (done in sRGB space so the shifts read as a pastry chef would name them).
+function patchFlavour(material) {
+ material.onBeforeCompile = sh => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute vec3 aTint; varying vec3 vTint;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvTint = aTint;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vTint;
+ vec3 rgb2hsv(vec3 c){ vec4 K = vec4(0., -1./3., 2./3., -1.); vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g));
+ vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); float d = q.x - min(q.w, q.y); float e = 1.0e-10;
+ return vec3(abs(q.z + (q.w - q.y) / (6. * d + e)), d / (q.x + e), q.x); }
+ vec3 hsv2rgb(vec3 c){ vec3 p = abs(fract(c.xxx + vec3(1., 2./3., 1./3.)) * 6. - 3.); return c.z * mix(vec3(1.), clamp(p - 1., 0., 1.), c.y); }`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ {
+ vec3 s = pow(max(diffuseColor.rgb, 0.0), vec3(1.0 / 2.2));
+ vec3 h = rgb2hsv(s);
+ h.x = fract(h.x + vTint.x + 1.0);
+ h.y = clamp(h.y * vTint.y, 0.0, 1.0);
+ h.z = clamp(h.z * vTint.z, 0.0, 1.0);
+ diffuseColor.rgb = pow(hsv2rgb(h), vec3(2.2));
+ }`);
+ };
+ material.customProgramCacheKey = () => 'sucre-flavour';
+ material.needsUpdate = true;
+}
+
+export class Patisserie {
+ constructor(scene) {
+ this.scene = scene;
+ this.types = {};
+ this.entries = [];
+ this.byCollider = new Map();
+ this.queue = [];
+ this.time = 0;
+ this.held = null;
+ this.holdTarget = new THREE.Vector3();
+ this.cursor = { target: new THREE.Vector3(0, -30, 0), prev: new THREE.Vector3(0, -30, 0), active: false };
+ this.onImpact = null;
+ this.onLost = null;
+ this.impulses = [];
+ }
+
+ async init() {
+ await RAPIER.init();
+ const world = this.world = new RAPIER.World({ x: 0, y: -GRAVITY, z: 0 });
+ world.integrationParameters.numSolverIterations = 6;
+ // Counter slab, back wall, and a low invisible lip at the back so nothing wedges behind the cake.
+ const fixed = world.createRigidBody(RAPIER.RigidBodyDesc.fixed());
+ const W = COUNTER.x1 - COUNTER.x0, D = COUNTER.z1 - COUNTER.z0;
+ world.createCollider(RAPIER.ColliderDesc.cuboid(W / 2, 1, D / 2).setTranslation((COUNTER.x0 + COUNTER.x1) / 2, -1, (COUNTER.z0 + COUNTER.z1) / 2).setFriction(0.9).setRestitution(0.35), fixed);
+ world.createCollider(RAPIER.ColliderDesc.cuboid(W / 2, 20, 0.5).setTranslation((COUNTER.x0 + COUNTER.x1) / 2, 20, COUNTER.z0 - 0.5).setFriction(0.4).setRestitution(0.3), fixed);
+ // Kinematic fingertip that follows the pointer across the marble.
+ this.cursorBody = world.createRigidBody(RAPIER.RigidBodyDesc.kinematicPositionBased().setTranslation(0, -30, 0));
+ this.cursorCol = world.createCollider(RAPIER.ColliderDesc.ball(0.34).setFriction(0.3).setRestitution(0.1), this.cursorBody);
+ }
+
+ /** Build instanced meshes + bodies for one type from its loaded glTFs. */
+ addType(def, gltf, shadowGltf) {
+ const { geo, material } = bakeGeometry(gltf.scene);
+ const sgeo = shadowGltf ? bakeGeometry(shadowGltf.scene).geo : geo;
+ geo.computeBoundingBox();
+ const bb = geo.boundingBox, dim = bb.getSize(new THREE.Vector3()), c = bb.getCenter(new THREE.Vector3());
+ const s = def.size / Math.max(dim.x, dim.y, dim.z);
+ const norm = new THREE.Matrix4().makeScale(s, s, s).multiply(new THREE.Matrix4().makeTranslation(-c.x, -c.y, -c.z));
+ geo.applyMatrix4(norm);
+ if (sgeo !== geo) sgeo.applyMatrix4(norm);
+ dim.multiplyScalar(s);
+ geo.computeBoundingSphere();
+
+ const mat = material;
+ mat.envMapIntensity = def.env ?? 1;
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap']) if (mat[k]) mat[k].anisotropy = 8;
+ if (def.key === 'macA' || def.key === 'macB') { mat.roughness = 1; patchFlavour(mat); }
+ if (def.key === 'berry') { mat.roughness = 0.55; mat.envMapIntensity = 1.5; }
+ if (def.key === 'tart') { mat.roughness = 0.8; mat.envMapIntensity = 1.2; }
+ const n = def.count;
+ const im = new THREE.InstancedMesh(geo, mat, n);
+ im.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
+ im.frustumCulled = false;
+ im.castShadow = false; im.receiveShadow = true;
+ const tint = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) { tint[i * 3 + 1] = 1; tint[i * 3 + 2] = 1; im.setMatrixAt(i, ZERO); }
+ const tintAttr = new THREE.InstancedBufferAttribute(tint, 3);
+ geo.setAttribute('aTint', tintAttr);
+ this.scene.add(im);
+ // Shadow proxy (≈1.5k tris) shares the instance matrices. It draws nothing in colour passes; only its shadow counts.
+ const sm = new THREE.InstancedMesh(sgeo, new THREE.MeshBasicMaterial({ colorWrite: false, depthWrite: false }), n);
+ sm.instanceMatrix = im.instanceMatrix;
+ sm.frustumCulled = false;
+ sm.castShadow = true;
+ sm.renderOrder = -10;
+ this.scene.add(sm);
+
+ const T = { def, im, sm, tintAttr, dim, entries: [] };
+ this.types[def.key] = T;
+
+ // Colliders fitted to the normalised bounds.
+ const mk = () => {
+ let cd;
+ if (def.shape === 'macaron') {
+ const r = Math.max(dim.x, dim.z) / 2 * 0.97, hh = dim.y / 2 * 0.96, br = Math.min(0.07, hh * 0.45);
+ cd = RAPIER.ColliderDesc.roundCylinder(hh - br, r - br, br);
+ T.hy = hh;
+ } else if (def.shape === 'ball') {
+ const r = (dim.x + dim.y + dim.z) / 6 * 0.86;
+ cd = RAPIER.ColliderDesc.ball(r); T.hy = r;
+ } else if (def.shape === 'capsule') {
+ const axis = dim.x >= dim.y && dim.x >= dim.z ? 'x' : dim.z >= dim.y ? 'z' : 'y';
+ const L = dim[axis], others = ['x', 'y', 'z'].filter(a => a !== axis).map(a => dim[a]);
+ const r = Math.min(...others) / 2 * 0.95;
+ cd = RAPIER.ColliderDesc.capsule(Math.max(0.01, L / 2 - r), r);
+ if (axis === 'x') cd.setRotation(new THREE.Quaternion().setFromEuler(new THREE.Euler(0, 0, Math.PI / 2)));
+ if (axis === 'z') cd.setRotation(new THREE.Quaternion().setFromEuler(new THREE.Euler(Math.PI / 2, 0, 0)));
+ T.hy = r;
+ } else {
+ cd = RAPIER.ColliderDesc.cylinder(dim.y / 2, Math.max(dim.x, dim.z) / 2 * 0.98); T.hy = dim.y / 2;
+ }
+ return cd.setFriction(def.fric).setRestitution(def.rest).setDensity(def.dens);
+ };
+ for (let i = 0; i < n; i++) {
+ const rb = this.world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(0, -40 - i, 0)
+ .setLinearDamping(0.12).setAngularDamping(def.adamp).setCcdEnabled(true));
+ const col = this.world.createCollider(mk(), rb);
+ rb.setEnabled(false);
+ let flavour = def.key === 'macB' ? 'pistache' : def.key === 'macA' ? MAC_A_MIX[i % MAC_A_MIX.length] : null;
+ const e = { id: this.entries.length, T, i, rb, col, state: 'parked', flavour, vy: 0, sq: 0, sqv: 0, bornAt: -10, lastImpact: -10 };
+ if (flavour) { const t = FLAVOURS[flavour].tint; tint.set(t, i * 3); }
+ T.entries.push(e);
+ this.entries.push(e);
+ this.byCollider.set(col.handle, e);
+ }
+ tintAttr.needsUpdate = true;
+ return T;
+ }
+
+ /** Static cake on a slowly turning stand: a velocity-driven kinematic body with stacked cylinders. */
+ addCake(pos, tiers, spin = 0.14) {
+ const rb = this.world.createRigidBody(RAPIER.RigidBodyDesc.kinematicVelocityBased().setTranslation(pos.x, pos.y, pos.z));
+ for (const t of tiers) this.world.createCollider(RAPIER.ColliderDesc.cylinder(t.h / 2, t.r).setTranslation(0, t.y + t.h / 2, 0).setFriction(0.9).setRestitution(0.25), rb);
+ rb.setAngvel({ x: 0, y: spin, z: 0 }, true);
+ this.cake = rb;
+ return rb;
+ }
+
+ isPastry(col) { return this.byCollider.has(col.handle); }
+
+ // ── spawning ────────────────────────────────────────────────────────────────
+ spawn(e, x, y, z, { vx = 0, vy = -2, vz = 0, spin = 6 } = {}) {
+ const rb = e.rb;
+ rb.setEnabled(true);
+ rb.setBodyType(RAPIER.RigidBodyType.Dynamic, true);
+ rb.setTranslation({ x, y, z }, true);
+ const up = e.T.def.upright;
+ const tilt = up ? 0.25 : e.T.def.shape === 'macaron' ? 1.6 : 3;
+ _e.set((Math.random() - 0.5) * tilt, Math.random() * Math.PI * 2, (Math.random() - 0.5) * tilt);
+ _q.setFromEuler(_e);
+ rb.setRotation(_q, true);
+ rb.setLinvel({ x: vx, y: vy, z: vz }, true);
+ const sp = up ? 0.8 : spin;
+ rb.setAngvel({ x: (Math.random() - 0.5) * sp, y: (Math.random() - 0.5) * spin * 0.5, z: (Math.random() - 0.5) * sp }, true);
+ e.state = 'live'; e.vy = vy; e.bornAt = this.time; e.sq = 0; e.sqv = 0;
+ }
+
+ park(e) {
+ e.rb.setEnabled(false);
+ e.rb.setTranslation({ x: 0, y: -40 - e.id, z: 0 }, false);
+ e.state = 'parked';
+ e.T.im.setMatrixAt(e.i, ZERO);
+ }
+
+ /**
+ * Rain pastries into a zone. `pick(e)` filters candidates; parked bodies are used first, then live ones
+ * the camera cannot see (farthest from the zone), so the body count never grows.
+ */
+ rain({ x, z, rx = 2, rz = 1.4, count = 20, over = 2, height = [7, 11], pick = () => true, avoid = null, delay = 0, vy = -3, prefer = null } = {}) {
+ const cand = this.entries.filter(e => (e.state === 'parked' || e.state === 'live') && !e.queued && this.held !== e && pick(e));
+ // Parked bodies first, then ones the camera cannot see, then the farthest away; never the one just landed.
+ const score = e => e.state === 'parked' ? -1e7 + Math.random() : (prefer && prefer(e) ? -1e6 : 0) - this._dist2(e, x, z) + (this.time - e.bornAt < 1.5 ? 1e5 : 0);
+ const sc = new Map(cand.map(e => [e, score(e)]));
+ cand.sort((a, b) => sc.get(a) - sc.get(b));
+ const chosen = cand.slice(0, count);
+ chosen.forEach((e, k) => {
+ let px, pz, tries = 0;
+ do {
+ // Gaussian-ish heap: most land near the centre, some roll away.
+ const a = Math.random() * Math.PI * 2, r = Math.sqrt(-2 * Math.log(1 - Math.random() * 0.98)) * 0.55;
+ px = x + Math.cos(a) * r * rx; pz = z + Math.sin(a) * r * rz;
+ tries++;
+ } while (avoid && avoid(px, pz) && tries < 12);
+ pz = clamp(pz, COUNTER.z0 + 0.5, COUNTER.z1 - 0.4);
+ e.queued = true;
+ this.queue.push({ at: this.time + delay + (k / Math.max(1, chosen.length - 1)) ** 1.15 * over + Math.random() * 0.08, e, x: px, z: pz, y: lerp(height[0], height[1], Math.random()), vy });
+ });
+ this.queue.sort((a, b) => a.at - b.at);
+ return chosen.length;
+ }
+
+ _dist2(e, x, z) { const t = e.rb.translation(); return (t.x - x) ** 2 + (t.z - z) ** 2; }
+
+ // ── gestures ────────────────────────────────────────────────────────────────
+ pick(origin, dir) {
+ const ray = new RAPIER.Ray(origin, dir);
+ const hit = this.world.castRay(ray, 200, true, undefined, undefined, this.cursorCol, undefined, c => this.byCollider.has(c.handle));
+ if (!hit) return null;
+ const e = this.byCollider.get(hit.collider.handle);
+ if (!e || (e.state !== 'live')) return null;
+ return { e, toi: hit.timeOfImpact ?? hit.toi };
+ }
+
+ grab(e) {
+ this.held = e;
+ e.state = 'held';
+ e.rb.wakeUp();
+ e.rb.setAngularDamping(5);
+ e.rb.setLinearDamping(0.5);
+ }
+
+ release() {
+ const e = this.held;
+ if (!e) return null;
+ this.held = null;
+ e.touchedAt = this.time;
+ if (e.state === 'held') e.state = 'live';
+ e.rb.setAngularDamping(e.T.def.adamp);
+ e.rb.setLinearDamping(0.12);
+ const v = e.rb.linvel();
+ e.rb.setLinvel({ x: v.x * 1.15, y: v.y * 1.1, z: v.z * 1.15 }, true);
+ return e;
+ }
+
+ /** Make every live pastry of a kind jump and flip, a few at a time. */
+ hop(pick, { strength = 1, spread = 0.35 } = {}) {
+ let n = 0;
+ for (const e of this.entries) {
+ if (e.state !== 'live' || !pick(e)) continue;
+ this.impulses.push({ at: this.time + Math.random() * spread, e, kind: 'hop', s: strength * (0.85 + Math.random() * 0.3) });
+ n++;
+ }
+ return n;
+ }
+
+ /** A knuckle on the marble: a ring of impulses travelling outward from the point. */
+ knock(p, { radius = 4.6, speed = 8, strength = 1 } = {}) {
+ for (const e of this.entries) {
+ if (e.state !== 'live') continue;
+ const t = e.rb.translation();
+ const d = Math.hypot(t.x - p.x, t.z - p.z);
+ if (d > radius) continue;
+ this.impulses.push({ at: this.time + d / speed, e, kind: 'knock', s: strength * (1 - d / radius) ** 0.7, ox: (t.x - p.x) / (d + 1e-3), oz: (t.z - p.z) / (d + 1e-3) });
+ }
+ }
+
+ _applyImpulse(it) {
+ const e = it.e;
+ if (e.state !== 'live') return;
+ const rb = e.rb, m = rb.mass();
+ rb.wakeUp();
+ const lv = rb.linvel();
+ if (it.kind === 'hop') {
+ rb.setLinvel({ x: lv.x * 0.3 + (Math.random() - 0.5) * 1.2, y: 10.5 * it.s, z: lv.z * 0.3 + (Math.random() - 0.5) * 1.2 }, true);
+ const a = Math.random() * Math.PI * 2, flip = e.T.def.upright ? 0.15 : 1;
+ rb.setAngvel({ x: Math.cos(a) * 11 * it.s * flip, y: (Math.random() - 0.5) * 3, z: Math.sin(a) * 11 * it.s * flip }, true);
+ } else {
+ rb.applyImpulse({ x: it.ox * m * 2.2 * it.s, y: m * (3 + 8.5 * it.s), z: it.oz * m * 2.2 * it.s }, true);
+ const flip = e.T.def.upright ? 0.15 : 1;
+ rb.setAngvel({ x: (Math.random() - 0.5) * 12 * it.s * flip, y: (Math.random() - 0.5) * 4, z: (Math.random() - 0.5) * 12 * it.s * flip }, true);
+ }
+ }
+
+ // ── simulation ──────────────────────────────────────────────────────────────
+ setCursor(p, active) {
+ this.cursor.active = active && !this.held;
+ if (this.cursor.active) this.cursor.target.copy(p); else this.cursor.target.set(0, -30, 0);
+ }
+
+ update(dt) {
+ this.time += dt;
+ const t = this.time;
+ while (this.queue.length && this.queue[0].at <= t) {
+ const q = this.queue.shift();
+ q.e.queued = false;
+ if (q.e.state === 'held' || q.e.state === 'boxed' || q.e.state === 'fly') continue;
+ this.spawn(q.e, q.x, q.y, q.z, { vy: q.vy, vx: (Math.random() - 0.5) * 1.5, vz: (Math.random() - 0.5) * 1.5 });
+ }
+ if (this.impulses.length) {
+ this.impulses = this.impulses.filter(it => { if (it.at <= t) { this._applyImpulse(it); return false; } return true; });
+ }
+
+ // Held pastry: critically damped spring toward the target.
+ if (this.held && this.holdActive !== false) {
+ const rb = this.held.rb, p = rb.translation();
+ const k = 16;
+ let vx = (this.holdTarget.x - p.x) * k, vy = (this.holdTarget.y - p.y) * k, vz = (this.holdTarget.z - p.z) * k;
+ const sp = Math.hypot(vx, vy, vz), max = 38;
+ if (sp > max) { vx *= max / sp; vy *= max / sp; vz *= max / sp; }
+ rb.setLinvel({ x: vx, y: vy, z: vz }, true);
+ }
+
+ // Sub-stepped world with the kinematic fingertip swept across each sub-step.
+ const n = Math.max(1, Math.ceil(dt / (1 / 100)));
+ const h = dt / n;
+ this.world.timestep = h;
+ const c = this.cursor, from = _p.copy(c.prev);
+ const jump = from.distanceTo(c.target);
+ if (jump > 2.5) { this.cursorBody.setTranslation(c.target, true); from.copy(c.target); }
+ for (let s = 1; s <= n; s++) {
+ const f = s / n;
+ this.cursorBody.setNextKinematicTranslation({ x: lerp(from.x, c.target.x, f), y: lerp(from.y, c.target.y, f), z: lerp(from.z, c.target.z, f) });
+ this.world.step();
+ }
+ c.prev.copy(c.target);
+
+ // Sync instances, detect landings for sugar puffs and squash.
+ for (const key in this.types) {
+ const T = this.types[key];
+ let dirty = false;
+ for (const e of T.entries) {
+ if (e.state === 'parked') continue;
+ const rb = e.rb;
+ const tr = rb.translation(), ro = rb.rotation(), lv = rb.linvel();
+ if (tr.y < -4 || tr.x < COUNTER.x0 - 1 || tr.x > COUNTER.x1 + 1) {
+ if (e.state === 'held') this.held = null;
+ this.park(e); this.onLost?.(e); dirty = true; continue;
+ }
+ // Landing: downward speed collapses in one step.
+ if (e.state === 'live' && e.vy < -6 && lv.y > e.vy * 0.45 && t - e.lastImpact > 0.12) {
+ const sp = -e.vy;
+ e.lastImpact = t;
+ e.sqv -= Math.min(sp * 0.018, 0.5);
+ this.onImpact?.(e, tr, sp);
+ }
+ e.vy = lv.y;
+ // Tarts and croissants right themselves (a weeble's instinct: they are bottom-heavy).
+ if (e.T.def.upright && e.state === 'live') {
+ _p.set(0, 1, 0).applyQuaternion(_q.set(ro.x, ro.y, ro.z, ro.w));
+ if (_p.y < 0.97) {
+ // Even at rest on an edge (asleep), a tilted tart is nudged back flat.
+ const m = rb.mass() * (e.T.def.key === 'tart' ? 7 : 3.5) * dt * (_p.y < 0 ? 2 : 1);
+ rb.applyTorqueImpulse({ x: -_p.z * m, y: 0, z: _p.x * m }, true);
+ if (e.T.def.key === 'tart') { const w = rb.angvel(); rb.setAngvel({ x: w.x * 0.94, y: w.y, z: w.z * 0.94 }, true); }
+ }
+ }
+ // Squash & stretch spring (tiny: pastries are soft, not rubber).
+ e.sqv += (-e.sq * 260 - e.sqv * 16) * dt;
+ e.sq += e.sqv * dt;
+ e.sq = clamp(e.sq, -0.12, 0.08);
+ _q.set(ro.x, ro.y, ro.z, ro.w);
+ _m.makeRotationFromQuaternion(_q);
+ if (Math.abs(e.sq) > 0.002) {
+ const el = _m.elements, sy = 1 + e.sq, sxz = 1 - e.sq * 0.5;
+ el[0] *= sxz; el[4] *= sxz; el[8] *= sxz;
+ el[1] *= sy; el[5] *= sy; el[9] *= sy;
+ el[2] *= sxz; el[6] *= sxz; el[10] *= sxz;
+ }
+ _m.setPosition(tr.x, tr.y + (e.sq < 0 ? e.sq * T.hy : 0), tr.z);
+ T.im.setMatrixAt(e.i, _m);
+ dirty = true;
+ }
+ if (dirty) T.im.instanceMatrix.needsUpdate = true;
+ }
+ }
+
+ /** Current world position of an entry (for UI / box logic). */
+ pos(e, out = new THREE.Vector3()) { const t = e.rb.translation(); return out.set(t.x, t.y, t.z); }
+ liveCount() { return this.entries.filter(e => e.state === 'live').length; }
+}
diff --git a/examples/sucre/set.js b/examples/sucre/set.js
new file mode 100644
index 0000000..3662314
--- /dev/null
+++ b/examples/sucre/set.js
@@ -0,0 +1,163 @@
+// The set: a pale pink marble counter against a panelled (boiserie) wall, lit through a tall shop window.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture, fbmNormal } from '../../src/core/textures.js';
+import { RoundedBoxGeometry } from 'three/examples/jsm/geometries/RoundedBoxGeometry.js';
+
+// Units: 1 = 10 cm. Counter top is y = 0.
+export const COUNTER = { x0: -16, x1: 24, z0: -3.6, z1: 4.6, thick: 0.62 };
+export const WALL_Z = COUNTER.z0;
+
+// Shared marble look (Rosa Portogallo-ish): long warped streaks of varying width, sparse hairlines, soft clouds.
+// Written in linear space. Everything is periodic in uv so the slab tiles seamlessly.
+const MARBLE_BODY = `
+ vec3 lin(vec3 c){ return pow(c, vec3(2.2)); }
+ // returns (cloud, vein, hairline)
+ vec3 marble(vec2 p){
+ vec2 w = vec2(fbm(p * 2.0, 2.0, 5, 0.5), fbm(p * 2.0 + vec2(5.2, 1.3), 2.0, 5, 0.5));
+ vec2 q = p + w * 0.2;
+ float s = fbm(q * 4.0, 4.0, 6, 0.55);
+ float t = (q.x * 2.0 + q.y) * 2.0 + s * 1.3;
+ float d = abs(fract(t) - 0.5);
+ float width = 0.012 + 0.05 * smoothstep(0.0, 0.5, fbm(q * 3.0 + 9.1, 3.0, 4, 0.5) + 0.2);
+ float amp = smoothstep(-0.25, 0.35, fbm(q * 2.0 + vec2(mod(floor(t), 2.0) * 0.5), 2.0, 4, 0.5));
+ float vein = exp(-pow(d / width, 2.0)) * amp;
+ vein += exp(-pow(d / (width * 5.0), 2.0)) * amp * 0.25; // soft halo around each streak
+ float f2 = fbm((q + vec2(s) * 0.1) * 6.0, 6.0, 5, 0.55);
+ float hair = pow(1.0 - clamp(abs(f2) * 10.0, 0.0, 1.0), 22.0) * smoothstep(0.05, 0.4, fbm(q * 2.0 + 3.3, 2.0, 3, 0.5));
+ float cloud = fbm(p * 2.0 + w * 0.6, 2.0, 5, 0.5);
+ return vec3(cloud, clamp(vein, 0.0, 1.0), hair);
+ }
+`;
+
+export function marbleTextures(renderer, size = 2048) {
+ const map = bakeTexture(renderer, size, `${MARBLE_BODY}
+ void main(){
+ vec3 m = marble(vUv);
+ vec3 base = mix(vec3(0.935, 0.895, 0.893), vec3(0.975, 0.955, 0.945), smoothstep(-0.3, 0.3, m.x));
+ base = mix(base, vec3(0.95, 0.875, 0.88), smoothstep(0.05, 0.45, m.x) * 0.4);
+ vec3 c = mix(base, vec3(0.74, 0.62, 0.64), m.y * 0.62);
+ c = mix(c, vec3(0.66, 0.56, 0.58), m.z * 0.28);
+ c *= 0.988 + fbm(vUv * 90.0, 90.0, 3, 0.5) * 0.025;
+ gl_FragColor = vec4(lin(c), 1.0);
+ }`);
+ const rough = bakeTexture(renderer, 1024, `${MARBLE_BODY}
+ void main(){
+ vec3 m = marble(vUv);
+ float smudge = fbm(vUv * 7.0, 7.0, 5, 0.5);
+ float r = 0.1 + smoothstep(0.05, 0.45, smudge) * 0.12 + m.y * 0.08 + fbm(vUv * 60.0, 60.0, 3, 0.5) * 0.03;
+ gl_FragColor = vec4(1.0, clamp(r, 0.05, 1.0), 0.0, 1.0);
+ }`);
+ return { map, rough };
+}
+
+/** Soft window cookie for the key light: six tall panes, fine mullions, a hint of foliage outside. */
+export function windowCookie() {
+ const S = 1024;
+ const c = document.createElement('canvas'); c.width = c.height = S;
+ const g = c.getContext('2d');
+ g.fillStyle = '#000'; g.fillRect(0, 0, S, S);
+ g.filter = 'blur(10px)';
+ const x0 = S * 0.1, x1 = S * 0.9, y0 = S * 0.04, y1 = S * 0.96;
+ const cols = 4, rows = 5, mull = 12;
+ const pw = (x1 - x0 - mull * (cols - 1)) / cols, ph = (y1 - y0 - mull * (rows - 1)) / rows;
+ for (let i = 0; i < cols; i++) for (let j = 0; j < rows; j++) {
+ const x = x0 + i * (pw + mull), y = y0 + j * (ph + mull);
+ const grd = g.createLinearGradient(x, y, x + pw, y + ph);
+ grd.addColorStop(0, '#fff'); grd.addColorStop(1, '#f2ece4');
+ g.fillStyle = grd;
+ g.fillRect(x, y, pw, ph);
+ }
+ // Vignette the cookie so the pool of light falls off gently.
+ g.filter = 'none';
+ g.globalCompositeOperation = 'multiply';
+ const v = g.createRadialGradient(S / 2, S / 2, S * 0.2, S / 2, S / 2, S * 0.62);
+ v.addColorStop(0, '#fff'); v.addColorStop(1, '#222');
+ g.fillStyle = v; g.fillRect(0, 0, S, S);
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace;
+ return t;
+}
+
+export function buildSet(renderer, scene) {
+ const group = new THREE.Group();
+ scene.add(group);
+ const W = COUNTER.x1 - COUNTER.x0, D = COUNTER.z1 - COUNTER.z0, cx = (COUNTER.x0 + COUNTER.x1) / 2, cz = (COUNTER.z0 + COUNTER.z1) / 2;
+
+ // Marble counter top (a plane so it can carry the planar reflection) + slab edge with a bullnose.
+ const { map, rough } = marbleTextures(renderer);
+ const tile = 13;
+ map.repeat.set(W / tile, D / tile); rough.repeat.set(W / tile, D / tile);
+ const marble = new THREE.MeshStandardMaterial({ map, roughnessMap: rough, roughness: 1, metalness: 0, envMapIntensity: 0.5 });
+ const top = new THREE.Mesh(new THREE.PlaneGeometry(W, D), marble);
+ top.rotation.x = -Math.PI / 2;
+ top.position.set(cx, 0, cz);
+ top.receiveShadow = true;
+ group.add(top);
+
+ const edgeMap = map.clone(); edgeMap.repeat.set(W / tile, 0.06); edgeMap.needsUpdate = true;
+ const edgeMat = new THREE.MeshStandardMaterial({ map: edgeMap, roughness: 0.2, metalness: 0, envMapIntensity: 0.9, emissive: new THREE.Color(0xf3e4e2), emissiveIntensity: 0.34 });
+ // Half cylinder (theta −90°..90° is the +z half), laid along x: the rounded front of the slab.
+ const bull = new THREE.Mesh(new THREE.CylinderGeometry(COUNTER.thick / 2, COUNTER.thick / 2, W, 48, 1, true, -Math.PI / 2, Math.PI), edgeMat);
+ bull.rotation.z = Math.PI / 2;
+ bull.position.set(cx, -COUNTER.thick / 2, COUNTER.z1);
+ bull.receiveShadow = true;
+ group.add(bull);
+
+ // Gold-leaf strip under the slab and a pistachio lacquered cabinet front.
+ const gold = new THREE.MeshStandardMaterial({ color: 0xd9b56e, metalness: 1, roughness: 0.28, envMapIntensity: 1.4 });
+ const stripGold = new THREE.MeshStandardMaterial({ color: 0xe6c98c, metalness: 0.85, roughness: 0.35, envMapIntensity: 1.6, emissive: new THREE.Color(0xc9a664), emissiveIntensity: 0.35 });
+ const strip = new THREE.Mesh(new RoundedBoxGeometry(W, 0.12, 0.14, 2, 0.03), stripGold);
+ strip.position.set(cx, -COUNTER.thick - 0.07, COUNTER.z1 - 0.12);
+ group.add(strip);
+ const cab = new THREE.Mesh(new THREE.BoxGeometry(W, 9, 0.3), new THREE.MeshStandardMaterial({ color: 0xf4ebe2, roughness: 0.5, envMapIntensity: 1.0, emissive: new THREE.Color(0xf1e2dc), emissiveIntensity: 0.5 }));
+ cab.position.set(cx, -COUNTER.thick - 0.13 - 4.5, COUNTER.z1 - 0.2);
+ cab.receiveShadow = true;
+ group.add(cab);
+
+ // Plaster wall with tone-on-tone boiserie.
+ const plasterN = fbmNormal(renderer, { size: 512, scale: 6, octaves: 6, strength: 0.7 });
+ plasterN.repeat.set(8, 4);
+ const wallMat = new THREE.MeshStandardMaterial({ color: 0xe6bcc4, roughness: 0.86, normalMap: plasterN, normalScale: new THREE.Vector2(0.5, 0.5), envMapIntensity: 0.55, vertexColors: true });
+ // Light falls off toward the ceiling: bake a vertical gradient into vertex colours.
+ const wallGeo = new THREE.PlaneGeometry(W + 20, 40, 1, 16);
+ const wc = [], wp = wallGeo.getAttribute('position');
+ for (let i = 0; i < wp.count; i++) { const y = wp.getY(i) + 18; const k = 1 - Math.min(1, Math.max(0, (y - 1) / 16)) ** 1.4 * 0.38; wc.push(k, k * 0.985, k * 0.985); }
+ wallGeo.setAttribute('color', new THREE.Float32BufferAttribute(wc, 3));
+ const wall = new THREE.Mesh(wallGeo, wallMat);
+ wall.position.set(cx, 18, WALL_Z);
+ wall.receiveShadow = true;
+ group.add(wall);
+
+ const mould = new THREE.MeshStandardMaterial({ color: 0xecc6cd, roughness: 0.62, envMapIntensity: 0.7 });
+ const mouldGold = new THREE.MeshStandardMaterial({ color: 0xe3c07a, metalness: 1, roughness: 0.32, envMapIntensity: 1.2 });
+ const addFrame = (x, y, w, h, prof = 0.13, depth = 0.08) => {
+ const geoH = new RoundedBoxGeometry(w, prof, depth, 2, 0.03), geoV = new RoundedBoxGeometry(prof, h, depth, 2, 0.03);
+ for (const [gx, gy, geo] of [[x, y + h / 2, geoH], [x, y - h / 2, geoH], [x - w / 2, y, geoV], [x + w / 2, y, geoV]]) {
+ const m = new THREE.Mesh(geo, mould);
+ m.position.set(gx, gy, WALL_Z + depth / 2);
+ m.castShadow = true; m.receiveShadow = true;
+ group.add(m);
+ }
+ // Hairline of gold leaf inside the frame.
+ const lh = new THREE.BoxGeometry(w - 0.34, 0.018, 0.012), lv = new THREE.BoxGeometry(0.018, h - 0.34, 0.012);
+ for (const [gx, gy, geo] of [[x, y + h / 2 - 0.17, lh], [x, y - h / 2 + 0.17, lh], [x - w / 2 + 0.17, y, lv], [x + w / 2 - 0.17, y, lv]]) {
+ const m = new THREE.Mesh(geo, mouldGold);
+ m.position.set(gx, gy, WALL_Z + 0.01);
+ group.add(m);
+ }
+ };
+ const panelW = 5.2, gap = 0.9;
+ for (let x = -14.6; x < 26; x += panelW + gap) {
+ addFrame(x, 5.2, panelW, 7.6);
+ addFrame(x, 12.4, panelW, 4.4);
+ }
+ // Dado rail just above the counter and a cornice line.
+ for (const [y, h, d] of [[0.55, 0.22, 0.12], [15.4, 0.34, 0.2]]) {
+ const r = new THREE.Mesh(new RoundedBoxGeometry(W + 20, h, d, 2, 0.04), mould);
+ r.position.set(cx, y, WALL_Z + d / 2);
+ r.castShadow = true; r.receiveShadow = true;
+ group.add(r);
+ }
+
+ return { group, top, marble, wallMat, gold };
+}
diff --git a/examples/sucre/sound.js b/examples/sucre/sound.js
new file mode 100644
index 0000000..34b6ad9
--- /dev/null
+++ b/examples/sucre/sound.js
@@ -0,0 +1,76 @@
+// Optional, muted-by-default foley: soft pats when pastries land, a knuckle on marble, paper and a chime for the box.
+// Everything is synthesised (no files), throttled, and starts only after the visitor turns it on.
+export class Foley {
+ constructor() { this.on = false; this.ctx = null; this.last = 0; this.budget = 0; }
+
+ enable(v) {
+ this.on = v;
+ if (v && !this.ctx) {
+ try {
+ this.ctx = new AudioContext();
+ this.out = this.ctx.createGain(); this.out.gain.value = 0.55;
+ const comp = this.ctx.createDynamicsCompressor(); comp.threshold.value = -18; comp.ratio.value = 4;
+ this.out.connect(comp).connect(this.ctx.destination);
+ const len = this.ctx.sampleRate * 0.25, b = this.ctx.createBuffer(1, len, this.ctx.sampleRate), d = b.getChannelData(0);
+ for (let i = 0; i < len; i++) d[i] = Math.random() * 2 - 1;
+ this.noise = b;
+ } catch { this.on = false; }
+ }
+ this.ctx?.resume?.();
+ }
+
+ _ok() {
+ if (!this.on || !this.ctx) return false;
+ const t = this.ctx.currentTime;
+ this.budget = Math.max(0, this.budget - (t - this.last) * 14);
+ this.last = t;
+ if (this.budget > 10) return false;
+ this.budget++;
+ return true;
+ }
+
+ _burst(t, { freq = 900, q = 0.8, dur = 0.08, gain = 0.3, type = 'lowpass' }) {
+ const c = this.ctx, s = c.createBufferSource(); s.buffer = this.noise;
+ const f = c.createBiquadFilter(); f.type = type; f.frequency.value = freq; f.Q.value = q;
+ const g = c.createGain(); g.gain.setValueAtTime(gain, t); g.gain.exponentialRampToValueAtTime(0.0005, t + dur);
+ s.connect(f).connect(g).connect(this.out); s.start(t, Math.random() * 0.1); s.stop(t + dur + 0.02);
+ }
+
+ _tone(t, { f0 = 180, f1 = 90, dur = 0.09, gain = 0.25, type = 'sine' }) {
+ const c = this.ctx, o = c.createOscillator(); o.type = type;
+ o.frequency.setValueAtTime(f0, t); o.frequency.exponentialRampToValueAtTime(f1, t + dur);
+ const g = c.createGain(); g.gain.setValueAtTime(gain, t); g.gain.exponentialRampToValueAtTime(0.0005, t + dur);
+ o.connect(g).connect(this.out); o.start(t); o.stop(t + dur + 0.02);
+ }
+
+ land(kind, speed) {
+ if (!this._ok()) return;
+ const t = this.ctx.currentTime, v = Math.min(1, (speed - 5) / 18);
+ if (v <= 0) return;
+ const pitch = 0.85 + Math.random() * 0.3;
+ if (kind === 'berry') { this._tone(t, { f0: 420 * pitch, f1: 160, dur: 0.06, gain: 0.12 * v }); this._burst(t, { freq: 2400, dur: 0.03, gain: 0.05 * v }); }
+ else if (kind === 'croissant') this._burst(t, { freq: 1700 * pitch, q: 0.4, dur: 0.12, gain: 0.2 * v, type: 'bandpass' });
+ else if (kind === 'tart') { this._tone(t, { f0: 150, f1: 70, dur: 0.12, gain: 0.25 * v }); this._burst(t, { freq: 900, dur: 0.06, gain: 0.12 * v }); }
+ else { this._tone(t, { f0: 240 * pitch, f1: 110, dur: 0.07, gain: 0.16 * v }); this._burst(t, { freq: 1300 * pitch, dur: 0.05, gain: 0.1 * v }); }
+ }
+
+ knock() {
+ if (!this.on || !this.ctx) return;
+ const t = this.ctx.currentTime;
+ this._tone(t, { f0: 210, f1: 120, dur: 0.12, gain: 0.5 });
+ this._burst(t, { freq: 3200, q: 1.2, dur: 0.025, gain: 0.25, type: 'bandpass' });
+ }
+
+ paper() {
+ if (!this.on || !this.ctx) return;
+ const t = this.ctx.currentTime;
+ this._tone(t, { f0: 120, f1: 60, dur: 0.16, gain: 0.45 });
+ this._burst(t, { freq: 1100, q: 0.5, dur: 0.14, gain: 0.25 });
+ }
+
+ chime() {
+ if (!this.on || !this.ctx) return;
+ const t = this.ctx.currentTime;
+ [1318.5, 1760, 2093].forEach((f, i) => this._tone(t + i * 0.09, { f0: f, f1: f * 0.995, dur: 0.9, gain: 0.07, type: 'sine' }));
+ }
+}
diff --git a/examples/sucre/style.css b/examples/sucre/style.css
new file mode 100644
index 0000000..7193f87
--- /dev/null
+++ b/examples/sucre/style.css
@@ -0,0 +1,235 @@
+:root {
+ --bg: #f6d9df;
+ --cream: #fbf4ec;
+ --ink: #45202b;
+ --ink-2: #6d3a47;
+ --muted: #95636f;
+ --rose: #e7a3b1;
+ --pist: #b3c28f;
+ --pist-deep: #5f7340;
+ --gold: #b08a4a;
+ --gold-foil: linear-gradient(115deg, #8a6630 0%, #e9d08f 28%, #b08743 46%, #f5e2ad 62%, #a37a38 84%, #d9bb77 100%);
+ --serif: 'Playfair Display', 'Didot', 'Bodoni 72', Georgia, serif;
+ --sans: 'DM Sans', system-ui, -apple-system, sans-serif;
+ --gut: clamp(18px, 4.2vw, 64px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; overflow-x: clip; }
+body { font: 400 16px/1.6 var(--sans); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; touch-action: pan-y; }
+em { font-family: var(--serif); font-style: italic; font-weight: 400; }
+
+/* ── loader ───────────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--cream); display: grid; place-content: center; justify-items: center; gap: 14px; }
+.loader-mac { position: relative; width: 132px; height: 96px; margin-bottom: 20px; filter: drop-shadow(0 18px 18px rgba(120,40,60,.18)); }
+.loader-mac i { position: absolute; left: 0; right: 0; }
+.loader-mac .shell { height: 38px; border-radius: 66px / 30px; background: radial-gradient(110% 130% at 38% 18%, #fbd3da 0%, #eea9b6 55%, #dc8d9d 100%); }
+.loader-mac .shell::after { content: ''; position: absolute; left: 6px; right: 6px; height: 7px; border-radius: 4px;
+ background: repeating-linear-gradient(90deg, #e59fad 0 3px, #f3bcc6 3px 6px); }
+.loader-mac .shell.top { top: calc(-34px + var(--p, 0) * 34px); z-index: 2; }
+.loader-mac .shell.top::after { bottom: -3px; }
+.loader-mac .shell.bot { bottom: 0; border-radius: 66px / 22px; background: radial-gradient(120% 120% at 40% 80%, #eea9b6, #d98a9a); }
+.loader-mac .shell.bot::after { top: -3px; }
+.loader-mac .fill { left: 12px; right: 12px; top: 36px; height: 22px; border-radius: 11px; background: linear-gradient(#fff6ee, #f5e3d6);
+ transform: scaleX(calc(.2 + var(--p, 0) * .8)); box-shadow: inset 0 -3px 0 rgba(160,110,90,.12); }
+.loader-line { font: 400 italic 26px/1 var(--serif); color: var(--ink); }
+.loader-g { font: 500 12px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--muted); font-variant-numeric: tabular-nums; }
+.loader-g em { font: inherit; opacity: .7; }
+
+/* ── nav ─────────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 30; display: flex; align-items: center; justify-content: space-between;
+ padding: 20px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 12px; text-decoration: none; }
+.brand-mark { width: 38px; height: 38px; border-radius: 50%; display: grid; place-items: center; font: 500 italic 15px/1 var(--serif);
+ color: #fff8ec; background: var(--gold-foil); box-shadow: 0 6px 18px -6px rgba(120,80,30,.6), inset 0 0 0 1px rgba(255,255,255,.35); letter-spacing: -.02em; }
+.brand-name { font: 500 13px/1 var(--sans); letter-spacing: .28em; text-transform: uppercase; }
+.brand-name em { font-size: 21px; letter-spacing: 0; text-transform: none; margin-left: 3px; }
+.links { display: flex; gap: 6px; padding: 5px; border-radius: 999px; background: rgba(251,244,236,.55); backdrop-filter: blur(14px) saturate(1.3);
+ box-shadow: inset 0 0 0 1px rgba(69,32,43,.08); }
+.links a { text-decoration: none; font: 500 13px/1 var(--sans); padding: 10px 16px; border-radius: 999px; color: var(--ink-2); transition: background .3s, color .3s; }
+.links a:hover, .links a.on { background: var(--ink); color: var(--cream); }
+.btn { position: relative; display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 48px; padding: 0 24px; border-radius: 999px;
+ text-decoration: none; font: 500 14px/1 var(--sans); letter-spacing: .01em; white-space: nowrap; transition: background .35s, color .35s, box-shadow .35s, opacity .35s; }
+.btn-solid { background: var(--ink); color: var(--cream); box-shadow: 0 14px 30px -14px rgba(69,32,43,.7); }
+.btn-solid:hover { background: #5c2a39; box-shadow: 0 18px 36px -12px rgba(69,32,43,.75); }
+.btn-ghost { color: var(--ink); background: rgba(251,244,236,.6); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(69,32,43,.22); }
+.btn-ghost:hover { box-shadow: inset 0 0 0 1px var(--ink); background: rgba(251,244,236,.9); }
+.nav-cta { height: 44px; }
+.nav-right { display: flex; align-items: center; gap: 10px; }
+.sound { display: flex; align-items: center; gap: 3px; height: 44px; padding: 0 16px 0 14px; border-radius: 999px; background: rgba(251,244,236,.55);
+ backdrop-filter: blur(14px); box-shadow: inset 0 0 0 1px rgba(69,32,43,.08); font: 500 12px/1 var(--sans); color: var(--ink-2); }
+.sound i { width: 2px; height: 10px; border-radius: 1px; background: currentColor; transform: scaleY(.3); transform-origin: 50% 50%; transition: transform .3s; }
+.sound span { margin-left: 7px; }
+.sound[aria-pressed="true"] i { animation: eq 1s ease-in-out infinite; }
+.sound[aria-pressed="true"] i:nth-child(2) { animation-delay: -.3s; } .sound[aria-pressed="true"] i:nth-child(3) { animation-delay: -.6s; } .sound[aria-pressed="true"] i:nth-child(4) { animation-delay: -.15s; }
+@keyframes eq { 0%, 100% { transform: scaleY(.3); } 50% { transform: scaleY(1); } }
+
+/* ── stages ──────────────────────────────────────────────── */
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, main input, main li[data-hop], .menu-card, .box-panel { pointer-events: auto; }
+.stage { position: relative; min-height: 100vh; padding: 0 var(--gut); }
+.eyebrow { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; font: 600 11px/1.4 var(--sans); letter-spacing: .22em; text-transform: uppercase; color: var(--ink-2); margin-bottom: 22px; }
+.eyebrow.center { justify-content: center; }
+.eyebrow .dot { width: 4px; height: 4px; border-radius: 50%; background: var(--gold); }
+h2 { font: 400 clamp(40px, 5.2vw, 84px)/.98 var(--serif); letter-spacing: -.025em; }
+h2 em { display: block; color: var(--ink-2); }
+
+/* hero */
+.hero { height: 100vh; display: grid; align-content: start; }
+.hero-copy { position: relative; max-width: min(760px, 54vw); padding-top: max(116px, 14.5vh); }
+/* A feathered pane of soft focus behind the copy, so mouldings and falling pastries never cut through the type. */
+.hero-copy::before { content: ''; position: absolute; left: -12vw; right: -6vw; top: 9vh; bottom: -6vh; z-index: -1; pointer-events: none;
+ -webkit-backdrop-filter: blur(7px) saturate(1.05); backdrop-filter: blur(7px) saturate(1.05);
+ background: radial-gradient(closest-side, rgba(246,217,223,.42), rgba(246,217,223,0));
+ -webkit-mask-image: radial-gradient(closest-side, #000 55%, transparent 100%); mask-image: radial-gradient(closest-side, #000 55%, transparent 100%); }
+.title { font: 400 clamp(46px, 6.3vw, 104px)/.9 var(--serif); letter-spacing: -.035em; margin-bottom: 22px; }
+.title .line { display: block; }
+.title em { font-weight: 400; color: var(--ink-2); }
+.grav .w { display: inline-block; white-space: nowrap; }
+.grav .ch { display: inline-block; will-change: transform; }
+.sub { max-width: 28em; font: 400 clamp(15px, 1.15vw, 18px)/1.55 var(--sans); color: var(--ink-2); margin-bottom: 26px; }
+.hero-cta { display: flex; gap: 12px; flex-wrap: wrap; }
+.hint { position: absolute; right: var(--gut); top: max(104px, 13vh); list-style: none; display: grid; gap: 8px; justify-items: end; transition: opacity .6s; }
+.hint li { font: 400 12.5px/1 var(--sans); color: var(--ink-2); padding: 9px 14px 9px 9px; border-radius: 999px; background: rgba(251,244,236,.62);
+ backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px rgba(69,32,43,.07); display: flex; align-items: center; gap: 10px; }
+.hint b { font: 600 10px/1 var(--sans); letter-spacing: .14em; text-transform: uppercase; padding: 6px 9px; border-radius: 999px; background: var(--ink); color: var(--cream); }
+.hint .hint-touch { display: none; }
+.hint.used { opacity: .0; }
+.scroll-cue { position: absolute; left: 50%; bottom: 4vh; transform: translateX(-50%); display: grid; justify-items: center; gap: 10px;
+ font: 600 10px/1 var(--sans); letter-spacing: .3em; text-transform: uppercase; color: var(--ink-2); opacity: .75; }
+.scroll-cue i { width: 1px; height: 38px; background: linear-gradient(var(--ink-2), transparent); animation: cue 2.2s ease-in-out infinite; transform-origin: top; }
+@keyframes cue { 0% { transform: scaleY(0); } 50% { transform: scaleY(1); } 100% { transform: scaleY(1); opacity: 0; } }
+
+/* la carte */
+.carte { display: grid; align-content: start; padding-top: 13vh; padding-bottom: 12vh; min-height: 150vh; }
+.menu-card { width: min(460px, 38vw); padding: 32px 34px 28px; background: rgba(251,244,236,.84); backdrop-filter: blur(18px) saturate(1.2);
+ border-radius: 4px; box-shadow: 0 40px 80px -40px rgba(90,30,50,.45), inset 0 0 0 1px rgba(176,138,74,.35), inset 0 0 0 7px rgba(251,244,236,.9), inset 0 0 0 8px rgba(176,138,74,.28); }
+.menu-card h2 { font-size: clamp(34px, 3.4vw, 54px); text-align: center; }
+.menu-card h2 em { display: inline; }
+.menu-note { text-align: center; color: var(--muted); font-size: 13px; margin: 12px auto 16px; max-width: 26em; }
+.menu-group { display: flex; justify-content: space-between; align-items: baseline; font: 600 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase;
+ color: var(--gold); padding: 14px 0 10px; border-bottom: 1px solid rgba(176,138,74,.35); margin-top: 8px; }
+.menu-group span { font-weight: 500; color: var(--muted); letter-spacing: .08em; text-transform: none; font-size: 12px; }
+.menu { list-style: none; }
+.menu li { display: grid; grid-template-columns: auto 1fr auto; column-gap: 12px; align-items: baseline; padding: 7px 8px; margin: 0 -8px; border-radius: 3px;
+ transition: background .3s; cursor: pointer; }
+.menu li:hover { background: rgba(231,163,177,.18); }
+.menu .sw { width: 11px; height: 11px; border-radius: 50%; background: var(--c); box-shadow: inset 0 -2px 0 rgba(0,0,0,.08), 0 0 0 1px rgba(69,32,43,.12); align-self: center; grid-row: span 2; }
+.menu .nm { font: 400 italic 19px/1.2 var(--serif); }
+.menu .ds { grid-column: 2 / 4; font-size: 12.5px; line-height: 1.4; color: var(--muted); }
+.menu-priced li { grid-template-columns: 1fr auto; }
+.menu-priced .ds { grid-column: 1 / 2; }
+.menu-priced b { grid-column: 2; grid-row: 1; font: 500 13px/1 var(--sans); color: var(--ink-2); font-variant-numeric: tabular-nums; }
+
+/* coffret */
+.coffret { height: 250vh; padding: 0; }
+.coffret-sticky { position: sticky; top: 0; height: 100vh; display: grid; align-content: center; padding: 10vh var(--gut) 6vh; pointer-events: none; }
+.box-panel { width: min(430px, 36vw); padding: 34px; border-radius: 4px; background: rgba(251,244,236,.82); backdrop-filter: blur(18px) saturate(1.2);
+ box-shadow: 0 40px 80px -40px rgba(90,30,50,.45), inset 0 0 0 1px rgba(69,32,43,.08); }
+.box-panel h2 { font-size: clamp(34px, 3.3vw, 52px); }
+.box-lede { color: var(--ink-2); margin: 18px 0 24px; font-size: 15px; }
+.slots { list-style: none; display: grid; grid-template-columns: repeat(6, 1fr); gap: 8px; margin-bottom: 14px; }
+.slots li { aspect-ratio: 1; border-radius: 50%; box-shadow: inset 0 0 0 1.5px rgba(69,32,43,.18); background: rgba(255,255,255,.35); transition: background .4s, box-shadow .4s, transform .5s cubic-bezier(.3,1.8,.5,1); }
+.slots li.on { background: var(--c); box-shadow: inset 0 -4px 0 rgba(0,0,0,.08), 0 6px 14px -6px rgba(69,32,43,.5); transform: scale(1.06); }
+.box-count { font: 500 13px/1.4 var(--sans); color: var(--ink-2); }
+.box-count .n { font: 500 italic 24px/1 var(--serif); color: var(--ink); margin-right: 2px; }
+.box-status { color: var(--muted); }
+.box-flavours { min-height: 2.8em; margin: 8px 0 18px; font: 400 italic 16px/1.4 var(--serif); color: var(--ink-2); }
+.box-actions { display: flex; flex-wrap: wrap; gap: 10px; }
+.order-btn[aria-disabled="true"] { opacity: .38; pointer-events: none; box-shadow: none; }
+.order-btn.ready { animation: ready 1.8s ease-in-out infinite; }
+@keyframes ready { 0%, 100% { box-shadow: 0 14px 30px -14px rgba(69,32,43,.7), 0 0 0 0 rgba(176,138,74,.5); } 50% { box-shadow: 0 14px 30px -14px rgba(69,32,43,.7), 0 0 0 9px rgba(176,138,74,0); } }
+.reset-btn { margin-top: 16px; font: 500 12px/1 var(--sans); letter-spacing: .08em; color: var(--muted); text-decoration: underline; text-underline-offset: 4px; opacity: 0; pointer-events: none !important; transition: opacity .4s; }
+.is-closed .reset-btn { opacity: 1; pointer-events: auto !important; }
+
+/* atelier */
+.atelier { display: grid; justify-items: end; align-content: center; padding-top: 10vh; padding-bottom: 10vh; }
+.atelier-copy { width: min(540px, 42vw); padding: 40px 42px 34px; border-radius: 4px; background: rgba(251,244,236,.8); backdrop-filter: blur(18px) saturate(1.2);
+ box-shadow: 0 40px 80px -40px rgba(90,30,50,.45), inset 0 0 0 1px rgba(176,138,74,.3); pointer-events: auto; }
+.atelier-copy h2 { font-size: clamp(38px, 4vw, 66px); }
+.atelier .lede { font: 400 clamp(19px, 1.55vw, 24px)/1.45 var(--serif); margin: 26px 0 18px; }
+.atelier .body { color: var(--ink-2); font-size: 15px; }
+.stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 20px; margin: 34px 0 24px; padding-top: 24px; border-top: 1px solid rgba(176,138,74,.4); }
+.stats dt { font: 400 italic clamp(30px, 2.6vw, 42px)/1 var(--serif); color: var(--ink); }
+.stats dd { font-size: 12.5px; line-height: 1.45; color: var(--muted); margin-top: 8px; }
+.sig { font-size: 13px; color: var(--muted); }
+.sig em { font-size: 16px; }
+
+/* visit */
+.visit { display: grid; grid-template-rows: 1fr auto; padding-top: 15vh; padding-bottom: 7vh; min-height: 110vh; }
+.visit-head { justify-self: end; text-align: right; }
+.visit-head .eyebrow { justify-content: flex-end; }
+.visit-head h2 { font-size: clamp(44px, 5.6vw, 92px); }
+.visit-card { display: grid; grid-template-columns: repeat(3, 1fr) auto; gap: 30px; align-items: end; padding: 28px 32px; border-radius: 4px;
+ background: rgba(251,244,236,.84); backdrop-filter: blur(18px) saturate(1.2); box-shadow: 0 40px 80px -40px rgba(90,30,50,.45), inset 0 0 0 1px rgba(69,32,43,.08); pointer-events: auto; }
+.visit-card h3 { font: 600 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--gold); margin-bottom: 12px; }
+.visit-card p { font-size: 14.5px; line-height: 1.65; }
+.muted { color: var(--muted); }
+
+/* footer */
+.foot { position: relative; z-index: 3; background: var(--cream); padding: 12vh var(--gut) 5vh; }
+.foot-inner { max-width: 1320px; margin: 0 auto; }
+.foot-mark { font: 400 clamp(64px, 12vw, 200px)/.9 var(--serif); letter-spacing: -.04em; background: var(--gold-foil); -webkit-background-clip: text; background-clip: text; color: transparent; }
+.foot-mark em { font-style: italic; }
+.letter { margin: 7vh 0 9vh; max-width: 560px; }
+.letter label { display: block; font: 400 italic 20px/1.4 var(--serif); margin-bottom: 16px; }
+.letter-row { display: flex; gap: 10px; }
+.letter input { flex: 1; min-width: 0; height: 48px; padding: 0 20px; border-radius: 999px; border: 0; background: #fff; color: var(--ink); font: 400 15px/1 var(--sans);
+ box-shadow: inset 0 0 0 1px rgba(69,32,43,.15); outline: none; }
+.letter input:focus { box-shadow: inset 0 0 0 1.5px var(--ink); }
+.foot-row { display: flex; flex-wrap: wrap; justify-content: space-between; gap: 18px; padding-top: 24px; border-top: 1px solid rgba(176,138,74,.35); font-size: 13px; color: var(--muted); }
+.foot-links { display: flex; gap: 22px; }
+.foot-links a { text-decoration: none; }
+.foot-links a:hover { color: var(--ink); }
+
+.toast { position: fixed; left: 50%; bottom: 5vh; transform: translate(-50%, 16px); z-index: 40; padding: 13px 22px; border-radius: 999px;
+ background: rgba(69,32,43,.92); color: var(--cream); font: 400 italic 17px/1.2 var(--serif); opacity: 0; transition: opacity .45s, transform .45s; pointer-events: none; text-align: center; max-width: calc(100vw - 32px); }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+@media (max-width: 900px) {
+ .links { display: none; }
+ .brand-name { display: none; }
+ .nav { padding: 14px 16px; }
+ .nav-cta { height: 40px; padding: 0 18px; font-size: 13px; }
+ .sound { height: 40px; padding: 0 12px; }
+ .sound span { display: none; }
+ .hero { align-content: start; }
+ .hero-copy { max-width: none; padding-top: 12vh; }
+ .hero-copy::before { left: -16px; right: -16px; top: 8vh; bottom: -3vh; }
+ .title { font-size: clamp(44px, 12.5vw, 72px); margin-bottom: 16px; }
+ .sub { font-size: 15px; margin-bottom: 20px; max-width: 22em; }
+ .hero-cta .btn-ghost { display: none; }
+ .hint { left: 16px; right: 16px; top: auto; bottom: 9vh; justify-items: center; }
+ .hint li { display: none; }
+ .hint .hint-touch { display: flex; }
+ .scroll-cue { display: none; }
+ .carte { align-content: end; padding-bottom: 6vh; }
+ .menu-card { width: 100%; padding: 24px 20px; }
+ .menu-note { display: none; }
+ .menu .ds { display: none; }
+ .menu li { padding: 6px 8px; }
+ .menu .nm { font-size: 17px; }
+ .coffret-sticky { align-content: end; padding: 0 12px 12px; }
+ .box-panel { width: 100%; padding: 20px; }
+ .box-panel h2 { font-size: 30px; }
+ .box-panel h2 em { display: inline; }
+ .box-lede { display: none; }
+ .slots { gap: 6px; margin: 14px 0 8px; }
+ .box-flavours { min-height: 0; font-size: 14px; margin-bottom: 12px; }
+ .box-actions .btn { height: 42px; padding: 0 16px; font-size: 13px; }
+ .atelier { justify-items: stretch; align-content: end; }
+ .atelier-copy { width: 100%; padding: 22px; border-radius: 4px; background: rgba(251,244,236,.84); backdrop-filter: blur(16px); }
+ .atelier .body { display: none; }
+ .atelier-copy { padding: 22px 20px; }
+ .atelier-copy h2 { font-size: 34px; }
+ .atelier .lede { font-size: 17px; margin: 14px 0 6px; }
+ .stats { gap: 12px; margin: 20px 0 12px; }
+ .stats dd { font-size: 11px; }
+ .visit-card { grid-template-columns: 1fr; gap: 16px; padding: 22px; }
+ .letter-row { flex-direction: column; }
+ .letter input { flex: none; }
+ .foot-row { flex-direction: column; }
+}
diff --git a/examples/terrarium/glass.js b/examples/terrarium/glass.js
new file mode 100644
index 0000000..7337175
--- /dev/null
+++ b/examples/terrarium/glass.js
@@ -0,0 +1,433 @@
+// Hand-blown glass cloche with a live condensation layer.
+// The bell is a LatheGeometry whose UVs are (angle, arc length). A ping-pong render target holds the state of the
+// inside surface of the glass in that UV space: R = clear (wiped) · G = wet band (beads pushed aside by a wipe)
+// B = drip trail · A = height of running drops (redrawn every frame). The glass material (MeshPhysicalMaterial with
+// transmission) reads it to decide, per pixel, how frosted the view through the glass is, how milky the fog is and
+// where the water beads bend the light.
+import { THREE } from '../../src/core/engine.js';
+
+const TAU = Math.PI * 2;
+const N_PROFILE = 180;
+
+/** Outer surface of the bell, rim → crown. Uniform arc-length sampling so v is proportional to distance along the glass. */
+export function bellProfile() {
+ const ctrl = [
+ [0.664, 0.0], [0.666, 0.045], [0.659, 0.28], [0.646, 0.56], [0.626, 0.79], [0.592, 0.965],
+ [0.532, 1.115], [0.442, 1.24], [0.322, 1.327], [0.176, 1.381], [0.06, 1.399], [0.0, 1.401],
+ ].map(([x, y]) => new THREE.Vector2(x, y));
+ const curve = new THREE.SplineCurve(ctrl);
+ const pts = curve.getSpacedPoints(N_PROFILE - 1);
+ const len = curve.getLength();
+ const data = new Float32Array(N_PROFILE * 4);
+ const slope = new Float32Array(N_PROFILE);
+ for (let i = 0; i < N_PROFILE; i++) {
+ const a = pts[Math.max(0, i - 1)], b = pts[Math.min(N_PROFILE - 1, i + 1)];
+ const t = new THREE.Vector2().subVectors(b, a).normalize();
+ data.set([pts[i].x, pts[i].y, t.x, t.y], i * 4);
+ slope[i] = Math.abs(t.y);
+ }
+ const tex = new THREE.DataTexture(data, N_PROFILE, 1, THREE.RGBAFormat, THREE.FloatType);
+ tex.minFilter = tex.magFilter = THREE.NearestFilter;
+ tex.needsUpdate = true;
+ const at = (arr, v) => {
+ const f = Math.min(Math.max(v, 0), 1) * (N_PROFILE - 1), i = Math.floor(f), k = f - i, j = Math.min(i + 1, N_PROFILE - 1);
+ return arr(i) * (1 - k) + arr(j) * k;
+ };
+ return {
+ pts, len, tex, n: N_PROFILE, rMax: 0.666,
+ rAt: v => at(i => pts[i].x, v),
+ yAt: v => at(i => pts[i].y, v),
+ slopeAt: v => at(i => slope[i], v),
+ /** local position on the bell for (u, v) — u = 0.5 faces +Z of the cloche group (the mesh is turned by π). */
+ pos(u, v, out = new THREE.Vector3()) {
+ const r = this.rAt(v), phi = u * TAU;
+ return out.set(r * Math.sin(phi), this.yAt(v), r * Math.cos(phi));
+ },
+ };
+}
+
+const NOISE = /* glsl */`
+ float gH(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+ vec2 gH2(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * vec3(.1031, .1030, .0973)); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.xx + p3.yz) * p3.zy); }
+ // value noise, periodic in x with period 'per' lattice cells
+ float gN(vec2 p, float per){
+ vec2 i = floor(p), f = fract(p); vec2 u = f * f * (3. - 2. * f);
+ float i0 = mod(i.x, per), i1 = mod(i.x + 1., per);
+ return mix(mix(gH(vec2(i0, i.y)), gH(vec2(i1, i.y)), u.x), mix(gH(vec2(i0, i.y + 1.)), gH(vec2(i1, i.y + 1.)), u.x), u.y);
+ }
+`;
+
+// ─── Glass material ─────────────────────────────────────────────────────────────
+function glassMaterial(glass) {
+ const mat = new THREE.MeshPhysicalMaterial({
+ color: 0xffffff, metalness: 0, roughness: 0.035, transmission: 1, thickness: 0.012, ior: 1.5,
+ attenuationColor: new THREE.Color(0xe9f3e6), attenuationDistance: 1.2, specularIntensity: 1,
+ envMapIntensity: 1.0, side: THREE.DoubleSide, transparent: false,
+ });
+ const U = glass.uniforms;
+ mat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, U);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', `#include <common>
+ varying vec2 vGUv; varying vec3 vGTan; varying vec3 vGUp; varying float vGR;`)
+ .replace('#include <begin_vertex>', `#include <begin_vertex>
+ vGUv = uv;
+ vGR = length(position.xz);
+ vec3 gT = normalize(vec3(position.z, 0.0, -position.x) + vec3(1e-6, 0.0, 0.0));
+ vec3 gU = normalize(cross(normal, gT));
+ vGTan = normalize((modelViewMatrix * vec4(gT, 0.0)).xyz);
+ vGUp = normalize((modelViewMatrix * vec4(gU, 0.0)).xyz);`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <transmission_fragment>', THREE.ShaderChunk.transmission_fragment)
+ .replace('#include <clipping_planes_pars_fragment>', `#include <clipping_planes_pars_fragment>
+ uniform sampler2D uMask; uniform vec2 uTexel; uniform float uCirc, uLen, uRMax, uRoughFog, uMilkAmt, uMilkGain, uLensThick, uFogK, uFogMax, uTime, uGlint;
+ uniform vec3 uEdgeTint;
+ varying vec2 vGUv; varying vec3 vGTan; varying vec3 vGUp; varying float vGR;
+ ${NOISE}
+ float gNP(float scale){ float per = floor(uCirc / scale + .5); return gN(vec2(vGUv.x * per, vGUv.y * uLen / scale), per); }
+ // one layer of beads on a jittered grid; returns (coverage, tilt.xy)
+ vec3 gBeads(vec2 g, float per, float amt, float maxR, float sq, float seed){
+ vec2 id0 = floor(g); vec3 best = vec3(0.);
+ for (int j = -1; j <= 1; j++) for (int i = -1; i <= 1; i++) {
+ vec2 id = id0 + vec2(float(i), float(j));
+ vec2 idw = vec2(mod(id.x, per), id.y);
+ vec2 h = gH2(idw + seed);
+ float thr = gH(idw * 1.7 + seed * 3.1);
+ float pres = smoothstep(thr, thr + .12, amt);
+ vec2 c = id + .12 + .76 * h;
+ float rad = maxR * (.35 + .65 * gH(idw + seed + 7.3)) * (.55 + .45 * pres);
+ vec2 d = (g - c) * vec2(sq, 1.) / rad;
+ float cov = pres * smoothstep(1., .62, dot(d, d));
+ if (cov > best.x) best = vec3(cov, d);
+ }
+ return best;
+ }`)
+ .replace('#include <normal_fragment_maps>', `#include <normal_fragment_maps>
+ vec4 gM = texture2D(uMask, vGUv);
+ float gSq = clamp(vGR / uRMax, .12, 1.);
+ // condensation: speckled threshold so it re-forms as nucleating dots, not a flat fade
+ float gSpeck = gNP(.011) * .6 + gNP(.034) * .4;
+ float gThr = mix(.06, .92, gSpeck);
+ float gFogAmt = 1. - gM.r;
+ float gFog = min(smoothstep(gThr - .1, gThr + .1, gFogAmt) * uFogK, uFogMax);
+ float gDens = .7 + .36 * gNP(.13) + .16 * (1. - smoothstep(.0, .2, vGUv.y)) - .05 * smoothstep(.75, 1., vGUv.y);
+ gFog *= clamp(gDens, 0., 1.) * (gl_FrontFacing ? 1. : .62);
+ // beads: micro condensation, the wet band pushed aside by a wipe, and a few big ones
+ vec2 gm = vec2(vGUv.x, vGUv.y * uLen / uCirc);
+ float perA = floor(uCirc / .0105 + .5), perB = floor(uCirc / .026 + .5), perC = floor(uCirc / .05 + .5);
+ vec3 bA = gBeads(gm * perA, perA, gFog * .9, .34, gSq, 1.0);
+ vec3 bB = gBeads(gm * perB, perB, clamp(gM.g * 1.5, 0., 1.) + gFog * .06, .36, gSq, 5.0);
+ vec3 bC = gBeads(gm * perC, perC, clamp(gM.g * 1.25 - .3, 0., 1.) + gFog * .015, .34, gSq, 9.0);
+ vec3 gB = bB; if (bC.x > gB.x) gB = bC;
+ // running drops (height in A) and their trails (B)
+ float hR = texture2D(uMask, vGUv + vec2(uTexel.x, 0.)).a, hL = texture2D(uMask, vGUv - vec2(uTexel.x, 0.)).a;
+ float hU = texture2D(uMask, vGUv + vec2(0., uTexel.y)).a, hD = texture2D(uMask, vGUv - vec2(0., uTexel.y)).a;
+ float tR = texture2D(uMask, vGUv + vec2(uTexel.x * 1.5, 0.)).b, tL = texture2D(uMask, vGUv - vec2(uTexel.x * 1.5, 0.)).b;
+ float gDrop = smoothstep(.04, .35, gM.a);
+ vec2 gTilt = gB.yz * gB.x * .8 + bA.yz * bA.x * .2 - vec2(hR - hL, hU - hD) * 1.6 - vec2(tR - tL, 0.) * .35;
+ float gTr = gM.b * (1. - gDrop);
+ float gLens = max(gB.x, gDrop);
+ gFog *= 1. - gLens * .8;
+ gTilt = clamp(gTilt, vec2(-.85), vec2(.85));
+ // water catches the window: a bright point up-left, a darker meniscus at the rim
+ float gGlint = smoothstep(.24, .0, length(gTilt - vec2(-.3, .34))) * gLens;
+ float gRim = smoothstep(.32, .72, length(gTilt)) * gLens;
+ float gGrain = gNP(.0065);
+ normal = normalize(normal * sqrt(max(.05, 1. - dot(gTilt, gTilt))) + vGTan * gTilt.x + vGUp * gTilt.y);
+ float gRough = uRoughFog * gFog;`)
+ .replace('material.thickness = thickness;', 'material.thickness = thickness + gLens * uLensThick;')
+ .replace('vec3 pos = vWorldPosition;', 'vec3 gLit = totalDiffuse;\n\tvec3 pos = vWorldPosition;')
+ .replace('n, v, material.roughness, material.diffuseContribution', 'n, v, gRough, material.diffuseContribution')
+ .replace('totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );', `totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission );
+ float gLum = dot(transmitted.rgb, vec3(.2126, .7152, .0722));
+ vec3 gMilk = (gLit * uMilkGain + mix(transmitted.rgb, vec3(gLum), .18) * .66) * (.93 + .14 * gGrain);
+ totalDiffuse = mix(totalDiffuse, gMilk, gFog * uMilkAmt);
+ totalDiffuse *= (1. + gTr * .05) * (1. - gRim * .4);
+ totalDiffuse += (gLit * .5 + .35) * gGlint * uGlint;
+ float gNV = abs(dot(normalize(vNormal), normalize(vViewPosition)));
+ totalDiffuse *= mix(vec3(1.), uEdgeTint, pow(1. - gNV, 2.2) * (1. - gFog * .6));`);
+ };
+ mat.customProgramCacheKey = () => 'fogglass-3';
+ return mat;
+}
+
+// ─── Mask simulation ────────────────────────────────────────────────────────────
+const SIM_FRAG = /* glsl */`
+ precision highp float;
+ uniform sampler2D uPrev, uProfile; uniform float uN, uDt, uGrow, uDry, uFront, uFrontOn, uR, uStr, uStroke, uWetDecay;
+ uniform vec3 uA, uB;
+ varying vec2 vUv;
+ vec3 profilePos(vec2 uv){
+ float f = clamp(uv.y, 0., 1.) * (uN - 1.); int i0 = int(floor(f)); float t = f - floor(f);
+ vec4 a = texelFetch(uProfile, ivec2(i0, 0), 0), b = texelFetch(uProfile, ivec2(min(i0 + 1, int(uN) - 1), 0), 0);
+ vec2 ry = mix(a.xy, b.xy, t); float phi = uv.x * 6.2831853;
+ return vec3(ry.x * sin(phi), ry.y, ry.x * cos(phi));
+ }
+ float segDist(vec3 p, vec3 a, vec3 b){ vec3 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-9), 0., 1.); return length(pa - ba * h); }
+ void main(){
+ vec4 s = texture2D(uPrev, vUv);
+ float clear = s.r, wet = s.g, trail = s.b, fog = 1. - clear;
+ // condensation nucleates slowly, then races: ~8 s from wiped to fully fogged
+ float rate = uGrow * (.15 + 2.2 * fog) / 8.0 * (1. - .7 * trail);
+ clear = max(0., clear - rate * uDt);
+ clear = max(clear, uDry);
+ clear = max(clear, uFrontOn * smoothstep(uFront - .05, uFront + .05, vUv.y));
+ trail = max(0., trail - uDt / 6.5);
+ wet = max(0., wet - uDt * uWetDecay);
+ if (uStr > 0.) {
+ vec3 P = profilePos(vUv);
+ float d = segDist(P, uA, uB);
+ float c = (1. - smoothstep(uR * .5, uR, d)) * uStr;
+ clear = max(clear, c);
+ float ring = smoothstep(uR * .6, uR * .93, d) * (1. - smoothstep(uR * 1.0, uR * 1.45, d));
+ wet = clamp(wet * (1. - c * .92) + ring * uStroke, 0., 1.);
+ }
+ gl_FragColor = vec4(clear, wet, trail, 0.);
+ }`;
+
+const DROP_VERT = /* glsl */`
+ attribute vec2 aP0, aP1; attribute float aR, aSU, aHead;
+ uniform float uLen;
+ varying vec2 vP, vA, vB; varying float vR, vSU, vHead;
+ void main(){
+ vec2 ext = vec2(aR * aSU, aR / uLen) * 1.7;
+ vec2 lo = min(aP0, aP1) - ext, hi = max(aP0, aP1) + ext;
+ vec2 p = mix(lo, hi, position.xy * .5 + .5);
+ vP = p; vA = aP0; vB = aP1; vR = aR; vSU = aSU; vHead = aHead;
+ gl_Position = vec4(p * 2. - 1., 0., 1.);
+ }`;
+const DROP_FRAG = /* glsl */`
+ precision highp float;
+ uniform float uLen;
+ varying vec2 vP, vA, vB; varying float vR, vSU, vHead;
+ void main(){
+ if (vR <= 0.) discard;
+ vec2 toM = vec2(1. / vSU, uLen);
+ vec2 q = (vP - vB) * toM, a = (vA - vB) * toM;
+ vec2 qh = q; qh.y *= q.y > 0. ? .78 : 1.12; // tear shape: round front below, tail above
+ float dh = length(qh) / vR;
+ float head = (1. - smoothstep(.72, 1., dh)) * vHead;
+ float height = sqrt(max(0., 1. - dh * dh)) * vHead;
+ float h = clamp(dot(q, a) / max(dot(a, a), 1e-12), 0., 1.);
+ float dtl = length(q - a * h);
+ float trail = (1. - smoothstep(vR * .3, vR * .55, dtl)) * step(1e-7, dot(a, a));
+ gl_FragColor = vec4(max(trail, head), 0., trail, height);
+ }`;
+
+const MAX_DROPS = 72;
+const _ws = new THREE.Vector3();
+
+export class FogGlass {
+ constructor(renderer, profile, { res = [2048, 1024], envIntensity = 2.0 } = {}) {
+ this.renderer = renderer;
+ this.profile = profile;
+ this.res = res;
+ const rtOpts = { type: THREE.HalfFloatType, format: THREE.RGBAFormat, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter,
+ wrapS: THREE.RepeatWrapping, wrapT: THREE.ClampToEdgeWrapping, depthBuffer: false, generateMipmaps: false };
+ this.rt = [new THREE.WebGLRenderTarget(res[0], res[1], rtOpts), new THREE.WebGLRenderTarget(res[0], res[1], rtOpts)];
+ this.idx = 0;
+ const circ = TAU * profile.rMax;
+ this.uniforms = {
+ uMask: { value: this.rt[0].texture }, uTexel: { value: new THREE.Vector2(1 / res[0], 1 / res[1]) },
+ uCirc: { value: circ }, uLen: { value: profile.len }, uRMax: { value: profile.rMax },
+ uRoughFog: { value: 0.46 }, uMilkAmt: { value: 0.5 }, uMilkGain: { value: 0.32 }, uLensThick: { value: 0.1 },
+ uFogK: { value: 1 }, uFogMax: { value: 1 }, uTime: { value: 0 }, uGlint: { value: 1.3 }, uEdgeTint: { value: new THREE.Color(0.66, 0.76, 0.68) },
+ };
+
+ // geometry: visible bell + low-res proxy for raycasting
+ this.group = new THREE.Group();
+ this.material = glassMaterial(this);
+ this.material.envMapIntensity = envIntensity;
+ this.mesh = new THREE.Mesh(new THREE.LatheGeometry(profile.pts, 200), this.material);
+ this.mesh.rotation.y = Math.PI; // the lathe seam faces the wall
+ this.mesh.renderOrder = 2;
+ this.group.add(this.mesh);
+ const proxyPts = [];
+ for (let i = 0; i < 60; i++) proxyPts.push(profile.pts[Math.round(i / 59 * (profile.n - 1))]);
+ this.proxy = new THREE.Mesh(new THREE.LatheGeometry(proxyPts, 72), new THREE.MeshBasicMaterial({ side: THREE.FrontSide }));
+ this.proxy.visible = false;
+ this.mesh.add(this.proxy);
+
+ // knob and rolled rim: solid glass, a touch of dispersion
+ const solid = new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.02, transmission: 1, thickness: 0.1, ior: 1.5,
+ dispersion: 3, attenuationColor: new THREE.Color(0xe4f0df), attenuationDistance: 0.9, envMapIntensity: envIntensity * 1.2 });
+ const knobPts = [[0, 1.388], [0.07, 1.392], [0.058, 1.41], [0.042, 1.44], [0.04, 1.462], [0.062, 1.485], [0.084, 1.52],
+ [0.089, 1.55], [0.08, 1.585], [0.052, 1.61], [0.02, 1.62], [0, 1.621]].map(([x, y]) => new THREE.Vector2(x, y));
+ const knob = new THREE.Mesh(new THREE.LatheGeometry(new THREE.SplineCurve(knobPts).getSpacedPoints(48), 64), solid);
+ knob.renderOrder = 3;
+ this.group.add(knob);
+ const rim = new THREE.Mesh(new THREE.TorusGeometry(profile.rMax - 0.004, 0.011, 16, 200), solid.clone());
+ rim.material.thickness = 0.03; rim.material.dispersion = 1;
+ rim.rotation.x = Math.PI / 2; rim.position.y = 0.012; rim.renderOrder = 3;
+ this.group.add(rim);
+ this.solids = [knob, rim];
+
+ // simulation passes
+ this.cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ this.simMat = new THREE.ShaderMaterial({
+ uniforms: {
+ uPrev: { value: null }, uProfile: { value: profile.tex }, uN: { value: profile.n }, uDt: { value: 0 }, uGrow: { value: 1 },
+ uDry: { value: 0 }, uFront: { value: 0 }, uFrontOn: { value: 0 }, uR: { value: 0.1 }, uStr: { value: 0 }, uStroke: { value: 0 },
+ uWetDecay: { value: 1 / 30 }, uA: { value: new THREE.Vector3() }, uB: { value: new THREE.Vector3() },
+ },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }',
+ fragmentShader: SIM_FRAG, depthTest: false, depthWrite: false,
+ });
+ this.simScene = new THREE.Scene();
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.simMat);
+ quad.frustumCulled = false;
+ this.simScene.add(quad);
+
+ const dg = new THREE.InstancedBufferGeometry();
+ const base = new THREE.PlaneGeometry(2, 2);
+ dg.index = base.index; dg.setAttribute('position', base.getAttribute('position'));
+ this.dA = {
+ aP0: new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS * 2), 2),
+ aP1: new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS * 2), 2),
+ aR: new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS), 1),
+ aSU: new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS), 1),
+ aHead: new THREE.InstancedBufferAttribute(new Float32Array(MAX_DROPS), 1),
+ };
+ for (const [k, a] of Object.entries(this.dA)) { a.setUsage(THREE.DynamicDrawUsage); dg.setAttribute(k, a); }
+ dg.instanceCount = MAX_DROPS;
+ this.dropMat = new THREE.ShaderMaterial({
+ uniforms: { uLen: { value: profile.len } }, vertexShader: DROP_VERT, fragmentShader: DROP_FRAG,
+ depthTest: false, depthWrite: false, transparent: true,
+ blending: THREE.CustomBlending, blendEquation: THREE.MaxEquation, blendEquationAlpha: THREE.MaxEquation,
+ blendSrc: THREE.OneFactor, blendDst: THREE.OneFactor, blendSrcAlpha: THREE.OneFactor, blendDstAlpha: THREE.OneFactor,
+ });
+ const dm = new THREE.Mesh(dg, this.dropMat);
+ dm.frustumCulled = false;
+ this.dropScene = new THREE.Scene();
+ this.dropScene.add(dm);
+ this.drops = [];
+
+ this.brushQ = null;
+ this.front = null;
+ this.dry = 0;
+ this.grow = 1;
+ this.wetDecay = 1 / 30;
+ this.ambientDrops = 0.55; // drops per second that run on their own
+ this.active = true;
+ this.clear(0);
+ }
+
+ get scale() { return this.group.scale.x; }
+
+ /** Fill the whole mask: 0 = fully fogged, 1 = clear. */
+ clear(v = 0) {
+ const r = this.renderer, prev = r.getRenderTarget(), cc = r.getClearColor(new THREE.Color()), ca = r.getClearAlpha();
+ for (const t of this.rt) { r.setRenderTarget(t); r.setClearColor(new THREE.Color(v, 0, 0), 1); r.clear(true, false, false); }
+ r.setRenderTarget(prev); r.setClearColor(cc, ca);
+ }
+
+ /** Brush stroke in the bell mesh's local space (A → B), radius in world units. */
+ brush(a, b, radiusWorld, strength = 1) {
+ const s = this.mesh.getWorldScale(_ws).x;
+ const len = a.distanceTo(b);
+ const R = radiusWorld / s;
+ this.brushQ = { a: a.clone(), b: b.clone(), R, str: strength, stroke: Math.min(len / R * 0.32, 0.6) };
+ // wipes push water to their edges; some of it gathers into drops and runs
+ this._acc = (this._acc ?? 0) + len;
+ const spacing = R * 0.9;
+ while (this._acc > spacing) {
+ this._acc -= spacing;
+ if (Math.random() < 0.5) {
+ const p = new THREE.Vector3().lerpVectors(a, b, Math.random());
+ const uv = this.uvOf(p);
+ if (uv.v < 0.07 || this.profile.slopeAt(uv.v) < 0.35) continue;
+ this.spawnDrop(uv.u + (Math.random() - 0.5) * 0.004, uv.v - R * (0.95 + Math.random() * 0.2) / this.profile.len,
+ 0.009 + Math.random() * 0.011, 0.25 + Math.random() * 2.2);
+ }
+ }
+ }
+
+ uvOf(p) {
+ let u = Math.atan2(p.x, p.z) / TAU; if (u < 0) u += 1;
+ // invert the profile's height (monotonic) by bisection
+ let lo = 0, hi = 1;
+ for (let i = 0; i < 18; i++) { const m = (lo + hi) / 2; if (this.profile.yAt(m) < p.y) lo = m; else hi = m; }
+ return { u, v: (lo + hi) / 2 };
+ }
+
+ spawnDrop(u, v, r, stick = 1) {
+ if (v < 0.02 || v > 0.9) return;
+ if (this.drops.length >= MAX_DROPS) this.drops.shift();
+ this.drops.push({ u, v, pu: u, pv: v, r, age: 0, stick, seed: Math.random() * 100, head: 0 });
+ }
+
+ /** Run one simulation step. */
+ step(dt, t) {
+ if (!this.active) return;
+ const r = this.renderer, U = this.simMat.uniforms, P = this.profile;
+ // ambient run-off: drops that let go on their own, mostly low on the walls
+ this._amb = (this._amb ?? 0) + dt * this.ambientDrops * (1 - this.dry);
+ while (this._amb > 1) {
+ this._amb -= 1;
+ this.spawnDrop(Math.random(), 0.12 + Math.random() * 0.55, 0.008 + Math.random() * 0.012, Math.random() * 1.5);
+ }
+ // drops
+ const A = this.dA;
+ for (let i = 0; i < MAX_DROPS; i++) {
+ const d = this.drops[i];
+ if (!d) { A.aR.array[i] = 0; A.aHead.array[i] = 0; A.aP0.array.set([-5, -5], i * 2); A.aP1.array.set([-5, -5], i * 2); continue; }
+ d.pu = d.u; d.pv = d.v;
+ d.age += dt;
+ d.head = Math.min(1, d.head + dt * 3);
+ if (d.age > d.stick) {
+ const n = 0.5 + 0.5 * Math.sin(t * 2.1 + d.seed) * Math.sin(t * 3.7 + d.seed * 1.7);
+ const go = n < 0.28 ? 0 : Math.min(1, (n - 0.28) * 2.5);
+ const speed = (0.035 + d.r * 7) * P.slopeAt(d.v) * go;
+ d.v -= speed * dt / P.len;
+ d.u += Math.sin(t * 1.3 + d.seed * 7) * speed * dt * 0.35 / (TAU * Math.max(P.rAt(d.v), 0.05));
+ d.r = Math.max(0, d.r - speed * dt * 0.02);
+ }
+ if (this.dry > 0.5) d.r -= dt * 0.02;
+ A.aP0.array.set([d.pu, d.pv], i * 2);
+ A.aP1.array.set([d.u, d.v], i * 2);
+ A.aR.array[i] = Math.max(0, d.r);
+ A.aSU.array[i] = 1 / (TAU * Math.max(P.rAt(d.v), 0.05));
+ A.aHead.array[i] = d.head;
+ }
+ this.drops = this.drops.filter(d => d.v > 0.012 && d.r > 0.004);
+ for (const a of Object.values(A)) a.needsUpdate = true;
+
+ U.uPrev.value = this.rt[this.idx].texture;
+ U.uDt.value = dt;
+ U.uGrow.value = this.grow;
+ U.uDry.value = this.dry;
+ U.uWetDecay.value = this.wetDecay + this.dry * 2;
+ if (this.front) { U.uFrontOn.value = 1; U.uFront.value = this.front.v; } else U.uFrontOn.value = 0;
+ const b = this.brushQ;
+ if (b) { U.uA.value.copy(b.a); U.uB.value.copy(b.b); U.uR.value = b.R; U.uStr.value = b.str; U.uStroke.value = b.stroke; }
+ else U.uStr.value = 0;
+ this.brushQ = null;
+
+ const out = this.rt[1 - this.idx];
+ const prev = r.getRenderTarget(), ac = r.autoClear;
+ r.setRenderTarget(out);
+ r.autoClear = false;
+ r.render(this.simScene, this.cam);
+ r.render(this.dropScene, this.cam);
+ r.autoClear = ac;
+ r.setRenderTarget(prev);
+ this.idx = 1 - this.idx;
+ this.uniforms.uMask.value = out.texture;
+ this.uniforms.uTime.value = t;
+ }
+
+ /** Raycast the bell; returns { local, uv } or null. */
+ hit(raycaster) {
+ const h = raycaster.intersectObject(this.proxy, false)[0];
+ if (!h) return null;
+ const local = this.mesh.worldToLocal(h.point.clone());
+ return { local, point: h.point, uv: h.uv };
+ }
+
+ /** Mesh-local azimuth (0..1 in u) that faces a world-space point, e.g. the camera. */
+ uFacing(worldPoint) {
+ const p = this.mesh.worldToLocal(worldPoint.clone());
+ let u = Math.atan2(p.x, p.z) / TAU; if (u < 0) u += 1;
+ return u;
+ }
+}
diff --git a/examples/terrarium/index.html b/examples/terrarium/index.html
new file mode 100644
index 0000000..1a9ba2a
--- /dev/null
+++ b/examples/terrarium/index.html
@@ -0,0 +1,204 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Bell &amp; Moss — A whole climate under glass</title>
+ <meta name="description" content="Hand-blown glass cloches sealed over living worlds in a London workshop. They make their own rain. Water it once, in 2031.">
+ <meta name="theme-color" content="#efe9dd">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Fraunces:ital,opsz,wght,SOFT,WONK@0,9..144,300..700,0..100,0..1;1,9..144,300..700,0..100,0..1&family=Manrope:wght@400;500;600;700&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-bell" aria-hidden="true">
+ <svg viewBox="0 0 120 150">
+ <defs>
+ <clipPath id="bell-clip"><path d="M14 132 C14 70 18 44 38 28 C48 20 56 18 60 18 C64 18 72 20 82 28 C102 44 106 70 106 132 Z"/></clipPath>
+ </defs>
+ <g clip-path="url(#bell-clip)">
+ <rect class="loader-fog" x="0" y="0" width="120" height="150"/>
+ </g>
+ <path class="loader-glass" d="M14 132 C14 70 18 44 38 28 C48 20 56 18 60 18 C64 18 72 20 82 28 C102 44 106 70 106 132"/>
+ <circle class="loader-glass" cx="60" cy="11" r="5.5"/>
+ <path class="loader-base" d="M6 132 H114 V140 C114 143 111 145 108 145 H12 C9 145 6 143 6 140 Z"/>
+ </svg>
+ </div>
+ <p class="loader-line">Letting the glass fog up <span class="loader-pct">0</span>%</p>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Bell &amp; Moss home">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><path d="M5 20c0-7 .6-10.5 3.2-12.6C9.6 6.3 10.9 6 12 6s2.4.3 3.8 1.4C18.4 9.5 19 13 19 20" fill="none" stroke="currentColor" stroke-width="1.3"/><circle cx="12" cy="4" r="1.4" fill="none" stroke="currentColor" stroke-width="1.2"/><path d="M3.5 20.5h17" stroke="currentColor" stroke-width="1.3"/><path d="M9 20c.4-2.6 1.6-4.3 3-5.2 1.4.9 2.6 2.6 3 5.2" fill="currentColor" opacity=".55"/></svg>
+ <span>Bell <em>&amp;</em> Moss</span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#climates">Climates</a>
+ <a href="#inside">Inside the glass</a>
+ <a href="#care">Care</a>
+ <a href="#shop">Shop</a>
+ </nav>
+ <a class="btn btn-solid btn-sm" href="#shop" data-magnetic><span>Shop the bells</span><b class="basket" aria-label="Basket">0</b></a>
+ </header>
+
+ <div class="wipe-cursor" aria-hidden="true"><i></i><span>wipe</span></div>
+ <div class="wipe-hint" aria-hidden="true"><span class="wipe-hint-dot"></span><span class="wipe-hint-text">Wipe the glass</span></div>
+
+ <main>
+ <section class="hero" id="top">
+ <div class="hero-copy">
+ <p class="eyebrow">Hand-blown in Hackney<span> &nbsp;·&nbsp; Sealed since 2011</span></p>
+ <h1 class="hero-title"><span class="ln">A whole climate</span> <span class="ln"><em>under glass.</em></span></h1>
+ <p class="hero-sub">Water it once, in 2031.</p>
+ <p class="hero-body">Every Bell &amp; Moss cloche is blown by hand, sealed over a living world and left to make its own weather. The moss breathes, the glass fogs, and it rains on the inside. You mostly just watch.</p>
+ <div class="hero-cta">
+ <a class="btn btn-solid" href="#climates" data-magnetic>Choose a climate</a>
+ <a class="btn btn-line" href="#inside" data-magnetic>What’s inside</a>
+ </div>
+ </div>
+ <p class="hero-label"><span>No. 0412</span><span>Moss Forest</span><span>Sealed 14 · 03 · 2026</span></p>
+ <p class="scroll-cue"><i></i>Scroll</p>
+ </section>
+
+ <section class="climates" id="climates" data-sec="climates">
+ <div class="sticky">
+ <div class="clim-panel">
+ <p class="eyebrow">Three climates</p>
+ <h2>Pick the weather you’d like to <em>live beside.</em></h2>
+ <div class="tabs" role="tablist" aria-label="Climates">
+ <button role="tab" class="tab on" data-i="0" aria-selected="true"><span>01</span>Moss Forest</button>
+ <button role="tab" class="tab" data-i="1" aria-selected="false"><span>02</span>High Desert</button>
+ <button role="tab" class="tab" data-i="2" aria-selected="false"><span>03</span>Cloud Tropic</button>
+ </div>
+ <div class="clim-cards">
+ <article class="clim on" data-i="0">
+ <h3>Moss Forest</h3>
+ <p class="latin">Leucobryum · Adiantum · <i>Ulmus parvifolia</i></p>
+ <p>A Kyoto moss garden in miniature: cushion moss, maidenhair fern, a path of river quartz and an eleven-year-old Chinese elm that has never been outdoors. Fogged by breakfast, clear by noon.</p>
+ <dl><div><dt>Humidity</dt><dd>92%</dd></div><div><dt>Light</dt><dd>Bright, indirect</dd></div><div><dt>Rain</dt><dd>Daily, inside</dd></div><div><dt>Water</dt><dd>Never</dd></div></dl>
+ </article>
+ <article class="clim" data-i="1">
+ <h3>High Desert</h3>
+ <p class="latin">Echeveria · Haworthia · <i>Mammillaria</i></p>
+ <p>The one exception to our rule. Rosettes and a flowering pincushion cactus on Arizona sand and sandstone, under a vented bell that only fogs on cold mornings. It likes a sunny sill.</p>
+ <dl><div><dt>Humidity</dt><dd>38%</dd></div><div><dt>Light</dt><dd>Sun is welcome</dd></div><div><dt>Rain</dt><dd>Rarely</dd></div><div><dt>Water</dt><dd>A spoon, at the equinox</dd></div></dl>
+ </article>
+ <article class="clim" data-i="2">
+ <h3>Cloud Tropic</h3>
+ <p class="latin">Fittonia · Nephrolepis · lava rock</p>
+ <p>Pink-veined fittonia and button fern around a pool, fed by a very small waterfall and a pump the size of a thimble. The glass rarely clears. It rains inside at about six every evening.</p>
+ <dl><div><dt>Humidity</dt><dd>98%</dd></div><div><dt>Light</dt><dd>Bright, indirect</dd></div><div><dt>Rain</dt><dd>Every evening</dd></div><div><dt>Water</dt><dd>Never</dd></div></dl>
+ </article>
+ </div>
+ </div>
+ <p class="clim-foot">Scroll, or choose a tab — the bell lifts, the base turns, a new world comes up.</p>
+ </div>
+ </section>
+
+ <section class="inside" id="inside" data-sec="inside">
+ <div class="sticky">
+ <div class="inside-head">
+ <p class="eyebrow">Inside the glass</p>
+ <h2>Five layers, one small <em>water cycle.</em></h2>
+ <p class="lede">Nothing in a sealed terrarium is decoration. Every layer has a job, and between them they turn a single glass of water into a decade of weather.</p>
+ </div>
+ <ol class="layer-labels">
+ <li data-k="world"><b>01</b><div><h4>Moss &amp; planting</h4><p>Set by hand, one cushion at a time.</p></div></li>
+ <li data-k="soil"><b>02</b><div><h4>Living soil</h4><p>Peat-free loam, bark, perlite and springtails.</p></div></li>
+ <li data-k="mesh"><b>03</b><div><h4>Fine mesh</h4><p>Keeps the soil out of the drainage.</p></div></li>
+ <li data-k="charcoal"><b>04</b><div><h4>Activated charcoal</h4><p>Keeps the water sweet and the air clean.</p></div></li>
+ <li data-k="stones"><b>05</b><div><h4>Drainage stones</h4><p>Where the rain waits until it’s needed.</p></div></li>
+ <li data-k="base"><b>06</b><div><h4>Walnut base</h4><p>One Herefordshire board. Oiled, never lacquered.</p></div></li>
+ </ol>
+ </div>
+ </section>
+
+ <section class="care" id="care" data-sec="care">
+ <div class="sticky">
+ <div class="care-panel">
+ <p class="eyebrow">Care</p>
+ <h2>Light: bright, indirect. <em>Water: never.</em></h2>
+ <div class="clock" aria-live="off"><b class="clock-time">07:00</b><span class="clock-note">The soil warms and the glass fogs over.</span><i class="clock-bar"><s></s></i></div>
+ <ul class="care-list">
+ <li><h4>Somewhere bright</h4><p>A north or east window is perfect. Summer sun turns a cloche into a greenhouse, so keep it a metre back.</p></li>
+ <li><h4>Leave the bell on</h4><p>Condensation is the point, not a problem. If the glass stays fogged all day, lift it for an hour, once.</p></li>
+ <li><h4>Trim in spring</h4><p>Moss is a lawn. Brass scissors come with every cloche, and so does a reminder, every March.</p></li>
+ <li><h4>Call us in 2031</h4><p>Every bell is guaranteed for ten years. If yours ever needs water, we’ll come round and give it some.</p></li>
+ </ul>
+ </div>
+ </div>
+ </section>
+
+ <section class="shop" id="shop" data-sec="shop">
+ <div class="sticky">
+ <div class="shop-head">
+ <p class="eyebrow">The collection</p>
+ <h2>Three bells, <em>sealed to order.</em></h2>
+ </div>
+ <div class="products">
+ <article class="product" data-i="0">
+ <p class="p-no">No. 01 · Moss Forest</p>
+ <h3>The Hollow</h3>
+ <p class="p-meta">24 cm bell · walnut base · 1.1 kg</p>
+ <div class="p-row"><b class="price">£240</b><button class="btn btn-solid btn-sm add" data-name="The Hollow">Reserve</button></div>
+ </article>
+ <article class="product" data-i="1">
+ <p class="p-no">No. 02 · High Desert</p>
+ <h3>The Mesa</h3>
+ <p class="p-meta">30 cm vented bell · walnut base · 2.3 kg</p>
+ <div class="p-row"><b class="price">£420</b><button class="btn btn-solid btn-sm add" data-name="The Mesa">Reserve</button></div>
+ </article>
+ <article class="product" data-i="2">
+ <p class="p-no">No. 03 · Cloud Tropic</p>
+ <h3>The Cloud Forest</h3>
+ <p class="p-meta">38 cm bell · waterfall · walnut base · 4.8 kg</p>
+ <div class="p-row"><b class="price">£680</b><button class="btn btn-solid btn-sm add" data-name="The Cloud Forest">Reserve</button></div>
+ </article>
+ </div>
+ <p class="shop-note">Blown to order and sealed on Thursdays. Delivered by hand in London, by a very careful courier everywhere else. Six weeks.</p>
+ </div>
+ </section>
+
+ <section class="visit" id="visit" data-sec="visit">
+ <div class="visit-inner">
+ <p class="eyebrow">The workshop</p>
+ <h2>Come and wipe the glass <em>yourself.</em></h2>
+ <p class="lede">Sundays on Columbia Road, nine till three. Bring a question, a jam jar or an old fern — leave with a climate.</p>
+ <a class="btn btn-solid" href="#foot" data-magnetic>Book a Sunday visit</a>
+ </div>
+ </section>
+
+ <footer class="foot" id="foot">
+ <div class="foot-inner">
+ <div class="foot-brand">
+ <p class="foot-mark">Bell <em>&amp;</em> Moss</p>
+ <p>Glass cloches and the worlds under them.<br>Blown in Hackney, sealed on Thursdays.</p>
+ </div>
+ <div class="foot-col">
+ <h5>Workshop</h5>
+ <p>Unit 4, 12 Ezra Street<br>London E2 7RH<br>Sundays 09:00 – 15:00</p>
+ </div>
+ <div class="foot-col">
+ <h5>Explore</h5>
+ <p><a href="#climates">Climates</a><br><a href="#inside">Inside the glass</a><br><a href="#care">Care</a><br><a href="#shop">Shop</a></p>
+ </div>
+ <form class="foot-news" onsubmit="return false">
+ <h5>The Condensation</h5>
+ <p>A short letter, four times a year — at each equinox and solstice.</p>
+ <label><span class="sr">Email address</span><input type="email" placeholder="[email protected]" autocomplete="email"></label>
+ <button class="btn btn-solid btn-sm" type="submit">Subscribe</button>
+ </form>
+ </div>
+ <p class="foot-small"><span>© 2026 Bell &amp; Moss Ltd</span><span>Walnut from Herefordshire · Glass from Hackney · Moss from Kent</span></p>
+ </footer>
+ </main>
+
+ <div class="toast" role="status"></div>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/terrarium/main.js b/examples/terrarium/main.js
new file mode 100644
index 0000000..5e934d5
--- /dev/null
+++ b/examples/terrarium/main.js
@@ -0,0 +1,655 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { FogGlass, bellProfile } from './glass.js';
+import { walnutMaterial, linenTextures, plasterTextures, WindowCookie, walnutBase, substrateLayers } from './set.js';
+
+const Q = new URLSearchParams(location.search);
+const MOBILE = matchMedia('(max-width: 760px)').matches;
+const V3 = (x, y, z) => new THREE.Vector3(x, y, z);
+
+// ─── Engine ────────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 28, near: 0.05, far: 60, dpr: 1.5, background: 0xe7dfd0,
+ post: {
+ ao: { aoRadius: 0.32, intensity: 1.7, distanceFalloff: 0.55 },
+ bloom: { intensity: 0.42, luminanceThreshold: 0.9, luminanceSmoothing: 0.25, radius: 0.62 },
+ tone: 'neutral',
+ vignette: { offset: 0.42, darkness: 0.34 },
+ noise: 0.028,
+ ca: 0.0005,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.localClippingEnabled = true;
+
+// A bright room: a four-pane window on the left (it shows up as a reflection on the glass), a warm ceiling, linen walls.
+const panes = [[0.86, -0.72], [0.86, 0.72], [-0.86, -0.72], [-0.86, 0.72]].map(([dy, dz]) => ({ pos: [-9, 3.3 + dy, 1.4 + dz], size: [1.3, 1.6], intensity: 11, color: 0xfff2de }));
+scene.environment = studioEnvironment(renderer, {
+ top: 0xd6cdbd, bottom: 0x6e6252, blur: 0.02,
+ panels: [...panes,
+ { pos: [0, 9, 1], size: [7, 5], intensity: 1.3, color: 0xfff6ea },
+ { pos: [9, 2.5, 2], size: [4, 5], intensity: 0.9, color: 0xf2ece2 },
+ { pos: [1, 2.2, 10], size: [10, 4], intensity: 0.75, color: 0xf6efe4 }],
+});
+scene.environmentIntensity = 0.75;
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 8 });
+const loaderEl = document.querySelector('.loader');
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1400,
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = Math.round(v * 100);
+ loaderEl.style.setProperty('--p', v.toFixed(3));
+ },
+ exit: () => { startIntro(); return gsap.to(loaderEl, { '--r': '150vmax', duration: 1.7, ease: 'power2.in' }); },
+});
+
+// ─── The room ──────────────────────────────────────────────────────────────────
+const cookie = new WindowCookie(renderer, 512);
+const linen = linenTextures(renderer, { threads: 150, color: [0.9, 0.86, 0.78] });
+for (const t of [linen.albedo, linen.normal]) t.repeat.set(34, 11);
+const table = new THREE.Mesh(new THREE.PlaneGeometry(44, 13), new THREE.MeshStandardMaterial({
+ map: linen.albedo, normalMap: linen.normal, normalScale: new THREE.Vector2(0.55, 0.55), roughness: 0.94, envMapIntensity: 0.7,
+}));
+table.rotation.x = -Math.PI / 2; table.position.set(7, 0, 3.9); table.receiveShadow = true;
+scene.add(table);
+const plaster = plasterTextures(renderer);
+for (const t of [plaster.albedo, plaster.normal]) t.repeat.set(6, 1.4);
+const wall = new THREE.Mesh(new THREE.PlaneGeometry(44, 10), new THREE.MeshStandardMaterial({
+ map: plaster.albedo, normalMap: plaster.normal, normalScale: new THREE.Vector2(0.4, 0.4), roughness: 0.97, envMapIntensity: 0.6,
+}));
+wall.position.set(7, 5, -2.6); wall.receiveShadow = true;
+scene.add(wall);
+
+scene.add(new THREE.HemisphereLight(0xfaf5ec, 0xd6c8ae, 1.55));
+const rim = new THREE.DirectionalLight(0xe4ecff, 0.55);
+rim.position.set(4, 3.5, -4);
+scene.add(rim, rim.target);
+
+function windowLight(tx) {
+ const s = new THREE.SpotLight(0xfff0d8, 3.6, 0, 0.42, 0.12, 0);
+ s.map = cookie.texture;
+ s.position.set(tx - 5.4, 4.7, 2.6);
+ s.target.position.set(tx + 0.4, 0.2, -0.7);
+ s.castShadow = !Q.has('noshadow');
+ s.shadow.mapSize.set(2048, 2048);
+ s.shadow.camera.near = 3; s.shadow.camera.far = 16;
+ s.shadow.bias = -0.00025; s.shadow.normalBias = 0.02; s.shadow.radius = 5;
+ scene.add(s, s.target);
+ return s;
+}
+const sun = windowLight(0);
+const SHOP_X = 7.4;
+const shopSun = windowLight(SHOP_X);
+
+// ─── The stage: walnut base, the world, the bell ──────────────────────────────
+const clip = new THREE.Plane(V3(0, 1, 0), -0.16);
+const walnut = walnutMaterial({ scale: 1.5, seed: 3 });
+const profile = bellProfile();
+
+const stage = new THREE.Group();
+scene.add(stage);
+const turntable = new THREE.Group();
+stage.add(turntable);
+const base = walnutBase(walnut);
+turntable.add(base.mesh);
+clip.constant = -base.top;
+const hero = new FogGlass(renderer, profile, { res: MOBILE ? [1024, 512] : [2048, 1024] });
+hero.group.position.y = base.grooveY;
+stage.add(hero.group);
+
+const CLIMATES = [
+ { key: 'moss', file: 'models/terrarium/moss.glb', width: 1.1, yaw: -2.3, name: 'Moss Forest', no: '0412', fog: 1, fogMax: 1, streak: [0.07, 0.31], spore: [1.0, 0.96, 0.78], blink: 0, count: 55 },
+ { key: 'desert', file: 'models/terrarium/desert.glb', width: 1.12, yaw: 0.25, name: 'High Desert', no: '0388', fog: 0.6, fogMax: 0.6, streak: [0.06, 0.24], spore: [1.0, 0.85, 0.55], blink: 0, count: 50 },
+ { key: 'tropic', file: 'models/terrarium/tropic.glb', width: 1.08, yaw: 0.1, name: 'Cloud Tropic', no: '0431', fog: 1, fogMax: 0.6, streak: [0.13, 0.4], spore: [0.8, 1.0, 0.45], blink: 1, count: 46 },
+];
+const worlds = CLIMATES.map(() => { const h = new THREE.Group(); h.position.y = base.top; h.visible = false; turntable.add(h); return h; });
+worlds[0].visible = true;
+
+// Spores / fireflies inside the bell. Additive but in the opaque list, so the fogged glass blurs them properly.
+const spores = (() => {
+ const N = 140;
+ const pos = new Float32Array(N * 3), seed = new Float32Array(N);
+ for (let i = 0; i < N; i++) {
+ const a = Math.random() * Math.PI * 2, r = Math.sqrt(Math.random()) * 0.46;
+ pos.set([Math.cos(a) * r, 0.34 + Math.random() * 0.9, Math.sin(a) * r], i * 3);
+ seed[i] = Math.random();
+ }
+ const geo = new THREE.BufferGeometry();
+ geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ geo.setAttribute('seed', new THREE.BufferAttribute(seed, 1));
+ const mat = new THREE.ShaderMaterial({
+ blending: THREE.AdditiveBlending, depthWrite: false, transparent: false,
+ uniforms: { uTime: { value: 0 }, uColor: { value: new THREE.Color(0.9, 1, 0.8) }, uBlink: { value: 0 }, uAlpha: { value: 0 }, uCount: { value: 90 }, uDpr: { value: 1 } },
+ vertexShader: `attribute float seed; uniform float uTime, uBlink, uAlpha, uCount, uDpr; varying float vA;
+ void main(){
+ vec3 p = position; float t = uTime * (0.08 + seed * 0.1);
+ p.x += sin(t * 2.3 + seed * 40.) * 0.07; p.z += cos(t * 1.9 + seed * 23.) * 0.07;
+ p.y = 0.3 + mod(p.y - 0.3 + t * 0.12 * (1. - uBlink * .8), 0.95);
+ float r = length(p.xz); if (r > 0.5) p.xz *= 0.5 / r;
+ float edge = smoothstep(0.3, 0.42, p.y) * smoothstep(1.25, 1.05, p.y);
+ float blink = mix(1., pow(0.5 + 0.5 * sin(uTime * (1.2 + seed * 1.6) + seed * 60.), 8.), uBlink);
+ vA = edge * blink * uAlpha * step(seed * 140., uCount);
+ vec4 mv = modelViewMatrix * vec4(p, 1.);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (7. + seed * 9.0 + uBlink * 6.) * uDpr * (3.2 / -mv.z);
+ }`,
+ fragmentShader: `uniform vec3 uColor; varying float vA;
+ void main(){ float d = length(gl_PointCoord - .5); float a = smoothstep(.5, .0, d); a = a * a * (0.4 + 0.6 * a); gl_FragColor = vec4(uColor * a * vA * 3.4, 1.); }`,
+ });
+ const pts = new THREE.Points(geo, mat);
+ pts.frustumCulled = false; pts.renderOrder = 10;
+ stage.add(pts);
+ engine.onResize((w, h, dpr) => { mat.uniforms.uDpr.value = dpr; });
+ return mat;
+})();
+function setSpores(i) {
+ const c = CLIMATES[i];
+ spores.uniforms.uColor.value.setRGB(...c.spore);
+ spores.uniforms.uBlink.value = c.blink;
+ spores.uniforms.uCount.value = c.count;
+}
+setSpores(0);
+
+// Exploded substrate
+const layers = substrateLayers(renderer, clip);
+const LAYER_Y = { soil: 1.14, mesh: 0.87, charcoal: 0.57, stones: 0.25 };
+const LAYER_T = { soil: [0.12, 0.55], mesh: [0.24, 0.66], charcoal: [0.36, 0.78], stones: [0.48, 0.9] };
+for (const L of layers) { L.group.position.y = base.top - L.h - 0.02; stage.add(L.group); }
+const WORLD_UP = 1.52;
+
+// ─── Shop row: three bells on the same sill, further along ───────────────────
+const SHOP = [
+ { ci: 0, x: SHOP_X - 1.95, s: 0.8, yaw: -2.0 },
+ { ci: 1, x: SHOP_X + 0.02, s: 1.0, yaw: 0.35 },
+ { ci: 2, x: SHOP_X + 2.1, s: 1.2, yaw: -0.3 },
+];
+for (const st of SHOP) {
+ st.group = new THREE.Group();
+ st.group.position.set(st.x, 0, st.ci === 1 ? -0.1 : 0.05);
+ st.group.scale.setScalar(st.s);
+ scene.add(st.group);
+ const b = new THREE.Mesh(base.mesh.geometry, walnut);
+ b.castShadow = b.receiveShadow = true;
+ b.rotation.y = st.ci * 2.1;
+ st.group.add(b);
+ st.holder = new THREE.Group(); st.holder.position.y = base.top; st.holder.rotation.y = st.yaw;
+ st.group.add(st.holder);
+ st.glass = new FogGlass(renderer, profile, { res: [1024, 512] });
+ st.glass.group.position.y = base.grooveY;
+ st.glass.ambientDrops = 0.3;
+ st.glass.uniforms.uFogK.value = CLIMATES[st.ci].fog;
+ st.glass.uniforms.uFogMax.value = CLIMATES[st.ci].fogMax;
+ st.group.add(st.glass.group);
+ st.glass.active = false;
+}
+const glasses = [hero, ...SHOP.map(s => s.glass)];
+const glassShadow = new THREE.MeshDepthMaterial({ depthPacking: THREE.RGBADepthPacking, alphaHash: true, opacity: 0.22 });
+for (const g of glasses) { g.mesh.castShadow = true; g.mesh.customDepthMaterial = glassShadow; }
+
+// ─── Load worlds ───────────────────────────────────────────────────────────────
+const loads = CLIMATES.map((c, i) => assets.gltf(c.file).then(g => {
+ const m = g.scene;
+ normalize(m, c.width, { axis: 'x' });
+ prepModel(m, renderer, { env: 0.8 });
+ const wrap = new THREE.Group(); wrap.rotation.y = c.yaw; wrap.add(m);
+ // shop copies share geometry but not clipping
+ for (const st of SHOP.filter(s => s.ci === i)) {
+ const copy = m.clone(true);
+ copy.traverse(o => { if (o.isMesh) { o.material = o.material.clone(); o.material.clippingPlanes = null; } });
+ st.holder.add(copy);
+ }
+ m.traverse(o => { if (o.isMesh) { o.material.clippingPlanes = [clip]; o.material.clipShadows = true; } });
+ worlds[i].add(wrap);
+}).catch(e => console.warn('world missing', c.key, e.message)));
+
+// ─── Climate swaps ─────────────────────────────────────────────────────────────
+const swap = { lift: 0, busy: false, cur: 0, want: 0, spin: 0 };
+const tabs = [...document.querySelectorAll('.tab')];
+const climCards = [...document.querySelectorAll('.clim')];
+const heroLabel = document.querySelector('.hero-label');
+function showClimate(i) {
+ tabs.forEach((t, k) => { t.classList.toggle('on', k === i); t.setAttribute('aria-selected', k === i); });
+ climCards.forEach((c, k) => c.classList.toggle('on', k === i));
+ const c = CLIMATES[i];
+ heroLabel.innerHTML = `<span>No. ${c.no}</span><span>${c.name}</span><span>Sealed 14 · 03 · 2026</span>`;
+}
+function requestClimate(i) {
+ if (swap.want === i) return;
+ swap.want = i;
+ showClimate(i);
+ if (!swap.busy) runSwap();
+}
+function runSwap() {
+ const from = swap.cur, to = swap.want;
+ if (from === to) return;
+ swap.busy = true;
+ const tl = gsap.timeline({ onComplete: () => { swap.busy = false; if (swap.want !== swap.cur) runSwap(); } });
+ const spinTo = swap.spin + Math.PI;
+ tl.to(swap, { lift: 1, duration: 0.85, ease: 'power2.inOut' })
+ .to(swap, { spin: spinTo, duration: 1.7, ease: 'power3.inOut' }, 0.4)
+ .to(worlds[from].position, { y: base.top - 0.98, duration: 0.72, ease: 'power2.in' }, 0.5)
+ .add(() => {
+ worlds[from].visible = false;
+ worlds[to].visible = true; worlds[to].position.y = base.top - 0.98; worlds[to].rotation.y = -spinTo; // faces front when the base stops
+ swap.cur = to; setSpores(to); hero.uniforms.uFogK.value = CLIMATES[to].fog; hero.uniforms.uFogMax.value = CLIMATES[to].fogMax;
+ }, 1.22)
+ .to(worlds[to].position, { y: base.top, duration: 0.9, ease: 'power3.out' }, 1.24)
+ .to(swap, { lift: 0, duration: 0.95, ease: 'power2.inOut' }, 2.0);
+}
+tabs.forEach((t, i) => t.addEventListener('click', () => {
+ const el = sections.climates;
+ const y = el.offsetTop + (el.offsetHeight - innerHeight) * ((i + 0.5) / 3);
+ window.__lenis?.scrollTo(y, { duration: 1.4 });
+ requestClimate(i);
+ manualUntil = performance.now() + 1600;
+}));
+let manualUntil = 0;
+
+// ─── Scroll choreography ───────────────────────────────────────────────────────
+const sections = Object.fromEntries([...document.querySelectorAll('[data-sec]')].map(el => [el.dataset.sec, el]));
+sections.hero = document.querySelector('.hero');
+const foot = document.querySelector('.foot');
+const navEl = document.querySelector('.nav');
+const navLinks = [...document.querySelectorAll('.links a')];
+let navCur = null;
+if (MOBILE) document.querySelector('.wipe-hint-text').textContent = 'Drag to wipe the glass';
+
+// camera poses: position, target, vertical fov, lens shift (fraction of the frame, +x moves the subject right)
+const P = (pos, look, fov, sx = 0, sy = 0, extra = {}) => ({ pos: V3(...pos), look: V3(...look), fov, sx, sy, ...extra });
+const POSES = MOBILE ? {
+ hero: P([0.8, 1.75, 8.4], [0, 0.82, 0], 34, 0, -0.1),
+ clim: P([0.35, 1.5, 8.0], [0, 0.8, 0], 34, 0, -0.03),
+ insideA: P([2.6, 2.8, 10.2], [0, 1.1, 0], 34, -0.17, 0.02),
+ insideB: P([3.3, 3.2, 11.0], [0, 1.25, 0], 34, -0.2, 0.02),
+ care: P([-1.5, 1.4, 8.4], [0, 0.8, 0], 34, 0, 0.14),
+ careB: P([-0.8, 1.5, 8.6], [0, 0.8, 0], 34, 0, 0.14),
+ shop: P([SHOP_X - 1.95, 1.45, 6.2], [SHOP_X - 1.95, 0.7, 0], 34, 0, 0.17),
+ shopB: P([SHOP_X + 2.1, 1.75, 7.6], [SHOP_X + 2.1, 0.9, 0], 34, 0, 0.17),
+ visit: P([SHOP_X + 5.4, 2.3, 6.2], [SHOP_X + 0.9, 0.72, -0.2], 34, 0, -0.14),
+} : {
+ hero: P([1.55, 1.5, 5.3], [0, 0.8, 0], 28, 0.17, 0.0),
+ clim: P([0.4, 1.12, 5.25], [0, 0.8, 0], 28, 0.2, 0.0),
+ insideA: P([2.3, 2.3, 7.4], [0, 1.0, 0], 28, 0.03, 0.0),
+ insideB: P([3.0, 2.75, 7.9], [0, 1.24, 0], 28, 0.03, 0.0),
+ care: P([-1.85, 1.05, 5.0], [0, 0.8, 0], 28, -0.2, 0.0),
+ careB: P([-1.0, 1.15, 5.2], [0, 0.8, 0], 28, -0.2, 0.0),
+ shop: P([SHOP_X, 1.7, 8.6], [SHOP_X, 0.95, 0], 28, 0, 0.075),
+ shopB: P([SHOP_X + 0.6, 1.65, 8.5], [SHOP_X, 0.95, 0], 28, 0, 0.075),
+ visit: P([SHOP_X + 5.0, 2.2, 5.6], [SHOP_X + 1.1, 0.72, -0.2], 30, 0.17, 0.02),
+};
+let KEYS = [];
+function layout() {
+ const vh = innerHeight;
+ const top = el => el.getBoundingClientRect().top + scrollY;
+ const s = sections;
+ const cT = top(s.climates), cH = s.climates.offsetHeight;
+ const iT = top(s.inside), iH = s.inside.offsetHeight;
+ const kT = top(s.care), kH = s.care.offsetHeight;
+ const sT = top(s.shop), sH = s.shop.offsetHeight;
+ const vT = top(s.visit);
+ const max = document.documentElement.scrollHeight - vh;
+ const k = (y, pose, o = {}) => ({ y, pose: POSES[pose], explode: 0, lift: 0, day: 0.25, ...o });
+ KEYS = [
+ k(0, 'hero'),
+ k(cT, 'clim'),
+ k(cT + cH - vh, 'clim', { day: 0.25 }),
+ k(iT, 'insideA'),
+ k(iT + (iH - vh) * 0.62, 'insideB', { explode: 1, lift: 1 }),
+ k(iT + iH - vh, 'insideB', { explode: 1, lift: 1 }),
+ k(kT, 'care', { day: 0 }),
+ k(kT + kH - vh, 'careB', { day: 1 }),
+ k(sT, 'shop', { day: 0.3 }),
+ k(sT + sH - vh, 'shopB', { day: 0.3 }),
+ k(vT + s.visit.offsetHeight * 0.35, 'visit', { day: 0.3 }),
+ k(max + 1, 'visit', { day: 0.3 }),
+ ];
+ // the lift during "inside" should happen before the layers separate
+ KEYS[4].liftEarly = true;
+}
+const ST = { pos: V3(), look: V3(), fov: 28, sx: 0, sy: 0, explode: 0, lift: 0, day: 0.25 };
+function sampleKeys(y) {
+ let i = 0;
+ while (i < KEYS.length - 2 && y > KEYS[i + 1].y) i++;
+ const a = KEYS[i], b = KEYS[i + 1];
+ const raw = clamp((y - a.y) / Math.max(1, b.y - a.y));
+ const f = smooth(0, 1, raw);
+ const out = {
+ pos: V3().lerpVectors(a.pose.pos, b.pose.pos, f), look: V3().lerpVectors(a.pose.look, b.pose.look, f),
+ fov: lerp(a.pose.fov, b.pose.fov, f), sx: lerp(a.pose.sx, b.pose.sx, f), sy: lerp(a.pose.sy, b.pose.sy, f),
+ explode: lerp(a.explode, b.explode, raw), lift: lerp(a.lift, b.lift, b.liftEarly ? smooth(0, 0.35, raw) : raw), day: lerp(a.day, b.day, raw),
+ seg: i, raw,
+ };
+ return out;
+}
+
+// ─── Wiping ────────────────────────────────────────────────────────────────────
+const ray = new THREE.Raycaster();
+const ndc = new THREE.Vector2();
+const wipeEl = document.querySelector('.wipe-cursor');
+const hintEl = document.querySelector('.wipe-hint');
+let lastHit = null; // { glass, local }
+let wiped = 0; // metres the visitor has wiped (drives the hint)
+let lastUserWipe = -99;
+let pointerMoved = false;
+let touchWipe = false;
+const BRUSH = 0.1;
+pointer.on('move', () => { pointerMoved = true; });
+let cursorApi = null;
+
+function castGlass(x, y) {
+ ndc.set(x, y);
+ ray.setFromCamera(ndc, camera);
+ let best = null;
+ for (const g of glasses) {
+ if (!g.active || g.lifted) continue;
+ const h = g.hit(ray);
+ if (h && (!best || h.point.distanceToSquared(camera.position) < best.h.point.distanceToSquared(camera.position))) best = { g, h };
+ }
+ return best;
+}
+addEventListener('touchstart', e => {
+ const t = e.touches[0];
+ const hit = castGlass(t.clientX / innerWidth * 2 - 1, -(t.clientY / innerHeight) * 2 + 1);
+ touchWipe = !!hit && !e.target.closest('a,button,input');
+}, { passive: true });
+addEventListener('touchmove', e => { if (touchWipe) e.preventDefault(); }, { passive: false });
+addEventListener('touchend', () => { touchWipe = false; lastHit = null; });
+
+// Ghost finger: draws a slow streak on the glass so the hero frame always shows the world through a wiped window.
+const ghost = { on: false };
+function ghostWipe(glass, { dur = 1.5, v0 = 0.36, v1 = 0.5, span = 0.2, delay = 0, wave = 0.05 } = {}) {
+ const uc = glass.uFacing(camera.position);
+ const st = { s: 0 };
+ let prev = null;
+ const R = BRUSH * 1.15;
+ return gsap.to(st, {
+ s: 1, duration: dur, delay, ease: 'power1.inOut',
+ onStart: () => { ghost.on = true; },
+ onUpdate: () => {
+ const s = st.s;
+ const u = uc + (s - 0.5) * span;
+ const v = lerp(v0, v1, s) + Math.sin(s * Math.PI * 1.6 + 0.4) * wave;
+ const p = profile.pos(((u % 1) + 1) % 1, v);
+ glass.brush(prev ?? p, p, R, 1);
+ prev = p;
+ },
+ onComplete: () => { ghost.on = false; },
+ });
+}
+
+// ─── HTML anchored to 3D ──────────────────────────────────────────────────────
+const labelEls = Object.fromEntries([...document.querySelectorAll('.layer-labels li')].map(li => [li.dataset.k, li]));
+const productEls = [...document.querySelectorAll('.product')];
+const careItems = [...document.querySelectorAll('.care-list li')];
+const clockTime = document.querySelector('.clock-time'), clockNote = document.querySelector('.clock-note'), clockBar = document.querySelector('.clock');
+const NOTES = [[0, 'The soil warms and the glass fogs over.'], [0.3, 'The sun climbs; the bell clears and the moss drinks.'],
+ [0.62, 'Afternoon. Water rises as vapour, invisibly.'], [0.8, 'Evening. It rains on the inside.']];
+const tmp = V3(), tmp2 = V3(), right = V3();
+function project(v) { tmp.copy(v).project(camera); return [(tmp.x + 1) / 2 * innerWidth, (1 - tmp.y) / 2 * innerHeight, tmp.z]; }
+
+// ─── Frame loop ────────────────────────────────────────────────────────────────
+const cam = { pos: V3().copy(POSES.hero.pos), look: V3().copy(POSES.hero.look), fov: POSES.hero.fov, sx: POSES.hero.sx, sy: POSES.hero.sy };
+const intro = { k: 0 };
+const liftState = new Map(glasses.map(g => [g, { seated: true }]));
+let dayS = 0.25, explodeS = 0, liftS = 0;
+let scrollYS = 0;
+let frameNo = 0;
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ const y = window.__lenis ? window.__lenis.scroll : scrollY;
+ scrollYS = y;
+ const st = sampleKeys(y);
+
+ // climate follows the scroll inside its section (tabs scroll there too)
+ const cs = sections.climates;
+ const cp = clamp((y - cs.offsetTop) / Math.max(1, cs.offsetHeight - innerHeight));
+ const inClim = y >= cs.offsetTop - innerHeight * 0.5;
+ const want = inClim ? Math.min(2, Math.floor(cp * 3 * 0.999)) : 0;
+ if (performance.now() > manualUntil && KEYS.length) requestClimate(want);
+
+ // camera
+ const lam = 4.2;
+ cam.pos.x = damp(cam.pos.x, st.pos.x, lam, dt); cam.pos.y = damp(cam.pos.y, st.pos.y, lam, dt); cam.pos.z = damp(cam.pos.z, st.pos.z, lam, dt);
+ cam.look.x = damp(cam.look.x, st.look.x, lam, dt); cam.look.y = damp(cam.look.y, st.look.y, lam, dt); cam.look.z = damp(cam.look.z, st.look.z, lam, dt);
+ cam.fov = damp(cam.fov, st.fov, lam, dt); cam.sx = damp(cam.sx, st.sx, lam, dt); cam.sy = damp(cam.sy, st.sy, lam, dt);
+ const ik = 1 - intro.k;
+ camera.position.copy(cam.pos).add(tmp.set(pointer.sx * 0.1 + Math.sin(t * 0.21) * 0.03, pointer.sy * 0.05 + Math.sin(t * 0.33) * 0.015 + ik * 0.35, ik * 0.9));
+ camera.lookAt(tmp2.copy(cam.look).add(tmp.set(0, ik * 0.1, 0)));
+ if (Math.abs(camera.fov - cam.fov) > 1e-3) { camera.fov = cam.fov; }
+ const w = innerWidth, h = innerHeight;
+ camera.setViewOffset(w, h, -cam.sx * w, cam.sy * h, w, h);
+
+ // scene params
+ explodeS = damp(explodeS, st.explode, 6, dt);
+ liftS = damp(liftS, st.lift, 6, dt);
+ dayS = damp(dayS, st.day, 5, dt);
+ const e = explodeS;
+
+ // bell lift: scroll (exploded view) or a climate swap
+ const lift = Math.max(liftS, swap.lift);
+ hero.group.position.y = base.grooveY + Math.max(smooth(0, 1, liftS) * 2.9, smooth(0, 1, swap.lift) * 1.3);
+ hero.group.rotation.z = Math.sin(lift * Math.PI) * 0.035;
+ hero.group.visible = hero.group.position.y < 2.9;
+ hero.lifted = lift > 0.04;
+ turntable.rotation.y = swap.spin + e * 0.5 + Math.sin(t * 0.1) * 0.02;
+ spores.uniforms.uAlpha.value = (1 - smooth(0, 0.4, lift)) * intro.k;
+ spores.uniforms.uTime.value = t;
+
+ // exploded substrate
+ const wy = base.top + smooth(0.0, 0.45, e) * WORLD_UP;
+ if (!swap.busy) worlds[swap.cur].position.y = wy;
+ for (const L of layers) {
+ const [a, b] = LAYER_T[L.key];
+ const k = smooth(a, b, e);
+ L.group.visible = e > 0.01;
+ L.group.position.y = lerp(base.top - L.h - 0.02, base.top + LAYER_Y[L.key], k);
+ L.group.rotation.y = turntable.rotation.y * 0.6 + (1 - k) * 0.4;
+ }
+
+ // time of day: the window light swings across the wall; the fog lifts at noon and returns with the evening rain
+ const d = dayS;
+ const ang = lerp(-0.35, 0.5, d);
+ sun.position.set(-5.4 * Math.cos(ang) , 4.1 + Math.sin(d * Math.PI) * 1.4, 2.6 + Math.sin(ang) * 5.2);
+ const warm = smooth(0.65, 1, d) + (1 - smooth(0, 0.18, d)) * 0.4;
+ if (Q.has('sunp')) { sun.position.set(...Q.get('sunp').split(',').map(Number)); sun.target.position.set(...(Q.get('sunt') ?? '0.4,0.2,-0.7').split(',').map(Number)); }
+ sun.color.setRGB(1, lerp(0.95, 0.87, warm), lerp(0.86, 0.74, warm));
+ sun.intensity = lerp(3.6, 2.8, warm) * (Q.has('nosun') ? 0 : 1);
+ cookie.mat.uniforms.uWarm.value = warm * 0.3;
+ const dryDay = smooth(0.16, 0.42, d) * (1 - smooth(0.56, 0.76, d)) * 0.92;
+ const inCare = st.seg >= 5 && st.seg <= 7 ? 1 : 0;
+ hero.ambientDrops = 0.5 + smooth(0.72, 0.95, d) * 7 * inCare;
+
+ // glass state machines: dry when lifted, fog creeps up from the rim when set down again
+ for (const g of glasses) {
+ const L = liftState.get(g);
+ const isHero = g === hero;
+ if (isHero && g.lifted) {
+ L.seated = false; g.front = null; g.grow = 1;
+ g.dry = damp(g.dry, 1, 2.5, dt);
+ } else if (isHero && !L.seated && lift < 0.02) {
+ L.seated = true;
+ g.dry = 0; g.clear(1); g.grow = 7;
+ g.front = { v: -0.1 };
+ gsap.to(g.front, { v: 1.15, duration: 2.6, ease: 'power1.inOut', onComplete: () => { g.front = null; g.grow = 1; if (g === hero) ghost.pending = engine.time + 0.9; } });
+ } else if (L.seated) {
+ g.dry = isHero ? dryDay * inCare : 0;
+ if (!g.front) g.grow = isHero && inCare ? 2.6 : 1;
+ }
+ }
+
+ // visibility / activity
+ const camX = camera.position.x;
+ hero.active = camX < 4.5 && !engine.paused;
+ for (const s of SHOP) s.glass.active = camX > 3.2 && !engine.paused;
+ frameNo++;
+ sun.shadow.autoUpdate = frameNo < 4 || camX < 4.8;
+ shopSun.shadow.autoUpdate = frameNo < 4 || camX > 2.8;
+
+ // wiping
+ const px = pointer.x, py = pointer.y;
+ let hit = null;
+ if (pointer.active && intro.k > 0.5 && (!MOBILE || touchWipe)) hit = castGlass(px, py);
+ const overUI = document.elementFromPoint?.(pointer.px, pointer.py)?.closest?.('a,button,input,.tabs,.product,.clim-panel h2,.nav');
+ if (hit && !overUI && (!MOBILE || touchWipe)) {
+ const local = hit.h.local;
+ const same = lastHit && lastHit.g === hit.g;
+ const R = BRUSH * (touchWipe ? 1.45 : pointer.down ? 1.7 : 1);
+ if (pointerMoved || pointer.down || touchWipe || !same) {
+ hit.g.brush(same ? lastHit.local : local, local, R, 1);
+ if (same) { wiped += lastHit.local.distanceTo(local) * hit.g.mesh.getWorldScale(tmp).x; lastUserWipe = t; }
+ }
+ lastHit = { g: hit.g, local };
+ // wipe cursor, sized to the brush footprint on screen
+ const [cx, cy] = project(hit.h.point);
+ const [ex, ey] = project(tmp2.copy(hit.h.point).addScaledVector(right.setFromMatrixColumn(camera.matrixWorld, 0), R));
+ const rad = Math.hypot(ex - cx, ey - cy);
+ wipeEl.style.transform = `translate3d(${pointer.px}px, ${pointer.py}px, 0)`;
+ wipeEl.style.setProperty('--s', (rad / 30).toFixed(3));
+ wipeEl.style.setProperty('--rad', rad.toFixed(1) + 'px');
+ if (!touchWipe) { wipeEl.classList.add('on'); cursorApi?.set('hidden'); }
+ } else {
+ lastHit = null;
+ if (wipeEl.classList.contains('on')) { wipeEl.classList.remove('on'); cursorApi?.set(''); }
+ }
+ pointerMoved = false;
+
+ // idle: if nobody has wiped for a while, the ghost finger draws another streak
+ const ghostReady = intro.done && !ghost.on && hero.active && !hero.lifted && liftState.get(hero).seated && !hero.front && !swap.busy && st.seg <= 1;
+ const afterLanding = ghost.pending && t > ghost.pending && t - lastUserWipe > 2;
+ if (ghostReady && (afterLanding || (t - lastUserWipe > 9 && t - (ghost.last ?? 0) > 9.5))) {
+ ghost.last = t; ghost.pending = null;
+ const r = Math.random(), [a, b] = CLIMATES[swap.cur].streak;
+ ghostWipe(hero, { dur: 1.8, v0: a + r * 0.04, v1: b + (r - 0.5) * 0.06, span: 0.26 + r * 0.05, wave: 0.02 + r * 0.02 });
+ }
+ if (ghost.pending && (st.seg > 1 || hero.lifted)) ghost.pending = null;
+
+ // hint beside the bell
+ const heroOn = st.seg === 0 && st.raw < 0.4;
+ const [hx, hy] = project(tmp2.set(0.72, 0.62, 0).applyMatrix4(stage.matrixWorld));
+ if (MOBILE) { const [bx, by] = project(tmp2.set(0, 0.02, 0.8).applyMatrix4(stage.matrixWorld)); hintEl.style.transform = `translate3d(${(bx - hintEl.offsetWidth / 2).toFixed(1)}px, ${(by + 18).toFixed(1)}px, 0)`; }
+ else hintEl.style.transform = `translate3d(${(hx + 24).toFixed(1)}px, ${hy.toFixed(1)}px, 0)`;
+ hintEl.classList.toggle('on', intro.done && heroOn && wiped < 0.9);
+
+ // simulate
+ for (const g of glasses) g.step(dt, t);
+ cookie.update(dt, t);
+
+ // layer labels
+ const labelOn = e > 0.55 && st.seg >= 3 && st.seg <= 5;
+ right.setFromMatrixColumn(camera.matrixWorld, 0);
+ const lx = MOBILE ? innerWidth * 0.6 : innerWidth * 0.655;
+ const anchors = {
+ world: tmp2.set(0, wy + 0.22, 0), soil: V3(0, base.top + LAYER_Y.soil + 0.06, 0), mesh: V3(0, base.top + LAYER_Y.mesh + 0.01, 0),
+ charcoal: V3(0, base.top + LAYER_Y.charcoal + 0.03, 0), stones: V3(0, base.top + LAYER_Y.stones + 0.05, 0), base: V3(0, 0.1, 0),
+ };
+ let n = 0;
+ for (const [k, el] of Object.entries(labelEls)) {
+ const a = anchors[k].clone().addScaledVector(right, k === 'base' ? 0.78 : k === 'world' ? 0.55 : 0.52);
+ const [ax, ay] = project(a);
+ el.style.transform = `translate3d(${lx.toFixed(1)}px, ${(ay - 10).toFixed(1)}px, 0)`;
+ el.style.setProperty('--lead', Math.max(10, lx - ax - 12).toFixed(1) + 'px');
+ el.classList.toggle('on', labelOn && e > 0.55 + n * 0.06);
+ n++;
+ }
+
+ // care clock
+ if (st.seg >= 5 && st.seg <= 7) {
+ const hours = 7 + d * 12;
+ const hh = Math.floor(hours), mm = Math.floor((hours - hh) * 60 / 5) * 5;
+ clockTime.textContent = `${String(hh).padStart(2, '0')}:${String(mm).padStart(2, '0')}`;
+ let note = NOTES[0][1]; for (const [v, s] of NOTES) if (d >= v) note = s;
+ if (clockNote.textContent !== note) clockNote.textContent = note;
+ clockBar.style.setProperty('--day', d.toFixed(3));
+ careItems.forEach((li, i) => { li.classList.toggle('on', d > i * 0.22 + 0.02); li.classList.toggle('cur', d > i * 0.25 - 0.01 && d <= (i + 1) * 0.25 + (i === 3 ? 1 : 0)); });
+ }
+
+ // product cards under their bells
+ const shopOn = st.seg >= 8 && st.seg <= 9 || (st.seg === 7 && st.raw > 0.8);
+ SHOP.forEach((s, i) => {
+ const [x] = project(tmp2.set(s.x, 0, 0));
+ const el = productEls[i];
+ if (!MOBILE) el.style.transform = `translate3d(${(x - el.offsetWidth / 2).toFixed(1)}px, 0, 0)`;
+ el.classList.toggle('on', shopOn);
+ if (MOBILE) el.classList.toggle('near', Math.abs(camera.position.x - s.x) < 1);
+ });
+ navEl.classList.toggle('solid', y > innerHeight * 0.6);
+ const cur = st.seg >= 8 ? 'shop' : st.seg >= 6 ? 'care' : st.seg >= 3 ? 'inside' : st.seg >= 1 || st.raw > 0.6 ? 'climates' : '';
+ if (cur !== navCur) { navCur = cur; navLinks.forEach(a => a.classList.toggle('on', a.getAttribute('href') === '#' + cur)); }
+
+ // nothing to draw once the footer covers the canvas
+ engine.paused = foot.getBoundingClientRect().top <= 0;
+});
+
+// ─── Shop buttons ──────────────────────────────────────────────────────────────
+const toastEl = document.querySelector('.toast');
+const basketEl = document.querySelector('.basket');
+let toastTimer, basket = 0;
+function toast(msg, ms = 2800) {
+ toastEl.textContent = msg; toastEl.classList.add('on');
+ clearTimeout(toastTimer); toastTimer = setTimeout(() => toastEl.classList.remove('on'), ms);
+}
+document.querySelectorAll('.add').forEach(b => b.addEventListener('click', () => {
+ basket++; basketEl.textContent = basket; basketEl.classList.remove('bump'); void basketEl.offsetWidth; basketEl.classList.add('bump');
+ toast(`${b.dataset.name} reserved — we’ll blow your bell on Thursday.`);
+}));
+document.querySelector('.foot-news').addEventListener('submit', e => { e.preventDefault(); toast('Thank you. See you at the equinox.'); });
+
+// ─── Boot ─────────────────────────────────────────────────────────────────────
+const INTRO_TEXT = '.hero .eyebrow, .hero-sub, .hero-body, .hero-cta, .hero-label, .scroll-cue, .nav';
+gsap.set('.hero-title .ln', { yPercent: 60, opacity: 0 });
+gsap.set(INTRO_TEXT, { opacity: 0, y: 16 });
+function startIntro() {
+ intro.done = false;
+ gsap.to(intro, { k: 1, duration: 3.0, ease: 'power3.out' });
+ gsap.to('.hero-title .ln', { yPercent: 0, opacity: 1, duration: 1.8, ease: 'expo.out', stagger: 0.12, delay: 0.55 });
+ gsap.to(INTRO_TEXT, { opacity: 1, y: 0, duration: 1.3, ease: 'power3.out', stagger: 0.07, delay: 0.95 });
+ ghostWipe(hero, { dur: 2.0, delay: 1.5, v0: 0.07, v1: 0.31, span: 0.3, wave: 0.02 }).then(() => { intro.done = true; ghost.last = engine.time; window.__introDone = true; });
+}
+worldNav('terrarium', { theme: 'light', corner: 'bl' });
+cursorApi = cursor({ color: '#22281f', blend: 'normal', size: 30 });
+magnetic();
+const lenis = smoothScroll({ lerp: 0.085 });
+document.querySelectorAll('a[href^="#"]').forEach(a => a.addEventListener('click', e => {
+ const id = a.getAttribute('href'); const el = id === '#top' ? document.body : document.querySelector(id);
+ if (!el) return; e.preventDefault(); lenis.scrollTo(id === '#top' ? 0 : el, { duration: 1.8 });
+}));
+reveal('.climates h2, .inside h2, .care h2, .shop h2, .visit h2', { type: 'lines', stagger: 0.08, start: 'top 92%' });
+layout();
+addEventListener('resize', () => requestAnimationFrame(layout));
+
+await Promise.all(loads);
+await document.fonts?.ready;
+layout();
+
+// warm-up: every world, every layer, lifted and seated, compiled before the first frame
+for (const wv of worlds) wv.visible = true;
+for (const L of layers) L.group.visible = true;
+renderer.compile(scene, camera);
+for (const wv of worlds) wv.visible = false;
+worlds[0].visible = true;
+for (const L of layers) L.group.visible = false;
+// let the glass fog and a few old drips run before anyone sees it
+for (const g of glasses) {
+ g.clear(0);
+ const act = g.active; g.active = true;
+ for (let i = 0; i < 6; i++) g.spawnDrop(Math.random(), 0.25 + Math.random() * 0.5, 0.01 + Math.random() * 0.01, Math.random() * 3);
+ for (let i = 0; i < 200; i++) g.step(1 / 30, i / 30);
+ g.active = act;
+}
+engine.start();
+await loader.finish();
+// QA hooks: scroll to a fraction of a section
+window.__glassRect = () => {
+ const pts = [V3(-0.67, 0.15, 0), V3(0.67, 0.15, 0), V3(0, 1.6, 0), V3(0, 0.15, 0.67)].map(v => project(v.applyMatrix4(stage.matrixWorld)));
+ const xs = pts.map(p => p[0]), ys = pts.map(p => p[1]);
+ return { x: Math.min(...xs), y: Math.min(...ys), w: Math.max(...xs) - Math.min(...xs), h: Math.max(...ys) - Math.min(...ys) };
+};
+window.__at = (sec, p = 0) => { const el = sections[sec]; const top = el.getBoundingClientRect().top + scrollY; return top + Math.max(0, el.offsetHeight - innerHeight) * p; };
+if (Q.has('debug')) Object.assign(window, { hero, glasses, THREE, camera, scene, engine, swap, requestClimate, ghostWipe });
diff --git a/examples/terrarium/set.js b/examples/terrarium/set.js
new file mode 100644
index 0000000..515993b
--- /dev/null
+++ b/examples/terrarium/set.js
@@ -0,0 +1,315 @@
+// The room: walnut (solid procedural grain), linen cloth, plaster, a live window-light cookie, substrate layers.
+import { THREE } from '../../src/core/engine.js';
+import { bakeTexture, NOISE_GLSL } from '../../src/core/textures.js';
+import { mergeVertices } from 'three/examples/jsm/utils/BufferGeometryUtils.js';
+
+const N3 = /* glsl */`
+ float h13(vec3 p){ p = fract(p * .1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+ float n3(vec3 p){ vec3 i = floor(p), f = fract(p); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(h13(i), h13(i + vec3(1,0,0)), f.x), mix(h13(i + vec3(0,1,0)), h13(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(h13(i + vec3(0,0,1)), h13(i + vec3(1,0,1)), f.x), mix(h13(i + vec3(0,1,1)), h13(i + vec3(1,1,1)), f.x), f.y), f.z); }
+ float fb3(vec3 p){ float s = 0., a = .5; for (int i = 0; i < 4; i++) { s += a * n3(p); p *= 2.03; a *= .5; } return s; }
+`;
+
+/** Oiled English walnut, grain computed in object space so a turned piece shows real flat-sawn figure. */
+export function walnutMaterial({ scale = 1, seed = 0, tone = 1 } = {}) {
+ const mat = new THREE.MeshPhysicalMaterial({ color: 0xffffff, roughness: 0.48, metalness: 0, clearcoat: 0.35, clearcoatRoughness: 0.32,
+ sheen: 0.3, sheenColor: new THREE.Color(0x6b4a33), sheenRoughness: 0.6, envMapIntensity: 0.9 });
+ mat.onBeforeCompile = sh => {
+ sh.uniforms.uSeed = { value: seed }; sh.uniforms.uScale = { value: scale }; sh.uniforms.uTone = { value: tone };
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vObj;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvObj = position;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', `#include <common>\nvarying vec3 vObj; uniform float uSeed, uScale, uTone;\n${N3}`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+ vec3 wp = vObj * uScale + uSeed;
+ float warp = fb3(wp * vec3(0.9, 3.2, 3.2)) * .55 + fb3(wp * 14.) * .05;
+ float ring = length(vec2(wp.y * 1.0 + 2.1, wp.z * .85 + .4)) * 11. + warp * 5.5;
+ float rr = fract(ring);
+ float late = smoothstep(.0, .18, rr) * (1. - smoothstep(.42, .9, rr));
+ float streak = fb3(wp * vec3(1.5, 22., 22.));
+ float pores = smoothstep(.62, .8, n3(wp * vec3(18., 260., 260.)));
+ vec3 dark = vec3(.030, .0135, .0062), mid = vec3(.078, .036, .016), light = vec3(.15, .074, .034);
+ vec3 wc = mix(mid, dark, late * .85);
+ wc = mix(wc, light, smoothstep(.45, .8, streak) * .55);
+ wc = mix(wc, vec3(.06, .04, .035), smoothstep(.55, .75, fb3(wp * 2.2 + 7.)) * .25); // a little purple-grey figure
+ wc *= 1. - pores * .35;
+ diffuseColor.rgb *= wc * uTone * 1.35;`)
+ .replace('#include <roughnessmap_fragment>', `#include <roughnessmap_fragment>
+ roughnessFactor = clamp(roughnessFactor + pores * .25 - late * .06, .05, 1.);`);
+ };
+ mat.customProgramCacheKey = () => 'walnut-1';
+ return mat;
+}
+
+/** Plain-weave linen: albedo + normal + roughness baked on the GPU. */
+export function linenTextures(renderer, { threads = 150, size = 1024, color = [0.86, 0.8, 0.7] } = {}) {
+ const H = `
+ float thread(float f){ return sqrt(max(0., sin(f * 3.14159))); }
+ float slubX(float id){ return .75 + .5 * fract(sin(id * 12.9898) * 43758.5453); }
+ float slubY(float id){ return .75 + .5 * fract(sin(id * 78.233) * 43758.5453); }
+ float H(vec2 uv){
+ vec2 p = uv * ${threads.toFixed(1)};
+ vec2 id = floor(p), f = fract(p);
+ float over = mod(id.x + id.y, 2.);
+ float wx = thread(f.x) * slubX(id.x) * (.85 + .3 * pnoise(vec2(id.x * .7, uv.y * 40.), 1000.));
+ float wy = thread(f.y) * slubY(id.y) * (.85 + .3 * pnoise(vec2(uv.x * 40., id.y * .7), 1000.));
+ float bendX = sin((f.y + over) * 3.14159) * .25, bendY = sin((f.x + 1. - over) * 3.14159) * .25;
+ return over > .5 ? max(wx * .9 + bendX, wy * .6) : max(wy * .9 + bendY, wx * .6);
+ }`;
+ const albedo = bakeTexture(renderer, size, `${H}
+ void main(){
+ float h = H(vUv);
+ float blot = fbm(vUv * 6., 6., 5, .55);
+ vec2 p = vUv * ${threads.toFixed(1)};
+ float slub = fract(sin(floor(p.x) * 3.1) * 9173.1) * .08 + fract(sin(floor(p.y) * 5.7) * 7211.3) * .08;
+ vec3 c = vec3(${color.map(v => v.toFixed(3)).join(',')});
+ c *= .8 + h * .24 + blot * .1 - slub;
+ gl_FragColor = vec4(c, 1.);
+ }`);
+ albedo.colorSpace = THREE.SRGBColorSpace;
+ const normal = bakeTexture(renderer, size, `${H}
+ void main(){
+ float e = 1. / ${size.toFixed(1)};
+ float hx = H(vUv + vec2(e, 0.)) - H(vUv - vec2(e, 0.));
+ float hy = H(vUv + vec2(0., e)) - H(vUv - vec2(0., e));
+ gl_FragColor = vec4(normalize(vec3(-hx * 1.6, -hy * 1.6, 1.)) * .5 + .5, 1.);
+ }`);
+ return { albedo, normal };
+}
+
+/** Warm plaster wall with a soft mottle. */
+export function plasterTextures(renderer) {
+ const albedo = bakeTexture(renderer, 1024, `
+ void main(){
+ float m = fbm(vUv * 3., 3., 6, .55), f = fbm(vUv * 28., 28., 4, .5);
+ vec3 c = vec3(.905, .87, .8) * (.93 + m * .12 + f * .03);
+ gl_FragColor = vec4(c, 1.);
+ }`);
+ albedo.colorSpace = THREE.SRGBColorSpace;
+ const normal = bakeTexture(renderer, 1024, `
+ float H(vec2 p){ return fbm(p * 9., 9., 6, .55) + fbm(p * 40., 40., 3, .5) * .3; }
+ void main(){ float e = 1. / 1024.; float hx = H(vUv + vec2(e,0.)) - H(vUv - vec2(e,0.)); float hy = H(vUv + vec2(0.,e)) - H(vUv - vec2(0.,e));
+ gl_FragColor = vec4(normalize(vec3(-hx * 6., -hy * 6., 1.)) * .5 + .5, 1.); }`);
+ return { albedo, normal };
+}
+
+/** A four-pane sash window with a tree outside, rendered live so the leaves move in the breeze. */
+export class WindowCookie {
+ constructor(renderer, size = 512) {
+ this.renderer = renderer;
+ this.rt = new THREE.WebGLRenderTarget(size, size, { type: THREE.UnsignedByteType, generateMipmaps: false, minFilter: THREE.LinearFilter, depthBuffer: false });
+ this.rt.texture.colorSpace = THREE.SRGBColorSpace;
+ this.mat = new THREE.ShaderMaterial({
+ uniforms: { uTime: { value: 0 }, uLeaf: { value: 1 }, uWarm: { value: 0 } },
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }',
+ fragmentShader: `precision highp float; varying vec2 vUv; uniform float uTime, uLeaf, uWarm; ${NOISE_GLSL}
+ float box(vec2 p, vec2 lo, vec2 hi, float s){ return smoothstep(lo.x - s, lo.x + s, p.x) * smoothstep(hi.x + s, hi.x - s, p.x) * smoothstep(lo.y - s, lo.y + s, p.y) * smoothstep(hi.y + s, hi.y - s, p.y); }
+ void main(){
+ vec2 p = vUv;
+ float win = box(p, vec2(.2, .1), vec2(.8, .9), .045);
+ float mv = smoothstep(.004, .03, abs(p.x - .5));
+ float mh = smoothstep(.004, .028, abs(p.y - .52));
+ float mh2 = 1. - (1. - smoothstep(.002, .016, abs(p.y - .255))) * .75;
+ float mh3 = 1. - (1. - smoothstep(.002, .016, abs(p.y - .745))) * .75;
+ float frame = win * mv * mh * mh2 * mh3;
+ vec2 sway = vec2(sin(uTime * .31) * .018 + sin(uTime * .83) * .006, cos(uTime * .27) * .012);
+ vec2 q = p * vec2(2.3, 2.0) + sway;
+ float lf = fbm(q * 2.0 + vec2(0., uTime * .004), 64., 5, .55) + .5 * fbm(q * 5.5 + sway * 3., 128., 3, .5);
+ float leaf = smoothstep(.16, .4, lf) * smoothstep(.95, .35, p.y) * uLeaf;
+ float branch = smoothstep(.03, .0, abs(p.y - .78 - sin(p.x * 5. + 1.) * .06 - sway.y)) * smoothstep(.1, .5, p.x) * uLeaf;
+ float light = frame * (1. - leaf * .6) * (1. - branch * .6);
+ vec3 col = mix(vec3(1., .96, .88), vec3(1., .72, .46), uWarm) * light;
+ gl_FragColor = vec4(col, 1.);
+ }`,
+ depthTest: false, depthWrite: false,
+ });
+ this.scene = new THREE.Scene();
+ const q = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.mat); q.frustumCulled = false;
+ this.scene.add(q);
+ this.cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ this.texture = this.rt.texture;
+ this._acc = 1;
+ }
+ update(dt, t) {
+ this._acc += dt;
+ if (this._acc < 1 / 30) return;
+ this._acc = 0;
+ this.mat.uniforms.uTime.value = t;
+ const r = this.renderer, prev = r.getRenderTarget();
+ r.setRenderTarget(this.rt); r.render(this.scene, this.cam); r.setRenderTarget(prev);
+ }
+}
+
+/** Walnut plinth: a turned lathe piece with a groove the glass sits in. Returns { mesh, top }. */
+export function walnutBase(material) {
+ const P = [[0, 0.16], [0.6, 0.16], [0.628, 0.158], [0.64, 0.146], [0.688, 0.146], [0.7, 0.158], [0.735, 0.16], [0.76, 0.152],
+ [0.775, 0.132], [0.772, 0.105], [0.752, 0.085], [0.742, 0.06], [0.75, 0.03], [0.762, 0.012], [0.758, 0.0], [0, 0.0]];
+ // round the corners a little with a spline, but keep the flat top and bottom exact
+ const pts = [];
+ for (let i = 0; i < P.length - 1; i++) {
+ const a = P[i], b = P[i + 1];
+ const n = i === 0 || i === P.length - 2 ? 1 : 4;
+ for (let k = 0; k < n; k++) pts.push(new THREE.Vector2(a[0] + (b[0] - a[0]) * k / n, a[1] + (b[1] - a[1]) * k / n));
+ }
+ pts.push(new THREE.Vector2(0, 0));
+ const smooth = pts.map((p, i) => {
+ if (i < 2 || i > pts.length - 3) return p;
+ return new THREE.Vector2((pts[i - 1].x + p.x * 2 + pts[i + 1].x) / 4, (pts[i - 1].y + p.y * 2 + pts[i + 1].y) / 4);
+ });
+ const geo = new THREE.LatheGeometry(smooth.reverse(), 160);
+ const mesh = new THREE.Mesh(geo, material);
+ mesh.castShadow = mesh.receiveShadow = true;
+ return { mesh, top: 0.16, grooveY: 0.146 };
+}
+
+// ─── Substrate layers for the exploded view ──────────────────────────────────────
+function rng(seed) { let s = seed; return () => (s = (s * 16807) % 2147483647) / 2147483647; }
+
+function scatterDisk(count, R, rand, minD) {
+ const out = [];
+ let tries = 0;
+ while (out.length < count && tries++ < count * 60) {
+ const a = rand() * Math.PI * 2, r = Math.sqrt(rand()) * R;
+ const x = Math.cos(a) * r, z = Math.sin(a) * r;
+ if (out.some(p => (p[0] - x) ** 2 + (p[1] - z) ** 2 < minD * minD)) continue;
+ out.push([x, z]);
+ }
+ return out;
+}
+
+export function substrateLayers(renderer, clip) {
+ const rand = rng(7);
+ const R = 0.5;
+ const layers = [];
+
+ // 05 drainage stones — rounded river pebbles and lava rock
+ {
+ const g = new THREE.Group();
+ let geo = new THREE.IcosahedronGeometry(1, 3);
+ geo.deleteAttribute('normal'); geo.deleteAttribute('uv');
+ geo = mergeVertices(geo);
+ const pos = geo.attributes.position, v = new THREE.Vector3();
+ for (let i = 0; i < pos.count; i++) {
+ v.fromBufferAttribute(pos, i);
+ const n = Math.sin(v.x * 3.1 + 1.3) * Math.sin(v.y * 2.7) * Math.sin(v.z * 3.3 + 0.4);
+ v.multiplyScalar(1 + n * 0.12);
+ pos.setXYZ(i, v.x, v.y, v.z);
+ }
+ geo.computeVertexNormals();
+ const pts = [...scatterDisk(95, R - 0.035, rand, 0.062), ...scatterDisk(70, R - 0.05, rand, 0.07)];
+ const mat = new THREE.MeshStandardMaterial({ roughness: 0.62, metalness: 0, envMapIntensity: 0.8 });
+ const im = new THREE.InstancedMesh(geo, mat, pts.length);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), s = new THREE.Vector3(), p = new THREE.Vector3(), e = new THREE.Euler(), c = new THREE.Color();
+ const tones = [0xd9d4ca, 0xbfb8aa, 0xe8e3d9, 0x9c948a, 0xcbb9a0, 0x6d6760];
+ pts.forEach(([x, z], i) => {
+ const sz = 0.024 + rand() * 0.02;
+ s.set(sz * (1 + rand() * 0.35), sz * (0.55 + rand() * 0.25), sz * (0.85 + rand() * 0.3));
+ p.set(x, i < 95 ? sz * 0.6 : 0.045 + sz * 0.5, z);
+ q.setFromEuler(e.set((rand() - 0.5) * 0.5, rand() * 6.28, (rand() - 0.5) * 0.5));
+ im.setMatrixAt(i, m.compose(p, q, s));
+ im.setColorAt(i, c.set(tones[Math.floor(rand() * tones.length)]).offsetHSL(0, 0, (rand() - 0.5) * 0.08));
+ });
+ im.castShadow = im.receiveShadow = true;
+ g.add(im);
+ layers.push({ key: 'stones', group: g, h: 0.085, mats: [mat] });
+ }
+
+ // 04 activated charcoal — sharp black chunks
+ {
+ const g = new THREE.Group();
+ let geo = new THREE.IcosahedronGeometry(1, 0);
+ geo.deleteAttribute('normal'); geo.deleteAttribute('uv');
+ geo = mergeVertices(geo);
+ const pos = geo.attributes.position;
+ for (let i = 0; i < pos.count; i++) pos.setXYZ(i, pos.getX(i) * (0.7 + rand() * 0.6), pos.getY(i) * (0.7 + rand() * 0.6), pos.getZ(i) * (0.7 + rand() * 0.6));
+ geo = geo.toNonIndexed(); geo.computeVertexNormals();
+ const pts = [...scatterDisk(230, R - 0.02, rand, 0.03), ...scatterDisk(150, R - 0.03, rand, 0.034)];
+ const mat = new THREE.MeshStandardMaterial({ color: 0x1b1a19, roughness: 0.52, metalness: 0.25, envMapIntensity: 1.2, flatShading: true });
+ const im = new THREE.InstancedMesh(geo, mat, pts.length);
+ const m = new THREE.Matrix4(), q = new THREE.Quaternion(), s = new THREE.Vector3(), p = new THREE.Vector3(), e = new THREE.Euler(), c = new THREE.Color();
+ pts.forEach(([x, z], i) => {
+ const sz = 0.011 + rand() * 0.012;
+ s.set(sz * (0.8 + rand() * 0.6), sz * (0.6 + rand() * 0.4), sz * (0.8 + rand() * 0.6));
+ p.set(x, i < 230 ? sz * 0.6 : 0.022 + sz * 0.5, z);
+ q.setFromEuler(e.set(rand() * 6.28, rand() * 6.28, rand() * 6.28));
+ im.setMatrixAt(i, m.compose(p, q, s));
+ im.setColorAt(i, c.setRGB(1, 1, 1).multiplyScalar(0.7 + rand() * 0.5));
+ });
+ im.castShadow = im.receiveShadow = true;
+ g.add(im);
+ layers.push({ key: 'charcoal', group: g, h: 0.045, mats: [mat] });
+ }
+
+ // 03 mesh — a fine woven sheet with a little sag
+ {
+ const g = new THREE.Group();
+ const grid = bakeTexture(renderer, 512, `
+ void main(){ vec2 p = fract(vUv * 26.); float l = max(smoothstep(.3, .36, abs(p.x - .5)), smoothstep(.3, .36, abs(p.y - .5)));
+ gl_FragColor = vec4(vec3(l), 1.); }`);
+ grid.generateMipmaps = false; grid.minFilter = THREE.LinearFilter;
+ const geo = new THREE.CircleGeometry(R + 0.01, 128, 0, Math.PI * 2);
+ const pos = geo.attributes.position;
+ for (let i = 0; i < pos.count; i++) { const x = pos.getX(i), y = pos.getY(i); pos.setZ(i, -0.014 * (1 - (x * x + y * y) / (R * R))); }
+ geo.computeVertexNormals();
+ const mat = new THREE.MeshStandardMaterial({ color: 0x4f5c47, roughness: 0.62, alphaMap: grid, alphaTest: 0.5, side: THREE.DoubleSide });
+ grid.repeat.set(1, 1);
+ const sheet = new THREE.Mesh(geo, mat);
+ sheet.rotation.x = -Math.PI / 2; sheet.position.y = 0.016;
+ sheet.castShadow = sheet.receiveShadow = true;
+ g.add(sheet);
+ const hem = new THREE.Mesh(new THREE.TorusGeometry(R + 0.01, 0.0035, 6, 160), new THREE.MeshStandardMaterial({ color: 0x4d5846, roughness: 0.6 }));
+ hem.rotation.x = Math.PI / 2; hem.position.y = 0.016;
+ g.add(hem);
+ layers.push({ key: 'mesh', group: g, h: 0.02, mats: [mat, hem.material] });
+ }
+
+ // 02 living soil — a puck of loam, bark and perlite
+ {
+ const g = new THREE.Group();
+ const soilMap = bakeTexture(renderer, 1024, `
+ void main(){
+ float n = fbm(vUv * 10., 10., 6, .55), m = fbm(vUv * 40., 40., 4, .5);
+ vec3 c = mix(vec3(.07, .045, .028), vec3(.16, .1, .06), n + .3);
+ vec2 g = vUv * 90.; vec2 id = floor(g), f = fract(g);
+ float h = fract(sin(dot(id, vec2(12.9898, 78.233))) * 43758.5453);
+ float perl = step(.93, h) * smoothstep(.42, .2, length(f - .5));
+ float h2 = fract(sin(dot(id, vec2(39.3, 11.7))) * 24634.63);
+ float bark = step(.86, h2) * smoothstep(.5, .3, abs(f.x - .5) + abs(f.y - .5) * .6);
+ c = mix(c, vec3(.35, .19, .09), bark * .8);
+ c = mix(c, vec3(.9, .88, .84), perl);
+ c *= .75 + m * .5;
+ gl_FragColor = vec4(c, 1.);
+ }`);
+ soilMap.colorSpace = THREE.SRGBColorSpace;
+ const soilN = bakeTexture(renderer, 512, `
+ float H(vec2 p){ return fbm(p * 14., 14., 6, .6) + ridge(p * 30., 30., 3) * .3; }
+ void main(){ float e = 1. / 512.; float hx = H(vUv + vec2(e,0.)) - H(vUv - vec2(e,0.)); float hy = H(vUv + vec2(0.,e)) - H(vUv - vec2(0.,e));
+ gl_FragColor = vec4(normalize(vec3(-hx * 5., -hy * 5., 1.)) * .5 + .5, 1.); }`);
+ const mat = new THREE.MeshStandardMaterial({ map: soilMap, normalMap: soilN, normalScale: new THREE.Vector2(1.4, 1.4), roughness: 1, envMapIntensity: 0.5 });
+ const top = new THREE.RingGeometry(0.0001, R, 160, 40);
+ const pos = top.attributes.position;
+ const bumps = Array.from({ length: 70 }, () => [(rand() - 0.5) * 2 * R, (rand() - 0.5) * 2 * R, 0.02 + rand() * 0.05, 0.004 + rand() * 0.012]);
+ for (let i = 0; i < pos.count; i++) {
+ const x = pos.getX(i), y = pos.getY(i), r = Math.hypot(x, y);
+ let n = Math.sin(x * 23 + 1) * Math.sin(y * 19) * 0.008 + Math.sin(x * 61) * Math.sin(y * 57 + 2) * 0.004;
+ for (const [bx, by, br, bh] of bumps) { const d = Math.hypot(x - bx, y - by); if (d < br) n += bh * (1 - (d / br) ** 2) ** 2; }
+ pos.setZ(i, (n + 0.012 * (1 - (r / R) ** 4)) * Math.min(1, (R - r) * 40 + 0.15));
+ }
+ top.computeVertexNormals();
+ const topM = new THREE.Mesh(top, mat); topM.rotation.x = -Math.PI / 2; topM.position.y = 0.1;
+ const sideGeo = new THREE.CylinderGeometry(R, R * 0.995, 0.1, 160, 8, true);
+ { const sp = sideGeo.attributes.position; for (let i = 0; i < sp.count; i++) { const x = sp.getX(i), z = sp.getZ(i), yy = sp.getY(i), a = Math.atan2(z, x);
+ const k = 1 + (Math.sin(a * 37 + yy * 40) * 0.006 + Math.sin(a * 91 - yy * 70) * 0.004); sp.setX(i, x * k); sp.setZ(i, z * k); } sideGeo.computeVertexNormals(); }
+ const side = new THREE.Mesh(sideGeo, mat);
+ side.position.y = 0.05;
+ const bot = new THREE.Mesh(new THREE.CircleGeometry(R, 64), mat); bot.rotation.x = Math.PI / 2;
+ for (const o of [topM, side, bot]) { o.castShadow = o.receiveShadow = true; g.add(o); }
+ layers.push({ key: 'soil', group: g, h: 0.11, mats: [mat] });
+ }
+
+ for (const L of layers) {
+ for (const m of L.mats) { m.clippingPlanes = [clip]; m.clipShadows = true; }
+ L.group.visible = false;
+ }
+ return layers;
+}
diff --git a/examples/terrarium/style.css b/examples/terrarium/style.css
new file mode 100644
index 0000000..8e23264
--- /dev/null
+++ b/examples/terrarium/style.css
@@ -0,0 +1,251 @@
+:root {
+ --linen: #efe9dd;
+ --linen-2: #e5ddcd;
+ --paper: #f7f3eb;
+ --ink: #22281f;
+ --ink-2: #4a5043;
+ --muted: #7d7a6b;
+ --sage: #9eab89;
+ --moss: #46602f;
+ --walnut: #5b3a25;
+ --walnut-2: #3b2517;
+ --rule: rgba(34, 40, 31, .14);
+ --frost: rgba(247, 243, 235, .56);
+ --serif: 'Fraunces', 'Iowan Old Style', Georgia, serif;
+ --sans: 'Manrope', system-ui, sans-serif;
+ --pad: clamp(18px, 5.2vw, 88px);
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--linen); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 16px/1.62 var(--sans); background: var(--linen); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+h1, h2, h3, h4, .serif { font-family: var(--serif); font-optical-sizing: auto; font-variation-settings: 'SOFT' 100, 'WONK' 0; font-weight: 340; }
+em { font-style: italic; }
+h1 em, h2 em { color: var(--moss); font-variation-settings: 'SOFT' 100, 'WONK' 1; }
+.sr { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+.eyebrow { font: 600 11px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--walnut); margin-bottom: 22px; display: flex; align-items: center; gap: 12px; }
+.eyebrow::before { content: ''; width: 26px; height: 1px; background: currentColor; opacity: .5; }
+
+/* ─── loader ─── */
+.loader { position: fixed; inset: 0; z-index: 100; background: var(--linen); display: grid; place-content: center; justify-items: center; gap: 26px;
+ --r: 0vmax; -webkit-mask-image: radial-gradient(circle at 50% 46%, transparent calc(var(--r) - 16vmax), #000 var(--r));
+ mask-image: radial-gradient(circle at 50% 46%, transparent calc(var(--r) - 16vmax), #000 var(--r)); }
+.loader-bell svg { width: 132px; height: 165px; overflow: visible; }
+.loader-fog { fill: #fff; opacity: .9; transform: translateY(calc((1 - var(--p, 0)) * 118px)); transition: transform .2s linear; filter: blur(3px); }
+.loader-glass { fill: none; stroke: var(--ink-2); stroke-width: 1.2; opacity: .55; }
+.loader-base { fill: var(--walnut); opacity: .85; }
+.loader-line { font: 400 italic 19px/1 var(--serif); font-variation-settings: 'SOFT' 100; color: var(--ink-2); }
+.loader-pct { font-variant-numeric: tabular-nums; display: inline-block; min-width: 1.6em; text-align: right; }
+
+/* ─── nav ─── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 20; display: flex; align-items: center; justify-content: space-between;
+ padding: 22px var(--pad); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font: 400 23px/1 var(--serif); font-variation-settings: 'SOFT' 100; letter-spacing: -.01em; }
+.brand em { font-style: italic; color: var(--moss); }
+.brand svg { width: 24px; height: 24px; color: var(--walnut); }
+.links { display: flex; gap: 6px; padding: 5px; border-radius: 999px; background: rgba(247,243,235,.42); backdrop-filter: blur(14px) saturate(1.2);
+ -webkit-backdrop-filter: blur(14px) saturate(1.2); box-shadow: inset 0 0 0 1px rgba(255,255,255,.45), 0 10px 30px -18px rgba(60,45,25,.35); }
+.links a { text-decoration: none; font: 500 13.5px/1 var(--sans); color: var(--ink-2); padding: 10px 16px; border-radius: 999px; transition: background .3s, color .3s; }
+.links a:hover, .links a.on { background: rgba(255,255,255,.7); color: var(--ink); }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 50px; padding: 0 26px; border-radius: 999px;
+ text-decoration: none; font: 600 14px/1 var(--sans); letter-spacing: .01em; transition: background .35s, color .35s, box-shadow .35s; white-space: nowrap; }
+.btn-sm { height: 42px; padding: 0 18px; font-size: 13px; }
+.btn-solid { background: var(--walnut-2); color: #f6efe3; box-shadow: 0 12px 30px -14px rgba(59,37,23,.7); }
+.btn-solid:hover { background: var(--moss); }
+.btn-line { box-shadow: inset 0 0 0 1px rgba(34,40,31,.3); color: var(--ink); background: rgba(247,243,235,.35); backdrop-filter: blur(8px); }
+.btn-line:hover { box-shadow: inset 0 0 0 1px var(--ink); background: rgba(255,255,255,.6); }
+.basket { display: inline-grid; place-items: center; min-width: 22px; height: 22px; padding: 0 6px; border-radius: 99px; background: rgba(246,239,227,.16); font: 600 11px/1 var(--sans); font-variant-numeric: tabular-nums; }
+.basket.bump { animation: bump .6s cubic-bezier(.2,.9,.3,1.4); }
+@keyframes bump { 40% { transform: scale(1.45); background: var(--sage); color: var(--ink); } }
+
+/* ─── wipe cursor & hint ─── */
+.wipe-cursor { position: fixed; left: 0; top: 0; z-index: 30; pointer-events: none; opacity: 0; transition: opacity .25s; }
+.wipe-cursor.on { opacity: 1; }
+@media (pointer: coarse) { .wipe-cursor { display: none; } }
+.wipe-cursor i { position: absolute; left: 0; top: 0; width: 60px; height: 60px; margin: -30px 0 0 -30px; border-radius: 50%;
+ border: 1.5px solid rgba(34,40,31,.55); box-shadow: 0 0 0 1px rgba(255,255,255,.4), inset 0 0 18px rgba(255,255,255,.35); transform: scale(var(--s, 1)); transition: transform .2s; }
+.wipe-cursor span { position: absolute; left: 0; top: 0; transform: translate(calc(var(--rad, 30px) + 10px), -8px); font: 600 10px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink); white-space: nowrap; }
+.wipe-hint { position: fixed; left: 0; top: 0; z-index: 6; pointer-events: none; display: flex; align-items: center; gap: 12px; padding: 12px 18px 12px 14px; border-radius: 999px;
+ background: var(--frost); backdrop-filter: blur(16px) saturate(1.2); -webkit-backdrop-filter: blur(16px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,.55), 0 16px 40px -20px rgba(60,45,25,.45); opacity: 0; transition: opacity .6s; will-change: transform; }
+.wipe-hint.on { opacity: 1; }
+.wipe-hint-text { font: 600 11px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; }
+.wipe-hint-dot { position: relative; width: 14px; height: 14px; border-radius: 50%; background: var(--walnut-2); }
+.wipe-hint-dot::after { content: ''; position: absolute; inset: -6px; border-radius: 50%; border: 1px solid var(--walnut-2); animation: ping 1.8s ease-out infinite; }
+@keyframes ping { from { transform: scale(.5); opacity: .8; } to { transform: scale(1.6); opacity: 0; } }
+
+/* ─── sections ─── */
+main { position: relative; z-index: 2; }
+section { position: relative; pointer-events: none; }
+section a, section button, section input, section .tabs, section .product { pointer-events: auto; }
+.sticky { position: sticky; top: 0; height: 100vh; overflow: hidden; }
+
+.hero { height: 100vh; min-height: 620px; display: grid; align-content: center; padding: 0 var(--pad); }
+.hero-copy { max-width: 36rem; margin-top: 4vh; }
+.hero-title { font-size: clamp(52px, 7.4vw, 124px); line-height: .9; letter-spacing: -.03em; font-weight: 320; margin-bottom: 26px; }
+.hero-title .ln { display: block; }
+.hero-title em { font-weight: 300; }
+.hero-sub { font: 400 italic clamp(21px, 1.9vw, 28px)/1.2 var(--serif); font-variation-settings: 'SOFT' 100, 'WONK' 1; color: var(--walnut); margin-bottom: 22px; }
+.hero-body { max-width: 29em; color: var(--ink-2); font-size: 16px; }
+.hero-cta { display: flex; gap: 12px; margin-top: 34px; flex-wrap: wrap; }
+.hero-label { position: absolute; right: var(--pad); bottom: 6.5vh; display: flex; gap: 18px; font: 600 10.5px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--ink-2); }
+.hero-label span + span::before { content: '·'; margin-right: 18px; opacity: .5; }
+.scroll-cue { position: absolute; left: 0; right: 0; margin: 0 auto; width: max-content; bottom: 4.5vh; flex-direction: column; display: flex; align-items: center; gap: 12px; font: 600 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--ink-2); }
+.scroll-cue i { width: 1px; height: 34px; background: linear-gradient(var(--ink-2), transparent); animation: cue 2.2s ease-in-out infinite; transform-origin: top; }
+@keyframes cue { 0% { transform: scaleY(0); } 50% { transform: scaleY(1); } 100% { transform: scaleY(1); opacity: 0; } }
+
+h2 { font-size: clamp(38px, 4.6vw, 76px); line-height: .98; letter-spacing: -.025em; font-weight: 320; }
+.lede { font: 400 clamp(16.5px, 1.25vw, 19px)/1.6 var(--sans); color: var(--ink-2); max-width: 31em; margin-top: 24px; }
+
+/* climates */
+.climates { height: 320vh; }
+.clim-panel { position: absolute; left: var(--pad); top: 50%; transform: translateY(-46%); width: min(33rem, 40vw); }
+.clim-panel h2 { margin-bottom: 30px; }
+.tabs { display: inline-flex; gap: 4px; padding: 5px; border-radius: 999px; background: var(--frost); backdrop-filter: blur(16px) saturate(1.2); -webkit-backdrop-filter: blur(16px) saturate(1.2);
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,.55), 0 14px 36px -22px rgba(60,45,25,.5); margin-bottom: 26px; }
+.tab { display: flex; align-items: center; gap: 8px; height: 40px; padding: 0 16px; border-radius: 999px; font: 600 13px/1 var(--sans); color: var(--ink-2); transition: background .35s, color .35s; }
+.tab span { font-size: 10px; letter-spacing: .1em; opacity: .55; }
+.tab:hover { color: var(--ink); background: rgba(255,255,255,.5); }
+.tab.on { background: var(--walnut-2); color: #f6efe3; }
+.clim-cards { display: grid; }
+.clim { grid-area: 1 / 1; opacity: 0; transform: translateY(10px); transition: opacity .22s, transform .3s; pointer-events: none; }
+.clim.on { opacity: 1; transform: none; transition: opacity .7s .28s, transform 1s .28s cubic-bezier(.2,.8,.2,1); }
+.clim h3 { font-size: clamp(30px, 2.6vw, 42px); line-height: 1; letter-spacing: -.02em; }
+.latin { font: 400 italic 15px/1.4 var(--serif); color: var(--walnut); margin: 8px 0 16px; }
+.clim > p:not(.latin) { color: var(--ink-2); max-width: 30em; }
+.clim dl { display: grid; grid-template-columns: repeat(4, auto); gap: 0; margin-top: 24px; border-top: 1px solid var(--rule); }
+.clim dl div { padding: 14px 18px 0 0; }
+.clim dt { font: 600 10px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--muted); margin-bottom: 8px; }
+.clim dd { font: 400 17px/1.2 var(--serif); font-variation-settings: 'SOFT' 100; }
+.clim-foot { position: absolute; left: var(--pad); bottom: 6vh; font: 600 10.5px/1 var(--sans); letter-spacing: .16em; text-transform: uppercase; color: var(--muted); }
+
+/* inside */
+.inside { height: 290vh; }
+.inside-head { position: absolute; left: var(--pad); top: 50%; transform: translateY(-50%); width: min(26rem, 28vw); }
+.layer-labels { list-style: none; position: absolute; inset: 0; }
+.layer-labels li { position: absolute; left: 0; top: 0; display: flex; gap: 14px; align-items: flex-start; width: 360px; opacity: 0; transition: opacity .5s; will-change: transform; }
+.layer-labels li.on { opacity: 1; }
+.layer-labels li::before { content: ''; position: absolute; right: 100%; top: 9px; width: var(--lead, 60px); margin-right: 12px; height: 1px;
+ background: linear-gradient(90deg, rgba(34,40,31,.55), rgba(34,40,31,.25)); }
+.layer-labels li::after { content: ''; position: absolute; top: 6px; left: calc(-12px - var(--lead, 60px) - 3px); width: 7px; height: 7px; border-radius: 50%; background: var(--ink); box-shadow: 0 0 0 3px rgba(247,243,235,.8); }
+.layer-labels b { font: 600 10.5px/1 var(--sans); letter-spacing: .12em; color: var(--walnut); padding-top: 5px; }
+.layer-labels h4 { font-size: 20px; line-height: 1.05; letter-spacing: -.01em; margin-bottom: 2px; }
+.layer-labels p { font-size: 13px; line-height: 1.45; color: var(--ink-2); white-space: nowrap; }
+
+/* care */
+.care { height: 280vh; }
+.care-panel { position: absolute; right: var(--pad); top: 50%; transform: translateY(-50%); width: min(31rem, 38vw); }
+.clock { display: grid; grid-template-columns: auto 1fr; align-items: center; gap: 4px 20px; margin: 30px 0 28px; padding: 18px 22px; border-radius: 18px;
+ background: var(--frost); backdrop-filter: blur(16px) saturate(1.2); -webkit-backdrop-filter: blur(16px) saturate(1.2); box-shadow: inset 0 0 0 1px rgba(255,255,255,.55), 0 20px 40px -26px rgba(60,45,25,.5); }
+.clock-time { font: 300 44px/1 var(--serif); font-variation-settings: 'SOFT' 100; font-variant-numeric: tabular-nums; letter-spacing: -.02em; grid-row: span 2; }
+.clock-note { font-size: 14px; color: var(--ink-2); line-height: 1.4; }
+.clock-bar { display: block; height: 2px; background: var(--rule); border-radius: 2px; overflow: hidden; }
+.clock-bar s { display: block; height: 100%; width: 100%; background: var(--walnut); transform-origin: left; transform: scaleX(var(--day, 0)); }
+.care-list { list-style: none; display: grid; grid-template-columns: 1fr 1fr; gap: 22px 28px; }
+.care-list li { opacity: .22; transform: translateY(8px); transition: opacity .6s, transform .8s cubic-bezier(.2,.8,.2,1); border-top: 1px solid var(--rule); padding-top: 14px; }
+.care-list li.on { opacity: 1; transform: none; }
+.care-list h4 { font-size: 20px; line-height: 1.1; margin-bottom: 6px; }
+.care-list p { font-size: 13.5px; line-height: 1.55; color: var(--ink-2); }
+
+/* shop */
+.shop { height: 180vh; }
+.shop-head { position: absolute; left: 0; right: 0; top: 13vh; text-align: center; }
+.shop-head .eyebrow { justify-content: center; }
+.shop-head .eyebrow::after { content: ''; width: 26px; height: 1px; background: currentColor; opacity: .5; }
+.products { position: absolute; inset: 0; }
+.product { position: absolute; left: 0; bottom: 10vh; width: 256px; padding: 16px 18px 16px; border-radius: 18px; background: var(--frost);
+ backdrop-filter: blur(18px) saturate(1.2); -webkit-backdrop-filter: blur(18px) saturate(1.2); box-shadow: inset 0 0 0 1px rgba(255,255,255,.6), 0 24px 50px -28px rgba(60,45,25,.55);
+ opacity: 0; transition: opacity .6s; will-change: transform; }
+.product.on { opacity: 1; }
+.p-no { font: 600 10px/1 var(--sans); letter-spacing: .18em; text-transform: uppercase; color: var(--walnut); }
+.product h3 { font-size: 27px; line-height: 1.05; letter-spacing: -.015em; margin: 10px 0 6px; }
+.p-meta { font-size: 13px; color: var(--ink-2); }
+.p-row { display: flex; align-items: center; justify-content: space-between; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule); }
+.price { font: 350 28px/1 var(--serif); font-variation-settings: 'SOFT' 100; }
+.shop-note { position: absolute; left: 0; right: 0; bottom: 4.2vh; text-align: center; font-size: 13px; color: var(--muted); }
+
+/* visit */
+.visit { height: 150vh; display: grid; place-items: start; align-content: start; padding: 30vh var(--pad) 0; }
+.visit-inner { text-align: left; max-width: 34rem; padding: 46px 48px 50px; border-radius: 28px; background: rgba(247,243,235,.5);
+ backdrop-filter: blur(20px) saturate(1.2); -webkit-backdrop-filter: blur(20px) saturate(1.2); box-shadow: inset 0 0 0 1px rgba(255,255,255,.6), 0 40px 80px -40px rgba(60,45,25,.5); }
+.visit-inner .lede { margin: 20px 0 30px; }
+
+/* footer */
+.foot { position: relative; z-index: 3; background: var(--linen-2); padding: 90px var(--pad) 32px; border-top: 1px solid var(--rule); }
+.foot-inner { display: grid; grid-template-columns: 1.4fr 1fr 1fr 1.5fr; gap: 40px; max-width: 1320px; margin: 0 auto; }
+.foot-mark { font: 330 clamp(44px, 5vw, 76px)/.95 var(--serif); font-variation-settings: 'SOFT' 100; letter-spacing: -.03em; margin-bottom: 18px; }
+.foot-mark em { color: var(--moss); }
+.foot p { color: var(--ink-2); font-size: 14.5px; line-height: 1.7; }
+.foot h5 { font: 600 10.5px/1 var(--sans); letter-spacing: .2em; text-transform: uppercase; color: var(--walnut); margin-bottom: 16px; }
+.foot a { text-decoration: none; }
+.foot a:hover { color: var(--moss); }
+.foot-news label { display: block; margin: 16px 0 12px; }
+.foot-news input { width: 100%; height: 48px; padding: 0 18px; border-radius: 999px; border: 0; background: var(--paper); box-shadow: inset 0 0 0 1px var(--rule); font: 500 14px var(--sans); color: var(--ink); outline: none; }
+.foot-news input:focus { box-shadow: inset 0 0 0 1px var(--walnut); }
+.foot-small { display: flex; justify-content: space-between; gap: 20px; max-width: 1320px; margin: 80px auto 0; padding-top: 22px; padding-left: 110px; border-top: 1px solid var(--rule);
+ font: 500 11.5px/1.5 var(--sans) !important; color: var(--muted) !important; }
+
+.toast { position: fixed; left: 50%; bottom: 5vh; transform: translate(-50%, 20px); z-index: 40; padding: 14px 22px; border-radius: 999px; background: rgba(34,40,31,.88);
+ color: #f3ecdf; font: 500 13.5px/1.3 var(--sans); opacity: 0; transition: opacity .5s, transform .5s; pointer-events: none; text-align: center; box-shadow: 0 20px 40px -20px rgba(0,0,0,.5); }
+.toast.on { opacity: 1; transform: translate(-50%, 0); }
+
+@media (max-width: 900px) {
+ .links { display: none; }
+ .nav { padding: 16px 18px; }
+ .brand { font-size: 20px; }
+ .nav .btn span { display: none; }
+ .nav .btn { padding: 0 14px; height: 40px; }
+ .hero { align-content: start; padding-top: 16vh; }
+ .hero-copy { margin-top: 0; }
+ .hero-title { font-size: clamp(44px, 12.6vw, 64px); margin-bottom: 14px; }
+ .hero-sub { margin-bottom: 10px; }
+ .hero-body { display: none; }
+ .hero-cta { position: absolute; left: 18px; right: 18px; bottom: 66px; margin: 0; }
+ .hero-cta .btn { flex: 1; height: 46px; padding: 0 12px; }
+ .hero-label, .scroll-cue { display: none; }
+ h2 { font-size: clamp(30px, 8.6vw, 42px); }
+ .clim-panel { left: 18px; right: 18px; width: auto; top: 11vh; bottom: 64px; transform: none; }
+ .clim-panel h2 { margin-bottom: 16px; }
+ .tabs { position: absolute; left: 0; right: 0; bottom: 0; justify-content: space-between; margin: 0; }
+ .tab { padding: 0 10px; font-size: 12px; }
+ .tab span { display: none; }
+ .clim-cards { position: absolute; left: 0; right: 0; bottom: 64px; }
+ .clim h3 { font-size: 26px; }
+ .clim > p:not(.latin), .clim dl { display: none; }
+ .clim-foot { display: none; }
+ .inside-head { left: 18px; right: 18px; width: auto; top: 11vh; }
+ .inside-head .lede { display: none; }
+ .layer-labels li { width: 150px; }
+ .layer-labels p { display: none; }
+ .layer-labels h4 { font-size: 15px; }
+ .care-panel { left: 18px; right: 18px; width: auto; top: auto; bottom: 66px; transform: none; }
+ .care-panel h2 { font-size: 30px; }
+ .clock { margin: 16px 0 12px; padding: 12px 16px; }
+ .clock-time { font-size: 32px; }
+ .care-list { grid-template-columns: 1fr; gap: 0; }
+ .care-list li { display: none; }
+ .care-list li.cur { display: block; opacity: 1; transform: none; }
+ .shop-head { top: 11vh; }
+ .product { width: auto; left: 18px !important; right: 18px; transform: none !important; bottom: auto; padding: 12px 16px; border-radius: 14px; transition: opacity .6s, box-shadow .4s, background .4s; }
+ .product.near { background: rgba(255,255,255,.78); box-shadow: inset 0 0 0 1.5px var(--walnut), 0 24px 50px -28px rgba(60,45,25,.55); }
+ .product[data-i="0"] { top: calc(100vh - 330px); } .product[data-i="1"] { top: calc(100vh - 248px); } .product[data-i="2"] { top: calc(100vh - 166px); }
+ .product h3 { font-size: 20px; margin: 4px 0 0; }
+ .p-meta { display: none; }
+ .p-row { position: absolute; right: 14px; top: 50%; transform: translateY(-50%); margin: 0; padding: 0; border: 0; gap: 12px; }
+ .price { font-size: 22px; }
+ .shop-note { display: none; }
+ .visit { padding: 26vh 18px 0; }
+ .foot { padding-bottom: 76px; }
+ .hero .eyebrow span { display: none; }
+ .visit-inner { margin: 0; padding: 30px 22px; }
+ .nav { transition: background .4s; }
+ .nav.solid { background: rgba(239,233,221,.78); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); }
+ .layer-labels li { width: 140px; gap: 8px; }
+ .layer-labels li::before { margin-right: 8px; }
+ .layer-labels li::after { left: calc(-8px - var(--lead, 60px) - 3px); }
+ .foot-inner { grid-template-columns: 1fr; }
+ .foot-small { flex-direction: column; padding-left: 0; }
+}
diff --git a/examples/velocity/index.html b/examples/velocity/index.html
new file mode 100644
index 0000000..77135c3
--- /dev/null
+++ b/examples/velocity/index.html
@@ -0,0 +1,188 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Velocity Lab — VX-1 Carbon</title>
+ <meta name="description" content="VX-1 Carbon. 186 grams of unfair advantage. Run the lens over it and see the plate, the foam and every dimension inside.">
+ <meta name="theme-color" content="#f2f3f5">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Archivo:ital,wdth,wght@0,62..125,100..900;1,62..125,100..900&family=JetBrains+Mono:wght@400;500;700&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+
+ <!-- Lens chrome: bezel ticks, arc label, crosshair. Positioned from JS to match the shader lens. -->
+ <div class="lens-ui" aria-hidden="true">
+ <svg viewBox="-120 -120 240 240">
+ <defs><path id="lens-arc" d="M 0,-114 A 114,114 0 1,1 -0.01,-114"/></defs>
+ <g class="lens-ticks"></g>
+ <text class="lens-arc"><textPath href="#lens-arc" startOffset="0">X-RAY · MODE 01/03 · VX-1 CARBON · PLATE 1.1 MM CFRP · FOAM 38 MM · </textPath></text>
+ <g class="lens-cross"><path d="M-9 0h-9M9 0h9M0 -9v-9M0 9v9"/><circle r="1.4"/></g>
+ </svg>
+ <div class="lens-tag"><span class="lens-tag-n">01</span><b class="lens-tag-m">X-RAY</b></div>
+ <div class="lens-coord">X 000.0 · Y 00.0 MM</div>
+ </div>
+
+ <div class="loader" role="status" aria-live="polite">
+ <div class="loader-top mono"><span>Velocity Lab</span><span>Lab file 07 — VX-1 Carbon</span><span>Optical bench 3</span></div>
+ <i class="loader-h"></i><i class="loader-v"></i>
+ <div class="loader-dial">
+ <svg viewBox="-60 -60 120 120" aria-hidden="true"><g class="loader-ticks"></g><circle class="loader-ring" r="40"/></svg>
+ <span class="loader-pct">000</span>
+ </div>
+ <p class="loader-line mono">Calibrating lens <span class="loader-step">— optics</span></p>
+ <div class="loader-bot mono"><span>186 g</span><span>38 mm stack</span><span>8 mm drop</span><span>1.1 mm CFRP</span></div>
+ </div>
+
+ <header class="nav">
+ <a class="brand" href="#top" aria-label="Velocity Lab home">
+ <svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9.5" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="M5.5 17.5 18.5 6.5" stroke="currentColor" stroke-width="1.6"/><circle cx="12" cy="12" r="2.2" fill="currentColor"/></svg>
+ <span>Velocity<em>Lab</em></span>
+ </a>
+ <nav class="links" aria-label="Primary">
+ <a href="#lens">Lens</a>
+ <a href="#plate">Plate</a>
+ <a href="#foam">Foam</a>
+ <a href="#upper">Upper</a>
+ <a href="#colour">Colourways</a>
+ </nav>
+ <a class="btn btn-ink" href="#drop" data-magnetic><span>Drop list</span><i class="dot"></i></a>
+ </header>
+
+ <!-- Lab HUD -->
+ <div class="hud" aria-hidden="true">
+ <i class="corner tl"></i><i class="corner tr"></i><i class="corner bl"></i><i class="corner br"></i>
+ <div class="ruler"><div class="ruler-mark"><span class="ruler-val mono">000</span></div></div>
+ <div class="chapter mono"><span class="chapter-n">00</span><span class="chapter-name">Launch file</span></div>
+ </div>
+
+ <svg class="leaders" aria-hidden="true"></svg>
+ <div class="callouts" aria-hidden="true"></div>
+
+ <div class="console" role="toolbar" aria-label="Lens mode">
+ <button class="mode is-on" data-mode="0" data-cursor="link"><span class="mono">01</span>X-Ray</button>
+ <button class="mode" data-mode="1" data-cursor="link"><span class="mono">02</span>Thermal</button>
+ <button class="mode" data-mode="2" data-cursor="link"><span class="mono">03</span>CAD</button>
+ <p class="console-hint mono"><span class="k-desk">Move to scan · Click to switch · Hold to magnify</span><span class="k-touch">Drag to scan · Hold to magnify</span></p>
+ </div>
+
+ <main id="top">
+ <section class="s hero" data-state="hero">
+ <div class="hero-copy" data-nolens>
+ <p class="eyebrow mono"><span class="tag">Lab file 07</span> Carbon race trainer — Release 16.10.2026</p>
+ <h1 class="title" aria-label="VX-1 Carbon."><span class="t1">VX-1</span><span class="t2">Carbon.</span></h1>
+ <p class="sub">186 grams of unfair advantage.</p>
+ </div>
+ <dl class="specs mono" data-nolens>
+ <div><dt>Weight</dt><dd>186<small>g</small></dd></div>
+ <div><dt>Stack</dt><dd>38<small>mm</small></dd></div>
+ <div><dt>Drop</dt><dd>8<small>mm</small></dd></div>
+ <div><dt>Plate</dt><dd>1.1<small>mm</small></dd></div>
+ </dl>
+ <p class="hero-note" data-nolens>A full-length carbon plate, thirty-eight millimetres of nitrogen-set foam and an upper you can see daylight through. We built a lens so you can check our work.</p>
+ </section>
+
+ <section class="s lens-s" id="lens" data-state="lens">
+ <div class="col col-r" data-nolens>
+ <p class="eyebrow mono"><span class="tag">01</span> The lens</p>
+ <h2>Every shoe says it’s fast. <em>Ours lets you look.</em></h2>
+ <p class="lede">Outside the glass it’s a product shot. Inside, it’s the lab file: what the plate does, where the heat goes, and every dimension we argued about for fourteen months.</p>
+ <ol class="modes">
+ <li><button data-mode="0" data-cursor="link"><span class="mono">01 — X-Ray</span><b>The shell turns to glass.</b><em>The plate and the foam lattice light up exactly where they sit.</em></button></li>
+ <li><button data-mode="1" data-cursor="link"><span class="mono">02 — Thermal</span><b>1,200 strides of pressure data.</b><em>Painted back onto the sole. Watch a footstrike roll heel to toe.</em></button></li>
+ <li><button data-mode="2" data-cursor="link"><span class="mono">03 — CAD</span><b>The master drawing.</b><em>Clean edges, true dimensions, no marketing.</em></button></li>
+ </ol>
+ </div>
+ </section>
+
+ <section class="s tech" id="plate" data-state="plate">
+ <div class="col col-l" data-nolens>
+ <p class="eyebrow mono"><span class="tag">02</span> Plate</p>
+ <h2>A spoon, <em>not a spring.</em></h2>
+ <p class="lede">1.1 mm of unidirectional carbon, laid in a scooped curve. It stiffens the forefoot so your toes stop spending energy on flexing, then rolls you forward off a 4.2° rocker. It doesn’t bounce. It just refuses to waste anything.</p>
+ <div class="stat"><b>8<small>mm</small></b><span class="mono">Heel-to-toe drop</span></div>
+ <ul class="minor mono"><li><b>1.1 mm</b> plate thickness</li><li><b>4.2°</b> toe spring</li><li><b>62%</b> rocker apex</li></ul>
+ </div>
+ </section>
+
+ <section class="s tech" id="foam" data-state="foam">
+ <div class="col col-r" data-nolens>
+ <p class="eyebrow mono"><span class="tag">03</span> Foam</p>
+ <h2>Thirty-eight millimetres <em>of almost nothing.</em></h2>
+ <p class="lede">VX Foam is a supercritical PEBA, expanded with nitrogen until it is 81% air. Under the thermal lens you can watch it take a footstrike, spread the load across the heel and hand it forward.</p>
+ <div class="stat"><b>38<small>mm</small></b><span class="mono">Heel stack height</span></div>
+ <ul class="minor mono"><li><b>87%</b> energy return</li><li><b>0.09</b> g/cm³ density</li><li><b>30 mm</b> forefoot</li></ul>
+ </div>
+ </section>
+
+ <section class="s tech" id="upper" data-state="upper">
+ <div class="col col-l" data-nolens>
+ <p class="eyebrow mono"><span class="tag">04</span> Upper</p>
+ <h2>Built from one thread <em>and an argument.</em></h2>
+ <p class="lede">A single-layer engineered mesh, knitted in one piece with 212 zones of different density — open where your foot runs hot, closed where it needs holding. The ripstop cage over the midfoot weighs less than the laces.</p>
+ <div class="stat"><b>186<small>g</small></b><span class="mono">Per shoe, US 9</span></div>
+ <ul class="minor mono"><li><b>212</b> knit zones</li><li><b>0</b> stitched seams</li><li><b>11 g</b> ripstop cage</li></ul>
+ </div>
+ </section>
+
+ <section class="s colour" id="colour" data-state="colour">
+ <div class="col col-l" data-nolens>
+ <p class="eyebrow mono"><span class="tag">05</span> Colourways</p>
+ <h2>Two ways <em>to be early.</em></h2>
+ <p class="lede">Same plate, same foam, same 186 grams. Pick the one you want to be photographed in.</p>
+ <div class="swatches">
+ <button class="swatch is-on" data-way="0" data-cursor="link">
+ <i class="chip chip-w"></i>
+ <span class="mono">VX-1 / 01</span><b>Lab White / Solar</b>
+ <em>Clinical white knit, solar-orange hardware. Photographs like it’s already on the podium.</em>
+ </button>
+ <button class="swatch" data-way="1" data-cursor="link">
+ <i class="chip chip-b"></i>
+ <span class="mono">VX-1 / 02</span><b>Carbon / Volt</b>
+ <em>Black on graphite with volt laces. For people who’d rather be seen at the finish than the start.</em>
+ </button>
+ <p class="swatch-hint mono">Select a colourway — watch it re-print</p>
+ </div>
+ </div>
+ </section>
+
+ <section class="s drop" id="drop" data-state="drop">
+ <div class="drop-inner" data-nolens>
+ <p class="eyebrow mono"><span class="tag">06</span> The drop — Friday 16.10.2026, 09:00 Zürich</p>
+ <h2 class="drop-title">3,000 pairs. <em>One per runner.</em></h2>
+ <div class="count" role="timer" aria-live="off">
+ <div><b data-u="d">00</b><span class="mono">Days</span></div>
+ <div><b data-u="h">00</b><span class="mono">Hours</span></div>
+ <div><b data-u="m">00</b><span class="mono">Min</span></div>
+ <div><b data-u="s">00</b><span class="mono">Sec</span></div>
+ </div>
+ <form class="join" onsubmit="event.preventDefault(); this.classList.add('done');">
+ <label class="mono" for="email">Drop list</label>
+ <input id="email" type="email" placeholder="[email protected]" autocomplete="email" required>
+ <button class="btn btn-volt" type="submit" data-magnetic>Join the list — €240</button>
+ <p class="join-ok mono">You’re on the list. Bring a race result.</p>
+ </form>
+ <p class="drop-note mono">1,500 per colourway · No bots — every entry is checked against a race result from the last 12 months</p>
+ </div>
+ </section>
+ </main>
+
+ <footer class="foot" id="footer" data-nolens>
+ <div class="foot-inner">
+ <h2 class="foot-title">Run what you can <em>see through.</em></h2>
+ <div class="foot-cols">
+ <div><p class="mono k">Velocity Lab AG</p><p>Werkstrasse 14<br>8005 Zürich</p></div>
+ <div><p class="mono k">Lab hours</p><p>Mon–Fri 07:00–19:00<br>Wear-test runs Sat 06:30</p></div>
+ <div><p class="mono k">Press &amp; teams</p><p>[email protected]<br>Athlete programme — invite only</p></div>
+ <a class="btn btn-ink" href="#drop" data-magnetic>Join the drop list</a>
+ </div>
+ <p class="legal mono"><span>© 2026 Velocity Lab — a fictional brand</span><span>VX-1 Carbon · Lab file 07 · All measurements US 9</span></p>
+ </div>
+ </footer>
+
+ <script type="module" src="./main.js"></script>
+</body>
+</html>
diff --git a/examples/velocity/lens.js b/examples/velocity/lens.js
new file mode 100644
index 0000000..6ccb9a7
--- /dev/null
+++ b/examples/velocity/lens.js
@@ -0,0 +1,568 @@
+// The X-ray lens. The shoe is rendered a second time — scissored to the lens, with a real zoom via camera view offset —
+// in one of three alternate modes, then composited over the product shot with a refractive glass rim.
+import { THREE } from '../../src/core/engine.js';
+import { Effect, EffectPass } from 'postprocessing';
+import { NOISE, PROFILE, GAIT, PALETTE, PERTURB } from './shaders.js';
+
+export const MODES = [
+ { key: 'xray', name: 'X-RAY', bg: 0x03060b },
+ { key: 'thermal', name: 'THERMAL', bg: 0x05030b },
+ { key: 'cad', name: 'CAD', bg: 0x101216 },
+];
+
+// ─── Composite ────────────────────────────────────────────────────────────────
+const LENS_FRAG = /* glsl */`
+ uniform sampler2D tAlt; uniform sampler2D tPrev;
+ uniform vec2 uC; uniform float uR; uniform float uZ; uniform float uWipe; uniform vec2 uVel; uniform float uHot; uniform float uTimeL;
+ uniform vec3 uTint; uniform float uMix;
+
+ vec3 altAt(sampler2D t, vec2 o, float g, float ca){
+ return vec3(texture2D(t, uC + o * g * (1.0 + ca)).r, texture2D(t, uC + o * g).g, texture2D(t, uC + o * g * (1.0 - ca)).b);
+ }
+
+ void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor){
+ vec2 px = (uv - uC) * resolution;
+ float R = max(uR, 1.0);
+ // liquid squash & stretch along the lens velocity
+ float sp = length(uVel);
+ vec2 vd = sp > 1e-3 ? uVel / sp : vec2(1.0, 0.0);
+ vec2 pd = vec2(-vd.y, vd.x);
+ float st = clamp(sp * 0.00012, 0.0, 0.2);
+ vec2 qs = vd * dot(px, vd) * (1.0 - st) + pd * dot(px, pd) * (1.0 + st * 0.5);
+ float d = length(qs) / R;
+ float aa = 1.2 / R;
+ vec3 col = inputColor.rgb;
+ vec2 dir = px / max(length(px), 1e-3);
+
+ // Outside: the glass lip bends the product shot, and the puck casts a soft shadow onto the page.
+ if (d >= 1.0) {
+ float lip = smoothstep(1.0 + 16.0 / R, 1.0, d);
+ vec2 duv = uv - dir * lip * lip * 9.0 / resolution;
+ vec3 bent = vec3(texture2D(inputBuffer, duv - dir * 1.5 / resolution).r, texture2D(inputBuffer, duv).g, texture2D(inputBuffer, duv + dir * 1.5 / resolution).b);
+ col = mix(col, bent, lip);
+ float sd = length(px - vec2(0.0, -R * 0.09)) / R;
+ float sh = smoothstep(1.5, 0.98, sd);
+ col *= 1.0 - 0.16 * sh * sh;
+ }
+
+ // Inside: the alternate render, magnified at the centre and compressed at the rim like a thick loupe.
+ float inside = 1.0 - smoothstep(1.0 - aa, 1.0 + aa, d);
+ if (inside > 0.0) {
+ float dd = min(d, 1.0);
+ float g = 1.0 + (uZ - 1.0) * pow(dd, 3.2);
+ float ca = 0.05 * pow(dd, 5.0);
+ vec2 o = px / resolution;
+ vec3 a = altAt(tAlt, o, g, ca);
+ if (uWipe < 1.0) {
+ vec3 p = altAt(tPrev, o, g, ca);
+ float w = uWipe * 1.15;
+ a = mix(p, a, smoothstep(w, w - 0.04, dd));
+ a += vec3(0.85, 1.0, 0.25) * 2.6 * exp(-pow((dd - w) * 34.0, 2.0)) * (1.0 - uWipe);
+ }
+ // glow around hot internals (the plate), independent of the page bloom
+ vec3 glo = vec3(0.0);
+ for (int k = 0; k < 8; k++) {
+ float an = float(k) * 0.7854 + 0.39;
+ vec2 dq = vec2(cos(an), sin(an)) / resolution;
+ glo += max(texture2D(tAlt, uC + o * g + dq * 8.0).rgb - 0.6, 0.0);
+ glo += max(texture2D(tAlt, uC + o * g + dq * 18.0).rgb - 0.6, 0.0) * 0.55;
+ }
+ a += glo * vec3(0.12, 0.045, 0.008);
+ // glass: darker rim, a caustic crescent at the bottom right, a glint at the top left
+ a *= mix(1.0, 0.5, smoothstep(0.72, 1.0, dd));
+ float up = dot(dir, normalize(vec2(-0.62, 0.78)));
+ a += vec3(1.0) * smoothstep(0.84, 0.985, dd) * smoothstep(0.35, 0.95, up) * 0.32;
+ a += uTint * smoothstep(0.8, 0.98, dd) * smoothstep(0.4, 0.95, -up) * 0.22;
+ col = mix(col, a, inside);
+ }
+
+ // Thin bright inner ring + dark bezel
+ float ring = exp(-pow((d - 0.988) * R / 1.05, 2.0));
+ col += uTint * ring * (2.6 + uHot * 6.0);
+ float bw = 3.0 / R;
+ float bezel = smoothstep(1.0 - aa * 0.5, 1.0 + aa, d) * (1.0 - smoothstep(1.0 + bw, 1.0 + bw + aa, d));
+ col = mix(col, vec3(0.008, 0.009, 0.011), bezel * 0.94);
+ outputColor = vec4(mix(inputColor.rgb, col, uMix), inputColor.a);
+ }
+`;
+
+class LensEffect extends Effect {
+ constructor(uniforms) {
+ super('LensEffect', LENS_FRAG, { uniforms: new Map(Object.entries(uniforms).map(([k, v]) => [k, new THREE.Uniform(v)])) });
+ }
+}
+
+// ─── Mode materials ──────────────────────────────────────────────────────────
+const SHELL_VERT = /* glsl */`
+ uniform mat4 uShoeInv;
+ varying vec3 vN; varying vec3 vVP; varying vec3 vSP; varying vec2 vUv;
+ void main(){
+ vUv = uv;
+ vec4 wp = modelMatrix * vec4(position, 1.0);
+ vSP = (uShoeInv * wp).xyz;
+ vec4 mv = viewMatrix * wp;
+ vVP = mv.xyz;
+ vN = normalize(normalMatrix * normal);
+ gl_Position = projectionMatrix * mv;
+ }
+`;
+
+const XRAY_FRAG = /* glsl */`
+ uniform sampler2D map; uniform sampler2D nmap; uniform float uTime; uniform float uScan;
+ varying vec3 vN; varying vec3 vVP; varying vec3 vSP; varying vec2 vUv;
+ ${NOISE} ${PROFILE} ${GAIT} ${PERTURB}
+ void main(){
+ vec3 n = normalize(vN); if (!gl_FrontFacing) n = -n;
+ vec3 mn = texture2D(nmap, vUv).xyz * 2.0 - 1.0; mn.xy *= 1.8;
+ n = perturbN(n, vVP, vUv, normalize(mn));
+ vec3 v = normalize(-vVP);
+ float ndv = clamp(abs(dot(n, v)), 0.0, 1.0);
+ float fres = pow(1.0 - ndv, 2.4);
+ vec3 alb = texture2D(map, vUv).rgb;
+ float lum = dot(alb, vec3(0.299, 0.587, 0.114));
+ vec4 pr = prof(vSP.x);
+ float mid = 1.0 - smoothstep(pr.a - 0.03, pr.a + 0.03, vSP.y);
+ float sat = max(max(alb.r, alb.g), alb.b) - min(min(alb.r, alb.g), alb.b);
+ float dens = mix(0.62, 1.0, mid) * mix(1.7, 0.75, lum) + sat * 2.2;
+ vec3 cold = vec3(0.42, 0.7, 1.0);
+ vec3 c = cold * (0.014 + 0.8 * fres + 1.1 * pow(1.0 - ndv, 8.0)) * dens;
+ // foam cell walls on the midsole skin, squeezed by the footstrike
+ float P = pressure(vSP.x);
+ vec2 vr = voro3(vSP * vec3(20.0, 24.0 + P * 8.0, 20.0));
+ float wall = 1.0 - smoothstep(0.0, 0.08, vr.y - vr.x);
+ c += mix(cold, vec3(1.0, 0.62, 0.25), P * 0.6) * wall * mid * (0.018 + 0.12 * fres + P * 0.05);
+ // scanning band
+ float scan = exp(-pow((vSP.x - uScan) * 7.0, 2.0));
+ c += vec3(0.7, 1.0, 0.25) * scan * (0.012 + 0.22 * fres);
+ gl_FragColor = vec4(c, 1.0);
+ }
+`;
+
+const THERMAL_FRAG = /* glsl */`
+ uniform float uTime;
+ varying vec3 vN; varying vec3 vVP; varying vec3 vSP; varying vec2 vUv;
+ ${NOISE} ${PROFILE} ${GAIT} ${PALETTE}
+ void main(){
+ vec3 n = normalize(vN); if (!gl_FrontFacing) n = -n;
+ vec3 v = normalize(-vVP);
+ float ndv = clamp(abs(dot(n, v)), 0.0, 1.0);
+ vec4 pr = prof(vSP.x);
+ float h = max(vSP.y - pr.r, 0.0);
+ float mid = 1.0 - smoothstep(pr.a - 0.04, pr.a + 0.05, vSP.y + (fbm3(vSP * 6.0) - 0.5) * 0.06);
+ float xw = vSP.x + (fbm3(vSP * 3.2 + 4.0) - 0.5) * 0.22 - h * 0.35;
+ float P = pressure(xw);
+ float Rz = residual(xw);
+ float sole = exp(-h * 8.0);
+ float collar = exp(-pow((vSP.x + 0.4) / 0.32, 2.0)) * smoothstep(0.05, 0.38, vSP.y);
+ float toe = smoothstep(0.55, 0.95, vSP.x);
+ float inner = gl_FrontFacing ? 0.0 : 0.22;
+ float T = mix(0.3, 0.47, 1.0 - mid) + (1.0 - mid) * (0.26 * collar - 0.12 * toe) + inner;
+ T += (P * 0.62 + Rz * 0.42) * sole + mid * (P * 0.2 + Rz * 0.15);
+ T += (fbm3(vSP * 7.0 + vec3(0.0, uTime * 0.12, 0.0)) - 0.5) * 0.08;
+ T *= 0.86 + 0.14 * ndv;
+ vec3 c = ironbow(T);
+ float k = T * 16.0; float w = fwidth(k); float fk = min(fract(k), 1.0 - fract(k));
+ c *= 1.0 - 0.35 * (1.0 - smoothstep(0.0, w * 1.4, fk));
+ gl_FragColor = vec4(c * 1.08, 1.0);
+ }
+`;
+
+const FLOORHEAT_FRAG = /* glsl */`
+ uniform float uTime; uniform mat4 uShoeInv; uniform vec2 uFloorC;
+ varying vec3 vWP;
+ ${NOISE} ${PROFILE} ${GAIT} ${PALETTE}
+ void main(){
+ vec3 sp = (uShoeInv * vec4(vWP, 1.0)).xyz;
+ vec4 pr = prof(sp.x);
+ float inX = smoothstep(uProfX.x - 0.03, uProfX.x + 0.07, sp.x) * smoothstep(uProfX.y + 0.03, uProfX.y - 0.07, sp.x);
+ float dz = abs(sp.z - pr.g) - pr.b * 0.92;
+ float foot = smoothstep(0.035, -0.035, dz) * inX;
+ float halo = exp(-max(dz, 0.0) * 10.0) * mix(0.4, 1.0, inX) * smoothstep(uProfX.x - 0.4, uProfX.x, sp.x) * smoothstep(uProfX.y + 0.4, uProfX.y, sp.x);
+ float gap = max(pr.r - sp.y, 0.0);
+ float contact = exp(-gap * 22.0);
+ float xw = sp.x + (fbm3(vec3(sp.xz * 3.0, 1.7)) - 0.5) * 0.2;
+ float heat = pressure(xw) + residual(xw) * 0.9;
+ float T = 0.06 + (foot * 0.62 + halo * 0.2) * contact * heat;
+ T += (vnoise(vec3(vWP.xz * 38.0, uTime * 3.0)) - 0.5) * 0.025;
+ float fade = smoothstep(3.2, 0.6, length(vWP.xz - uFloorC));
+ vec3 c = ironbow(T) * mix(0.35, 1.0, fade);
+ float k = T * 16.0; float w = fwidth(k); float fk = min(fract(k), 1.0 - fract(k));
+ c *= 1.0 - 0.3 * (1.0 - smoothstep(0.0, w * 1.4, fk)) * step(0.1, T);
+ gl_FragColor = vec4(c, 1.0);
+ }
+`;
+
+const NORMAL_FRAG = /* glsl */`
+ varying vec3 vN; varying vec3 vVP;
+ void main(){ vec3 n = normalize(vN); if (!gl_FrontFacing) n = -n; gl_FragColor = vec4(n * 0.5 + 0.5, -vVP.z * 0.1); }
+`;
+
+const CAD_FRAG = /* glsl */`
+ uniform sampler2D tN; uniform vec2 uRes; uniform float uDpr; uniform vec2 uC; uniform float uTime;
+ vec4 N(vec2 o){ return texture2D(tN, (gl_FragCoord.xy + o) / uRes); }
+ float cov(vec4 s){ return step(0.0005, s.a); }
+ float grid(vec2 p, float s, float w){ vec2 m = abs(fract(p / s + 0.5) - 0.5) * s; return 1.0 - smoothstep(0.0, w, min(m.x, m.y)); }
+ void main(){
+ float s = max(uDpr, 1.0);
+ vec4 c = N(vec2(0.0));
+ vec4 l = N(vec2(-s, 0.0)), r = N(vec2(s, 0.0)), u = N(vec2(0.0, s)), d = N(vec2(0.0, -s));
+ vec4 lu = N(vec2(-s, s)), ru = N(vec2(s, s)), ld = N(vec2(-s, -s)), rd = N(vec2(s, -s));
+ vec3 gx = (ru.rgb + 2.0 * r.rgb + rd.rgb) - (lu.rgb + 2.0 * l.rgb + ld.rgb);
+ vec3 gy = (lu.rgb + 2.0 * u.rgb + ru.rgb) - (ld.rgb + 2.0 * d.rgb + rd.rgb);
+ float cv = cov(c);
+ float allc = cov(l) * cov(r) * cov(u) * cov(d) * cov(lu) * cov(ru) * cov(ld) * cov(rd) * cv;
+ float anyc = max(max(max(cov(l), cov(r)), max(cov(u), cov(d))), cv);
+ float sil = anyc * (1.0 - allc);
+ float en = (length(gx) + length(gy)) * allc;
+ float dx = (ru.a + 2.0 * r.a + rd.a) - (lu.a + 2.0 * l.a + ld.a);
+ float dy = (lu.a + 2.0 * u.a + ru.a) - (ld.a + 2.0 * d.a + rd.a);
+ float ed = (abs(dx) + abs(dy)) / max(c.a, 0.02) * allc;
+ float line = max(smoothstep(1.0, 1.8, en) * 0.6, smoothstep(0.1, 0.24, ed));
+ line = max(line, sil);
+ vec2 cp = gl_FragCoord.xy / s;
+ vec3 bg = vec3(0.0052, 0.0058, 0.0072);
+ bg += vec3(0.010, 0.012, 0.016) * grid(cp, 12.0, 0.7) + vec3(0.02, 0.024, 0.03) * grid(cp, 60.0, 0.9);
+ vec3 n = c.rgb * 2.0 - 1.0;
+ float lam = clamp(dot(n, normalize(vec3(-0.45, 0.65, 0.6))), 0.0, 1.0);
+ float hatch = step(0.62, fract((cp.x + cp.y) / 4.0)) * (1.0 - smoothstep(0.15, 0.5, lam));
+ vec3 fill = vec3(0.012, 0.014, 0.018) + vec3(0.024, 0.028, 0.034) * lam + vec3(0.02, 0.024, 0.03) * hatch;
+ vec3 col = mix(bg, fill, cv);
+ col = mix(col, vec3(0.78, 0.84, 0.92), clamp(line, 0.0, 1.0) * 0.92);
+ gl_FragColor = vec4(col, 1.0);
+ }
+`;
+
+const BG_VERT = 'varying vec2 vQ; void main(){ vQ = position.xy; gl_Position = vec4(position.xy, 0.0, 1.0); }';
+const XRAY_BG = /* glsl */`
+ uniform vec2 uCpx; uniform float uRpx; uniform float uTime; uniform float uDpr;
+ ${NOISE}
+ void main(){
+ float d = length(gl_FragCoord.xy - uCpx) / max(uRpx, 1.0);
+ vec3 c = mix(vec3(0.010, 0.020, 0.040), vec3(0.0015, 0.003, 0.006), smoothstep(0.0, 1.1, d));
+ float scan = 0.5 + 0.5 * sin(gl_FragCoord.y / uDpr * 3.14159 / 1.5);
+ c *= 0.88 + 0.12 * scan;
+ c += (hash12(gl_FragCoord.xy + fract(uTime) * 100.0) - 0.5) * 0.004;
+ gl_FragColor = vec4(c, 1.0);
+ }
+`;
+
+// Point sprites for the foam lattice (cells squeezed by the footstrike) and lattice struts.
+const CELL_VERT = /* glsl */`
+ attribute float aSeed; attribute float aSize;
+ uniform float uPx; uniform float uTime;
+ varying float vA; varying float vP;
+ ${PROFILE} ${GAIT}
+ void main(){
+ vec3 p = position;
+ float P = pressure(p.x);
+ vec4 pf = prof(p.x);
+ float h = p.y - pf.r;
+ p.y = pf.r + h * (1.0 - 0.16 * P);
+ p.xz += vec2(sin(uTime * 0.7 + aSeed * 40.0), cos(uTime * 0.6 + aSeed * 23.0)) * 0.002;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = aSize * uPx / -mv.z * (1.0 - 0.18 * P);
+ vA = 0.5 + 0.35 * fract(aSeed * 7.13); vP = P;
+ }
+`;
+const CELL_FRAG = /* glsl */`
+ varying float vA; varying float vP;
+ void main(){
+ vec2 q = gl_PointCoord * 2.0 - 1.0; float d = length(q);
+ if (d > 1.0) discard;
+ float ring = smoothstep(0.2, 0.0, abs(d - 0.8));
+ float fill = (1.0 - d) * 0.1;
+ vec3 c = mix(vec3(0.35, 0.62, 1.0), vec3(1.0, 0.55, 0.18), clamp(vP * 1.3, 0.0, 1.0));
+ gl_FragColor = vec4(c * (ring * 0.42 + fill) * vA * (0.32 + vP * 1.5), 1.0);
+ }
+`;
+
+const PLATE_VERT = /* glsl */`
+ varying vec2 vUv; varying vec3 vN; varying vec3 vVP;
+ void main(){ vUv = uv; vec4 mv = modelViewMatrix * vec4(position, 1.0); vVP = mv.xyz; vN = normalize(normalMatrix * normal); gl_Position = projectionMatrix * mv; }
+`;
+const PLATE_FRAG = /* glsl */`
+ uniform float uTime; uniform float uHot;
+ varying vec2 vUv; varying vec3 vN; varying vec3 vVP;
+ void main(){
+ vec3 n = normalize(vN); vec3 v = normalize(-vVP); float ndv = abs(dot(n, v));
+ // 2x2 twill: diagonal ribs with alternating tow direction, faded out where it would alias
+ vec2 w = vec2(vUv.x * 124.0, vUv.y * 30.0);
+ float dg = (w.x + w.y) * 0.5;
+ float rib = 0.5 + 0.5 * sin(dg * 6.2832);
+ float tow = step(0.5, fract((w.x - w.y) * 0.25));
+ float weave = 1.0 - smoothstep(0.25, 0.7, fwidth(dg));
+ float thread = mix(0.6, rib * mix(0.7, 1.0, tow), weave);
+ float ev = min(vUv.y, 1.0 - vUv.y), eu = min(vUv.x, 1.0 - vUv.x);
+ float edge = exp(-ev * 42.0) + exp(-eu * 90.0);
+ float pulse = exp(-pow((vUv.x - fract(uTime * 0.3) * 1.3 + 0.15) * 8.0, 2.0));
+ vec3 hot = vec3(0.86, 0.15, 0.008);
+ vec3 c = hot * (0.55 + 0.6 * thread) * (0.8 + 0.45 * pow(1.0 - ndv, 1.4));
+ c += vec3(1.0, 0.62, 0.22) * edge * 3.6;
+ c += vec3(1.0, 0.7, 0.3) * pulse * (0.6 + thread) * 2.2;
+ gl_FragColor = vec4(c * uHot, 0.96);
+ }
+`;
+
+function textSprite(text, { color = '#d2ff1e', h = 0.06, weight = 600 } = {}) {
+ const c = document.createElement('canvas');
+ const g = c.getContext('2d');
+ const fs = 44;
+ g.font = `${weight} ${fs}px "JetBrains Mono", monospace`;
+ const w = Math.ceil(g.measureText(text).width) + 24;
+ c.width = w; c.height = 64;
+ g.font = `${weight} ${fs}px "JetBrains Mono", monospace`;
+ g.fillStyle = 'rgba(16,18,22,.86)'; g.fillRect(0, 6, w, 52);
+ g.fillStyle = color; g.textBaseline = 'middle'; g.fillText(text, 12, 34);
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
+ const s = new THREE.Sprite(new THREE.SpriteMaterial({ map: t, depthTest: false, depthWrite: false, transparent: true }));
+ s.scale.set(h * w / 64, h, 1);
+ s.renderOrder = 10;
+ return s;
+}
+
+// ─── The lens ────────────────────────────────────────────────────────────────
+export class Lens {
+ constructor(engine, shared) {
+ this.engine = engine;
+ this.renderer = engine.renderer;
+ this.camera = engine.camera;
+ this.u = shared; // { uTime, uShoeInv, uProfile, uProfX, uGait, uPx }
+ const hf = { type: THREE.HalfFloatType, depthBuffer: true, colorSpace: THREE.LinearSRGBColorSpace };
+ this.rtA = new THREE.WebGLRenderTarget(2, 2, hf);
+ this.rtB = new THREE.WebGLRenderTarget(2, 2, hf);
+ this.rtN = new THREE.WebGLRenderTarget(2, 2, { ...hf, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter });
+ this.mode = 0; this.prev = 0; this.wipe = 1;
+ this.cx = innerWidth / 2; this.cy = innerHeight / 2; this.r = 150; this.open = 0; this.zoom = 1.08; this.vx = 0; this.vy = 0; this.hot = 0; this.mix = 1;
+ this.sc = new THREE.Vector4();
+ this.effect = new LensEffect({
+ tAlt: this.rtA.texture, tPrev: this.rtB.texture, uC: new THREE.Vector2(0.5, 0.5), uR: 0, uZ: 1, uWipe: 1,
+ uVel: new THREE.Vector2(), uHot: 0, uTimeL: 0, uTint: new THREE.Color(0.85, 1.0, 0.45), uMix: 1,
+ });
+ this.pass = new EffectPass(this.camera, this.effect);
+ const comp = engine.post.composer;
+ const at = comp.passes.findIndex(p => p instanceof EffectPass);
+ comp.addPass(this.pass, at < 0 ? undefined : at);
+ this.ortho = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ engine.onResize((w, h, dpr) => {
+ const bw = Math.round(w * dpr), bh = Math.round(h * dpr);
+ this.bw = bw; this.bh = bh; this.dpr = dpr;
+ for (const rt of [this.rtA, this.rtB, this.rtN]) rt.setSize(bw, bh);
+ if (this.cadQuad) { this.cadQuad.material.uniforms.uRes.value.set(bw, bh); this.cadQuad.material.uniforms.uDpr.value = dpr; }
+ });
+ this.scenes = [new THREE.Scene(), new THREE.Scene(), null];
+ this.holders = [];
+ }
+
+ _holder(scene) { const h = new THREE.Group(); h.matrixAutoUpdate = false; scene.add(h); this.holders.push(h); return h; }
+
+ /** Build the alternate worlds once the shoe is measured. */
+ build(model, data) {
+ const u = this.u;
+ const src = data.mesh.material;
+ // X-RAY
+ const xs = this.scenes[0];
+ this.xrayBg = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({
+ vertexShader: BG_VERT, fragmentShader: XRAY_BG, depthTest: false, depthWrite: false,
+ uniforms: { uCpx: { value: new THREE.Vector2() }, uRpx: { value: 100 }, uTime: u.uTime, uDpr: { value: 1 } },
+ }));
+ this.xrayBg.frustumCulled = false; this.xrayBg.renderOrder = -10;
+ xs.add(this.xrayBg);
+ const xh = this._holder(xs);
+ this.uScan = { value: 0 };
+ const xrayMat = new THREE.ShaderMaterial({
+ vertexShader: SHELL_VERT, fragmentShader: XRAY_FRAG, transparent: true, depthTest: false, depthWrite: false,
+ blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ uniforms: { map: { value: src.map }, nmap: { value: src.normalMap }, uTime: u.uTime, uScan: this.uScan, uShoeInv: u.uShoeInv, uProfile: u.uProfile, uProfX: u.uProfX, uGait: u.uGait },
+ });
+ xh.add(this._cloneWith(model, xrayMat));
+ // plate
+ this.uHot = { value: 1 };
+ const plateMat = new THREE.ShaderMaterial({
+ vertexShader: PLATE_VERT, fragmentShader: PLATE_FRAG, transparent: true, depthTest: false, depthWrite: false,
+ side: THREE.DoubleSide, uniforms: { uTime: u.uTime, uHot: this.uHot },
+ });
+ const plate = new THREE.Mesh(data.plateGeo, plateMat); plate.renderOrder = 3;
+ xh.add(plate);
+ // foam lattice
+ const cellMat = new THREE.ShaderMaterial({
+ vertexShader: CELL_VERT, fragmentShader: CELL_FRAG, transparent: true, depthTest: false, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uPx: u.uPx, uTime: u.uTime, uProfile: u.uProfile, uProfX: u.uProfX, uGait: u.uGait },
+ });
+ const cells = new THREE.Points(data.cellGeo, cellMat); cells.frustumCulled = false; cells.renderOrder = 2;
+ xh.add(cells);
+ const struts = new THREE.LineSegments(data.strutGeo, new THREE.LineBasicMaterial({ color: new THREE.Color(0.025, 0.06, 0.11), transparent: true, depthTest: false, depthWrite: false, blending: THREE.AdditiveBlending }));
+ struts.renderOrder = 1; struts.frustumCulled = false;
+ xh.add(struts);
+
+ // THERMAL
+ const ts = this.scenes[1];
+ const th = this._holder(ts);
+ const thermalMat = new THREE.ShaderMaterial({
+ vertexShader: SHELL_VERT, fragmentShader: THERMAL_FRAG, side: THREE.DoubleSide,
+ uniforms: { uTime: u.uTime, uShoeInv: u.uShoeInv, uProfile: u.uProfile, uProfX: u.uProfX, uGait: u.uGait },
+ });
+ th.add(this._cloneWith(model, thermalMat));
+ this.uFloorC = { value: new THREE.Vector2() };
+ const heat = new THREE.Mesh(new THREE.PlaneGeometry(9, 9).rotateX(-Math.PI / 2), new THREE.ShaderMaterial({
+ vertexShader: 'varying vec3 vWP; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vWP = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }',
+ fragmentShader: FLOORHEAT_FRAG,
+ uniforms: { uTime: u.uTime, uShoeInv: u.uShoeInv, uProfile: u.uProfile, uProfX: u.uProfX, uGait: u.uGait, uFloorC: this.uFloorC },
+ }));
+ heat.position.y = 0.0005;
+ this.heatFloor = heat;
+ ts.add(heat);
+
+ // CAD: normals pass → Sobel quad → dimension overlay
+ this.cadN = new THREE.Scene();
+ const nh = this._holder(this.cadN);
+ const nMat = new THREE.ShaderMaterial({ vertexShader: SHELL_VERT, fragmentShader: NORMAL_FRAG, side: THREE.DoubleSide, uniforms: { uShoeInv: u.uShoeInv } });
+ nh.add(this._cloneWith(model, nMat));
+ this.cadQuadScene = new THREE.Scene();
+ this.cadQuad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), new THREE.ShaderMaterial({
+ vertexShader: BG_VERT, fragmentShader: CAD_FRAG, depthTest: false, depthWrite: false,
+ uniforms: { tN: { value: this.rtN.texture }, uRes: { value: new THREE.Vector2(this.bw, this.bh) }, uDpr: { value: this.dpr }, uC: { value: new THREE.Vector2() }, uTime: u.uTime },
+ }));
+ this.cadQuad.frustumCulled = false;
+ this.cadQuadScene.add(this.cadQuad);
+ this.cadDims = new THREE.Scene();
+ const dh = this._holder(this.cadDims);
+ dh.add(this._buildDims(data));
+ }
+
+ _cloneWith(model, mat) {
+ const c = model.clone(true);
+ c.traverse(o => { if (o.isMesh) { o.material = mat; o.castShadow = o.receiveShadow = false; o.frustumCulled = false; o.layers.set(0); } });
+ return c;
+ }
+
+ _buildDims(data) {
+ const g = new THREE.Group();
+ const volt = new THREE.Color(0xd2ff1e), white = new THREE.Color(0xc8d2de);
+ const segs = [], segsW = [];
+ const L = (arr, a, b) => arr.push(a[0], a[1], a[2], b[0], b[1], b[2]);
+ const tick = (arr, p, s = 0.025) => L(arr, [p[0] - s, p[1] - s, p[2]], [p[0] + s, p[1] + s, p[2]]);
+ const z = data.zFront + 0.02;
+ const { x0, x1, bottom, top, midTop, plateY } = data;
+ const hx = x0 + 0.1, fx = x1 - 0.16;
+ const yb = bottom(hx), yh = midTop(hx), yfb = bottom(fx), yft = midTop(fx);
+ // heel stack
+ const dxh = x0 - 0.14;
+ L(segsW, [hx - 0.02, yb, z], [dxh - 0.05, yb, z]); L(segsW, [hx - 0.02, yh, z], [dxh - 0.05, yh, z]);
+ L(segs, [dxh, yb, z], [dxh, yh, z]); tick(segs, [dxh, yb, z]); tick(segs, [dxh, yh, z]);
+ const sHeel = textSprite('38.0'); sHeel.position.set(dxh - 0.2, (yb + yh) / 2, z); g.add(sHeel);
+ // forefoot stack
+ const dxf = x1 + 0.12;
+ L(segsW, [fx + 0.02, yfb, z], [dxf + 0.05, yfb, z]); L(segsW, [fx + 0.02, yft, z], [dxf + 0.05, yft, z]);
+ L(segs, [dxf, yfb, z], [dxf, yft, z]); tick(segs, [dxf, yfb, z]); tick(segs, [dxf, yft, z]);
+ const sFore = textSprite('30.0'); sFore.position.set(dxf + 0.2, (yfb + yft) / 2, z); g.add(sFore);
+ // length
+ const ly = Math.min(bottom(0), bottom(x0 + 0.2)) - 0.12;
+ L(segsW, [x0, bottom(x0 + 0.03), z], [x0, ly - 0.04, z]); L(segsW, [x1, bottom(x1 - 0.03), z], [x1, ly - 0.04, z]);
+ L(segs, [x0, ly, z], [x1, ly, z]); tick(segs, [x0, ly, z]); tick(segs, [x1, ly, z]);
+ const sLen = textSprite('L 285.0'); sLen.position.set(0, ly - 0.06, z); g.add(sLen);
+ // overall height
+ const ty = top(x0 + 0.35);
+ const dxt = x0 - 0.36;
+ L(segsW, [x0 + 0.3, ty, z], [dxt - 0.05, ty, z]);
+ L(segs, [dxt, yb, z], [dxt, ty, z]); tick(segs, [dxt, ty, z]); tick(segs, [dxt, yb, z]);
+ const sH = textSprite('H 121.6', { color: '#c8d2de' }); sH.position.set(dxt - 0.02, ty + 0.07, z); g.add(sH);
+ // drop callout
+ const sDrop = textSprite('DROP 8.0', { color: '#ff7a3a' }); sDrop.position.set(0.02, midTop(0.02) + 0.11, z); g.add(sDrop);
+ // plate centreline, dashed
+ for (let i = 0; i < 60; i++) {
+ if (i % 2) continue;
+ const xa = x0 + 0.12 + (x1 - x0 - 0.2) * i / 60, xb = x0 + 0.12 + (x1 - x0 - 0.2) * (i + 1) / 60;
+ L(segs, [xa, plateY(xa), z], [xb, plateY(xb), z]);
+ }
+ const sPlate = textSprite('CFRP 1.1', { color: '#ff7a3a' }); sPlate.position.set(-0.28, plateY(-0.28) - 0.07, z); g.add(sPlate);
+ // centre line (dash-dot) along the last
+ for (let i = 0; i < 40; i++) {
+ const xa = x0 - 0.05 + (x1 - x0 + 0.1) * i / 40, xb = xa + (x1 - x0 + 0.1) / 40 * (i % 3 === 2 ? 0.15 : 0.7);
+ L(segsW, [xa, (yb + ty) * 0.5, z], [xb, (yb + ty) * 0.5, z]);
+ }
+ // toe spring angle
+ const ax = x1 - 0.42, ay = bottom(x1 - 0.42);
+ for (let i = 0; i < 12; i++) {
+ const a0 = i / 12 * 0.32, a1 = (i + 1) / 12 * 0.32, rr = 0.34;
+ L(segs, [ax + Math.cos(a0) * rr, ay + Math.sin(a0) * rr, z], [ax + Math.cos(a1) * rr, ay + Math.sin(a1) * rr, z]);
+ }
+ L(segsW, [ax, ay, z], [ax + 0.44, ay, z]);
+ const sA = textSprite('4.2°'); sA.position.set(ax + 0.46, ay + 0.1, z); g.add(sA);
+ const mk = (arr, col, op) => {
+ const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(arr, 3));
+ const m = new THREE.LineSegments(geo, new THREE.LineBasicMaterial({ color: col, depthTest: false, depthWrite: false, transparent: true, opacity: op }));
+ m.frustumCulled = false; m.renderOrder = 5; return m;
+ };
+ g.add(mk(segs, volt, 0.95), mk(segsW, white, 0.45));
+ return g;
+ }
+
+ setMode(i) {
+ if (i === this.mode) return false;
+ this.prev = this.mode; this.mode = i; this.wipe = 0;
+ return true;
+ }
+
+ sync(pivot) {
+ for (const h of this.holders) { h.matrix.copy(pivot.matrixWorld); h.matrixWorldNeedsUpdate = true; }
+ if (this.uFloorC) this.uFloorC.value.set(pivot.position.x, pivot.position.z);
+ if (this.heatFloor) { this.heatFloor.position.x = pivot.position.x; this.heatFloor.position.z = pivot.position.z; }
+ }
+
+ /** Draw the lens contents for this frame (call before the main render). */
+ render() {
+ const r = this.renderer, cam = this.camera;
+ const dpr = this.dpr, bw = this.bw, bh = this.bh;
+ const R = this.r * this.open * dpr;
+ const U = this.effect.uniforms;
+ const cx = this.cx * dpr, cy = bh - this.cy * dpr; // buffer px, y up
+ U.get('uC').value.set(cx / bw, cy / bh);
+ U.get('uR').value = R;
+ U.get('uZ').value = this.zoom;
+ U.get('uWipe').value = this.wipe;
+ U.get('uVel').value.set(this.vx * dpr, -this.vy * dpr);
+ U.get('uHot').value = this.hot;
+ U.get('uMix').value = this.mix;
+ this.pass.enabled = R > 1.5 && this.mix > 0.004;
+ if (!this.pass.enabled || !this.cadQuad) return;
+ const ext = R * 1.34 * this.zoom * 1.06 + 8;
+ const x0 = Math.max(0, Math.floor(cx - ext)), y0 = Math.max(0, Math.floor(cy - ext));
+ const x1 = Math.min(bw, Math.ceil(cx + ext)), y1 = Math.min(bh, Math.ceil(cy + ext));
+ if (x1 <= x0 || y1 <= y0) { this.pass.enabled = false; return; }
+ this.sc.set(x0, y0, x1 - x0, y1 - y0);
+ this.xrayBg.material.uniforms.uCpx.value.set(cx, cy);
+ this.xrayBg.material.uniforms.uRpx.value = R;
+ this.xrayBg.material.uniforms.uDpr.value = dpr;
+
+ const Z = this.zoom;
+ const cyTop = bh - cy;
+ cam.setViewOffset(bw, bh, cx * (1 - 1 / Z), cyTop * (1 - 1 / Z), bw / Z, bh / Z);
+ this.u.uPx.value = bh * cam.projectionMatrix.elements[5] / 2;
+ const prevRT = r.getRenderTarget(), prevAuto = r.autoClear, prevCol = r.getClearColor(new THREE.Color()), prevA = r.getClearAlpha();
+ r.autoClear = false;
+ this._draw(this.mode, this.rtA);
+ if (this.wipe < 1) this._draw(this.prev, this.rtB);
+ r.autoClear = prevAuto;
+ r.setClearColor(prevCol, prevA);
+ r.setRenderTarget(prevRT);
+ cam.clearViewOffset();
+ }
+
+ _draw(mode, target) {
+ const r = this.renderer, cam = this.camera;
+ target.scissor.copy(this.sc); target.scissorTest = true;
+ r.setRenderTarget(target);
+ r.setClearColor(MODES[mode].bg, 1); r.clear(true, true, false);
+ if (mode === 2) {
+ this.rtN.scissor.copy(this.sc); this.rtN.scissorTest = true;
+ r.setRenderTarget(this.rtN); r.setClearColor(0x000000, 0); r.clear(true, true, false);
+ r.render(this.cadN, cam);
+ r.setRenderTarget(target);
+ r.render(this.cadQuadScene, this.ortho);
+ r.render(this.cadDims, cam);
+ } else {
+ r.render(this.scenes[mode], cam);
+ }
+ }
+}
diff --git a/examples/velocity/main.js b/examples/velocity/main.js
new file mode 100644
index 0000000..64e4dd9
--- /dev/null
+++ b/examples/velocity/main.js
@@ -0,0 +1,787 @@
+import { Engine, THREE, normalize, prepModel, damp, clamp, smooth, lerp, studioEnvironment } from '../../src/core/engine.js';
+import { Assets, sampleSurface, firstMesh } from '../../src/core/assets.js';
+import { Pointer } from '../../src/core/input.js';
+import { smoothScroll, gsap, reveal } from '../../src/core/scroll.js';
+import { preloader, cursor, magnetic, worldNav } from '../../src/core/ui.js';
+import { PlanarReflection } from '../../src/core/reflector.js';
+import { Lens, MODES } from './lens.js';
+import { buildCyc, matTexture, ContactShadow, MM } from './studio.js';
+import { NOISE, DISSOLVE } from './shaders.js';
+
+const Q = new URLSearchParams(location.search);
+// Canvas-drawn labels (floor ruler, CAD dimensions) need the mono face.
+await Promise.race([Promise.all(['500 17px "JetBrains Mono"', '600 44px "JetBrains Mono"'].map(f => document.fonts.load(f))), new Promise(r => setTimeout(r, 1800))]).catch(() => {});
+const D = Math.PI / 180;
+const isTouch = matchMedia('(pointer: coarse)').matches;
+
+// ─── Choreography: one state per section ─────────────────────────────────────
+// cam/look in world units; pos = shoe pivot xz; yaw/bank/pitch in radians; lens radius as a fraction of the viewport.
+const STATES = {
+ hero: { cam: [0.0, 1.45, 5.75], look: [0.36, 0.47, 0], fov: 25, pos: [0.8, 0.05], yaw: -0.3, bank: 0, pitch: 0, lift: 0, lensR: 0.175, zoom: 1.12, mode: 0, dock: 'plateMid', mob: -0.05 },
+ lens: { cam: [0.0, 1.3, 5.7], look: [-0.12, 0.45, 0], fov: 25, pos: [-0.66, 0], yaw: 0.55, bank: 0, pitch: 0, lift: 0, lensR: 0.18, zoom: 1.15, mode: null, dock: 'midsole', text: 'r', mob: 0.74 },
+ plate: { cam: [0.0, 0.7, 5.1], look: [0.36, 0.6, 0], fov: 24, pos: [0.8, 0], yaw: -0.16, bank: -0.36, pitch: 0.06, lift: 0.36, lensR: 0.21, zoom: 1.12, mode: 0, dock: 'plateMid', text: 'l', mob: 0.62 },
+ foam: { cam: [0.0, 1.0, 4.7], look: [-0.2, 0.42, 0], fov: 24, pos: [-0.62, 0.1], yaw: 1.04, bank: 0, pitch: 0, lift: 0, lensR: 0.17, zoom: 1.2, mode: 1, dock: 'heelFoam', text: 'r', mob: 0.62 },
+ upper: { cam: [0.0, 3.1, 4.4], look: [0.5, 0.3, 0], fov: 25, pos: [0.82, 0], yaw: -0.6, bank: 0, pitch: 0, lift: 0, lensR: 0.17, zoom: 1.2, mode: 2, dock: 'vamp', text: 'l', mob: 0.62 },
+ colour: { cam: [0.0, 1.4, 5.9], look: [0.3, 0.5, 0], fov: 25, pos: [0.78, 0], yaw: 0.35, bank: 0, pitch: 0, lift: 0, lensR: 0.12, zoom: 1.1, mode: 0, dock: 'plateMid', sway: 1, text: 'l', mob: -0.5 },
+ drop: { cam: [0.0, 1.3, 7.3], look: [0.0, 0.34, 0], fov: 25, pos: [0.0, -0.2], yaw: -0.5, bank: 0, pitch: 0.06, lift: 0.86, lensR: 0.1, zoom: 1.1, mode: 0, dock: 'core', sway: 1, mob: 0.5 },
+};
+const CALLOUTS = {
+ plate: [
+ { a: 'plateMid', k: '02.1', t: 'Carbon plate', v: 'Full length · 1.1 mm UD', off: [60, -250] },
+ { a: 'plateFore', k: '02.2', t: 'Rocker apex', v: '62% of length · 4.2°', off: [140, 120] },
+ { a: 'heelWing', k: '02.3', t: 'Heel wing', v: 'Lateral stability rail', off: [-200, 150] },
+ ],
+ foam: [
+ { a: 'heelFoam', k: '03.1', t: 'Heel strike zone', v: '38 mm · 81% air', off: [-260, -120] },
+ { a: 'foreFoam', k: '03.2', t: 'Energy return', v: '87% · Supercritical PEBA', off: [90, -210] },
+ { a: 'lugs', k: '03.3', t: 'Outsole lugs', v: '1.5 mm · 36 per sole', off: [70, 120] },
+ ],
+ upper: [
+ { a: 'vamp', k: '04.1', t: 'Engineered mesh', v: '212 knit zones', off: [150, -120] },
+ { a: 'cage', k: '04.2', t: 'Ripstop cage', v: '11 g · zero seams', off: [-280, 90] },
+ { a: 'tab', k: '04.3', t: 'Heel tab', v: '3 g · Solar TPU', off: [-250, -110] },
+ ],
+};
+
+// ─── Engine ──────────────────────────────────────────────────────────────────
+const canvas = document.getElementById('gl');
+const engine = new Engine({
+ canvas, fov: 25, near: 0.05, far: 120, dpr: 1.6, background: 0xf2f3f5,
+ post: {
+ ao: { aoRadius: 0.34, intensity: 2.4, distanceFalloff: 0.55 },
+ bloom: { intensity: 1.25, luminanceThreshold: 1.55, luminanceSmoothing: 0.3, radius: 0.66 },
+ tone: 'neutral',
+ vignette: { offset: 0.42, darkness: 0.34 },
+ noise: 0.028,
+ ca: 0.0003,
+ },
+});
+const { scene, camera, renderer } = engine;
+renderer.shadowMap.type = THREE.PCFShadowMap;
+scene.environment = studioEnvironment(renderer, {
+ top: 0xe4e5e7, bottom: 0x808286, panels: [
+ { pos: [0, 7, 2.5], size: [9, 4], intensity: 3.4, color: 0xffffff },
+ { pos: [-7, 3, 3.5], size: [3, 7], intensity: 2.4, color: 0xfff5ec },
+ { pos: [7, 3.2, -2], size: [2.5, 7], intensity: 2.8, color: 0xf2f5fa },
+ { pos: [0, 2.2, -8], size: [12, 3], intensity: 1.5, color: 0xffffff },
+ ],
+});
+scene.environmentIntensity = 0.8;
+
+// Lights: a big key from front-left, a cool rim from back-right, a wash on the cyc.
+const key = new THREE.DirectionalLight(0xfffcf8, 2.6);
+key.position.set(-2.8, 6.8, 4.4);
+key.castShadow = true;
+key.shadow.mapSize.set(2048, 2048);
+Object.assign(key.shadow.camera, { left: -2.6, right: 2.6, top: 2.6, bottom: -2.6, near: 2, far: 16 });
+key.shadow.radius = 7; key.shadow.blurSamples = 16;
+key.shadow.bias = -0.0004; key.shadow.normalBias = 0.025;
+const keyTarget = new THREE.Object3D();
+key.target = keyTarget;
+scene.add(key, keyTarget);
+const rim = new THREE.DirectionalLight(0xf4f6fa, 1.7);
+rim.position.set(4.5, 3.6, -5);
+scene.add(rim);
+const hemi = new THREE.HemisphereLight(0xffffff, 0xc9cdd4, 0.3);
+scene.add(hemi);
+
+
+// Studio
+const cyc = buildCyc({ z0: -3.4, R: 4.4, wallColor: 0xcfd0d3 });
+scene.add(cyc.group);
+const mat = matTexture(2048, 7);
+mat.wrapS = mat.wrapT = THREE.ClampToEdgeWrapping;
+mat.repeat.set(10, 40 / 7);
+mat.offset.set(-4.5, 0.5 - (-3.4 + 40) / 7);
+cyc.floorMat.map = mat;
+cyc.floorMat.color.set(0xe6e6e8);
+const reflection = new PlanarReflection(renderer, { resolution: 0.5 });
+reflection.hidden.push(cyc.floor);
+reflection.patch(cyc.floorMat, { strength: 0.32, distort: 0, lodScale: 3.2, lodBias: 0.2, f0: 0.03 });
+{
+ const base = cyc.floorMat.onBeforeCompile;
+ cyc.floorMat.onBeforeCompile = (sh, r) => {
+ base(sh, r);
+ sh.fragmentShader = sh.fragmentShader.replace('outgoingLight += refl', 'outgoingLight += smoothstep(-3.0, -0.6, vReflW.z) * smoothstep(8.0, 2.5, length(vReflW.xz)) * refl');
+ };
+}
+engine.onResize((w, h, dpr) => reflection.setSize(w, h, dpr));
+const contact = new ContactShadow(renderer, { size: 512, width: 4.6, height: 4.6, far: 1.15, blur: 3.4, opacity: 0.88, darkness: 1.6 });
+scene.add(contact.group);
+reflection.hidden.push(contact.plane);
+
+// ─── Shoe ────────────────────────────────────────────────────────────────────
+const pivot = new THREE.Group();
+scene.add(pivot);
+const U = {
+ uTime: { value: 0 }, uShoeInv: { value: new THREE.Matrix4() }, uGait: { value: 0 }, uPx: { value: 500 },
+ uProfile: { value: null }, uProfX: { value: new THREE.Vector2(-1, 1) }, uDis: { value: -0.25 },
+};
+
+const assets = new Assets();
+const pointer = new Pointer({ lambda: 9 });
+const loaderEl = document.querySelector('.loader');
+// loader dial
+{
+ const g = loaderEl.querySelector('.loader-ticks');
+ let s = '';
+ for (let i = 0; i < 72; i++) {
+ const a = i / 72 * Math.PI * 2 - Math.PI / 2, major = i % 6 === 0;
+ const r0 = major ? 45 : 47, r1 = 52;
+ s += `<line class="${major ? 'major' : ''}" x1="${(Math.cos(a) * r0).toFixed(2)}" y1="${(Math.sin(a) * r0).toFixed(2)}" x2="${(Math.cos(a) * r1).toFixed(2)}" y2="${(Math.sin(a) * r1).toFixed(2)}"/>`;
+ }
+ g.innerHTML = s;
+}
+const loaderTicks = [...loaderEl.querySelectorAll('.loader-ticks line')];
+const STEPS = ['— optics', '— carbon plate', '— foam lattice', '— thermal', '— ready'];
+const loader = preloader({
+ assets, el: loaderEl, minTime: 1400,
+ exit: async () => {
+ const o = { h: 0 };
+ loaderEl.querySelector('.loader-dial').style.transition = 'transform .6s cubic-bezier(.7,0,.3,1), opacity .4s';
+ loaderEl.querySelector('.loader-dial').style.transform = 'scale(.6)';
+ loaderEl.querySelector('.loader-dial').style.opacity = '0';
+ loaderEl.querySelector('.loader-line').style.opacity = '0';
+ await gsap.to(o, { h: Math.hypot(innerWidth, innerHeight) * 0.6, duration: 1.15, ease: 'expo.inOut', delay: 0.15, onUpdate: () => loaderEl.style.setProperty('--hole', o.h + 'px') });
+ },
+ onValue: v => {
+ loaderEl.querySelector('.loader-pct').textContent = String(Math.round(v * 100)).padStart(3, '0');
+ const n = Math.round(v * loaderTicks.length);
+ loaderTicks.forEach((l, i) => l.classList.toggle('on', i < n));
+ loaderEl.querySelector('.loader-step').textContent = STEPS[Math.min(4, Math.floor(v * 4.2))];
+ },
+});
+
+function prepShoe(g, black) {
+ const m = g.scene;
+ m.rotation.y = Math.PI; // toe to +x, lateral side (the photographed one) to +z
+ normalize(m, 2.0, { axis: 'x' });
+ const box = new THREE.Box3().setFromObject(m);
+ m.position.y -= box.max.y / 2;
+ prepModel(m, renderer, {
+ env: 1.0, onMat: (mat) => {
+ mat.envMapIntensity = black ? 1.1 : 0.55;
+ if (mat.normalScale) mat.normalScale.multiplyScalar(1.5);
+ patchDissolve(mat, black);
+ },
+ });
+ m.traverse(o => { if (o.isMesh) o.layers.enable(contact.layer); });
+ return { model: m, height: box.max.y };
+}
+
+function patchDissolve(mat, black) {
+ mat.onBeforeCompile = sh => {
+ sh.uniforms.uDis = U.uDis; sh.uniforms.uShoeInv = U.uShoeInv;
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nuniform mat4 uShoeInv; varying vec3 vSP;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvSP = (uShoeInv * modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>\nuniform float uDis; varying vec3 vSP;\n${NOISE}\n${DISSOLVE}`)
+ .replace('#include <map_fragment>', `#include <map_fragment>
+ diffuseColor.rgb = max(mix(vec3(dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722))), diffuseColor.rgb, ${black ? '1.25' : '1.4'}), 0.0);`)
+ .replace('#include <clipping_planes_fragment>', `#include <clipping_planes_fragment>
+ float dF = disField(vSP) - uDis;
+ ${black ? 'if (dF > 0.0) discard;' : 'if (dF < 0.0) discard;'}
+ float dEdge = 1.0 - smoothstep(0.0, 0.05, abs(dF));`)
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ totalEmissiveRadiance += mix(vec3(1.0, 0.24, 0.02), vec3(1.0, 0.9, 0.62), dEdge * dEdge * dEdge) * dEdge * 7.0;`);
+ };
+ mat.customProgramCacheKey = () => 'vx-dissolve-' + (black ? 'b' : 'w');
+ mat.needsUpdate = true;
+}
+
+// Measure the sole so the plate, the foam lattice, the thermal field and the callouts sit where the real shoe is.
+function measure(model) {
+ model.updateMatrixWorld(true);
+ const mesh = firstMesh(model);
+ const pos = mesh.geometry.attributes.position;
+ const v = new THREE.Vector3();
+ const n = pos.count;
+ const P = new Float32Array(n * 3);
+ const box = new THREE.Box3();
+ for (let i = 0; i < n; i++) { v.fromBufferAttribute(pos, i).applyMatrix4(mesh.matrixWorld); P[i * 3] = v.x; P[i * 3 + 1] = v.y; P[i * 3 + 2] = v.z; box.expandByPoint(v); }
+ const NX = 64, NY = 32;
+ const x0 = box.min.x, x1 = box.max.x, y0 = box.min.y, y1 = box.max.y;
+ const bx = x => clamp(Math.floor((x - x0) / (x1 - x0) * NX), 0, NX - 1);
+ const by = y => clamp(Math.floor((y - y0) / (y1 - y0) * NY), 0, NY - 1);
+ const minY = new Float32Array(NX).fill(Infinity), maxY = new Float32Array(NX).fill(-Infinity);
+ const side = new Float32Array(NX * NY).fill(-Infinity), sideN = new Float32Array(NX * NY).fill(Infinity);
+ for (let i = 0; i < n; i++) {
+ const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2];
+ const ix = bx(x);
+ if (y < minY[ix]) minY[ix] = y;
+ if (y > maxY[ix]) maxY[ix] = y;
+ const k = by(y) * NX + ix;
+ if (z > side[k]) side[k] = z;
+ if (z < sideN[k]) sideN[k] = z;
+ }
+ const zlo = new Float32Array(NX).fill(Infinity), zhi = new Float32Array(NX).fill(-Infinity);
+ for (let i = 0; i < n; i++) {
+ const x = P[i * 3], y = P[i * 3 + 1], z = P[i * 3 + 2];
+ const ix = bx(x);
+ if (y < minY[ix] + 0.06) { if (z < zlo[ix]) zlo[ix] = z; if (z > zhi[ix]) zhi[ix] = z; }
+ }
+ const fillGaps = a => { for (let i = 0; i < a.length; i++) if (!isFinite(a[i])) a[i] = isFinite(a[i - 1]) ? a[i - 1] : a.find(isFinite); return a; };
+ const blur = (a, r = 2) => { const o = new Float32Array(a.length); for (let i = 0; i < a.length; i++) { let s = 0, c = 0; for (let j = -r; j <= r; j++) { const k = clamp(i + j, 0, a.length - 1); s += a[k]; c++; } o[i] = s / c; } return o; };
+ [minY, maxY, zlo, zhi].forEach(fillGaps);
+ const bottomA = blur(minY, 2), topA = blur(maxY, 1);
+ const zc = new Float32Array(NX), hw = new Float32Array(NX);
+ for (let i = 0; i < NX; i++) { zc[i] = (zlo[i] + zhi[i]) / 2; hw[i] = Math.max(0.02, (zhi[i] - zlo[i]) / 2); }
+ const zcA = blur(zc, 3), hwA = blur(hw, 2);
+ const at = (a, x) => { const f = clamp((x - x0) / (x1 - x0) * NX - 0.5, 0, NX - 1); const i = Math.floor(f), t = f - i; return lerp(a[i], a[Math.min(NX - 1, i + 1)], t); };
+ const bottom = x => at(bottomA, x), top = x => at(topA, x);
+ const H = y1 - y0;
+ const midTop = x => bottom(x) + H * lerp(0.38, 0.17, smooth(-0.55, 0.5, x));
+ const plateY = x => bottom(x) + H * lerp(0.215, 0.075, smooth(-0.5, 0.32, x));
+ const sideZ = (x, y) => { const ix = bx(x), iy = by(y); let z = side[iy * NX + ix]; if (!isFinite(z)) z = at(zcA, x) + at(hwA, x); return z; };
+ // profile texture
+ const tex = new Float32Array(NX * 4);
+ for (let i = 0; i < NX; i++) {
+ const x = x0 + (i + 0.5) / NX * (x1 - x0);
+ tex[i * 4] = bottom(x); tex[i * 4 + 1] = at(zcA, x); tex[i * 4 + 2] = at(hwA, x); tex[i * 4 + 3] = midTop(x);
+ }
+ const dt = new THREE.DataTexture(tex, NX, 1, THREE.RGBAFormat, THREE.FloatType);
+ dt.minFilter = dt.magFilter = THREE.NearestFilter; // float linear filtering is not universal; 64 bins is smooth enough
+ dt.needsUpdate = true;
+
+ // Carbon plate: a spoon-shaped sheet following the rocker.
+ const nu = 90, nv = 12;
+ const pp = [], uv = [], idx = [];
+ const pu0 = x0 + 0.1, pu1 = x1 - 0.1;
+ for (let i = 0; i <= nu; i++) {
+ const x = lerp(pu0, pu1, i / nu);
+ const c = at(zcA, x), w = at(hwA, x) * lerp(0.62, 0.8, smooth(-0.6, 0.4, x));
+ for (let j = 0; j <= nv; j++) {
+ const s = j / nv * 2 - 1;
+ pp.push(x, plateY(x) + 0.02 * s * s, c + s * w);
+ uv.push(i / nu, j / nv);
+ }
+ }
+ for (let i = 0; i < nu; i++) for (let j = 0; j < nv; j++) { const a = i * (nv + 1) + j, b = a + nv + 1; idx.push(a, b, a + 1, b, b + 1, a + 1); }
+ const plateGeo = new THREE.BufferGeometry();
+ plateGeo.setAttribute('position', new THREE.Float32BufferAttribute(pp, 3));
+ plateGeo.setAttribute('uv', new THREE.Float32BufferAttribute(uv, 2));
+ plateGeo.setIndex(idx); plateGeo.computeVertexNormals();
+
+ // Foam lattice: surface samples of the midsole pushed inward, thinned to an even spacing.
+ const smp = sampleSurface(mesh, 30000, { colors: false });
+ const cells = [], seeds = [], sizes = [];
+ const cellHash = new Map(), CS = 0.034;
+ const key3 = (x, y, z) => `${Math.floor(x / CS)},${Math.floor(y / CS)},${Math.floor(z / CS)}`;
+ for (let i = 0; i < 30000 && cells.length / 3 < 2600; i++) {
+ let x = smp.position[i * 3], y = smp.position[i * 3 + 1], z = smp.position[i * 3 + 2];
+ const b = bottom(x), mt = midTop(x);
+ if (y > mt - 0.01 || y < b + 0.012 || x < x0 + 0.05 || x > x1 - 0.05) continue;
+ const d = Math.pow(Math.random(), 0.8) * at(hwA, x) * 0.9;
+ x -= smp.normal[i * 3] * d * 0.3; y -= smp.normal[i * 3 + 1] * d; z -= smp.normal[i * 3 + 2] * d;
+ y = clamp(y, b + 0.02, mt - 0.02);
+ const c = at(zcA, x), w = at(hwA, x) * 0.92;
+ z = clamp(z, c - w, c + w);
+ const k = key3(x, y, z);
+ if (cellHash.has(k)) continue;
+ cellHash.set(k, cells.length / 3);
+ cells.push(x, y, z); seeds.push(Math.random()); sizes.push(lerp(0.026, 0.05, Math.random()));
+ }
+ const cellGeo = new THREE.BufferGeometry();
+ cellGeo.setAttribute('position', new THREE.Float32BufferAttribute(cells, 3));
+ cellGeo.setAttribute('aSeed', new THREE.Float32BufferAttribute(seeds, 1));
+ cellGeo.setAttribute('aSize', new THREE.Float32BufferAttribute(sizes, 1));
+ // struts between near neighbours
+ const struts = [];
+ const nc = cells.length / 3;
+ const grid = new Map(), GS = 0.07;
+ for (let i = 0; i < nc; i++) { const k = `${Math.floor(cells[i * 3] / GS)},${Math.floor(cells[i * 3 + 1] / GS)},${Math.floor(cells[i * 3 + 2] / GS)}`; if (!grid.has(k)) grid.set(k, []); grid.get(k).push(i); }
+ for (let i = 0; i < nc; i++) {
+ const ax = cells[i * 3], ay = cells[i * 3 + 1], az = cells[i * 3 + 2];
+ const gx = Math.floor(ax / GS), gy = Math.floor(ay / GS), gz = Math.floor(az / GS);
+ const near = [];
+ for (let a = -1; a <= 1; a++) for (let b = -1; b <= 1; b++) for (let c = -1; c <= 1; c++) {
+ const l = grid.get(`${gx + a},${gy + b},${gz + c}`); if (!l) continue;
+ for (const j of l) { if (j <= i) continue; const dx = cells[j * 3] - ax, dy = cells[j * 3 + 1] - ay, dz = cells[j * 3 + 2] - az; const d2 = dx * dx + dy * dy + dz * dz; if (d2 < GS * GS) near.push([d2, j]); }
+ }
+ near.sort((p, q) => p[0] - q[0]);
+ for (const [, j] of near.slice(0, 2)) struts.push(ax, ay, az, cells[j * 3], cells[j * 3 + 1], cells[j * 3 + 2]);
+ }
+ const strutGeo = new THREE.BufferGeometry();
+ strutGeo.setAttribute('position', new THREE.Float32BufferAttribute(struts, 3));
+
+ // Embers for the colourway dissolve
+ const em = sampleSurface(mesh, 7000, { colors: false });
+ const emSeed = new Float32Array(7000).map(() => Math.random());
+ const emberGeo = new THREE.BufferGeometry();
+ emberGeo.setAttribute('position', new THREE.BufferAttribute(em.position, 3));
+ emberGeo.setAttribute('aN', new THREE.BufferAttribute(em.normal, 3));
+ emberGeo.setAttribute('aSeed', new THREE.BufferAttribute(emSeed, 1));
+
+ const surf = (x, dy) => { const y = bottom(x) + dy; return new THREE.Vector3(x, y, sideZ(x, y) + 0.004); };
+ const anchors = {
+ plateMid: new THREE.Vector3(-0.05, plateY(-0.05), at(zcA, -0.05)),
+ core: new THREE.Vector3(-0.08, lerp(bottom(-0.08), top(-0.08), 0.36), at(zcA, -0.08)),
+ plateFore: new THREE.Vector3(0.5, plateY(0.5), at(zcA, 0.5)),
+ midsole: new THREE.Vector3(-0.15, lerp(bottom(-0.15), midTop(-0.15), 0.5), at(zcA, -0.15)),
+ heelWing: surf(x0 + 0.22, H * 0.3),
+ heelFoam: surf(x0 + 0.3, H * 0.17),
+ foreFoam: surf(0.48, H * 0.1),
+ lugs: surf(0.2, H * 0.012),
+ vamp: surf(0.5, H * 0.34),
+ cage: surf(-0.12, H * 0.5),
+ tab: new THREE.Vector3(x0 + 0.05, top(x0 + 0.05) - 0.07, at(zcA, x0 + 0.05)),
+ };
+ return {
+ mesh, box, H, x0, x1, bottom, top, midTop, plateY, zFront: box.max.z,
+ profileTex: dt, plateGeo, cellGeo, strutGeo, emberGeo, anchors,
+ };
+}
+
+// Dissolve embers
+function makeEmbers(geo) {
+ const m = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ uniforms: { uDis: U.uDis, uDir: { value: 1 }, uPx: { value: 500 }, uOn: { value: 0 } },
+ vertexShader: `
+ attribute vec3 aN; attribute float aSeed;
+ uniform float uDis, uDir, uPx, uOn; varying float vA; varying float vH;
+ ${NOISE} ${DISSOLVE}
+ void main(){
+ float f = disField(position) - uDis;
+ float passed = -f * uDir;
+ float life = clamp(passed / 0.22, 0.0, 1.0);
+ vec3 drift = aN * 0.5 + vec3(0.0, 1.0, 0.0) * (0.7 + aSeed) + vec3(sin(aSeed * 91.0), 0.0, cos(aSeed * 57.0)) * 0.35;
+ vec3 p = position + drift * life * life * 0.3 * (0.4 + aSeed);
+ vA = uOn * (exp(-pow(f / 0.022, 2.0)) * 0.9 + step(0.0, passed) * (1.0 - life) * 0.8) * step(0.35, aSeed);
+ vH = 1.0 - life;
+ vec4 mv = modelViewMatrix * vec4(p, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = (0.006 + aSeed * 0.01) * uPx / -mv.z;
+ }`,
+ fragmentShader: `
+ varying float vA; varying float vH;
+ void main(){ float d = length(gl_PointCoord - 0.5); float a = smoothstep(0.5, 0.0, d); if (vA < 0.01) discard;
+ gl_FragColor = vec4(mix(vec3(1.0, 0.2, 0.02), vec3(1.0, 0.85, 0.5), vH) * a * vA * 6.0, 1.0); }`,
+ });
+ const p = new THREE.Points(geo, m);
+ p.frustumCulled = false;
+ return p;
+}
+
+// ─── Load ───────────────────────────────────────────────────────────────────
+const [gw, gb] = await Promise.all([assets.gltf('models/velocity/white.glb'), assets.gltf('models/velocity/black.glb')]);
+const white = prepShoe(gw, false), black = prepShoe(gb, true);
+const H = white.height;
+const data = measure(white.model);
+pivot.add(white.model, black.model);
+black.model.visible = false;
+U.uProfile.value = data.profileTex;
+U.uProfX.value.set(data.x0, data.x1);
+const embers = makeEmbers(data.emberGeo);
+embers.visible = false;
+pivot.add(embers);
+if (Q.has('debug')) {
+ firstMesh(white.model).material && console.log('mat', ['roughness', 'metalness', 'envMapIntensity'].map(k => k + '=' + firstMesh(white.model).material[k]).join(' '), !!firstMesh(white.model).material.roughnessMap);
+}
+
+const lens = new Lens(engine, U);
+lens.build(white.model, data);
+
+// ─── Interaction state ───────────────────────────────────────────────────────
+const lensUI = document.querySelector('.lens-ui');
+const lensSvg = lensUI.querySelector('svg');
+const lensTicks = lensUI.querySelector('.lens-ticks');
+{
+ let s = '';
+ for (let i = 0; i < 120; i++) {
+ const a = i / 120 * Math.PI * 2, major = i % 10 === 0, hot = i === 90;
+ const r0 = 102.5, r1 = hot ? 113 : major ? 109 : 105.5;
+ s += `<line class="${hot ? 'hot' : major ? 'major' : ''}" x1="${(Math.cos(a) * r0).toFixed(2)}" y1="${(Math.sin(a) * r0).toFixed(2)}" x2="${(Math.cos(a) * r1).toFixed(2)}" y2="${(Math.sin(a) * r1).toFixed(2)}"/>`;
+ }
+ lensTicks.innerHTML = s;
+}
+const lensArc = lensUI.querySelector('.lens-arc textPath');
+lensUI.querySelector('#lens-arc').setAttribute('d', 'M -118,0 A 118,118 0 0,1 118,0');
+lensArc.setAttribute('startOffset', '50%');
+lensArc.parentNode.setAttribute('text-anchor', 'middle');
+const lensTag = lensUI.querySelector('.lens-tag');
+lensArc.textContent = 'X-RAY · MODE 01/03 · CFRP PLATE 1.1 MM · PEBA LATTICE';
+const lensCoord = lensUI.querySelector('.lens-coord');
+const ARC = [
+ 'X-RAY · MODE 01/03 · CFRP PLATE 1.1 MM · PEBA LATTICE',
+ 'THERMAL · MODE 02/03 · 1,200 STRIDES · 18–36 °C',
+ 'CAD · MODE 03/03 · MASTER DRAWING REV. 14 · MM',
+];
+
+let userAt = -100, userMode = false, holdT = -1, holding = false, overUI = false;
+let stageIdx = -1, stage = 0, stageRaw = 0;
+const state = { open: 0, r: 150, zoom: 1.1, userW: 0, heroIn: 0, spinIn: 0, dockX: innerWidth * 0.6, dockY: innerHeight * 0.6, dockS: 1, idleVis: 1 };
+
+// ─── Idle docking: which on-shoe anchor can hold the lens without covering copy ────────────────────
+const TEXT_SEL = '.hero .eyebrow, .title .t1, .title .t2, .hero .sub, .hero-note, .s .col > .eyebrow, .s .col > h2, .s .col > .lede, .drop-inner > .eyebrow, .drop-inner > h2, .drop-note';
+const BOX_SEL = '.specs, .s .col > .stat, .s .col > .minor, .s .col > .modes, .swatches, .count, .join';
+const BOX_SEL_PHONE = '.s .col, .specs, .hero-copy > *, .drop-inner > *';
+const copyEls = { text: [...document.querySelectorAll(TEXT_SEL)], box: [...document.querySelectorAll(BOX_SEL)], phone: [...document.querySelectorAll(BOX_SEL_PHONE)] };
+const copyRange = document.createRange();
+let copyRects = [];
+function readCopy() {
+ copyRects = [];
+ const vis = r => r.width > 0 && r.bottom > 0 && r.top < innerHeight;
+ if (innerWidth <= 900) { for (const el of copyEls.phone) { const r = el.getBoundingClientRect(); if (vis(r)) copyRects.push(r); } return; }
+ for (const el of copyEls.text) { copyRange.selectNodeContents(el); const r = copyRange.getBoundingClientRect(); if (vis(r)) copyRects.push(r); }
+ for (const el of copyEls.box) { const r = el.getBoundingClientRect(); if (vis(r)) copyRects.push(r); }
+}
+const DOCK_ALT = ['plateMid', 'core', 'midsole', 'plateFore', 'heelFoam', 'foreFoam', 'vamp', 'cage'];
+let dockKey = null;
+const pD = { x: 0, y: 0, z: 0 };
+function dockOK(key, r) {
+ project(data.anchors[key], pD);
+ if (pD.z > 1 || pD.x < 24 + r * 0.3 || pD.x > innerWidth - 24 - r * 0.3 || pD.y < 80 + r * 0.3 || pD.y > innerHeight - 84 - r * 0.3) return false;
+ const rr = r * 1.18 + 12; // bezel ticks and arc lettering
+ for (const q of copyRects) { const dx = pD.x - clamp(pD.x, q.left, q.right), dy = pD.y - clamp(pD.y, q.top, q.bottom); if (dx * dx + dy * dy < rr * rr) return false; }
+ return true;
+}
+function chooseDock(pref, baseR) {
+ for (const s of [1, 0.72]) {
+ for (const k of [pref, dockKey, ...DOCK_ALT]) {
+ if (k && dockOK(k, baseR * s)) { dockKey = k; return { key: k, x: pD.x, y: pD.y, scale: s }; }
+ }
+ }
+ dockKey = null;
+ return { key: null, scale: 0.72 };
+}
+const modeButtons = [...document.querySelectorAll('[data-mode]')];
+function setMode(i, fromUser = false) {
+ if (fromUser) userMode = true;
+ if (!lens.setMode(i)) return;
+ gsap.killTweensOf(lens, 'wipe,hot');
+ gsap.to(lens, { wipe: 1, duration: 0.8, ease: 'power2.out' });
+ gsap.fromTo(lens, { hot: 1 }, { hot: 0, duration: 0.9, ease: 'power2.out' });
+ modeButtons.forEach(b => b.classList.toggle('is-on', +b.dataset.mode === i));
+ lensTag.querySelector('.lens-tag-n').textContent = String(i + 1).padStart(2, '0');
+ lensTag.querySelector('.lens-tag-m').textContent = MODES[i].name;
+ lensArc.textContent = ARC[i];
+}
+modeButtons.forEach(b => b.addEventListener('click', e => { e.stopPropagation(); setMode(+b.dataset.mode, true); }));
+addEventListener('keydown', e => {
+ if (e.target.closest?.('input')) return;
+ if (e.key >= '1' && e.key <= '3') setMode(+e.key - 1, true);
+ if (e.key === 'c' || e.key === 'C') setWay(way ? 0 : 1);
+});
+const UI_SEL = 'a,button,input,label,form,[data-nolens],.console,.nav,.tw-nav,.foot';
+pointer.on('move', e => {
+ userAt = engine.time;
+ overUI = !!e.target?.closest?.(UI_SEL);
+ cur?.set(overUI ? (e.target.closest('a,button,input') ? 'link' : '') : 'hidden');
+});
+pointer.on('down', e => {
+ userAt = engine.time;
+ if (e.button !== 0 || e.target?.closest?.(UI_SEL)) return;
+ holdT = engine.time; holding = false;
+});
+pointer.on('up', e => {
+ if (holdT < 0) return;
+ const quick = engine.time - holdT < 0.24;
+ holdT = -1;
+ if (holding) { holding = false; return; }
+ if (quick && e.pointerType === 'mouse') setMode((lens.mode + 1) % 3, true);
+});
+
+// Colourways
+let way = 0;
+const swatches = [...document.querySelectorAll('.swatch')];
+function setWay(i) {
+ if (i === way) return;
+ way = i;
+ swatches.forEach(s => s.classList.toggle('is-on', +s.dataset.way === i));
+ white.model.visible = black.model.visible = true;
+ embers.visible = true;
+ embers.material.uniforms.uDir.value = i ? 1 : -1;
+ gsap.killTweensOf(U.uDis);
+ gsap.to(embers.material.uniforms.uOn, { value: 1, duration: 0.2 });
+ gsap.to(U.uDis, {
+ value: i ? 1.25 : -0.25, duration: 2.1, ease: 'power1.inOut',
+ onComplete: () => { white.model.visible = !i; black.model.visible = !!i; gsap.to(embers.material.uniforms.uOn, { value: 0, duration: 0.4, onComplete: () => { embers.visible = false; } }); },
+ });
+}
+swatches.forEach(s => s.addEventListener('click', e => { e.stopPropagation(); setWay(+s.dataset.way); }));
+let autoWay = false;
+
+// ─── Callouts ───────────────────────────────────────────────────────────────
+const leadersEl = document.querySelector('.leaders');
+const calloutsEl = document.querySelector('.callouts');
+const SVGNS = 'http://www.w3.org/2000/svg';
+const callouts = [];
+for (const [sk, list] of Object.entries(CALLOUTS)) {
+ for (const c of list) {
+ const el = document.createElement('div');
+ el.className = 'callout';
+ el.innerHTML = `<span class="c-k">${c.k}</span><b>${c.t}</b><span class="c-v">${c.v}</span>`;
+ calloutsEl.appendChild(el);
+ const g = document.createElementNS(SVGNS, 'g');
+ g.innerHTML = '<path pathLength="1"/><circle class="ring" r="8"/><circle class="pin" r="3"/>';
+ g.style.opacity = 0;
+ leadersEl.appendChild(g);
+ callouts.push({ ...c, state: sk, el, g, path: g.firstChild, ring: g.children[1], pin: g.children[2], vis: 0 });
+ }
+}
+
+// ─── HUD ────────────────────────────────────────────────────────────────────
+const sections = [...document.querySelectorAll('[data-state]')].map(el => ({ el, key: el.dataset.state }));
+const stateList = sections.map(s => STATES[s.key]);
+const chapterN = document.querySelector('.chapter-n'), chapterName = document.querySelector('.chapter-name');
+const CHAPTERS = ['Launch file', 'The lens', 'Plate', 'Foam', 'Upper', 'Colourways', 'The drop'];
+const rulerMark = document.querySelector('.ruler-mark'), rulerVal = document.querySelector('.ruler-val'), rulerEl = document.querySelector('.ruler');
+const footEl = document.querySelector('.foot');
+const navLinks = [...document.querySelectorAll('.links a')];
+let anchorsY = [];
+function measureSections() {
+ const max = document.documentElement.scrollHeight - innerHeight;
+ anchorsY = sections.map(s => { const r = s.el.getBoundingClientRect(); return clamp(r.top + scrollY + r.height / 2 - innerHeight / 2, 0, max); });
+ anchorsY[0] = 0;
+}
+addEventListener('resize', measureSections);
+function stageAt(y) {
+ const a = anchorsY;
+ if (y <= a[0]) return 0;
+ for (let i = 0; i < a.length - 1; i++) if (y < a[i + 1]) return i + smooth(0.12, 0.88, (y - a[i]) / Math.max(1, a[i + 1] - a[i]));
+ return a.length - 1;
+}
+
+// countdown to Friday 16 Oct 2026, 09:00 Zürich (CEST)
+const DROP = new Date('2026-10-16T09:00:00+02:00').getTime();
+const cnt = Object.fromEntries([...document.querySelectorAll('.count b')].map(b => [b.dataset.u, b]));
+function tickCount() {
+ let s = Math.max(0, Math.floor((DROP - Date.now()) / 1000));
+ const d = Math.floor(s / 86400); s -= d * 86400;
+ const h = Math.floor(s / 3600); s -= h * 3600;
+ const m = Math.floor(s / 60); s -= m * 60;
+ cnt.d.textContent = String(d).padStart(2, '0'); cnt.h.textContent = String(h).padStart(2, '0');
+ cnt.m.textContent = String(m).padStart(2, '0'); cnt.s.textContent = String(s).padStart(2, '0');
+}
+tickCount(); setInterval(tickCount, 1000);
+
+// ─── Frame loop ─────────────────────────────────────────────────────────────
+const cur0 = { cam: new THREE.Vector3(), look: new THREE.Vector3() };
+const tv = new THREE.Vector3(), tv2 = new THREE.Vector3(), ray = new THREE.Raycaster(), plane = new THREE.Plane();
+const inv = new THREE.Matrix4();
+const L3 = (a, b, f, out) => out.set(lerp(a[0], b[0], f), lerp(a[1], b[1], f), lerp(a[2], b[2], f));
+function blendState(s) {
+ const i = Math.min(stateList.length - 2, Math.floor(s)), f = s - i;
+ const A = stateList[i], B = stateList[i + 1] ?? A;
+ return { A, B, f, i };
+}
+function project(v, out) { tv2.copy(v).applyMatrix4(pivot.matrixWorld).project(camera); out.x = (tv2.x + 1) / 2 * innerWidth; out.y = (1 - tv2.y) / 2 * innerHeight; out.z = tv2.z; return out; }
+const pA = { x: 0, y: 0, z: 0 }, pB = { x: 0, y: 0, z: 0 };
+let prevCx = 0, prevCy = 0;
+let cur = null;
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ U.uTime.value = t;
+ U.uGait.value = (t * 0.62) % 1;
+ lens.uScan.value = ((t * 0.32) % 1) * 2.8 - 1.4;
+
+ // stage
+ stageRaw = stageAt(scrollY);
+ stage = damp(stage, stageRaw, 6, dt);
+ const { A, B, f, i } = blendState(stage);
+ const near = Math.round(stage);
+ if (near !== stageIdx) {
+ stageIdx = near;
+ userMode = false;
+ const st = stateList[near];
+ if (st.mode !== null && st.mode !== undefined) setMode(st.mode);
+ chapterN.textContent = String(near).padStart(2, '0');
+ chapterName.textContent = CHAPTERS[near] ?? '';
+ const key = sections[near]?.key;
+ navLinks.forEach(a => a.classList.toggle('is-on', a.getAttribute('href') === '#' + (key === 'lens' ? 'lens' : sections[near]?.el.id)));
+ if (sections[near]?.key === 'colour' && !autoWay) { autoWay = true; setTimeout(() => { if (way === 0) setWay(1); }, 700); }
+ }
+
+ // camera
+ L3(A.cam, B.cam, f, cur0.cam); L3(A.look, B.look, f, cur0.look);
+ const fov = lerp(A.fov, B.fov, f);
+ const aspect = innerWidth / innerHeight, narrow = aspect < 0.95;
+ const wide = Math.max(1, aspect / 1.6); // keep screen-space staging constant on wide viewports
+ cur0.look.x *= wide;
+ if (narrow) {
+ // Portrait: centre the shoe, back off until it fits the width, and aim low so it sits above the text card.
+ const k = Math.pow(clamp(1.6 / aspect, 1, 3.4), 0.56);
+ cur0.look.x = 0;
+ tv.subVectors(cur0.cam, cur0.look).multiplyScalar(k);
+ cur0.cam.copy(cur0.look).add(tv); cur0.cam.x = 0;
+ cur0.look.y -= lerp(A.mob ?? 0.42, B.mob ?? 0.42, f) * Math.tan(fov * D / 2) * tv.length();
+ }
+ camera.position.copy(cur0.cam).add(tv.set(pointer.sx * 0.08, pointer.sy * 0.04, 0));
+ camera.lookAt(cur0.look);
+ if (Math.abs(camera.fov - fov) > 1e-4) { camera.fov = fov; camera.updateProjectionMatrix(); }
+ camera.updateMatrixWorld();
+
+ // shoe
+ const sway = lerp(A.sway ?? 0, B.sway ?? 0, f);
+ // past the last section the shoe rises with the page, so the countdown never scrolls over it
+ const tail = Math.max(0, scrollY - (anchorsY[anchorsY.length - 1] ?? 1e9)) / innerHeight;
+ const lift = lerp(A.lift, B.lift, f) + tail * 2 * Math.tan(fov * D / 2) * camera.position.distanceTo(cur0.look);
+ const bob = lift > 0.01 ? Math.sin(t * 1.1) * 0.012 * smooth(0, 0.3, lift) : 0;
+ pivot.position.set(narrow ? 0 : lerp(A.pos[0], B.pos[0], f) * wide, H / 2 + lift + bob, lerp(A.pos[1], B.pos[1], f));
+ const intro = state.heroIn;
+ pivot.rotation.set(lerp(A.bank, B.bank, f), lerp(A.yaw, B.yaw, f) + Math.sin(t * 0.35) * 0.03 + sway * Math.sin(t * 0.3) * 0.75 - (1 - intro) * 0.9, lerp(A.pitch, B.pitch, f) + (1 - intro) * 0.08, 'YXZ');
+ pivot.updateMatrixWorld(true);
+ U.uShoeInv.value.copy(pivot.matrixWorld).invert();
+ keyTarget.position.copy(pivot.position); keyTarget.updateMatrixWorld();
+ key.position.set(pivot.position.x - 2.8, 6.8, pivot.position.z + 4.4);
+ contact.group.position.set(pivot.position.x, 0, pivot.position.z);
+ cyc.sweepMat.userData.halo.uHalo.value.x = pivot.position.x * 0.8;
+ // the measuring mat travels with the shoe
+ mat.offset.set(-4.5 - pivot.position.x / 7, 0.5 - (-3.4 + 40) / 7 + pivot.position.z / 7);
+
+ // lens target: the pointer when in use; otherwise parked on the shoe, never over copy (fades out if nowhere fits)
+ const userActive = pointer.active && (t - userAt < 2.6 || pointer.down) && !isTouch || (isTouch && pointer.down);
+ state.userW = damp(state.userW, userActive ? 1 : 0, userActive ? 10 : 1.8, dt);
+ const unit = isTouch ? Math.min(innerHeight, innerWidth * 1.15) : innerHeight;
+ const footCover = clamp(1 - footEl.getBoundingClientRect().top / innerHeight);
+ const baseR = lerp(A.lensR, B.lensR, f) * unit;
+ if (engine._frames % 3 === 0) readCopy();
+ const dock = chooseDock(stateList[near].dock, baseR);
+ if (dock.key) { state.dockX = dock.x; state.dockY = dock.y; state.dockS = damp(state.dockS, dock.scale, 5, dt); }
+ state.idleVis = damp(state.idleVis, dock.key ? 1 : 0, dock.key ? 3 : 7, dt);
+ const aimX = lerp(state.dockX, pointer.px, state.userW), aimY = lerp(state.dockY, pointer.py, state.userW);
+ const follow = lerp(6, 14, state.userW);
+ lens.cx = damp(lens.cx, aimX, follow, dt); lens.cy = damp(lens.cy, aimY, follow, dt);
+ const vx = (lens.cx - prevCx) / Math.max(dt, 1e-3), vy = (lens.cy - prevCy) / Math.max(dt, 1e-3);
+ prevCx = lens.cx; prevCy = lens.cy;
+ lens.vx = damp(lens.vx, vx, 12, dt); lens.vy = damp(lens.vy, vy, 12, dt);
+ if (holdT >= 0 && t - holdT > 0.24) holding = true;
+ const rT = baseR * lerp(state.dockS, 1, state.userW) * (holding ? 1.22 : 1) * (overUI && state.userW > 0.5 ? 0.12 : 1);
+ lens.r = damp(lens.r, rT, 9, dt);
+ lens.zoom = damp(lens.zoom, holding ? 2.7 : lerp(A.zoom, B.zoom, f), holding ? 5 : 7, dt);
+ lens.open = state.open;
+ lens.mix = (1 - smooth(0.12, 0.5, footCover)) * lerp(state.idleVis, 1, state.userW);
+ lens.sync(pivot);
+ lens.render();
+
+ // lens chrome
+ const R = lens.r * lens.open;
+ const sp = Math.hypot(lens.vx, lens.vy), st = clamp(sp * 0.00012, 0, 0.2);
+ const ang = Math.atan2(lens.vy, lens.vx) / D;
+ lensUI.classList.toggle('on', R > 20);
+ lensUI.style.setProperty('--mix', lens.mix.toFixed(3));
+ lensSvg.style.transform = `translate3d(${lens.cx.toFixed(1)}px, ${lens.cy.toFixed(1)}px, 0) rotate(${ang.toFixed(2)}deg) scale(${(1 / (1 - st)).toFixed(4)}, ${(1 / (1 + st * 0.5)).toFixed(4)}) rotate(${(-ang).toFixed(2)}deg) scale(${(R / 100).toFixed(4)})`;
+ lensTicks.style.transform = `rotate(${(lens.cx * 0.12).toFixed(2)}deg)`;
+ const ta = 38 * D;
+ lensTag.style.transform = `translate3d(${(lens.cx + Math.cos(ta) * (R * 1.1 + 6)).toFixed(1)}px, ${(lens.cy + Math.sin(ta) * (R * 1.1 + 6) - 14).toFixed(1)}px, 0)`;
+ lensCoord.style.opacity = rT > innerHeight * 0.15 ? 1 : 0;
+ lensCoord.style.transform = `translate3d(${(lens.cx - lensCoord.offsetWidth / 2).toFixed(1)}px, ${(lens.cy + R * 1.14 + 12).toFixed(1)}px, 0)`;
+ // lens position in shoe millimetres (on the shoe's centre plane)
+ if ((engine._frames & 3) === 0) {
+ ray.setFromCamera(tv.set(lens.cx / innerWidth * 2 - 1, -(lens.cy / innerHeight) * 2 + 1, 0), camera);
+ plane.setFromNormalAndCoplanarPoint(tv2.set(0, 0, 1).transformDirection(pivot.matrixWorld), pivot.position);
+ if (ray.ray.intersectPlane(plane, tv)) {
+ tv.applyMatrix4(U.uShoeInv.value);
+ const xx = clamp(tv.x, data.x0, data.x1);
+ const mx = (tv.x - data.x0) * MM, my = (tv.y - data.bottom(xx)) * MM;
+ const inX = tv.x > data.x0 && tv.x < data.x1, b = data.bottom(xx);
+ const what = !inX || tv.y > data.top(xx) || tv.y < b - 0.01 ? 'AIR'
+ : tv.y < b + 0.035 ? 'OUTSOLE · 1.5 MM LUGS'
+ : Math.abs(tv.y - data.plateY(xx)) < 0.045 ? 'CFRP PLATE · 1.1 MM'
+ : tv.y < data.midTop(xx) ? 'PEBA FOAM · 81% AIR'
+ : tv.x < data.x0 + 0.28 ? 'HEEL COUNTER · TPU'
+ : tv.y > data.top(xx) - 0.14 && tv.x > -0.35 && tv.x < 0.55 ? 'LACING · 6 EYELETS'
+ : 'ENGINEERED MESH';
+ lensCoord.innerHTML = `X ${mx.toFixed(1).padStart(5, '0')} · Y ${my.toFixed(1).padStart(4, '0')} MM · <b>${what}</b>${lens.zoom > 1.6 ? ' · ×' + lens.zoom.toFixed(1) : ''}`;
+ }
+ }
+
+ // callouts
+ const placed = [{ x: lens.cx + Math.cos(38 * D) * (R * 1.1 + 6), y: lens.cy + Math.sin(38 * D) * (R * 1.1 + 6) - 14, w: 100, h: 32 }];
+ const activeKey = sections[near]?.key;
+ const sf = Math.abs(stage - near);
+ for (const c of callouts) {
+ const on = c.state === activeKey && sf < 0.3 && lens.open > 0.5 && innerWidth > 700;
+ c.vis = on;
+ c.el.classList.toggle('on', on);
+ c.g.style.opacity = on ? 1 : 0;
+ if (!on && !c.el.classList.contains('on')) continue;
+ project(data.anchors[c.a], pA);
+ const w = c.el.offsetWidth || 160, hgt = c.el.offsetHeight || 60;
+ const side = STATES[c.state].text;
+ let lx = pA.x + c.off[0] * (innerWidth / 1440), ly = pA.y + c.off[1] * (innerHeight / 900);
+ if (side === 'l') lx = Math.max(lx, innerWidth * 0.4); else if (side === 'r') lx = Math.min(lx, innerWidth * 0.6 - w);
+ // keep labels clear of the lens (and its bezel lettering)
+ const rr = R * 1.22 + 14;
+ for (let k = 0; k < 3; k++) {
+ const qx = clamp(lens.cx, lx, lx + w), qy = clamp(lens.cy, ly, ly + hgt);
+ const dx = qx - lens.cx, dy = qy - lens.cy, dd = Math.hypot(dx, dy);
+ if (dd >= rr) break;
+ let nx = lx + w / 2 - lens.cx, ny = ly + hgt / 2 - lens.cy; const nl = Math.hypot(nx, ny) || 1;
+ nx /= nl; ny /= nl;
+ lx += nx * (rr - dd + 2); ly += ny * (rr - dd + 2);
+ }
+ // back out of the text column; if that lands on the lens again, slide vertically instead
+ const lx0 = lx;
+ if (side === 'l') lx = Math.max(lx, innerWidth * 0.4); else if (side === 'r') lx = Math.min(lx, innerWidth * 0.6 - w);
+ if (lx !== lx0) {
+ const qx = clamp(lens.cx, lx, lx + w), qy = clamp(lens.cy, ly, ly + hgt);
+ const dy0 = qy - lens.cy, need = Math.sqrt(Math.max(0, rr * rr - (qx - lens.cx) ** 2));
+ if (Math.hypot(qx - lens.cx, dy0) < rr) ly = ly + hgt / 2 > lens.cy ? lens.cy + need + 4 : lens.cy - need - hgt - 4;
+ }
+ lx = clamp(lx, 24, innerWidth - w - 48); ly = clamp(ly, 96, innerHeight - hgt - 90);
+ for (let k = 0; k < 3; k++) for (const p of placed) {
+ if (lx < p.x + p.w + 10 && lx + w + 10 > p.x && ly < p.y + p.h + 10 && ly + hgt + 10 > p.y) ly = ly > p.y ? p.y + p.h + 12 : p.y - hgt - 12;
+ }
+ ly = clamp(ly, 96, innerHeight - hgt - 90);
+ placed.push({ x: lx, y: ly, w, h: hgt });
+ const right = lx + w / 2 > pA.x;
+ const ax = right ? lx - 2 : lx + w + 2, ay = ly + 14;
+ const ex = right ? ax - 26 : ax + 26;
+ c.path.setAttribute('d', `M${pA.x.toFixed(1)} ${pA.y.toFixed(1)} L${ex.toFixed(1)} ${ay.toFixed(1)} L${ax.toFixed(1)} ${ay.toFixed(1)}`);
+ c.pin.setAttribute('cx', pA.x.toFixed(1)); c.pin.setAttribute('cy', pA.y.toFixed(1));
+ c.ring.setAttribute('cx', pA.x.toFixed(1)); c.ring.setAttribute('cy', pA.y.toFixed(1));
+ c.el.style.transform = `translate3d(${lx.toFixed(1)}px, ${ly.toFixed(1)}px, 0)`;
+ }
+
+ // HUD
+ const max = document.documentElement.scrollHeight - innerHeight;
+ const prog = max > 0 ? scrollY / max : 0;
+ const rh = rulerEl.offsetHeight;
+ rulerMark.style.setProperty('--y', (prog * rh).toFixed(1) + 'px');
+ rulerVal.textContent = String(Math.round(prog * 1000)).padStart(3, '0');
+ document.body.classList.toggle('is-footer', footCover > 0.35);
+ document.body.classList.toggle('nav-dark', footEl.getBoundingClientRect().top < 64);
+
+ engine.paused = footCover >= 0.999;
+ if (engine.paused) return;
+ // world passes
+ embers.material.uniforms.uPx.value = innerHeight * Math.min(devicePixelRatio, 1.6) * camera.projectionMatrix.elements[5] / 2;
+ if ((engine._frames & 1) === 0) contact.update(scene);
+ reflection.update(scene, camera);
+});
+
+// ─── Boot ───────────────────────────────────────────────────────────────────
+worldNav('velocity', { theme: 'light', corner: 'bl' });
+cur = cursor({ color: '#111317', blend: 'normal', size: 30 });
+cur?.set('hidden');
+magnetic();
+const lenis = smoothScroll({ lerp: 0.085 });
+reveal('.s h2', { type: 'lines', stagger: 0.08 });
+reveal('.lede', { type: 'lines', stagger: 0.04, y: '100%' });
+measureSections();
+if (isTouch) document.querySelector('.console-hint')?.classList.add('touch');
+
+// Warm up every program (both colourways, every lens mode) before revealing.
+white.model.visible = black.model.visible = true; embers.visible = true;
+renderer.compile(scene, camera);
+for (const s of [...lens.scenes.filter(Boolean), lens.cadN, lens.cadQuadScene, lens.cadDims]) renderer.compile(s, camera);
+black.model.visible = false; embers.visible = false;
+lens.open = 0;
+engine.start();
+await loader.finish();
+setMode(0);
+gsap.to(state, { heroIn: 1, duration: 2.4, ease: 'expo.out' });
+gsap.to(state, { open: 1, duration: 1.5, ease: 'expo.out', delay: 0.55 });
+gsap.from('.title .t1', { yPercent: 60, opacity: 0, duration: 1.6, ease: 'expo.out', delay: 0.05 });
+gsap.from('.title .t2', { yPercent: 60, opacity: 0, duration: 1.6, ease: 'expo.out', delay: 0.14 });
+gsap.from('.hero .eyebrow, .hero .sub, .hero-note, .specs > div, .nav > *', { opacity: 0, y: 12, duration: 1.2, ease: 'power3.out', stagger: 0.05, delay: 0.4 });
+setTimeout(() => document.body.classList.add('ready'), 900);
+window.__vx = {
+ setMode, setWay, lens, state, U, get stage() { return stage; },
+ goto(k) { measureSections(); const i = typeof k === 'number' ? -1 : sections.findIndex(s => s.key === k); const y = i >= 0 ? anchorsY[i] : k * (document.documentElement.scrollHeight - innerHeight); lenis.scrollTo(y, { immediate: true, force: true }); },
+};
+setTimeout(() => { window.__vxReady = true; }, 2600);
diff --git a/examples/velocity/shaders.js b/examples/velocity/shaders.js
new file mode 100644
index 0000000..3651e03
--- /dev/null
+++ b/examples/velocity/shaders.js
@@ -0,0 +1,80 @@
+// GLSL chunks shared by the lens modes, the dissolve and the studio.
+
+export const NOISE = /* glsl */`
+ float hash13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+ float hash12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+ float vnoise(vec3 p){
+ vec3 i = floor(p), f = fract(p); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mix(hash13(i), hash13(i + vec3(1,0,0)), f.x), mix(hash13(i + vec3(0,1,0)), hash13(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(hash13(i + vec3(0,0,1)), hash13(i + vec3(1,0,1)), f.x), mix(hash13(i + vec3(0,1,1)), hash13(i + vec3(1,1,1)), f.x), f.y), f.z);
+ }
+ float fbm3(vec3 p){ float a = 0.5, s = 0.0; for (int i = 0; i < 4; i++){ s += a * vnoise(p); p = p * 2.03 + 11.7; a *= 0.5; } return s; }
+ // F1/F2 cellular distance for foam cells.
+ vec2 voro3(vec3 p){
+ vec3 i = floor(p), f = fract(p); float d1 = 8.0, d2 = 8.0;
+ for (int z = -1; z <= 1; z++) for (int y = -1; y <= 1; y++) for (int x = -1; x <= 1; x++){
+ vec3 g = vec3(float(x), float(y), float(z));
+ vec3 o = vec3(hash13(i + g), hash13(i + g + 17.1), hash13(i + g + 41.7));
+ vec3 r = g + o - f; float d = dot(r, r);
+ if (d < d1){ d2 = d1; d1 = d; } else if (d < d2) d2 = d;
+ }
+ return vec2(sqrt(d1), sqrt(d2));
+ }
+`;
+
+// Shoe profile lookup: a 64x1 texture of the measured sole (R bottom y, G centre z, B half width, A midsole top).
+export const PROFILE = /* glsl */`
+ uniform sampler2D uProfile; uniform vec2 uProfX; // x range (min, max) in shoe space
+ vec4 prof(float x){
+ float f = clamp((x - uProfX.x) / (uProfX.y - uProfX.x), 0.0, 1.0) * 64.0 - 0.5;
+ float i = floor(f), t = f - i;
+ vec4 a = texture2D(uProfile, vec2((clamp(i, 0.0, 63.0) + 0.5) / 64.0, 0.5));
+ vec4 b = texture2D(uProfile, vec2((clamp(i + 1.0, 0.0, 63.0) + 0.5) / 64.0, 0.5));
+ return mix(a, b, t * t * (3.0 - 2.0 * t));
+ }
+`;
+
+// Gait: a footstrike rolling heel -> toe. Phase 0..1 (stance 0..0.68, swing after).
+export const GAIT = /* glsl */`
+ uniform float uGait;
+ float gaitX(){ float s = clamp(uGait / 0.68, 0.0, 1.0); s = s * s * (3.0 - 2.0 * s); return mix(-0.86, 0.9, s); }
+ float gaitAmp(){ return smoothstep(0.0, 0.05, uGait) * (1.0 - smoothstep(0.62, 0.78, uGait)); }
+ // Pressure at shoe-space x (sole level). Heel strike is sharp, forefoot load is broad, toe-off is a narrow spike.
+ float pressure(float x){
+ float gx = gaitX(); float a = gaitAmp();
+ float heel = exp(-pow((x + 0.72) / 0.2, 2.0)) * (1.0 - smoothstep(0.1, 0.4, uGait / 0.68));
+ float roll = exp(-pow((x - gx) / 0.24, 2.0));
+ float trail = smoothstep(gx + 0.1, gx - 0.25, x) * exp(-max(gx - x, 0.0) * 1.6) * 0.45;
+ return a * clamp(heel * 1.1 + roll + trail, 0.0, 1.4);
+ }
+ // Heat left behind by recent strides (slow decay, always a bit warm under the heel and forefoot).
+ float residual(float x){ return 0.32 * exp(-pow((x + 0.68) / 0.26, 2.0)) + 0.36 * exp(-pow((x - 0.5) / 0.3, 2.0)); }
+`;
+
+// FLIR-style ironbow palette, returned in linear space.
+export const PALETTE = /* glsl */`
+ vec3 ironbow(float t){
+ t = clamp(t, 0.0, 1.0);
+ vec3 c0 = vec3(0.02, 0.01, 0.06), c1 = vec3(0.16, 0.03, 0.42), c2 = vec3(0.58, 0.05, 0.52),
+ c3 = vec3(0.93, 0.25, 0.14), c4 = vec3(1.0, 0.64, 0.06), c5 = vec3(1.0, 0.97, 0.78);
+ vec3 c = t < 0.2 ? mix(c0, c1, t / 0.2) : t < 0.4 ? mix(c1, c2, (t - 0.2) / 0.2) : t < 0.6 ? mix(c2, c3, (t - 0.4) / 0.2)
+ : t < 0.8 ? mix(c3, c4, (t - 0.6) / 0.2) : mix(c4, c5, (t - 0.8) / 0.2);
+ return pow(c, vec3(2.2));
+ }
+`;
+
+// Normal-map perturbation without tangents (cotangent frame).
+export const PERTURB = /* glsl */`
+ vec3 perturbN(vec3 n, vec3 pos, vec2 uv, vec3 mapN){
+ vec3 dp1 = dFdx(pos), dp2 = dFdy(pos); vec2 duv1 = dFdx(uv), duv2 = dFdy(uv);
+ vec3 dp2perp = cross(dp2, n), dp1perp = cross(n, dp1);
+ vec3 T = dp2perp * duv1.x + dp1perp * duv2.x; vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;
+ float im = inversesqrt(max(max(dot(T, T), dot(B, B)), 1e-12));
+ return normalize(mat3(T * im, B * im, n) * mapN);
+ }
+`;
+
+// Colourway dissolve field in shoe space: sweeps heel -> toe with a noisy front.
+export const DISSOLVE = /* glsl */`
+ float disField(vec3 sp){ return (sp.x + 1.0) * 0.36 + fbm3(sp * 5.5) * 0.36 + vnoise(sp * 23.0) * 0.07; }
+`;
diff --git a/examples/velocity/studio.js b/examples/velocity/studio.js
new file mode 100644
index 0000000..6d99684
--- /dev/null
+++ b/examples/velocity/studio.js
@@ -0,0 +1,158 @@
+// The lab: a white cyclorama, a measured floor mat with soft planar reflection, and drei-style contact shadows.
+import { THREE } from '../../src/core/engine.js';
+import { HorizontalBlurShader } from 'three/examples/jsm/shaders/HorizontalBlurShader.js';
+import { VerticalBlurShader } from 'three/examples/jsm/shaders/VerticalBlurShader.js';
+import { FullScreenQuad } from 'three/examples/jsm/postprocessing/Pass.js';
+
+export const MM = 142.5; // millimetres per scene unit (the shoe is 2 units = 285 mm long)
+
+/** Floor mat texture: 1 cm minor grid, 5 cm major, millimetre ruler along the front edge, fading out radially. */
+export function matTexture(size = 2048, span = 7) {
+ const c = document.createElement('canvas'); c.width = c.height = size;
+ const g = c.getContext('2d');
+ g.fillStyle = '#f3f4f6'; g.fillRect(0, 0, size, size);
+ const ppu = size / span, cm = ppu * 10 / MM;
+ const cx = size / 2, cy = size / 2;
+ const fade = (x, y) => { const d = Math.hypot(x - cx, y - cy) / (size / 2); return Math.max(0, 1 - Math.pow(d / 0.92, 2.2)); };
+ // grid lines drawn as short segments so each can fade with radius
+ const seg = 16;
+ for (let i = -60; i <= 60; i++) {
+ const p = cx + i * cm; if (p < 0 || p > size) continue;
+ const major = i % 5 === 0;
+ for (let s = 0; s < size; s += seg) {
+ for (const vertical of [true, false]) {
+ const x = vertical ? p : s + seg / 2, y = vertical ? s + seg / 2 : p;
+ const a = fade(x, y) * (major ? 0.16 : 0.075);
+ if (a < 0.004) continue;
+ g.fillStyle = `rgba(28,32,40,${a})`;
+ if (vertical) g.fillRect(p - (major ? 1 : 0.6), s, major ? 2 : 1.2, seg); else g.fillRect(s, p - (major ? 1 : 0.6), seg, major ? 2 : 1.2);
+ }
+ }
+ }
+ // millimetre ruler along the front (towards +z = bottom of the texture)
+ const ry = cy + 4.2 * cm * 2.2;
+ g.fillStyle = 'rgba(20,22,28,.5)';
+ for (let mm = -150; mm <= 150; mm++) {
+ const x = cx + mm * cm / 10; const len = mm % 10 === 0 ? 26 : mm % 5 === 0 ? 16 : 8;
+ const a = fade(x, ry) * 0.9; if (a < 0.02) continue;
+ g.globalAlpha = a; g.fillRect(x - 0.6, ry, 1.2, len);
+ }
+ g.globalAlpha = 1;
+ g.font = '500 17px "JetBrains Mono", monospace'; g.textAlign = 'center';
+ for (let mm = -140; mm <= 140; mm += 20) {
+ const x = cx + mm * cm / 10; const a = fade(x, ry) * 0.6; if (a < 0.05) continue;
+ g.fillStyle = `rgba(20,22,28,${a})`; g.fillText(String(mm + 140).padStart(3, '0'), x, ry + 50);
+ }
+ // crosshair registration marks at the mat corners
+ g.strokeStyle = 'rgba(20,22,28,.28)'; g.lineWidth = 2;
+ for (const [sx, sy] of [[-1, -1], [1, -1], [-1, 1], [1, 1]]) {
+ const x = cx + sx * 12.5 * cm, y = cy + sy * 7.5 * cm;
+ g.beginPath(); g.moveTo(x - 22, y); g.lineTo(x + 22, y); g.moveTo(x, y - 22); g.lineTo(x, y + 22); g.stroke();
+ g.beginPath(); g.arc(x, y, 9, 0, Math.PI * 2); g.stroke();
+ }
+ const t = new THREE.CanvasTexture(c);
+ t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 16;
+ return t;
+}
+
+/** Cyclorama: floor sweep curving up into a back wall. Returns { floor, sweep }. */
+export function buildCyc({ z0 = -3.2, R = 4.2, width = 70, top = 26, floorColor = 0xf2f3f5, wallColor = 0xeceef1 }) {
+ const group = new THREE.Group();
+ // Floor (flat, reflective) — separate so the planar reflection stays exact.
+ const floorGeo = new THREE.PlaneGeometry(width, 40, 1, 1);
+ floorGeo.rotateX(-Math.PI / 2);
+ floorGeo.translate(0, 0, z0 + 20);
+ const floorMat = new THREE.MeshStandardMaterial({ color: floorColor, roughness: 0.42, metalness: 0, envMapIntensity: 0.5 });
+ const floor = new THREE.Mesh(floorGeo, floorMat);
+ floor.receiveShadow = true;
+ group.add(floor);
+ // Sweep + wall
+ const prof = [];
+ const N = 40;
+ for (let i = 0; i <= N; i++) { const a = (i / N) * Math.PI / 2; prof.push([z0 - Math.sin(a) * R, R - Math.cos(a) * R]); }
+ prof.push([z0 - R, top]);
+ const cols = 2, rows = prof.length;
+ const pos = [], idx = [];
+ for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) pos.push((c ? 1 : -1) * width / 2, prof[r][1], prof[r][0]);
+ for (let r = 0; r < rows - 1; r++) { const a = r * 2, b = a + 1, c = a + 2, d = a + 3; idx.push(a, b, c, b, d, c); }
+ const sg = new THREE.BufferGeometry();
+ sg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ sg.setIndex(idx); sg.computeVertexNormals();
+ const sweepMat = new THREE.MeshStandardMaterial({ color: wallColor, roughness: 1, metalness: 0, envMapIntensity: 0.45 });
+ // A soft light pool on the sweep behind the subject (a spotlight edge would show as a dome).
+ sweepMat.userData.halo = { uHalo: { value: new THREE.Vector3(0.5, 1.6, 0.34) }, uHaloI: { value: 0.3 } };
+ sweepMat.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, sweepMat.userData.halo);
+ sh.vertexShader = sh.vertexShader.replace('#include <common>', '#include <common>\nvarying vec3 vWp;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvWp = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader.replace('#include <common>', '#include <common>\nvarying vec3 vWp; uniform vec3 uHalo; uniform float uHaloI;')
+ .replace('#include <emissivemap_fragment>', `#include <emissivemap_fragment>
+ vec2 hd = (vWp.xy - uHalo.xy) * vec2(0.16, 0.24);
+ totalEmissiveRadiance += vec3(uHaloI) * exp(-dot(hd, hd) * 1.6) + vec3(uHaloI * 0.35) * smoothstep(8.0, 0.0, vWp.y);`);
+ };
+ const sweep = new THREE.Mesh(sg, sweepMat);
+ sweep.receiveShadow = true;
+ group.add(sweep);
+ return { group, floor, floorMat, sweep, sweepMat };
+}
+
+/** Soft contact shadow: depth from below, blurred, laid on the floor. */
+export class ContactShadow {
+ constructor(renderer, { size = 512, width = 4.2, height = 4.2, far = 1.0, blur = 2.6, opacity = 0.8, darkness = 1.4, layer = 3 } = {}) {
+ this.renderer = renderer; this.blur = blur; this.layer = layer;
+ const opts = { type: THREE.HalfFloatType };
+ this.rt = new THREE.WebGLRenderTarget(size, size, opts);
+ this.rtB = new THREE.WebGLRenderTarget(size, size, opts);
+ this.cam = new THREE.OrthographicCamera(-width / 2, width / 2, height / 2, -height / 2, 0, far);
+ this.cam.rotation.x = Math.PI / 2;
+ this.cam.layers.set(layer);
+ this.depthMat = new THREE.ShaderMaterial({
+ uniforms: { uDark: { value: darkness } },
+ vertexShader: 'varying float vZ; void main(){ vec4 p = projectionMatrix * modelViewMatrix * vec4(position, 1.0); vZ = p.z / p.w * 0.5 + 0.5; gl_Position = p; }',
+ fragmentShader: 'uniform float uDark; varying float vZ; void main(){ float a = pow(clamp(1.0 - vZ, 0.0, 1.0), 1.6) * uDark; gl_FragColor = vec4(0.0, 0.0, 0.0, clamp(a, 0.0, 1.0)); }',
+ side: THREE.DoubleSide,
+ });
+ this.hq = new FullScreenQuad(new THREE.ShaderMaterial(HorizontalBlurShader));
+ this.vq = new FullScreenQuad(new THREE.ShaderMaterial(VerticalBlurShader));
+ this.hq.material.depthTest = this.vq.material.depthTest = false;
+ const mat = new THREE.MeshBasicMaterial({ map: this.rt.texture, transparent: true, opacity, depthWrite: false, color: 0x0c0e12 });
+ mat.onBeforeCompile = sh => {
+ sh.fragmentShader = sh.fragmentShader.replace('#include <map_fragment>', 'vec4 sampledDiffuseColor = texture2D(map, vMapUv); diffuseColor.a *= sampledDiffuseColor.a;');
+ };
+ this.plane = new THREE.Mesh(new THREE.PlaneGeometry(width, height).rotateX(-Math.PI / 2), mat);
+ this.plane.scale.z = -1; // the camera looks up, so flip to match
+ this.plane.position.y = 0.0015;
+ this.plane.renderOrder = 1;
+ this.group = new THREE.Group();
+ this.group.add(this.plane, this.cam);
+ this._c = new THREE.Color();
+ }
+
+ update(scene) {
+ const r = this.renderer;
+ const prevBg = scene.background, prevOv = scene.overrideMaterial, prevRT = r.getRenderTarget();
+ r.getClearColor(this._c); const prevA = r.getClearAlpha();
+ const prevAuto = r.shadowMap.autoUpdate;
+ r.shadowMap.autoUpdate = false;
+ scene.background = null; scene.overrideMaterial = this.depthMat;
+ this.plane.visible = false;
+ r.setClearColor(0x000000, 0);
+ r.setRenderTarget(this.rt); r.clear(); r.render(scene, this.cam);
+ scene.overrideMaterial = prevOv;
+ this._blurPass(this.blur / 256);
+ this._blurPass(this.blur * 0.45 / 256);
+ this.plane.visible = true;
+ r.setRenderTarget(prevRT);
+ r.setClearColor(this._c, prevA);
+ scene.background = prevBg;
+ r.shadowMap.autoUpdate = prevAuto;
+ }
+
+ _blurPass(amount) {
+ const r = this.renderer;
+ this.hq.material.uniforms.tDiffuse.value = this.rt.texture; this.hq.material.uniforms.h.value = amount;
+ r.setRenderTarget(this.rtB); this.hq.render(r);
+ this.vq.material.uniforms.tDiffuse.value = this.rtB.texture; this.vq.material.uniforms.v.value = amount;
+ r.setRenderTarget(this.rt); this.vq.render(r);
+ }
+}
diff --git a/examples/velocity/style.css b/examples/velocity/style.css
new file mode 100644
index 0000000..39ad5ee
--- /dev/null
+++ b/examples/velocity/style.css
@@ -0,0 +1,276 @@
+:root {
+ --bg: #f2f3f5;
+ --ink: #111317;
+ --ink2: #3b3f47;
+ --muted: #7a7f89;
+ --line: rgba(17, 19, 23, .14);
+ --line2: rgba(17, 19, 23, .07);
+ --orange: #ff5b1a;
+ --volt: #d2ff1e;
+ --gut: clamp(16px, 4.2vw, 64px);
+ --disp: 'Archivo', 'Helvetica Neue', Arial, sans-serif;
+ --mono: 'JetBrains Mono', ui-monospace, Menlo, monospace;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; text-rendering: optimizeLegibility; }
+body { font: 400 16px/1.55 var(--disp); background: var(--bg); overflow-x: hidden; }
+a { color: inherit; }
+button { font: inherit; color: inherit; background: none; border: 0; cursor: pointer; }
+.mono { font-family: var(--mono); font-size: 11px; letter-spacing: .09em; text-transform: uppercase; font-weight: 500; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; z-index: 0; }
+
+/* ── loader ─────────────────────────────────────────── */
+.loader { position: fixed; inset: 0; z-index: 200; background: var(--bg); display: grid; place-content: center; justify-items: center; gap: 26px;
+ -webkit-mask-image: radial-gradient(circle at 50% 50%, transparent var(--hole, 0px), #000 calc(var(--hole, 0px) + 1px));
+ mask-image: radial-gradient(circle at 50% 50%, transparent var(--hole, 0px), #000 calc(var(--hole, 0px) + 1px)); }
+.loader-dial { position: relative; width: 168px; height: 168px; display: grid; place-items: center; }
+.loader-dial svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
+.loader-ticks line { stroke: var(--ink); stroke-width: .7; opacity: .16; transition: opacity .25s, stroke .25s; }
+.loader-ticks line.on { opacity: 1; }
+.loader-ticks line.major { stroke-width: 1; }
+.loader-ring { fill: none; stroke: var(--ink); stroke-width: .6; opacity: .3; }
+.loader-pct { font: 700 30px/1 var(--mono); letter-spacing: .02em; font-variant-numeric: tabular-nums; }
+.loader-line { color: var(--muted); }
+.loader-top, .loader-bot { position: absolute; left: var(--gut); right: var(--gut); display: flex; justify-content: space-between; color: var(--muted); font-size: 10px; }
+.loader-top { top: 28px; } .loader-bot { bottom: 30px; justify-content: center; gap: 48px; color: var(--ink2); }
+.loader-top span:first-child { color: var(--ink); font-weight: 700; }
+.loader-h, .loader-v { position: absolute; left: 50%; top: calc(50% - 30px); background: rgba(17,19,23,.14); }
+.loader-h { width: min(560px, 80vw); height: 1px; transform: translateX(-50%); }
+.loader-v { width: 1px; height: 360px; transform: translate(-50%, -50%); }
+.loader-h::before, .loader-h::after { content: ''; position: absolute; top: -4px; width: 1px; height: 9px; background: var(--ink); }
+.loader-h::before { left: 0; } .loader-h::after { right: 0; }
+.loader-step { color: var(--ink); }
+
+/* ── nav ────────────────────────────────────────────── */
+.nav { position: fixed; top: 0; left: 0; right: 0; z-index: 40; display: flex; align-items: center; justify-content: space-between;
+ padding: 20px var(--gut); pointer-events: none; }
+.nav > * { pointer-events: auto; }
+.nav::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 130px; z-index: -1; pointer-events: none;
+ background: linear-gradient(rgba(242,243,245,.96) 0%, rgba(242,243,245,.82) 45%, rgba(242,243,245,0) 100%); transition: opacity .4s; }
+.nav-dark .nav::before { opacity: 0; }
+.brand { display: flex; align-items: center; gap: 10px; text-decoration: none; font: 800 15px/1 var(--disp); font-stretch: 125%; letter-spacing: -.01em; text-transform: uppercase; }
+.brand em { font-style: normal; font-weight: 400; font-stretch: 100%; margin-left: 5px; color: var(--muted); }
+.brand svg { width: 22px; height: 22px; }
+.links { display: flex; gap: 30px; padding: 11px 22px; border-radius: 999px; background: rgba(242,243,245,.6); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--line2); }
+.links a { text-decoration: none; font: 500 13px/1 var(--disp); color: var(--ink2); transition: color .25s; }
+.links a:hover { color: var(--orange); }
+.links a { position: relative; }
+.links a.is-on { color: var(--ink); }
+.links a::after { content: ''; position: absolute; left: 50%; bottom: -7px; width: 4px; height: 4px; margin-left: -2px; border-radius: 50%; background: var(--orange); transform: scale(0); transition: transform .3s; }
+.links a.is-on::after { transform: scale(1); }
+.btn { display: inline-flex; align-items: center; justify-content: center; gap: 12px; height: 44px; padding: 0 22px; border-radius: 999px;
+ text-decoration: none; font: 600 13px/1 var(--disp); letter-spacing: .01em; transition: background .3s, color .3s, box-shadow .3s; white-space: nowrap; }
+.btn-ink { background: var(--ink); color: #fff; }
+.btn-ink:hover { background: #000; box-shadow: 0 10px 30px -10px rgba(0,0,0,.5); }
+.btn-ink .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--volt); box-shadow: 0 0 12px var(--volt); animation: blink 1.6s steps(2) infinite; }
+@keyframes blink { 50% { opacity: .25; } }
+.btn-volt { background: var(--volt); color: var(--ink); }
+.btn-volt:hover { background: #e4ff6b; box-shadow: 0 10px 40px -8px rgba(160,210,0,.7); }
+
+/* ── HUD ────────────────────────────────────────────── */
+.hud { position: fixed; inset: 0; z-index: 3; pointer-events: none; }
+.corner { position: absolute; width: 16px; height: 16px; border: 0 solid rgba(17,19,23,.35); }
+.corner.tl { left: 12px; top: 12px; border-width: 1px 0 0 1px; } .corner.tr { right: 12px; top: 12px; border-width: 1px 1px 0 0; }
+.corner.bl { left: 12px; bottom: 12px; border-width: 0 0 1px 1px; } .corner.br { right: 12px; bottom: 12px; border-width: 0 1px 1px 0; }
+.ruler { position: absolute; right: 20px; top: 22vh; bottom: 22vh; width: 12px;
+ background: repeating-linear-gradient(to bottom, rgba(17,19,23,.32) 0 1px, transparent 1px 8px) right / 5px 100% no-repeat,
+ repeating-linear-gradient(to bottom, rgba(17,19,23,.5) 0 1px, transparent 1px 40px) right / 12px 100% no-repeat; }
+.ruler-mark { position: absolute; right: 0; top: 0; width: 22px; height: 1px; background: var(--orange); transform: translateY(var(--y, 0px)); }
+.ruler-val { position: absolute; right: 28px; top: -7px; font-size: 10px; color: var(--ink); font-variant-numeric: tabular-nums; }
+.chapter { position: absolute; left: 20px; top: 50%; display: flex; gap: 12px; color: var(--ink2); writing-mode: vertical-rl; transform: translateY(-50%) rotate(180deg); font-size: 10px; }
+.chapter-n { color: var(--orange); font-variant-numeric: tabular-nums; }
+
+/* ── lens chrome ────────────────────────────────────── */
+.lens-ui { position: fixed; left: 0; top: 0; z-index: 30; pointer-events: none; opacity: 0; transition: opacity .5s; }
+.lens-ui.on { opacity: var(--mix, 1); }
+.lens-ui svg { position: absolute; left: -120px; top: -120px; width: 240px; height: 240px; overflow: visible; will-change: transform; }
+.lens-ticks line { stroke: var(--ink); stroke-width: .55; vector-effect: non-scaling-stroke; }
+.lens-ticks line.major { stroke-width: 1.1; }
+.lens-ticks line.hot { stroke: var(--orange); stroke-width: 2.2; }
+.lens-arc { font: 600 6.4px var(--mono); letter-spacing: .24em; fill: var(--ink); text-transform: uppercase; }
+.lens-cross path { stroke: #fff; stroke-width: 1; vector-effect: non-scaling-stroke; opacity: .85; }
+.lens-cross circle { fill: var(--volt); }
+.lens-tag { position: absolute; left: 0; top: 0; display: flex; align-items: center; gap: 8px; padding: 7px 12px 7px 8px; border-radius: 999px;
+ background: var(--ink); color: #fff; white-space: nowrap; will-change: transform; font: 600 11px/1 var(--mono); letter-spacing: .1em; }
+.lens-tag-n { display: grid; place-items: center; min-width: 22px; height: 18px; border-radius: 999px; background: var(--volt); color: var(--ink); font-size: 10px; }
+.lens-coord b { color: var(--orange); font-weight: 700; }
+.lens-coord { position: absolute; left: 0; top: 0; transition: opacity .4s; font: 500 10px/1 var(--mono); letter-spacing: .1em; color: var(--ink2); white-space: nowrap; will-change: transform; font-variant-numeric: tabular-nums; }
+
+/* ── console (mode switcher / hint) ─────────────────── */
+.console { position: fixed; left: 50%; bottom: 22px; transform: translateX(-50%); z-index: 35; display: flex; align-items: center; gap: 4px; padding: 5px;
+ border-radius: 999px; background: rgba(250,250,251,.72); backdrop-filter: blur(14px) saturate(1.3); box-shadow: inset 0 0 0 1px var(--line), 0 20px 40px -24px rgba(17,19,23,.35);
+ transition: opacity .6s, transform .6s; opacity: 0; }
+.ready .console { opacity: 1; }
+.console .mode { white-space: nowrap; display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 16px 0 10px; border-radius: 999px; font: 600 13px/1 var(--disp); color: var(--ink2); transition: background .3s, color .3s; }
+.console .mode .mono { font-size: 10px; opacity: .55; }
+.console .mode:hover { color: var(--ink); background: rgba(17,19,23,.06); }
+.console .mode.is-on { background: var(--ink); color: #fff; }
+.console .mode.is-on .mono { color: var(--volt); opacity: 1; }
+.console-hint { padding: 0 14px 0 10px; color: var(--muted); font-size: 10px; white-space: nowrap; }
+.console-hint .k-touch { display: none; }
+.ready.is-footer .console { opacity: 0; transform: translate(-50%, 20px); pointer-events: none; }
+
+/* ── callouts from 3D anchors ───────────────────────── */
+.leaders { position: fixed; inset: 0; width: 100vw; height: 100vh; z-index: 4; pointer-events: none; overflow: visible; }
+.leaders path { fill: none; stroke: var(--ink); stroke-width: 1; }
+.leaders .ring { fill: none; stroke: var(--ink); stroke-width: 1; }
+.leaders .pin { fill: var(--orange); }
+.callouts { position: fixed; inset: 0; z-index: 5; pointer-events: none; }
+.callout { position: absolute; left: 0; top: 0; display: grid; gap: 3px; padding: 9px 12px 10px; min-width: 150px; background: rgba(250,250,251,.82); backdrop-filter: blur(8px);
+ box-shadow: inset 0 0 0 1px var(--line); opacity: 0; transition: opacity .45s; will-change: transform; }
+.callout.on { opacity: 1; }
+.callout .c-k { font: 600 9.5px/1 var(--mono); letter-spacing: .12em; color: var(--orange); text-transform: uppercase; }
+.callout b { font: 700 14px/1.15 var(--disp); font-stretch: 110%; letter-spacing: -.01em; }
+.callout .c-v { font: 500 10px/1.3 var(--mono); letter-spacing: .06em; color: var(--ink2); text-transform: uppercase; }
+
+/* ── sections ───────────────────────────────────────── */
+main { position: relative; z-index: 2; pointer-events: none; }
+main a, main button, main input, main form, main [data-nolens] { pointer-events: auto; }
+.s { position: relative; min-height: 100vh; padding: 0 var(--gut); display: grid; align-items: center; }
+.eyebrow { display: flex; align-items: center; gap: 12px; color: var(--ink2); margin-bottom: 22px; }
+.tag { white-space: nowrap; display: inline-grid; place-items: center; height: 20px; padding: 0 7px; background: var(--ink); color: #fff; font-size: 10px; letter-spacing: .08em; }
+
+.hero { height: 100vh; align-items: start; padding-top: 118px; grid-template-rows: auto 1fr auto; }
+.hero-copy { max-width: 52vw; }
+.title { display: grid; justify-items: start; line-height: .8; letter-spacing: -.045em; margin-left: -.04em; }
+.title .t1 { font: 900 clamp(80px, 11.4vw, 200px)/.8 var(--disp); font-stretch: 125%; }
+.title .t2 { font: 300 clamp(58px, 7.6vw, 132px)/.9 var(--disp); font-stretch: 62%; font-style: italic; letter-spacing: -.03em; margin-top: .06em; color: var(--ink2); }
+.sub { margin-top: 26px; font: 600 clamp(19px, 1.7vw, 26px)/1.2 var(--disp); font-stretch: 112%; letter-spacing: -.015em; }
+.hero-note { grid-row: 3; max-width: 34ch; font-size: 14.5px; line-height: 1.55; color: var(--ink2); margin-bottom: 168px; }
+.specs { grid-row: 3; position: absolute; left: var(--gut); bottom: 86px; display: flex; gap: 0; }
+.specs div { padding: 0 26px 0 14px; border-left: 1px solid var(--line); }
+.specs div:first-child { padding-left: 0; border-left: 0; }
+.specs dt { color: var(--muted); font-size: 9.5px; margin-bottom: 6px; }
+.specs dd { font: 800 26px/1 var(--disp); font-stretch: 118%; letter-spacing: -.02em; text-transform: none; color: var(--ink); }
+.specs small { font: 500 11px var(--mono); margin-left: 3px; color: var(--muted); letter-spacing: .04em; }
+
+.col { width: min(440px, 34vw); padding: 40px 0; }
+.col-r { justify-self: end; margin-right: 3vw; }
+.col-l { justify-self: start; }
+h2 { font: 800 clamp(34px, 3.9vw, 62px)/.98 var(--disp); font-stretch: 110%; letter-spacing: -.035em; }
+h2 em { display: block; font-style: italic; font-weight: 300; font-stretch: 70%; color: var(--ink2); letter-spacing: -.02em; }
+.lede { margin-top: 24px; font-size: 16px; line-height: 1.6; color: var(--ink2); max-width: 40ch; }
+.stat { margin-top: 38px; padding-top: 22px; border-top: 1px solid var(--ink); display: flex; align-items: baseline; justify-content: space-between; gap: 20px; }
+.stat b { font: 900 clamp(64px, 7vw, 116px)/.8 var(--disp); font-stretch: 125%; letter-spacing: -.05em; }
+.stat b small { font: 500 .22em var(--mono); letter-spacing: .04em; margin-left: .3em; color: var(--muted); }
+.stat span { color: var(--ink2); text-align: right; }
+.minor { list-style: none; margin-top: 20px; display: grid; grid-template-columns: repeat(3, 1fr); border-top: 1px solid var(--line); }
+.minor li { padding: 12px 10px 0 0; color: var(--muted); font-size: 9.5px; line-height: 1.5; }
+.minor li b { display: block; color: var(--ink); font-size: 13px; letter-spacing: .02em; }
+
+.lens-s .col { width: min(470px, 36vw); }
+.modes { list-style: none; margin-top: 36px; border-top: 1px solid var(--line); }
+.modes li { border-bottom: 1px solid var(--line); }
+.modes button { display: grid; grid-template-columns: 110px 1fr; column-gap: 16px; row-gap: 4px; text-align: left; width: 100%; padding: 16px 0; transition: padding .35s; position: relative; }
+.modes button::before { content: ''; position: absolute; left: -18px; top: 50%; width: 7px; height: 7px; margin-top: -3px; border-radius: 50%; background: var(--orange); transform: scale(0); transition: transform .35s; }
+.modes button.is-on::before { transform: scale(1); }
+.modes button .mono { grid-row: span 2; color: var(--muted); font-size: 10px; padding-top: 3px; }
+.modes button.is-on .mono { color: var(--orange); }
+.modes button b { font: 700 16px/1.2 var(--disp); font-stretch: 108%; }
+.modes button em { font-style: normal; font-size: 13.5px; line-height: 1.45; color: var(--ink2); }
+.modes button:hover b { color: var(--orange); }
+
+.colour { align-items: center; }
+.colour .col { padding-bottom: 0; }
+.swatches { display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-top: 30px; width: min(440px, 34vw); }
+.swatch { display: grid; gap: 6px; text-align: left; padding: 16px 18px 18px; background: rgba(250,250,251,.7); backdrop-filter: blur(10px); box-shadow: inset 0 0 0 1px var(--line); transition: box-shadow .35s, background .35s; }
+.swatch.is-on { box-shadow: inset 0 0 0 1.5px var(--ink); background: rgba(255,255,255,.9); }
+.swatch .chip { width: 38px; height: 38px; border-radius: 50%; margin-bottom: 10px; box-shadow: 0 0 0 1px var(--line), 0 8px 16px -8px rgba(0,0,0,.4); }
+.chip-w { background: conic-gradient(from 210deg, #fbfbfb 0 70%, #ff8a1f 70% 86%, #c9ccd2 86%); }
+.chip-b { background: conic-gradient(from 210deg, #1a1b1e 0 70%, #d9ff2a 70% 86%, #62656b 86%); }
+.swatch .mono { color: var(--muted); font-size: 9.5px; }
+.swatch b { font: 800 17px/1.1 var(--disp); font-stretch: 112%; letter-spacing: -.015em; }
+.swatch em { font-style: normal; font-size: 12.5px; line-height: 1.45; color: var(--ink2); }
+.swatch-hint { grid-column: span 2; color: var(--muted); font-size: 10px; margin-top: 6px; }
+
+.drop { align-items: end; padding-bottom: 116px; min-height: 100vh; }
+.drop-inner { width: 100%; display: grid; justify-items: center; text-align: center; }
+.drop .eyebrow { justify-content: center; }
+.drop-title { font-size: clamp(34px, 3.4vw, 54px); }
+.drop-title em { display: inline; }
+.count { display: flex; margin-top: 32px; }
+.count div { padding: 0 clamp(14px, 2.4vw, 38px); border-left: 1px solid var(--line); display: grid; justify-items: center; gap: 8px; }
+.count div:first-child { border-left: 0; }
+.count b { font: 900 clamp(54px, 7.4vw, 128px)/.82 var(--disp); font-stretch: 125%; letter-spacing: -.04em; font-variant-numeric: tabular-nums; min-width: 1.25em; }
+.count span { color: var(--muted); }
+.join { margin-top: 42px; display: flex; align-items: center; gap: 10px; padding: 6px 6px 6px 22px; border-radius: 999px; background: #fff; box-shadow: inset 0 0 0 1px var(--line), 0 24px 50px -30px rgba(17,19,23,.5); position: relative; }
+.join label { color: var(--muted); font-size: 10px; }
+.join input { width: 240px; height: 40px; border: 0; outline: 0; background: none; font: 500 15px var(--disp); color: var(--ink); }
+.join input::placeholder { color: #a5a9b1; }
+.join-ok { position: absolute; left: 0; right: 0; top: calc(100% + 14px); color: var(--ink); opacity: 0; transition: opacity .4s; }
+.join.done .join-ok { opacity: 1; }
+.drop-note { margin-top: 44px; color: var(--muted); font-size: 10px; }
+
+.foot { position: relative; z-index: 6; background: var(--ink); color: #eceef1; padding: 16vh var(--gut) 84px; overflow: hidden; }
+.foot::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 18px;
+ background: repeating-linear-gradient(90deg, rgba(255,255,255,.28) 0 1px, transparent 1px 10px) top / 100% 7px no-repeat,
+ repeating-linear-gradient(90deg, var(--volt) 0 1px, transparent 1px 100px) top / 100% 18px no-repeat; opacity: .8; }
+.foot::after { content: 'VX-1'; position: absolute; right: -2vw; top: 6vh; font: 900 clamp(160px, 26vw, 420px)/.8 var(--disp); font-stretch: 125%; letter-spacing: -.05em;
+ color: transparent; -webkit-text-stroke: 1px rgba(255,255,255,.1); pointer-events: none; }
+.foot-inner { position: relative; z-index: 1; }
+.foot-inner { max-width: 1320px; margin: 0 auto; }
+.foot-title { font-size: clamp(48px, 7.6vw, 132px); color: #fff; }
+.foot-title em { color: #8d929c; }
+.foot-cols { display: grid; grid-template-columns: repeat(3, 1fr) auto; gap: 40px; align-items: end; margin-top: 12vh; padding-top: 28px; border-top: 1px solid rgba(255,255,255,.14); }
+.foot-cols p { font-size: 14px; line-height: 1.7; color: #b9bdc5; }
+.foot-cols .k { color: var(--volt); font-size: 10px; margin-bottom: 8px; }
+.foot .btn-ink { background: var(--volt); color: var(--ink); }
+.legal { display: flex; justify-content: space-between; gap: 20px; margin-top: 10vh; color: #6f747e; font-size: 10px; }
+
+.nav .brand, .nav .btn { transition: color .4s, background .4s; }
+.nav-dark .nav .brand { color: #fff; }
+.nav-dark .nav .brand em { color: #8d929c; }
+.nav-dark .nav .btn-ink { background: var(--volt); color: var(--ink); }
+.hud { transition: opacity .6s; opacity: 0; }
+.ready .hud { opacity: 1; }
+.ready.is-footer .hud { opacity: 0; }
+@media (max-width: 900px) {
+ .loader-top span:last-child, .loader-bot span:nth-child(n+3) { display: none; }
+ .loader-bot { gap: 24px; }
+ .links, .ruler, .corner, .console-hint .k-desk { display: none; }
+ .console-hint .k-touch { display: inline; }
+ .console { bottom: 64px; }
+ .console .mode { padding: 0 12px 0 9px; font-size: 12px; height: 34px; }
+ .console-hint { display: none; }
+ .nav { padding: 14px 16px; }
+ .nav .btn { height: 38px; padding: 0 16px; font-size: 12px; }
+ .hero { padding-top: 88px; }
+ .hero-copy { max-width: none; }
+ .hero-note { display: none; }
+ .specs { bottom: 118px; left: 16px; right: 16px; }
+ .specs div { padding: 0 12px 0 10px; }
+ .specs dd { font-size: 20px; }
+ .s { align-items: end; padding-bottom: 14vh; }
+ .col, .lens-s .col { width: 100%; margin: 0; padding: 22px 18px 24px; background: rgba(242,243,245,.9); backdrop-filter: blur(12px); box-shadow: inset 0 0 0 1px var(--line2); }
+ .col-r { justify-self: stretch; }
+ .lede { font-size: 14.5px; }
+ .stat b { font-size: 58px; }
+ .modes button { grid-template-columns: 1fr; padding: 12px 0; }
+ .modes button .mono { grid-row: auto; }
+ .modes button em { display: none; }
+ .colour { align-items: start; padding-top: 90px; }
+ .swatches { left: 16px; right: 16px; bottom: 14vh; grid-template-columns: 1fr 1fr; }
+ .swatch em { display: none; }
+ .swatches { width: 100%; }
+ .swatch b { font-size: 15px; }
+ .drop { padding-bottom: 200px; }
+ .lens-ui { z-index: 1; }
+ .minor { display: none; }
+ h2 { font-size: 30px; }
+ .stat { margin-top: 18px; padding-top: 14px; }
+ .stat b { font-size: 48px; }
+ .lede { margin-top: 14px; }
+ .lens-s .modes { display: none; }
+ .drop-note { display: none; }
+ .swatch-hint { display: none; }
+ .count b { font-size: 46px; }
+ .count div { padding: 0 10px; }
+ .join { flex-wrap: wrap; border-radius: 18px; padding: 12px; justify-content: center; }
+ .join input { width: 100%; text-align: center; }
+ .foot-cols { grid-template-columns: 1fr; }
+ .legal { flex-direction: column; }
+ .chapter { bottom: 118px; display: none; }
+ .callout { min-width: 0; padding: 6px 8px; }
+ .callout b { font-size: 12px; }
+ .callout .c-v { display: none; }
+}
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..f5a788e
--- /dev/null
+++ b/index.html
@@ -0,0 +1,70 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+ <title>Dioramas</title>
+ <meta name="description" content="Twenty interactive 3D landing pages. Every one built around a single idea you can touch.">
+ <meta name="theme-color" content="#060607">
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Inter+Tight:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
+ <link rel="stylesheet" href="./src/index/style.css">
+</head>
+<body>
+ <canvas id="gl" aria-hidden="true"></canvas>
+ <header class="top">
+ <a class="mark" href="./" aria-label="Dioramas">
+ <svg viewBox="0 0 20 20" aria-hidden="true"><g fill="currentColor"><rect x="1" y="2" width="2.2" height="2.2" rx=".6"/><rect x="4.8" y="2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="8.6" y="2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="12.4" y="2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="16.2" y="2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="1" y="6.4" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="4.8" y="6.4" width="2.2" height="2.2" rx=".6"/><rect x="8.6" y="6.4" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="12.4" y="6.4" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="16.2" y="6.4" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="1" y="10.8" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="4.8" y="10.8" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="8.6" y="10.8" width="2.2" height="2.2" rx=".6"/><rect x="12.4" y="10.8" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="16.2" y="10.8" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="1" y="15.2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="4.8" y="15.2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="8.6" y="15.2" width="2.2" height="2.2" rx=".6" opacity=".4"/><rect x="12.4" y="15.2" width="2.2" height="2.2" rx=".6"/><rect x="16.2" y="15.2" width="2.2" height="2.2" rx=".6" opacity=".4"/></g></svg>
+ <span>Dioramas</span>
+ </a>
+ <nav><a href="#list">Index</a><a href="#about">About</a></nav>
+ </header>
+
+ <main>
+ <section class="ring-section" aria-label="Browse the worlds">
+ <div class="ring-sticky">
+ <div class="intro">
+ <p class="kicker mono">Twenty interactive 3D landing pages</p>
+ <h1>Twenty <em>Worlds</em></h1>
+ </div>
+ <div class="active" aria-live="polite">
+ <p class="active-num mono"><span class="n">01</span> / 20</p>
+ <h2 class="active-name">Reliquary</h2>
+ <p class="active-line">A museum you can only see by lantern light</p>
+ <a class="enter" href="./examples/reliquary/" data-cursor="link">Enter world <span aria-hidden="true">→</span></a>
+ </div>
+ <div class="ring-hint mono" aria-hidden="true">Scroll or drag to turn · Click a window to enter</div>
+ <div class="progress" aria-hidden="true"><i></i></div>
+ </div>
+ </section>
+
+ <section class="list" id="list">
+ <div class="list-head">
+ <h2>The index</h2>
+ <p>Each world is a complete landing page for a fictional brand, built around one interaction you can touch. Hero objects are Meshy&nbsp;7.1 image-to-3D models generated from Nano&nbsp;Banana&nbsp;2 reference images, lit and choreographed in three.js.</p>
+ </div>
+ <ol class="rows"></ol>
+ </section>
+
+ <section class="about" id="about">
+ <div class="about-grid">
+ <div>
+ <p class="mono kicker">How they were made</p>
+ <h2>One idea per world. <em>No stock anything.</em></h2>
+ </div>
+ <div class="about-cols">
+ <p><b>Assets.</b> Clean product plates from Nano Banana 2, turned into 60k–250k-triangle PBR models by Meshy 7.1 at 4K geometry, then compressed with meshopt and WebP.</p>
+ <p><b>Rendering.</b> three.js with an HDR post stack: N8AO ambient occlusion, mip-chain bloom, AgX tone mapping, raymarched volumetric light, planar reflections and film grain.</p>
+ <p><b>Interaction.</b> Every page has a signature mechanic: a lantern, a forge, a pond, a lens, a tide, a turntable. The page is the scene; the scroll is the camera.</p>
+ </div>
+ </div>
+ <footer class="foot mono"><span>Dioramas · 2026</span><span>three.js · Meshy 7.1 · Nano Banana 2 · fal</span></footer>
+ </section>
+ </main>
+
+ <div class="preview" aria-hidden="true"><img alt=""></div>
+ <div class="wipe" aria-hidden="true"></div>
+ <script type="module" src="./src/index/main.js"></script>
+</body>
+</html>
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..e3e09e9
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,3676 @@
+{
+ "name": "dioramas",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "dioramas",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "^0.21.0",
+ "gsap": "^3.15.0",
+ "lenis": "^1.3.26",
+ "n8ao": "^2.0.1",
+ "postprocessing": "^6.39.5",
+ "three": "^0.186.1"
+ },
+ "devDependencies": {
+ "@fal-ai/client": "^1.10.1",
+ "@gltf-transform/cli": "^4.5.1",
+ "@gltf-transform/core": "^4.5.1",
+ "@gltf-transform/extensions": "^4.5.1",
+ "@gltf-transform/functions": "^4.5.1",
+ "dotenv": "^18.0.4",
+ "meshoptimizer": "^1.3.0",
+ "playwright": "^1.63.0",
+ "sharp": "^0.35.5",
+ "vite": "^8.3.1"
+ }
+ },
+ "node_modules/@colors/colors": {
+ "version": "1.5.0",
+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz",
+ "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.1.90"
+ }
+ },
+ "node_modules/@dabh/diagnostics": {
+ "version": "2.0.9",
+ "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.9.tgz",
+ "integrity": "sha512-R6siwR65Hm+3yfgP7o8DKhNvputQAwfoz9zTc3kyDudnomj2/BcLmD+uGQQPICjuFUp8ounPBU+jmKsocwVVAg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@so-ric/colorspace": "^1.1.6",
+ "enabled": "2.0.x",
+ "kuler": "^2.0.0"
+ }
+ },
+ "node_modules/@dimforge/rapier3d-compat": {
+ "version": "0.21.0",
+ "resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.21.0.tgz",
+ "integrity": "sha512-tCl1HPGwOhn5aCQbgqWbOH+Nx/5fnr3IPAnzQuR7zIhC/raqi2yxC6LhvZqjdI2El5hQgY5RDAwDrAjAi2FdPA==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/@donmccurdy/caporal": {
+ "version": "0.0.10",
+ "resolved": "https://registry.npmjs.org/@donmccurdy/caporal/-/caporal-0.0.10.tgz",
+ "integrity": "sha512-VdaJjOqYFYcDTM5We2x8cL+B+U9UFQvq0iW2ypqEGX31SDf2oYFjEg7INEJorBwJJnFNXV8jXoYGzJyLeYl1EQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/glob": "^8.1.0",
+ "@types/lodash": "^4.14.197",
+ "@types/node": "20.5.6",
+ "@types/table": "5.0.0",
+ "@types/wrap-ansi": "^8.0.1",
+ "chalk": "3.0.0",
+ "glob": "^10.3.3",
+ "lodash": "^4.17.21",
+ "table": "5.4.6",
+ "winston": "3.10.0",
+ "wrap-ansi": "^8.1.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/@donmccurdy/caporal/node_modules/@types/node": {
+ "version": "20.5.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.6.tgz",
+ "integrity": "sha512-Gi5wRGPbbyOTX+4Y2iULQ27oUPrefaB0PxGQJnfyWN3kvEDGM3mIB5M/gQLmitZf7A9FmLeaqxD3L1CXpm3VKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@emnapi/runtime": {
+ "version": "1.11.3",
+ "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz",
+ "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@fal-ai/client": {
+ "version": "1.10.1",
+ "resolved": "https://registry.npmjs.org/@fal-ai/client/-/client-1.10.1.tgz",
+ "integrity": "sha512-c3AVeH31OioiI2J1BfW8Cryi1DhUYldnY3X35nv6xLMq3fU2NQOo+eYaR5mL2O8MoHHh+HzXdQuIyanIyeq+ug==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@msgpack/msgpack": "^3.0.0-beta2",
+ "eventsource-parser": "^1.1.2",
+ "robot3": "^0.4.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/@gltf-transform/cli": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/cli/-/cli-4.5.1.tgz",
+ "integrity": "sha512-TNPU20U7caqUpyXdbqobQueUjWmrdEhsZeno77MGJJCyiV1EyrC5yOE+aFrpxPli45VSk6aNT0FHAed8LE7ecg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@donmccurdy/caporal": "~0.0.10",
+ "@gltf-transform/core": "^4.5.1",
+ "@gltf-transform/extensions": "^4.5.1",
+ "@gltf-transform/functions": "^4.5.1",
+ "@types/micromatch": "~4.0.10",
+ "@types/prompts": "^2.4.9",
+ "@types/tmp": "~0.2.6",
+ "cli-table3": "~0.6.5",
+ "csv-stringify": "~6.8.3",
+ "draco3dgltf": "~1.5.7",
+ "gltf-validator": "~2.0.0-dev.3.10",
+ "keyframe-resample": "~0.1.0",
+ "ktx-parse": "^1.1.0",
+ "listr2": "~8.3.3",
+ "meshoptimizer": "~1.2.0",
+ "micromatch": "~4.0.8",
+ "mikktspace": "~1.1.1",
+ "prompts": "^2.4.2",
+ "sharp": "~0.35.3",
+ "tmp": "~0.2.7",
+ "watlas": "^1.0.1"
+ },
+ "bin": {
+ "gltf-transform": "bin/cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/cli/node_modules/meshoptimizer": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.2.0.tgz",
+ "integrity": "sha512-davRZeIJbxJrE24cwQle7ZDsxjdk/OphNOV83oX+efQinyoHY9Jcyz3MHbaoG0qySZajldGztNZ1RN/T19PZsg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@gltf-transform/core": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/core/-/core-4.5.1.tgz",
+ "integrity": "sha512-OWgBYssKHKoXMIrMb2N20jXqWRnMP9HdtcTFQBEAJtz4P+OOxx5fozl5eAeK7nktIs5uDE/lu4NbkE5VCZaR9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "property-graph": "^4.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/extensions": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/extensions/-/extensions-4.5.1.tgz",
+ "integrity": "sha512-3jTe+GWRy4fj1TU790LPsO+rpO/4byUWPTpNkjy6M6h8RvrUivRf12Mptc0770K4ZczibpJDNHXZFkFsFMRDLA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.5.1",
+ "ktx-parse": "^1.1.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@gltf-transform/functions": {
+ "version": "4.5.1",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/functions/-/functions-4.5.1.tgz",
+ "integrity": "sha512-rfm4nQY2DJ+ip1e15xp7YfQwhRno3kPLcGw4EZiRk1dVwMV3cdFMcF08glYcO/+oLyYkUEs3xXMJYXa0cPgcTg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.5.1",
+ "@gltf-transform/extensions": "^4.5.1",
+ "ktx-parse": "^1.1.0",
+ "ndarray": "^1.0.19",
+ "ndarray-lanczos": "^0.3.0",
+ "ndarray-pixels": "^5.2.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
+ "node_modules/@img/colour": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
+ "integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@img/sharp-darwin-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.35.5.tgz",
+ "integrity": "sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-darwin-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.35.5.tgz",
+ "integrity": "sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-darwin-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-freebsd-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-freebsd-wasm32/-/sharp-freebsd-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.3.4.tgz",
+ "integrity": "sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-darwin-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.3.4.tgz",
+ "integrity": "sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.3.4.tgz",
+ "integrity": "sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.3.4.tgz",
+ "integrity": "sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-ppc64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.3.4.tgz",
+ "integrity": "sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-riscv64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.3.4.tgz",
+ "integrity": "sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-s390x": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.3.4.tgz",
+ "integrity": "sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linux-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.3.4.tgz",
+ "integrity": "sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-arm64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.3.4.tgz",
+ "integrity": "sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-libvips-linuxmusl-x64": {
+ "version": "1.3.4",
+ "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.3.4.tgz",
+ "integrity": "sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.35.5.tgz",
+ "integrity": "sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.35.5.tgz",
+ "integrity": "sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-ppc64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.35.5.tgz",
+ "integrity": "sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-ppc64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-riscv64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.35.5.tgz",
+ "integrity": "sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-riscv64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-s390x": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.35.5.tgz",
+ "integrity": "sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-s390x": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linux-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.35.5.tgz",
+ "integrity": "sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linux-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.35.5.tgz",
+ "integrity": "sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-linuxmusl-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.35.5.tgz",
+ "integrity": "sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4"
+ }
+ },
+ "node_modules/@img/sharp-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.35.5.tgz",
+ "integrity": "sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==",
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/runtime": "^1.11.3"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-webcontainers-wasm32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-webcontainers-wasm32/-/sharp-webcontainers-wasm32-0.35.5.tgz",
+ "integrity": "sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==",
+ "cpu": [
+ "wasm32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "dependencies": {
+ "@img/sharp-wasm32": "0.35.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-arm64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.35.5.tgz",
+ "integrity": "sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-ia32": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.35.5.tgz",
+ "integrity": "sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@img/sharp-win32-x64": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.35.5.tgz",
+ "integrity": "sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 AND LGPL-3.0-or-later",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ }
+ },
+ "node_modules/@isaacs/cliui": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/@isaacs/cliui/-/cliui-8.0.2.tgz",
+ "integrity": "sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^5.1.2",
+ "string-width-cjs": "npm:string-width@^4.2.0",
+ "strip-ansi": "^7.0.1",
+ "strip-ansi-cjs": "npm:strip-ansi@^6.0.1",
+ "wrap-ansi": "^8.1.0",
+ "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@isaacs/cliui/node_modules/emoji-regex": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@isaacs/cliui/node_modules/string-width": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
+ "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eastasianwidth": "^0.2.0",
+ "emoji-regex": "^9.2.2",
+ "strip-ansi": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/@msgpack/msgpack": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/@msgpack/msgpack/-/msgpack-3.1.3.tgz",
+ "integrity": "sha512-47XIizs9XZXvuJgoaJUIE2lFoID8ugvc0jzSHP+Ptfk8nTbnR8g788wv48N03Kx0UkAv559HWRQ3yzOgzlRNUA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.151.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.151.0.tgz",
+ "integrity": "sha512-J1yXrIlNDZVzE3ada310xeAw7nH8yCAyLPuUIsjKatFPmfn5bS1oW+cM+QsGOtVWd5nhSpbwZWx/rue+r5Z+PA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@pkgjs/parseargs": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz",
+ "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==",
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "engines": {
+ "node": ">=14"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.11.tgz",
+ "integrity": "sha512-A5kXfGKvKWWZE0TtPrfsvT+q4Y5d1QG8gGUzpYjGydM+fARM9MuX90PrXYXe0XbsDVgyxxNzHo6giCj90bsFNw==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.11.tgz",
+ "integrity": "sha512-z6cTycz+iJ4PVkuL4HHW4DfTfoeU/2nqYYuSOrTmH7yHK5Y0LCOnA03V4ZNxavyVaU1oOqUgIg2klN/s+USGOA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.11.tgz",
+ "integrity": "sha512-jShvqNtP6vDC6/A5JOAzbVV+DkgHqhl/ScVCJEbt+TUY6QYz7YnXcrg3sLtFBniro0f/Ld50ZwCWA6f7KYD1nQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.11.tgz",
+ "integrity": "sha512-f2i2xiNWq1Z1l2++q2fuhZRdLAT3aqxD6vRNm1RAxpUoBcdqNB3C0s1Bt+K+PbEx2F5F4gQp6hqKkphCY/xF9w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.11.tgz",
+ "integrity": "sha512-4Ir5FSOKIAMr4r0kExpt1s3bMgzJU3rA45AYOHtQpls0oNeqcYBKrWMlckrYH4KCfGLfkfn1tN1dmZPMVsdXow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.11.tgz",
+ "integrity": "sha512-/gnRDM+39BROzAN/k1OZjDPnDMcZxB/0EUxKjONO5yVkNEvlsoMDrxGNKgZi/ttFriS2gwlDNzB65pvNbFOXIQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.11.tgz",
+ "integrity": "sha512-PFaK8HwvAHbaKbBcDNQihjMKYvFnA5hiENx/l5tphTDz1E0WFp32l0A7aq7lyUwGsRw/xSrNIy/gIK4thrSCrw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.11.tgz",
+ "integrity": "sha512-AskzJUIKRLPxkruR1wLKewGbOw+EYfU/9lOrBFj4AFrEA8hPpKFnODWNu2WLaNs0QNkEb9QIJufmVZZIL/bJlg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.11.tgz",
+ "integrity": "sha512-qlUGAheh2yh8afH7QBgx0PrRHN85hKnNd78x8MeMhXivuevgd8vgf6/CstOzmNKY/lLTHvNTrPy98cLnAugzJw==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.11.tgz",
+ "integrity": "sha512-secpEad+0vCbSfn8upFySkDskv+bGPk3THSDS9Y89yc4rb4kzqHp8Dmyd9BkQW4SnhNXBZCl/6CrO//hZahNJQ==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.11.tgz",
+ "integrity": "sha512-mOVBT3dPpkWm8XBWPmU4bf+U6dYDLeMo/9ojUmis4N0L5uu10qra5vOyngZ7/PSdoE4G9KvRt4bloRxNjLas7A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.11.tgz",
+ "integrity": "sha512-Is78i9A8Ui4SqcxUwFJ9uMmjDn58IbVTjFWYdQestFEgeuEmHMLGNriXnVJKkwG2YiZjw8cP0zCTyDMdDGtOOg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.11.tgz",
+ "integrity": "sha512-dUCXneZ87INUMyQ0D+C0HrEBNUPNXHaPmU5GTjyKTJEiussw9Kaj5Ln8UztPe4epV/ffvgNBEadksdYhmW6xJA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.11.tgz",
+ "integrity": "sha512-jByxb6qfd+bH1xUd0qnfFnb17i9sWBPY2tOavJ0l3tdr3OTu+Kvtm8cd/JV5nFt657b1VqGltxg9olOEfofXWw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.11.tgz",
+ "integrity": "sha512-/PzKqzAJ03i19oy2ItPvyvaVjOjBCNnfaJs8yvUdGBKmiESgnrJSQ2awd81QzFbbnAmu7YO9ZnJrDCb9VSJPRA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@so-ric/colorspace": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/@so-ric/colorspace/-/colorspace-1.1.6.tgz",
+ "integrity": "sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color": "^5.0.2",
+ "text-hex": "1.0.x"
+ }
+ },
+ "node_modules/@types/braces": {
+ "version": "3.0.5",
+ "resolved": "https://registry.npmjs.org/@types/braces/-/braces-3.0.5.tgz",
+ "integrity": "sha512-SQFof9H+LXeWNz8wDe7oN5zu7ket0qwMu5vZubW4GCJ8Kkeh6nBWUz87+KTz/G3Kqsrp0j/W253XJb3KMEeg3w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/glob": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/@types/glob/-/glob-8.1.0.tgz",
+ "integrity": "sha512-IO+MJPVhoqz+28h1qLAcBEH2+xHMK6MTyHJc7MTnnYb6wsoLR29POVGJ7LycmVXIqyy/4/2ShP5sUwTXuOwb/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/minimatch": "^5.1.2",
+ "@types/node": "*"
+ }
+ },
+ "node_modules/@types/lodash": {
+ "version": "4.17.25",
+ "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.25.tgz",
+ "integrity": "sha512-+K1NIO8I+F9/wNulfVvu23QYd0Pe9/OCqRrim4NoYIf1VoEDL90Ve4ClzpyqBLc7NpGGWRvYNCKZ1BE/Jpf8dQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/micromatch": {
+ "version": "4.0.10",
+ "resolved": "https://registry.npmjs.org/@types/micromatch/-/micromatch-4.0.10.tgz",
+ "integrity": "sha512-5jOhFDElqr4DKTrTEbnW8DZ4Hz5LRUEmyrGpCMrD/NphYv3nUnaF08xmSLx1rGGnyEs/kFnhiw6dCgcDqMr5PQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/braces": "*"
+ }
+ },
+ "node_modules/@types/minimatch": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/@types/minimatch/-/minimatch-5.1.2.tgz",
+ "integrity": "sha512-K0VQKziLUWkVKiRVrx4a40iPaxTUefQmjtkQofBkYRcoaaL/8rhwDWww9qWbrgicNOgnpIsMxyNIUM4+n6dUIA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/ndarray": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.1.0.tgz",
+ "integrity": "sha512-go+C6vHBUuO9jH6Tj6qEZ63JEGoMSxFdmd+6QAtthGD6xumBfIz3RbNDDs2aoRVLf9naH8lk5jnWy2UHHKgYQQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.3",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.3.tgz",
+ "integrity": "sha512-dsqMQQoeTLqu9wynDD00q573mNzso3IdQOAfHRJqLCcmCFPoGo9A1bDpUcv/9tnKpErQWv9uKeGfl37EIS02Yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/prompts": {
+ "version": "2.4.9",
+ "resolved": "https://registry.npmjs.org/@types/prompts/-/prompts-2.4.9.tgz",
+ "integrity": "sha512-qTxFi6Buiu8+50/+3DGIWLHM6QuWsEKugJnnP6iv2Mc4ncxE4A/OJkjuVOA+5X0X1S/nq5VJRa8Lu+nwcvbrKA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "kleur": "^3.0.3"
+ }
+ },
+ "node_modules/@types/table": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/@types/table/-/table-5.0.0.tgz",
+ "integrity": "sha512-fQLtGLZXor264zUPWI95WNDsZ3QV43/c0lJpR/h1hhLJumXRmHNsrvBfEzW2YMhb0EWCsn4U6h82IgwsajAuTA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/tmp": {
+ "version": "0.2.6",
+ "resolved": "https://registry.npmjs.org/@types/tmp/-/tmp-0.2.6.tgz",
+ "integrity": "sha512-chhaNf2oKHlRkDGt+tiKE2Z5aJ6qalm7Z9rlLdBwmOiAAf09YQvvoLXjWK4HWPF1xU/fqvMgfNfpVoBscA/tKA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/triple-beam": {
+ "version": "1.3.5",
+ "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.5.tgz",
+ "integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/wrap-ansi": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/@types/wrap-ansi/-/wrap-ansi-8.0.2.tgz",
+ "integrity": "sha512-mdaFibQzYYqJF8Sc9By84eBLtDQD9Hnko0yXuezHBU5f5KdtQk+j5hPRQc1j4ayzdqGddKON6PjeuzxD5U1hPg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/ajv": {
+ "version": "6.15.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz",
+ "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.1",
+ "fast-json-stable-stringify": "^2.0.0",
+ "json-schema-traverse": "^0.4.1",
+ "uri-js": "^4.2.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ansi-escapes": {
+ "version": "7.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz",
+ "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "environment": "^1.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "6.4.0",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.4.0.tgz",
+ "integrity": "sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-regex?sponsor=1"
+ }
+ },
+ "node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/astral-regex": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-1.0.0.tgz",
+ "integrity": "sha512-+Ryf6g3BKoRc7jfp7ad8tM4TtMiaWvbF/1/sQcZPkkS7ag3D5nMBCe2UfOTONtAkaG0tO0ij3C5Lwmf1EiyjHg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/async": {
+ "version": "3.2.6",
+ "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz",
+ "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/balanced-match": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
+ "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/brace-expansion": {
+ "version": "2.1.7",
+ "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz",
+ "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "balanced-match": "^1.0.0"
+ }
+ },
+ "node_modules/braces": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
+ "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fill-range": "^7.1.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/chalk": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz",
+ "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.1.0",
+ "supports-color": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/cli-cursor": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz",
+ "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "restore-cursor": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cli-table3": {
+ "version": "0.6.5",
+ "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz",
+ "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "string-width": "^4.2.0"
+ },
+ "engines": {
+ "node": "10.* || >= 12.*"
+ },
+ "optionalDependencies": {
+ "@colors/colors": "1.5.0"
+ }
+ },
+ "node_modules/cli-truncate": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-4.0.0.tgz",
+ "integrity": "sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "slice-ansi": "^5.0.0",
+ "string-width": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/cli-truncate/node_modules/emoji-regex": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cli-truncate/node_modules/string-width": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^10.3.0",
+ "get-east-asian-width": "^1.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/color": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/color/-/color-5.0.3.tgz",
+ "integrity": "sha512-ezmVcLR3xAVp8kYOm4GS45ZLLgIE6SPAFoduLr6hTDajwb3KZ2F46gulK3XpcwRFb5KKGCSezCBAY4Dw4HsyXA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^3.1.3",
+ "color-string": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/color-string": {
+ "version": "2.1.4",
+ "resolved": "https://registry.npmjs.org/color-string/-/color-string-2.1.4.tgz",
+ "integrity": "sha512-Bb6Cq8oq0IjDOe8wJmi4JeNn763Xs9cfrBcaylK1tPypWzyoy2G3l90v9k64kjphl/ZJjPIShFztenRomi8WTg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/color-string/node_modules/color-name": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-2.1.1.tgz",
+ "integrity": "sha512-p2FdgwVx1a9yWBHP2wI0VgShkDpgN4kZISkxdNipGBJWpa5G6b04OINlVWCyJj0JmfvcPrgqt95E9k8yvaOJFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20"
+ }
+ },
+ "node_modules/color/node_modules/color-convert": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-3.1.3.tgz",
+ "integrity": "sha512-fasDH2ont2GqF5HpyO4w0+BcewlhHEZOFn9c1ckZdHpJ56Qb7MHhH/IcJZbBGgvdtwdwNbLvxiBEdg336iA9Sg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=14.6"
+ }
+ },
+ "node_modules/color/node_modules/color-name": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-2.1.1.tgz",
+ "integrity": "sha512-p2FdgwVx1a9yWBHP2wI0VgShkDpgN4kZISkxdNipGBJWpa5G6b04OINlVWCyJj0JmfvcPrgqt95E9k8yvaOJFg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20"
+ }
+ },
+ "node_modules/colorette": {
+ "version": "2.0.20",
+ "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz",
+ "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/csv-stringify": {
+ "version": "6.8.3",
+ "resolved": "https://registry.npmjs.org/csv-stringify/-/csv-stringify-6.8.3.tgz",
+ "integrity": "sha512-gIeSCvq5F4VtXV3naV3VAewLhBkiZBz+PPhTOA8H3Y8h/ELa+R1ml0GZck/4/Nzo9ep2lvOluilJ6MJlbZsKMA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/cwise-compiler": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/cwise-compiler/-/cwise-compiler-1.1.3.tgz",
+ "integrity": "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "uniq": "^1.0.0"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/dotenv": {
+ "version": "18.0.4",
+ "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-18.0.4.tgz",
+ "integrity": "sha512-jGt9uI5BIxpVO15kvy+iEFqNAwxYClKWnkptLjSNPnFLC003Imd0ofr3aEVsbpHdSBdSsbcApNIlz4nbyGMwdA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "bin": {
+ "dotenv": "dist/index.cjs"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://dotenvx.com"
+ }
+ },
+ "node_modules/draco3dgltf": {
+ "version": "1.5.7",
+ "resolved": "https://registry.npmjs.org/draco3dgltf/-/draco3dgltf-1.5.7.tgz",
+ "integrity": "sha512-LeqcpmoHIyYUi0z70/H3tMkGj8QhqVxq6FJGPjlzR24BNkQ6jyMheMvFKJBI0dzGZrEOUyQEmZ8axM1xRrbRiw==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/eastasianwidth": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/eastasianwidth/-/eastasianwidth-0.2.0.tgz",
+ "integrity": "sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/enabled": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/enabled/-/enabled-2.0.0.tgz",
+ "integrity": "sha512-AKrN98kuwOzMIdAizXGI86UFBoo26CL21UM763y1h/GMSJ4/OHU9k2YlsmBpyScFo/wbLzWQJBMCW4+IO3/+OQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/environment": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz",
+ "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/eventemitter3": {
+ "version": "5.0.4",
+ "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
+ "integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/eventsource-parser": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-1.1.2.tgz",
+ "integrity": "sha512-v0eOBUbiaFojBu2s2NPBfYUoRR9GjcDNvCXVaqEf5vVfpIAh9f8RCo4vXTP8c63QRKCFwoLpMpTdPwwhEKVgzA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.18"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-json-stable-stringify": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz",
+ "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fecha": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz",
+ "integrity": "sha512-OP2IUU6HeYKJi3i0z4A19kHMQoLVs4Hc+DPqqxI2h/DPZHTm/vjsfC6P0b4jCMy14XizLBqvndQ+UilD7707Jw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fill-range": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
+ "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "to-regex-range": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/fn.name": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/fn.name/-/fn.name-1.1.0.tgz",
+ "integrity": "sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/foreground-child": {
+ "version": "3.3.1",
+ "resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",
+ "integrity": "sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "cross-spawn": "^7.0.6",
+ "signal-exit": "^4.0.1"
+ },
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/get-east-asian-width": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz",
+ "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/glob": {
+ "version": "10.5.0",
+ "resolved": "https://registry.npmjs.org/glob/-/glob-10.5.0.tgz",
+ "integrity": "sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg==",
+ "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "foreground-child": "^3.1.0",
+ "jackspeak": "^3.1.2",
+ "minimatch": "^9.0.4",
+ "minipass": "^7.1.2",
+ "package-json-from-dist": "^1.0.0",
+ "path-scurry": "^1.11.1"
+ },
+ "bin": {
+ "glob": "dist/esm/bin.mjs"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/gltf-validator": {
+ "version": "2.0.0-dev.3.10",
+ "resolved": "https://registry.npmjs.org/gltf-validator/-/gltf-validator-2.0.0-dev.3.10.tgz",
+ "integrity": "sha512-odJ4k0tRkGXiDGn78yDBg+fBbAIvBnXxh3RwAta0emSxGtyagFE8B4xELB1oYe3S5RD8Ci3uZAsZaascH2LAEQ==",
+ "dev": true,
+ "license": "Apache-2.0"
+ },
+ "node_modules/gsap": {
+ "version": "3.15.0",
+ "resolved": "https://registry.npmjs.org/gsap/-/gsap-3.15.0.tgz",
+ "integrity": "sha512-dMW4CWBTUK1AEEDeZc1g4xpPGIrSf9fJF960qbTZmN/QwZIWY5wgliS6JWl9/25fpTGJrMRtSjGtOmPnfjZB+A==",
+ "license": "Standard 'no charge' license: https://gsap.com/standard-license."
+ },
+ "node_modules/has-flag": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz",
+ "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/iota-array": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
+ "integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/is-buffer": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-1.1.6.tgz",
+ "integrity": "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-4.0.0.tgz",
+ "integrity": "sha512-O4L094N2/dZ7xqVdrXhh9r1KODPJpFms8B5sGdJLPy664AgvXsreZUyCQQNItZRDlYug4xStLjNp/sz3HvBowQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/is-number": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz",
+ "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.12.0"
+ }
+ },
+ "node_modules/is-stream": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
+ "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/jackspeak": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-3.4.3.tgz",
+ "integrity": "sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "@isaacs/cliui": "^8.0.2"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ },
+ "optionalDependencies": {
+ "@pkgjs/parseargs": "^0.11.0"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
+ "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/keyframe-resample": {
+ "version": "0.1.0",
+ "resolved": "https://registry.npmjs.org/keyframe-resample/-/keyframe-resample-0.1.0.tgz",
+ "integrity": "sha512-z1au6Q6qCWP734q44t/5SyGwNydC7MvOWo2ZETAz7ZqAgtcyb5EGO7jwgk3DEH7CaDtb0DkGec9iwVpeDWX5dA==",
+ "dev": true,
+ "license": "BlueOak-1.0.0"
+ },
+ "node_modules/kleur": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",
+ "integrity": "sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/ktx-parse": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/ktx-parse/-/ktx-parse-1.1.0.tgz",
+ "integrity": "sha512-mKp3y+FaYgR7mXWAbyyzpa/r1zDWeaunH+INJO4fou3hb45XuNSwar+7llrRyvpMWafxSIi99RNFJ05MHedaJQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/kuler": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/kuler/-/kuler-2.0.0.tgz",
+ "integrity": "sha512-Xq9nH7KlWZmXAtodXDDRE7vs6DU1gTU8zYDHDiWLSip45Egwq3plLHzPn27NgvzL2r1LMPC1vdqh98sQxtqj4A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/lenis": {
+ "version": "1.3.26",
+ "resolved": "https://registry.npmjs.org/lenis/-/lenis-1.3.26.tgz",
+ "integrity": "sha512-s/xTCZCxTFvHbAN1OzuhNaN5YPJH2ail0XAkctKW1b+RUAG4nUL5UHLXwNko1h8aEeT2jspBXegMgPJd8zcuag==",
+ "license": "MIT",
+ "workspaces": [
+ "packages/*",
+ "playground",
+ "playground/*"
+ ],
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/darkroomengineering"
+ },
+ "peerDependencies": {
+ "@nuxt/kit": ">=3.0.0",
+ "react": ">=17.0.0",
+ "vue": ">=3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@nuxt/kit": {
+ "optional": true
+ },
+ "react": {
+ "optional": true
+ },
+ "vue": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "glibc"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "libc": [
+ "musl"
+ ],
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/listr2": {
+ "version": "8.3.3",
+ "resolved": "https://registry.npmjs.org/listr2/-/listr2-8.3.3.tgz",
+ "integrity": "sha512-LWzX2KsqcB1wqQ4AHgYb4RsDXauQiqhjLk+6hjbaeHG4zpjjVAB6wC/gz6X0l+Du1cN3pUB5ZlrvTbhGSNnUQQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cli-truncate": "^4.0.0",
+ "colorette": "^2.0.20",
+ "eventemitter3": "^5.0.1",
+ "log-update": "^6.1.0",
+ "rfdc": "^1.4.1",
+ "wrap-ansi": "^9.0.0"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/listr2/node_modules/ansi-styles": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/listr2/node_modules/emoji-regex": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/listr2/node_modules/string-width": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^10.3.0",
+ "get-east-asian-width": "^1.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/listr2/node_modules/wrap-ansi": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.2.1",
+ "string-width": "^7.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/lodash": {
+ "version": "4.18.1",
+ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz",
+ "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/log-update": {
+ "version": "6.1.0",
+ "resolved": "https://registry.npmjs.org/log-update/-/log-update-6.1.0.tgz",
+ "integrity": "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-escapes": "^7.0.0",
+ "cli-cursor": "^5.0.0",
+ "slice-ansi": "^7.1.0",
+ "strip-ansi": "^7.1.0",
+ "wrap-ansi": "^9.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/log-update/node_modules/ansi-styles": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/log-update/node_modules/emoji-regex": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz",
+ "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/log-update/node_modules/is-fullwidth-code-point": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz",
+ "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "get-east-asian-width": "^1.3.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/log-update/node_modules/slice-ansi": {
+ "version": "7.1.2",
+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-7.1.2.tgz",
+ "integrity": "sha512-iOBWFgUX7caIZiuutICxVgX1SdxwAVFFKwt1EvMYYec/NWO5meOJ6K5uQxhrYBdQJne4KxiqZc+KptFOWFSI9w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.2.1",
+ "is-fullwidth-code-point": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/slice-ansi?sponsor=1"
+ }
+ },
+ "node_modules/log-update/node_modules/string-width": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz",
+ "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^10.3.0",
+ "get-east-asian-width": "^1.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/log-update/node_modules/wrap-ansi": {
+ "version": "9.0.2",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz",
+ "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.2.1",
+ "string-width": "^7.0.0",
+ "strip-ansi": "^7.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/logform": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/logform/-/logform-2.7.0.tgz",
+ "integrity": "sha512-TFYA4jnP7PVbmlBIfhlSe+WKxs9dklXMTEGcBCIvLhE/Tn3H6Gk1norupVW7m5Cnd4bLcr08AytbyV/xj7f/kQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@colors/colors": "1.6.0",
+ "@types/triple-beam": "^1.3.2",
+ "fecha": "^4.2.0",
+ "ms": "^2.1.1",
+ "safe-stable-stringify": "^2.3.1",
+ "triple-beam": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ }
+ },
+ "node_modules/logform/node_modules/@colors/colors": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
+ "integrity": "sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.1.90"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "10.4.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
+ "integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/meshoptimizer": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-1.3.0.tgz",
+ "integrity": "sha512-2oZqMAcEEiCtXWUjIGtZ71oPx1B0ZxYGTqIKsXB1wzWFhleNsCFxQuUJzgCV706bRcwPWtMGf1odmQvAcqKkIw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/micromatch": {
+ "version": "4.0.8",
+ "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
+ "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "braces": "^3.0.3",
+ "picomatch": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=8.6"
+ }
+ },
+ "node_modules/mikktspace": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/mikktspace/-/mikktspace-1.1.1.tgz",
+ "integrity": "sha512-w+n5O2YLFsv/aRi3QUF0jxR+mEsl2J08ZkRItJHE08MWqiDIy8amyZN9vetBfbLhlWGMb8G3mzSPwtKHvBF7hQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/mimic-function": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz",
+ "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/minimatch": {
+ "version": "9.0.9",
+ "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz",
+ "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "brace-expansion": "^2.0.2"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/minipass": {
+ "version": "7.1.3",
+ "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz",
+ "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": ">=16 || 14 >=14.17"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/n8ao": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/n8ao/-/n8ao-2.0.1.tgz",
+ "integrity": "sha512-MoP1QKUdj4/3cKEnhFl917t0eQwWGER1l43ckz5mNOPyYWGRDGQbVoTOQz/VBvy01in6QVNG+AL6Xxx5AjZBYA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "postprocessing": ">=6.30.0",
+ "three": ">=0.137"
+ }
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.19",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.19.tgz",
+ "integrity": "sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/ndarray": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.1.1.tgz",
+ "integrity": "sha512-AsE8w/M2MS+0pD3nP5qbRRtJFeJJJaJ+qXZaZr0XjVGXhy6LIj2TERTlkpdK2AI3WufoOP+pwPk3q2ilAJcZ9g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "iota-array": "^1.0.0",
+ "is-buffer": "^1.0.2"
+ }
+ },
+ "node_modules/ndarray-lanczos": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/ndarray-lanczos/-/ndarray-lanczos-0.3.0.tgz",
+ "integrity": "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.11",
+ "ndarray": "^1.0.19"
+ }
+ },
+ "node_modules/ndarray-ops": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/ndarray-ops/-/ndarray-ops-1.2.2.tgz",
+ "integrity": "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cwise-compiler": "^1.0.0"
+ }
+ },
+ "node_modules/ndarray-pixels": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/ndarray-pixels/-/ndarray-pixels-5.2.0.tgz",
+ "integrity": "sha512-lTh4tFKziAatVTa9crIsidUyn+lqujVOQpzfdBWvdFu2wo9Uo6z261lVX7SgMyP89xGmj3TMTPbbxl9YDnV4SA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.14",
+ "ndarray": "^1.0.19",
+ "ndarray-ops": "^1.2.2",
+ "sharp": "^0.35.0"
+ }
+ },
+ "node_modules/one-time": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/one-time/-/one-time-1.0.0.tgz",
+ "integrity": "sha512-5DXOiRKwuSEcQ/l0kGCF6Q3jcADFv5tSmRaJck/OqkVFcOzutB134KRSfF0xDrL39MNnqxbHBbUUcjZIhTgb2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fn.name": "1.x.x"
+ }
+ },
+ "node_modules/onetime": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz",
+ "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mimic-function": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/package-json-from-dist": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz",
+ "integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
+ "dev": true,
+ "license": "BlueOak-1.0.0"
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-scurry": {
+ "version": "1.11.1",
+ "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-1.11.1.tgz",
+ "integrity": "sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "dependencies": {
+ "lru-cache": "^10.2.0",
+ "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0"
+ },
+ "engines": {
+ "node": ">=16 || 14 >=14.18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz",
+ "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/playwright": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz",
+ "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "playwright-core": "1.63.0"
+ },
+ "bin": {
+ "playwright": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/playwright-core": {
+ "version": "1.63.0",
+ "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz",
+ "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "playwright-core": "cli.js"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.28",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.28.tgz",
+ "integrity": "sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.18",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postprocessing": {
+ "version": "6.39.5",
+ "resolved": "https://registry.npmjs.org/postprocessing/-/postprocessing-6.39.5.tgz",
+ "integrity": "sha512-YmH+t74J2X1lwYjKzK/tgs9C9kqWWPB9JwZiDF5mEf4BdCEAmEFbO8lXBA7NM0/j4g+x6FgD/Tt5/kT7ogbEDA==",
+ "license": "Zlib",
+ "peerDependencies": {
+ "three": ">= 0.168.0 < 0.187.0"
+ }
+ },
+ "node_modules/prompts": {
+ "version": "2.4.2",
+ "resolved": "https://registry.npmjs.org/prompts/-/prompts-2.4.2.tgz",
+ "integrity": "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "kleur": "^3.0.3",
+ "sisteransi": "^1.0.5"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/property-graph": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/property-graph/-/property-graph-4.1.0.tgz",
+ "integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/readable-stream": {
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
+ "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "inherits": "^2.0.3",
+ "string_decoder": "^1.1.1",
+ "util-deprecate": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/restore-cursor": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz",
+ "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "onetime": "^7.0.0",
+ "signal-exit": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/rfdc": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz",
+ "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/robot3": {
+ "version": "0.4.1",
+ "resolved": "https://registry.npmjs.org/robot3/-/robot3-0.4.1.tgz",
+ "integrity": "sha512-hzjy826lrxzx8eRgv80idkf8ua1JAepRc9Efdtj03N3KNJuznQCPlyCJ7gnUmDFwZCLQjxy567mQVKmdv2BsXQ==",
+ "dev": true,
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.11",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.11.tgz",
+ "integrity": "sha512-qpSwIyz0jHQq5qXBTNxFmE6664rJ7O+4TvPFOiOaBSrz8IOHc1koKKSqTM2H6u1UG1+TveuC6vaDHKXFOvb1Kw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.151.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.11",
+ "@rolldown/binding-android-arm64": "1.2.11",
+ "@rolldown/binding-darwin-arm64": "1.2.11",
+ "@rolldown/binding-darwin-x64": "1.2.11",
+ "@rolldown/binding-freebsd-x64": "1.2.11",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.11",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.11",
+ "@rolldown/binding-linux-arm64-musl": "1.2.11",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.11",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-gnu": "1.2.11",
+ "@rolldown/binding-linux-x64-musl": "1.2.11",
+ "@rolldown/binding-openharmony-arm64": "1.2.11",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.11",
+ "@rolldown/binding-win32-x64-msvc": "1.2.11"
+ }
+ },
+ "node_modules/safe-buffer": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz",
+ "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/safe-stable-stringify": {
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz",
+ "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/sharp": {
+ "version": "0.35.5",
+ "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
+ "integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@img/colour": "^1.1.0",
+ "detect-libc": "^2.1.2",
+ "semver": "^7.8.5"
+ },
+ "engines": {
+ "node": ">=20.9.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/libvips"
+ },
+ "optionalDependencies": {
+ "@img/sharp-darwin-arm64": "0.35.5",
+ "@img/sharp-darwin-x64": "0.35.5",
+ "@img/sharp-freebsd-wasm32": "0.35.5",
+ "@img/sharp-libvips-darwin-arm64": "1.3.4",
+ "@img/sharp-libvips-darwin-x64": "1.3.4",
+ "@img/sharp-libvips-linux-arm": "1.3.4",
+ "@img/sharp-libvips-linux-arm64": "1.3.4",
+ "@img/sharp-libvips-linux-ppc64": "1.3.4",
+ "@img/sharp-libvips-linux-riscv64": "1.3.4",
+ "@img/sharp-libvips-linux-s390x": "1.3.4",
+ "@img/sharp-libvips-linux-x64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-arm64": "1.3.4",
+ "@img/sharp-libvips-linuxmusl-x64": "1.3.4",
+ "@img/sharp-linux-arm": "0.35.5",
+ "@img/sharp-linux-arm64": "0.35.5",
+ "@img/sharp-linux-ppc64": "0.35.5",
+ "@img/sharp-linux-riscv64": "0.35.5",
+ "@img/sharp-linux-s390x": "0.35.5",
+ "@img/sharp-linux-x64": "0.35.5",
+ "@img/sharp-linuxmusl-arm64": "0.35.5",
+ "@img/sharp-linuxmusl-x64": "0.35.5",
+ "@img/sharp-webcontainers-wasm32": "0.35.5",
+ "@img/sharp-win32-arm64": "0.35.5",
+ "@img/sharp-win32-ia32": "0.35.5",
+ "@img/sharp-win32-x64": "0.35.5"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/signal-exit": {
+ "version": "4.1.0",
+ "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
+ "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/isaacs"
+ }
+ },
+ "node_modules/sisteransi": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
+ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/slice-ansi": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-5.0.0.tgz",
+ "integrity": "sha512-FC+lgizVPfie0kkhqUScwRu1O/lF6NOgJmlCgK+/LYxDCTk8sGelYaHDhFcDN+Sn3Cv+3VSa4Byeo+IMCzpMgQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.0.0",
+ "is-fullwidth-code-point": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/slice-ansi?sponsor=1"
+ }
+ },
+ "node_modules/slice-ansi/node_modules/ansi-styles": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
+ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stack-trace": {
+ "version": "0.0.10",
+ "resolved": "https://registry.npmjs.org/stack-trace/-/stack-trace-0.0.10.tgz",
+ "integrity": "sha512-KGzahc7puUKkzyMt+IqAep+TVNbKP+k2Lmwhub39m1AsTSkaDutx56aDCo+HLDzf/D26BIHTJWNiTG1KAJiQCg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/string_decoder": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+ "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "safe-buffer": "~5.2.0"
+ }
+ },
+ "node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width-cjs": {
+ "name": "string-width",
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width-cjs/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width-cjs/node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width-cjs/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width/node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/string-width/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz",
+ "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^6.2.2"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/strip-ansi?sponsor=1"
+ }
+ },
+ "node_modules/strip-ansi-cjs": {
+ "name": "strip-ansi",
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi-cjs/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/supports-color": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz",
+ "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "has-flag": "^4.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/table": {
+ "version": "5.4.6",
+ "resolved": "https://registry.npmjs.org/table/-/table-5.4.6.tgz",
+ "integrity": "sha512-wmEc8m4fjnob4gt5riFRtTu/6+4rSe12TpAELNSqHMfF3IqnA+CH37USM6/YR3qRZv7e56kAEAtd6nKZaxe0Ug==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "ajv": "^6.10.2",
+ "lodash": "^4.17.14",
+ "slice-ansi": "^2.1.0",
+ "string-width": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/table/node_modules/ansi-regex": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.1.tgz",
+ "integrity": "sha512-ILlv4k/3f6vfQ4OoP2AGvirOktlQ98ZEL1k9FaQjxa3L1abBgbuTDAdPOpvbGncC0BTVQrl+OM8xZGK6tWXt7g==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/table/node_modules/ansi-styles": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
+ "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^1.9.0"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/table/node_modules/color-convert": {
+ "version": "1.9.3",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
+ "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "1.1.3"
+ }
+ },
+ "node_modules/table/node_modules/color-name": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
+ "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/table/node_modules/emoji-regex": {
+ "version": "7.0.3",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-7.0.3.tgz",
+ "integrity": "sha512-CwBLREIQ7LvYFB0WyRvwhq5N5qPhc6PMjD6bYggFlI5YyDgl+0vxq5VHbMOFqLg7hfWzmu8T5Z1QofhmTIhItA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/table/node_modules/is-fullwidth-code-point": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-2.0.0.tgz",
+ "integrity": "sha512-VHskAKYM8RfSFXwee5t5cbN5PZeq1Wrh6qd5bkyiXIf6UQcN6w/A0eXM9r6t8d+GYOh+o6ZhiEnb88LN/Y8m2w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/table/node_modules/slice-ansi": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-2.1.0.tgz",
+ "integrity": "sha512-Qu+VC3EwYLldKa1fCxuuvULvSJOKEgk9pi8dZeCVK7TqBfUNTH4sFkk4joj8afVSfAYgJoSOetjx9QWOJ5mYoQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^3.2.0",
+ "astral-regex": "^1.0.0",
+ "is-fullwidth-code-point": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/table/node_modules/string-width": {
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz",
+ "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^7.0.1",
+ "is-fullwidth-code-point": "^2.0.0",
+ "strip-ansi": "^5.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/table/node_modules/strip-ansi": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz",
+ "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^4.1.0"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/text-hex": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/text-hex/-/text-hex-1.0.0.tgz",
+ "integrity": "sha512-uuVGNWzgJ4yhRaNSiubPY7OjISw4sw4E5Uv0wbjp+OzcbmVU/rsT8ujgcXJhn9ypzsgr5vlzpPqP+MBBKcGvbg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/three": {
+ "version": "0.186.1",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.186.1.tgz",
+ "integrity": "sha512-blFeqb49wRCSGUGj7gtpfnSGHy2lwDk94RhUmS1c/hTby70kvChbWpkJ4Pm1390LqzzvTmzgXKHPEafJwCb8jA==",
+ "license": "MIT"
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinyglobby/node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/tinyglobby/node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/tmp": {
+ "version": "0.2.7",
+ "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.7.tgz",
+ "integrity": "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.14"
+ }
+ },
+ "node_modules/to-regex-range": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
+ "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "is-number": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=8.0"
+ }
+ },
+ "node_modules/triple-beam": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/triple-beam/-/triple-beam-1.4.1.tgz",
+ "integrity": "sha512-aZbgViZrg1QNcG+LULa7nhZpJTZSLm/mXnHXnbAbjmN5aSa0y7V+wvv6+4WaBtpISJzThKy+PIPxc1Nq1EJ9mg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD",
+ "optional": true
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/uniq": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz",
+ "integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/uri-js": {
+ "version": "4.4.1",
+ "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
+ "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "punycode": "^2.1.0"
+ }
+ },
+ "node_modules/util-deprecate": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
+ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/vite": {
+ "version": "8.3.1",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.1.tgz",
+ "integrity": "sha512-/bvH9E9tmCXRGp2uXY3WbOldqpTwFkbha/8ANaEQ6VkxhH60KyqLwgZq6lG2y+4uT55x9+9eUHMpQ7uGnOCKjA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.9",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite/node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/watlas": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/watlas/-/watlas-1.0.1.tgz",
+ "integrity": "sha512-TmB++BFqEQY19cPNby5iszACZd8t6uauB7YdObkqhWarhed79OMPS8wufoDSo0p85A/8QW/aqZwEJf+nD4emSw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/winston": {
+ "version": "3.10.0",
+ "resolved": "https://registry.npmjs.org/winston/-/winston-3.10.0.tgz",
+ "integrity": "sha512-nT6SIDaE9B7ZRO0u3UvdrimG0HkB7dSTAgInQnNR2SOPJ4bvq5q79+pXLftKmP52lJGW15+H5MCK0nM9D3KB/g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@colors/colors": "1.5.0",
+ "@dabh/diagnostics": "^2.0.2",
+ "async": "^3.2.3",
+ "is-stream": "^2.0.0",
+ "logform": "^2.4.0",
+ "one-time": "^1.0.0",
+ "readable-stream": "^3.4.0",
+ "safe-stable-stringify": "^2.3.1",
+ "stack-trace": "0.0.x",
+ "triple-beam": "^1.3.0",
+ "winston-transport": "^4.5.0"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ }
+ },
+ "node_modules/winston-transport": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
+ "integrity": "sha512-8drMJ4rkgaPo1Me4zD/3WLfI/zPdA9o2IipKODunnGDcuqbHwjsbB79ylv04LCGGzU0xQ6vTznOMpQGaLhhm6A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "logform": "^2.7.0",
+ "readable-stream": "^3.6.2",
+ "triple-beam": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ }
+ },
+ "node_modules/wrap-ansi": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-8.1.0.tgz",
+ "integrity": "sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^6.1.0",
+ "string-width": "^5.0.1",
+ "strip-ansi": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/wrap-ansi-cjs": {
+ "name": "wrap-ansi",
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/wrap-ansi-cjs/node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi-cjs/node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/ansi-styles": {
+ "version": "6.2.3",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz",
+ "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/wrap-ansi/node_modules/emoji-regex": {
+ "version": "9.2.2",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz",
+ "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/wrap-ansi/node_modules/string-width": {
+ "version": "5.1.2",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
+ "integrity": "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "eastasianwidth": "^0.2.0",
+ "emoji-regex": "^9.2.2",
+ "strip-ansi": "^7.0.1"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..82a2096
--- /dev/null
+++ b/package.json
@@ -0,0 +1,33 @@
+{
+ "name": "dioramas",
+ "private": true,
+ "description": "A framework for cinematic, interactive 3D websites with AI-generated assets (Nano Banana 2 + Meshy 7.1 on fal).",
+ "license": "MIT",
+ "version": "0.1.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite --port 5190",
+ "build": "vite build",
+ "preview": "vite preview --port 5191"
+ },
+ "devDependencies": {
+ "@fal-ai/client": "^1.10.1",
+ "@gltf-transform/cli": "^4.5.1",
+ "@gltf-transform/core": "^4.5.1",
+ "@gltf-transform/extensions": "^4.5.1",
+ "@gltf-transform/functions": "^4.5.1",
+ "dotenv": "^18.0.4",
+ "meshoptimizer": "^1.3.0",
+ "playwright": "^1.63.0",
+ "sharp": "^0.35.5",
+ "vite": "^8.3.1"
+ },
+ "dependencies": {
+ "@dimforge/rapier3d-compat": "^0.21.0",
+ "gsap": "^3.15.0",
+ "lenis": "^1.3.26",
+ "n8ao": "^2.0.1",
+ "postprocessing": "^6.39.5",
+ "three": "^0.186.1"
+ }
+}
diff --git a/public/img/artemis/centrifuge.webp b/public/img/artemis/centrifuge.webp
new file mode 100644
index 0000000..b9559a5
Binary files /dev/null and b/public/img/artemis/centrifuge.webp differ
diff --git a/public/img/artemis/earth.webp b/public/img/artemis/earth.webp
new file mode 100644
index 0000000..0d68073
Binary files /dev/null and b/public/img/artemis/earth.webp differ
diff --git a/public/img/artemis/habitat.webp b/public/img/artemis/habitat.webp
new file mode 100644
index 0000000..9c49a00
Binary files /dev/null and b/public/img/artemis/habitat.webp differ
diff --git a/public/img/artemis/training.webp b/public/img/artemis/training.webp
new file mode 100644
index 0000000..484bbde
Binary files /dev/null and b/public/img/artemis/training.webp differ
diff --git a/public/img/ember/brick-n.webp b/public/img/ember/brick-n.webp
new file mode 100644
index 0000000..666ddf9
Binary files /dev/null and b/public/img/ember/brick-n.webp differ
diff --git a/public/img/ember/brick.webp b/public/img/ember/brick.webp
new file mode 100644
index 0000000..b9bb056
Binary files /dev/null and b/public/img/ember/brick.webp differ
diff --git a/public/img/ember/damascus.webp b/public/img/ember/damascus.webp
new file mode 100644
index 0000000..db18b63
Binary files /dev/null and b/public/img/ember/damascus.webp differ
diff --git a/public/img/ember/floor-n.webp b/public/img/ember/floor-n.webp
new file mode 100644
index 0000000..c2fcf65
Binary files /dev/null and b/public/img/ember/floor-n.webp differ
diff --git a/public/img/ember/floor.webp b/public/img/ember/floor.webp
new file mode 100644
index 0000000..12df9b7
Binary files /dev/null and b/public/img/ember/floor.webp differ
diff --git a/public/img/hangar/dawn.webp b/public/img/hangar/dawn.webp
new file mode 100644
index 0000000..405522f
Binary files /dev/null and b/public/img/hangar/dawn.webp differ
diff --git a/public/img/hangar/pilot.webp b/public/img/hangar/pilot.webp
new file mode 100644
index 0000000..4675345
Binary files /dev/null and b/public/img/hangar/pilot.webp differ
diff --git a/public/img/index/abyssal.webp b/public/img/index/abyssal.webp
new file mode 100644
index 0000000..62e075d
Binary files /dev/null and b/public/img/index/abyssal.webp differ
diff --git a/public/img/index/artemis.webp b/public/img/index/artemis.webp
new file mode 100644
index 0000000..fdddba6
Binary files /dev/null and b/public/img/index/artemis.webp differ
diff --git a/public/img/index/atlas.webp b/public/img/index/atlas.webp
new file mode 100644
index 0000000..73df086
Binary files /dev/null and b/public/img/index/atlas.webp differ
diff --git a/public/img/index/ember.webp b/public/img/index/ember.webp
new file mode 100644
index 0000000..606fb54
Binary files /dev/null and b/public/img/index/ember.webp differ
diff --git a/public/img/index/florae.webp b/public/img/index/florae.webp
new file mode 100644
index 0000000..e94e617
Binary files /dev/null and b/public/img/index/florae.webp differ
diff --git a/public/img/index/gambit.webp b/public/img/index/gambit.webp
new file mode 100644
index 0000000..349369e
Binary files /dev/null and b/public/img/index/gambit.webp differ
diff --git a/public/img/index/hangar.webp b/public/img/index/hangar.webp
new file mode 100644
index 0000000..e99f0cf
Binary files /dev/null and b/public/img/index/hangar.webp differ
diff --git a/public/img/index/horologie.webp b/public/img/index/horologie.webp
new file mode 100644
index 0000000..b31b8ec
Binary files /dev/null and b/public/img/index/horologie.webp differ
diff --git a/public/img/index/keeper.webp b/public/img/index/keeper.webp
new file mode 100644
index 0000000..17cd370
Binary files /dev/null and b/public/img/index/keeper.webp differ
diff --git a/public/img/index/koen.webp b/public/img/index/koen.webp
new file mode 100644
index 0000000..3a385b2
Binary files /dev/null and b/public/img/index/koen.webp differ
diff --git a/public/img/index/koi.webp b/public/img/index/koi.webp
new file mode 100644
index 0000000..9c6b724
Binary files /dev/null and b/public/img/index/koi.webp differ
diff --git a/public/img/index/lithos.webp b/public/img/index/lithos.webp
new file mode 100644
index 0000000..ac9b78b
Binary files /dev/null and b/public/img/index/lithos.webp differ
diff --git a/public/img/index/lowfreq.webp b/public/img/index/lowfreq.webp
new file mode 100644
index 0000000..443fc4f
Binary files /dev/null and b/public/img/index/lowfreq.webp differ
diff --git a/public/img/index/monolith.webp b/public/img/index/monolith.webp
new file mode 100644
index 0000000..c373e5b
Binary files /dev/null and b/public/img/index/monolith.webp differ
diff --git a/public/img/index/nocturne.webp b/public/img/index/nocturne.webp
new file mode 100644
index 0000000..ab76f0f
Binary files /dev/null and b/public/img/index/nocturne.webp differ
diff --git a/public/img/index/racer.webp b/public/img/index/racer.webp
new file mode 100644
index 0000000..7dd75e0
Binary files /dev/null and b/public/img/index/racer.webp differ
diff --git a/public/img/index/reliquary.webp b/public/img/index/reliquary.webp
new file mode 100644
index 0000000..238fae0
Binary files /dev/null and b/public/img/index/reliquary.webp differ
diff --git a/public/img/index/sucre.webp b/public/img/index/sucre.webp
new file mode 100644
index 0000000..15dcab7
Binary files /dev/null and b/public/img/index/sucre.webp differ
diff --git a/public/img/index/terrarium.webp b/public/img/index/terrarium.webp
new file mode 100644
index 0000000..9101447
Binary files /dev/null and b/public/img/index/terrarium.webp differ
diff --git a/public/img/index/velocity.webp b/public/img/index/velocity.webp
new file mode 100644
index 0000000..5409b16
Binary files /dev/null and b/public/img/index/velocity.webp differ
diff --git a/public/img/keeper/room-fog.webp b/public/img/keeper/room-fog.webp
new file mode 100644
index 0000000..fc909a8
Binary files /dev/null and b/public/img/keeper/room-fog.webp differ
diff --git a/public/img/keeper/room-lamp.webp b/public/img/keeper/room-lamp.webp
new file mode 100644
index 0000000..09a8fb4
Binary files /dev/null and b/public/img/keeper/room-lamp.webp differ
diff --git a/public/img/keeper/room-quarters.webp b/public/img/keeper/room-quarters.webp
new file mode 100644
index 0000000..4337229
Binary files /dev/null and b/public/img/keeper/room-quarters.webp differ
diff --git a/public/img/keeper/room-watch.webp b/public/img/keeper/room-watch.webp
new file mode 100644
index 0000000..03cf2a2
Binary files /dev/null and b/public/img/keeper/room-watch.webp differ
diff --git a/public/img/koen/azalea.webp b/public/img/koen/azalea.webp
new file mode 100644
index 0000000..280b8c4
Binary files /dev/null and b/public/img/koen/azalea.webp differ
diff --git a/public/img/koen/enso.webp b/public/img/koen/enso.webp
new file mode 100644
index 0000000..0e876b4
Binary files /dev/null and b/public/img/koen/enso.webp differ
diff --git a/public/img/koen/juniper.webp b/public/img/koen/juniper.webp
new file mode 100644
index 0000000..7980e1a
Binary files /dev/null and b/public/img/koen/juniper.webp differ
diff --git a/public/img/koen/pine.webp b/public/img/koen/pine.webp
new file mode 100644
index 0000000..56b57b8
Binary files /dev/null and b/public/img/koen/pine.webp differ
diff --git a/public/img/koen/quince.webp b/public/img/koen/quince.webp
new file mode 100644
index 0000000..f866aec
Binary files /dev/null and b/public/img/koen/quince.webp differ
diff --git a/public/img/koen/washi.webp b/public/img/koen/washi.webp
new file mode 100644
index 0000000..c88710e
Binary files /dev/null and b/public/img/koen/washi.webp differ
diff --git a/public/img/koi/canopy.webp b/public/img/koi/canopy.webp
new file mode 100644
index 0000000..f2e215b
Binary files /dev/null and b/public/img/koi/canopy.webp differ
diff --git a/public/img/koi/cookie.webp b/public/img/koi/cookie.webp
new file mode 100644
index 0000000..c01fb00
Binary files /dev/null and b/public/img/koi/cookie.webp differ
diff --git a/public/img/koi/floor.webp b/public/img/koi/floor.webp
new file mode 100644
index 0000000..7afb339
Binary files /dev/null and b/public/img/koi/floor.webp differ
diff --git a/public/img/koi/moss.webp b/public/img/koi/moss.webp
new file mode 100644
index 0000000..8b44a57
Binary files /dev/null and b/public/img/koi/moss.webp differ
diff --git a/public/img/koi/room-maple.webp b/public/img/koi/room-maple.webp
new file mode 100644
index 0000000..cb61d73
Binary files /dev/null and b/public/img/koi/room-maple.webp differ
diff --git a/public/img/koi/room-moon.webp b/public/img/koi/room-moon.webp
new file mode 100644
index 0000000..35e2c4b
Binary files /dev/null and b/public/img/koi/room-moon.webp differ
diff --git a/public/img/koi/room-moss.webp b/public/img/koi/room-moss.webp
new file mode 100644
index 0000000..3abf00c
Binary files /dev/null and b/public/img/koi/room-moss.webp differ
diff --git a/public/img/lithos/miner.webp b/public/img/lithos/miner.webp
new file mode 100644
index 0000000..d959574
Binary files /dev/null and b/public/img/lithos/miner.webp differ
diff --git a/public/img/lithos/pendant.webp b/public/img/lithos/pendant.webp
new file mode 100644
index 0000000..e520cc1
Binary files /dev/null and b/public/img/lithos/pendant.webp differ
diff --git a/public/img/lithos/ring.webp b/public/img/lithos/ring.webp
new file mode 100644
index 0000000..a0df6af
Binary files /dev/null and b/public/img/lithos/ring.webp differ
diff --git a/public/img/lithos/studs.webp b/public/img/lithos/studs.webp
new file mode 100644
index 0000000..ac048c4
Binary files /dev/null and b/public/img/lithos/studs.webp differ
diff --git a/public/img/lowfreq/aubergine.webp b/public/img/lowfreq/aubergine.webp
new file mode 100644
index 0000000..ba56ab2
Binary files /dev/null and b/public/img/lowfreq/aubergine.webp differ
diff --git a/public/img/lowfreq/counter.webp b/public/img/lowfreq/counter.webp
new file mode 100644
index 0000000..06e4e27
Binary files /dev/null and b/public/img/lowfreq/counter.webp differ
diff --git a/public/img/lowfreq/geometry.webp b/public/img/lowfreq/geometry.webp
new file mode 100644
index 0000000..99951da
Binary files /dev/null and b/public/img/lowfreq/geometry.webp differ
diff --git a/public/img/lowfreq/rain.webp b/public/img/lowfreq/rain.webp
new file mode 100644
index 0000000..dea993e
Binary files /dev/null and b/public/img/lowfreq/rain.webp differ
diff --git a/public/img/lowfreq/tidal.webp b/public/img/lowfreq/tidal.webp
new file mode 100644
index 0000000..f67b84a
Binary files /dev/null and b/public/img/lowfreq/tidal.webp differ
diff --git a/public/img/lowfreq/valves.webp b/public/img/lowfreq/valves.webp
new file mode 100644
index 0000000..3635052
Binary files /dev/null and b/public/img/lowfreq/valves.webp differ
diff --git a/public/img/monolith/lajes.webp b/public/img/monolith/lajes.webp
new file mode 100644
index 0000000..2265778
Binary files /dev/null and b/public/img/monolith/lajes.webp differ
diff --git a/public/img/monolith/mertola.webp b/public/img/monolith/mertola.webp
new file mode 100644
index 0000000..82117b2
Binary files /dev/null and b/public/img/monolith/mertola.webp differ
diff --git a/public/img/monolith/stal.webp b/public/img/monolith/stal.webp
new file mode 100644
index 0000000..0d426b0
Binary files /dev/null and b/public/img/monolith/stal.webp differ
diff --git a/public/img/monolith/studio.webp b/public/img/monolith/studio.webp
new file mode 100644
index 0000000..3396433
Binary files /dev/null and b/public/img/monolith/studio.webp differ
diff --git a/public/img/monolith/ulvik.webp b/public/img/monolith/ulvik.webp
new file mode 100644
index 0000000..4b7d1df
Binary files /dev/null and b/public/img/monolith/ulvik.webp differ
diff --git a/public/img/racer/asphalt.webp b/public/img/racer/asphalt.webp
new file mode 100644
index 0000000..a8db520
Binary files /dev/null and b/public/img/racer/asphalt.webp differ
diff --git a/public/img/racer/brick.webp b/public/img/racer/brick.webp
new file mode 100644
index 0000000..e3cd1de
Binary files /dev/null and b/public/img/racer/brick.webp differ
diff --git a/public/img/racer/city.webp b/public/img/racer/city.webp
new file mode 100644
index 0000000..a9d6510
Binary files /dev/null and b/public/img/racer/city.webp differ
diff --git a/public/img/racer/shutter.webp b/public/img/racer/shutter.webp
new file mode 100644
index 0000000..d24451c
Binary files /dev/null and b/public/img/racer/shutter.webp differ
diff --git a/public/img/racer/workshop.webp b/public/img/racer/workshop.webp
new file mode 100644
index 0000000..00bc8c4
Binary files /dev/null and b/public/img/racer/workshop.webp differ
diff --git a/public/img/reliquary/court.webp b/public/img/reliquary/court.webp
new file mode 100644
index 0000000..69ef860
Binary files /dev/null and b/public/img/reliquary/court.webp differ
diff --git a/public/models/abyssal/angler.glb b/public/models/abyssal/angler.glb
new file mode 100644
index 0000000..1641285
Binary files /dev/null and b/public/models/abyssal/angler.glb differ
diff --git a/public/models/abyssal/nautilus.glb b/public/models/abyssal/nautilus.glb
new file mode 100644
index 0000000..a8c28f7
Binary files /dev/null and b/public/models/abyssal/nautilus.glb differ
diff --git a/public/models/abyssal/sub.glb b/public/models/abyssal/sub.glb
new file mode 100644
index 0000000..c480d1f
Binary files /dev/null and b/public/models/abyssal/sub.glb differ
diff --git a/public/models/abyssal/vent.glb b/public/models/abyssal/vent.glb
new file mode 100644
index 0000000..bceddd3
Binary files /dev/null and b/public/models/abyssal/vent.glb differ
diff --git a/public/models/artemis/astro-rig.glb b/public/models/artemis/astro-rig.glb
new file mode 100644
index 0000000..92f0c6c
Binary files /dev/null and b/public/models/artemis/astro-rig.glb differ
diff --git a/public/models/artemis/astro.animation_glb.glb b/public/models/artemis/astro.animation_glb.glb
new file mode 100644
index 0000000..93006a7
Binary files /dev/null and b/public/models/artemis/astro.animation_glb.glb differ
diff --git a/public/models/artemis/astro.glb b/public/models/artemis/astro.glb
new file mode 100644
index 0000000..ed75b4c
Binary files /dev/null and b/public/models/artemis/astro.glb differ
diff --git a/public/models/artemis/astro.rigged_character_glb.glb b/public/models/artemis/astro.rigged_character_glb.glb
new file mode 100644
index 0000000..a62d3f4
Binary files /dev/null and b/public/models/artemis/astro.rigged_character_glb.glb differ
diff --git a/public/models/artemis/astro.running_armature_glb.glb b/public/models/artemis/astro.running_armature_glb.glb
new file mode 100644
index 0000000..cb4c863
Binary files /dev/null and b/public/models/artemis/astro.running_armature_glb.glb differ
diff --git a/public/models/artemis/astro.running_glb.glb b/public/models/artemis/astro.running_glb.glb
new file mode 100644
index 0000000..3590665
Binary files /dev/null and b/public/models/artemis/astro.running_glb.glb differ
diff --git a/public/models/artemis/astro.walking_armature_glb.glb b/public/models/artemis/astro.walking_armature_glb.glb
new file mode 100644
index 0000000..1ad9543
Binary files /dev/null and b/public/models/artemis/astro.walking_armature_glb.glb differ
diff --git a/public/models/artemis/astro.walking_glb.glb b/public/models/artemis/astro.walking_glb.glb
new file mode 100644
index 0000000..768b01c
Binary files /dev/null and b/public/models/artemis/astro.walking_glb.glb differ
diff --git a/public/models/artemis/lander.glb b/public/models/artemis/lander.glb
new file mode 100644
index 0000000..d8e77d3
Binary files /dev/null and b/public/models/artemis/lander.glb differ
diff --git a/public/models/atlas/falls.glb b/public/models/atlas/falls.glb
new file mode 100644
index 0000000..5d79b69
Binary files /dev/null and b/public/models/atlas/falls.glb differ
diff --git a/public/models/atlas/lighthouse.glb b/public/models/atlas/lighthouse.glb
new file mode 100644
index 0000000..da11f91
Binary files /dev/null and b/public/models/atlas/lighthouse.glb differ
diff --git a/public/models/atlas/pagoda.glb b/public/models/atlas/pagoda.glb
new file mode 100644
index 0000000..87e481c
Binary files /dev/null and b/public/models/atlas/pagoda.glb differ
diff --git a/public/models/atlas/windmill.glb b/public/models/atlas/windmill.glb
new file mode 100644
index 0000000..e00103a
Binary files /dev/null and b/public/models/atlas/windmill.glb differ
diff --git a/public/models/ember/anvil.glb b/public/models/ember/anvil.glb
new file mode 100644
index 0000000..4fcf9b4
Binary files /dev/null and b/public/models/ember/anvil.glb differ
diff --git a/public/models/ember/hammer.glb b/public/models/ember/hammer.glb
new file mode 100644
index 0000000..5c5c990
Binary files /dev/null and b/public/models/ember/hammer.glb differ
diff --git a/public/models/ember/sword.glb b/public/models/ember/sword.glb
new file mode 100644
index 0000000..91ab954
Binary files /dev/null and b/public/models/ember/sword.glb differ
diff --git a/public/models/florae/morpho.glb b/public/models/florae/morpho.glb
new file mode 100644
index 0000000..8db525d
Binary files /dev/null and b/public/models/florae/morpho.glb differ
diff --git a/public/models/florae/orchid.glb b/public/models/florae/orchid.glb
new file mode 100644
index 0000000..dc7a192
Binary files /dev/null and b/public/models/florae/orchid.glb differ
diff --git a/public/models/florae/protea.glb b/public/models/florae/protea.glb
new file mode 100644
index 0000000..39bcb92
Binary files /dev/null and b/public/models/florae/protea.glb differ
diff --git a/public/models/florae/rose.glb b/public/models/florae/rose.glb
new file mode 100644
index 0000000..e37a03d
Binary files /dev/null and b/public/models/florae/rose.glb differ
diff --git a/public/models/gambit/bishop.glb b/public/models/gambit/bishop.glb
new file mode 100644
index 0000000..cbfc881
Binary files /dev/null and b/public/models/gambit/bishop.glb differ
diff --git a/public/models/gambit/far-bishop.glb b/public/models/gambit/far-bishop.glb
new file mode 100644
index 0000000..03f83fe
Binary files /dev/null and b/public/models/gambit/far-bishop.glb differ
diff --git a/public/models/gambit/far-king.glb b/public/models/gambit/far-king.glb
new file mode 100644
index 0000000..b5e435f
Binary files /dev/null and b/public/models/gambit/far-king.glb differ
diff --git a/public/models/gambit/far-knight.glb b/public/models/gambit/far-knight.glb
new file mode 100644
index 0000000..fb0c927
Binary files /dev/null and b/public/models/gambit/far-knight.glb differ
diff --git a/public/models/gambit/far-pawn.glb b/public/models/gambit/far-pawn.glb
new file mode 100644
index 0000000..64c0107
Binary files /dev/null and b/public/models/gambit/far-pawn.glb differ
diff --git a/public/models/gambit/far-queen.glb b/public/models/gambit/far-queen.glb
new file mode 100644
index 0000000..9b42ff1
Binary files /dev/null and b/public/models/gambit/far-queen.glb differ
diff --git a/public/models/gambit/far-rook.glb b/public/models/gambit/far-rook.glb
new file mode 100644
index 0000000..070c86b
Binary files /dev/null and b/public/models/gambit/far-rook.glb differ
diff --git a/public/models/gambit/king.glb b/public/models/gambit/king.glb
new file mode 100644
index 0000000..7638cc5
Binary files /dev/null and b/public/models/gambit/king.glb differ
diff --git a/public/models/gambit/knight.glb b/public/models/gambit/knight.glb
new file mode 100644
index 0000000..6593adf
Binary files /dev/null and b/public/models/gambit/knight.glb differ
diff --git a/public/models/gambit/pawn-lo.glb b/public/models/gambit/pawn-lo.glb
new file mode 100644
index 0000000..126c5bd
Binary files /dev/null and b/public/models/gambit/pawn-lo.glb differ
diff --git a/public/models/gambit/pawn.glb b/public/models/gambit/pawn.glb
new file mode 100644
index 0000000..f14ddb9
Binary files /dev/null and b/public/models/gambit/pawn.glb differ
diff --git a/public/models/gambit/queen.glb b/public/models/gambit/queen.glb
new file mode 100644
index 0000000..eb72cf0
Binary files /dev/null and b/public/models/gambit/queen.glb differ
diff --git a/public/models/gambit/rook.glb b/public/models/gambit/rook.glb
new file mode 100644
index 0000000..dfd438b
Binary files /dev/null and b/public/models/gambit/rook.glb differ
diff --git a/public/models/hangar/drone.glb b/public/models/hangar/drone.glb
new file mode 100644
index 0000000..7eb678b
Binary files /dev/null and b/public/models/hangar/drone.glb differ
diff --git a/public/models/hangar/mech.glb b/public/models/hangar/mech.glb
new file mode 100644
index 0000000..c0c34c1
Binary files /dev/null and b/public/models/hangar/mech.glb differ
diff --git a/public/models/horologie/watch.glb b/public/models/horologie/watch.glb
new file mode 100644
index 0000000..691de43
Binary files /dev/null and b/public/models/horologie/watch.glb differ
diff --git a/public/models/keeper/boat.glb b/public/models/keeper/boat.glb
new file mode 100644
index 0000000..b3224c1
Binary files /dev/null and b/public/models/keeper/boat.glb differ
diff --git a/public/models/keeper/lighthouse.glb b/public/models/keeper/lighthouse.glb
new file mode 100644
index 0000000..6f31c64
Binary files /dev/null and b/public/models/keeper/lighthouse.glb differ
diff --git a/public/models/koen/maple.glb b/public/models/koen/maple.glb
new file mode 100644
index 0000000..f8e4247
Binary files /dev/null and b/public/models/koen/maple.glb differ
diff --git a/public/models/koen/maple2.glb b/public/models/koen/maple2.glb
new file mode 100644
index 0000000..5cd0f79
Binary files /dev/null and b/public/models/koen/maple2.glb differ
diff --git a/public/models/koi/kohaku.glb b/public/models/koi/kohaku.glb
new file mode 100644
index 0000000..e90914f
Binary files /dev/null and b/public/models/koi/kohaku.glb differ
diff --git a/public/models/koi/lantern.glb b/public/models/koi/lantern.glb
new file mode 100644
index 0000000..8f5a12a
Binary files /dev/null and b/public/models/koi/lantern.glb differ
diff --git a/public/models/koi/lotus.glb b/public/models/koi/lotus.glb
new file mode 100644
index 0000000..d5ea20e
Binary files /dev/null and b/public/models/koi/lotus.glb differ
diff --git a/public/models/koi/showa.glb b/public/models/koi/showa.glb
new file mode 100644
index 0000000..9e31076
Binary files /dev/null and b/public/models/koi/showa.glb differ
diff --git a/public/models/lithos/ammonite.glb b/public/models/lithos/ammonite.glb
new file mode 100644
index 0000000..4e0946e
Binary files /dev/null and b/public/models/lithos/ammonite.glb differ
diff --git a/public/models/lithos/geode.glb b/public/models/lithos/geode.glb
new file mode 100644
index 0000000..9a5acd9
Binary files /dev/null and b/public/models/lithos/geode.glb differ
diff --git a/public/models/lithos/pyrite.glb b/public/models/lithos/pyrite.glb
new file mode 100644
index 0000000..dbf6926
Binary files /dev/null and b/public/models/lithos/pyrite.glb differ
diff --git a/public/models/lithos/quartz.glb b/public/models/lithos/quartz.glb
new file mode 100644
index 0000000..2fdd4cb
Binary files /dev/null and b/public/models/lithos/quartz.glb differ
diff --git a/public/models/lowfreq/speaker.glb b/public/models/lowfreq/speaker.glb
new file mode 100644
index 0000000..e70eb49
Binary files /dev/null and b/public/models/lowfreq/speaker.glb differ
diff --git a/public/models/lowfreq/turntable.glb b/public/models/lowfreq/turntable.glb
new file mode 100644
index 0000000..296032f
Binary files /dev/null and b/public/models/lowfreq/turntable.glb differ
diff --git a/public/models/monolith/house.glb b/public/models/monolith/house.glb
new file mode 100644
index 0000000..8ea854d
Binary files /dev/null and b/public/models/monolith/house.glb differ
diff --git a/public/models/nocturne/bergamot.glb b/public/models/nocturne/bergamot.glb
new file mode 100644
index 0000000..494e6b6
Binary files /dev/null and b/public/models/nocturne/bergamot.glb differ
diff --git a/public/models/nocturne/cap.glb b/public/models/nocturne/cap.glb
new file mode 100644
index 0000000..cd7a910
Binary files /dev/null and b/public/models/nocturne/cap.glb differ
diff --git a/public/models/nocturne/iris.glb b/public/models/nocturne/iris.glb
new file mode 100644
index 0000000..e60dac0
Binary files /dev/null and b/public/models/nocturne/iris.glb differ
diff --git a/public/models/nocturne/oud.glb b/public/models/nocturne/oud.glb
new file mode 100644
index 0000000..8aacfc0
Binary files /dev/null and b/public/models/nocturne/oud.glb differ
diff --git a/public/models/nocturne/vanilla.glb b/public/models/nocturne/vanilla.glb
new file mode 100644
index 0000000..f993cd6
Binary files /dev/null and b/public/models/nocturne/vanilla.glb differ
diff --git a/public/models/pilot/astrolabe-lo.glb b/public/models/pilot/astrolabe-lo.glb
new file mode 100644
index 0000000..5420f39
Binary files /dev/null and b/public/models/pilot/astrolabe-lo.glb differ
diff --git a/public/models/pilot/astrolabe.glb b/public/models/pilot/astrolabe.glb
new file mode 100644
index 0000000..1641b25
Binary files /dev/null and b/public/models/pilot/astrolabe.glb differ
diff --git a/public/models/racer/bike.glb b/public/models/racer/bike.glb
new file mode 100644
index 0000000..9e83085
Binary files /dev/null and b/public/models/racer/bike.glb differ
diff --git a/public/models/racer/helmet.glb b/public/models/racer/helmet.glb
new file mode 100644
index 0000000..76a39bb
Binary files /dev/null and b/public/models/racer/helmet.glb differ
diff --git a/public/models/reliquary/amphora.glb b/public/models/reliquary/amphora.glb
new file mode 100644
index 0000000..87700b9
Binary files /dev/null and b/public/models/reliquary/amphora.glb differ
diff --git a/public/models/reliquary/astrolabe.glb b/public/models/reliquary/astrolabe.glb
new file mode 100644
index 0000000..1641b25
Binary files /dev/null and b/public/models/reliquary/astrolabe.glb differ
diff --git a/public/models/reliquary/bust.glb b/public/models/reliquary/bust.glb
new file mode 100644
index 0000000..ea7b582
Binary files /dev/null and b/public/models/reliquary/bust.glb differ
diff --git a/public/models/reliquary/guardian.glb b/public/models/reliquary/guardian.glb
new file mode 100644
index 0000000..118ca71
Binary files /dev/null and b/public/models/reliquary/guardian.glb differ
diff --git a/public/models/reliquary/helmet.glb b/public/models/reliquary/helmet.glb
new file mode 100644
index 0000000..8d18adc
Binary files /dev/null and b/public/models/reliquary/helmet.glb differ
diff --git a/public/models/reliquary/mask.glb b/public/models/reliquary/mask.glb
new file mode 100644
index 0000000..2a454cc
Binary files /dev/null and b/public/models/reliquary/mask.glb differ
diff --git a/public/models/sucre/cake.glb b/public/models/sucre/cake.glb
new file mode 100644
index 0000000..5ac4d2f
Binary files /dev/null and b/public/models/sucre/cake.glb differ
diff --git a/public/models/sucre/croissant-lo.glb b/public/models/sucre/croissant-lo.glb
new file mode 100644
index 0000000..c061486
Binary files /dev/null and b/public/models/sucre/croissant-lo.glb differ
diff --git a/public/models/sucre/croissant-shadow.glb b/public/models/sucre/croissant-shadow.glb
new file mode 100644
index 0000000..a48a884
Binary files /dev/null and b/public/models/sucre/croissant-shadow.glb differ
diff --git a/public/models/sucre/croissant.glb b/public/models/sucre/croissant.glb
new file mode 100644
index 0000000..24a1af3
Binary files /dev/null and b/public/models/sucre/croissant.glb differ
diff --git a/public/models/sucre/macaron-lo.glb b/public/models/sucre/macaron-lo.glb
new file mode 100644
index 0000000..9651d97
Binary files /dev/null and b/public/models/sucre/macaron-lo.glb differ
diff --git a/public/models/sucre/macaron-shadow.glb b/public/models/sucre/macaron-shadow.glb
new file mode 100644
index 0000000..bc28636
Binary files /dev/null and b/public/models/sucre/macaron-shadow.glb differ
diff --git a/public/models/sucre/macaron.glb b/public/models/sucre/macaron.glb
new file mode 100644
index 0000000..68a096b
Binary files /dev/null and b/public/models/sucre/macaron.glb differ
diff --git a/public/models/sucre/macaron2-lo.glb b/public/models/sucre/macaron2-lo.glb
new file mode 100644
index 0000000..e588a55
Binary files /dev/null and b/public/models/sucre/macaron2-lo.glb differ
diff --git a/public/models/sucre/macaron2-shadow.glb b/public/models/sucre/macaron2-shadow.glb
new file mode 100644
index 0000000..a58c467
Binary files /dev/null and b/public/models/sucre/macaron2-shadow.glb differ
diff --git a/public/models/sucre/macaron2.glb b/public/models/sucre/macaron2.glb
new file mode 100644
index 0000000..865ee93
Binary files /dev/null and b/public/models/sucre/macaron2.glb differ
diff --git a/public/models/sucre/strawberry-lo.glb b/public/models/sucre/strawberry-lo.glb
new file mode 100644
index 0000000..26ccc08
Binary files /dev/null and b/public/models/sucre/strawberry-lo.glb differ
diff --git a/public/models/sucre/strawberry-shadow.glb b/public/models/sucre/strawberry-shadow.glb
new file mode 100644
index 0000000..9818cae
Binary files /dev/null and b/public/models/sucre/strawberry-shadow.glb differ
diff --git a/public/models/sucre/strawberry.glb b/public/models/sucre/strawberry.glb
new file mode 100644
index 0000000..e04c7b9
Binary files /dev/null and b/public/models/sucre/strawberry.glb differ
diff --git a/public/models/sucre/tart-lo.glb b/public/models/sucre/tart-lo.glb
new file mode 100644
index 0000000..f6d919b
Binary files /dev/null and b/public/models/sucre/tart-lo.glb differ
diff --git a/public/models/sucre/tart-shadow.glb b/public/models/sucre/tart-shadow.glb
new file mode 100644
index 0000000..621edc9
Binary files /dev/null and b/public/models/sucre/tart-shadow.glb differ
diff --git a/public/models/sucre/tart.glb b/public/models/sucre/tart.glb
new file mode 100644
index 0000000..f15f094
Binary files /dev/null and b/public/models/sucre/tart.glb differ
diff --git a/public/models/terrarium/desert.glb b/public/models/terrarium/desert.glb
new file mode 100644
index 0000000..b7b84ba
Binary files /dev/null and b/public/models/terrarium/desert.glb differ
diff --git a/public/models/terrarium/moss.glb b/public/models/terrarium/moss.glb
new file mode 100644
index 0000000..ca79204
Binary files /dev/null and b/public/models/terrarium/moss.glb differ
diff --git a/public/models/terrarium/tropic.glb b/public/models/terrarium/tropic.glb
new file mode 100644
index 0000000..f74efef
Binary files /dev/null and b/public/models/terrarium/tropic.glb differ
diff --git a/public/models/velocity/black.glb b/public/models/velocity/black.glb
new file mode 100644
index 0000000..ad2c8cf
Binary files /dev/null and b/public/models/velocity/black.glb differ
diff --git a/public/models/velocity/white.glb b/public/models/velocity/white.glb
new file mode 100644
index 0000000..ec9fe77
Binary files /dev/null and b/public/models/velocity/white.glb differ
diff --git a/scripts/contact.mjs b/scripts/contact.mjs
new file mode 100644
index 0000000..c5f452d
--- /dev/null
+++ b/scripts/contact.mjs
@@ -0,0 +1,22 @@
+// Contact sheet: node scripts/contact.mjs <outPrefix> <cols> <cell> file...
+import sharp from 'sharp';
+import path from 'node:path';
+const [, , out, colsS, cellS, ...files] = process.argv;
+const cols = +colsS, cell = +cellS, per = cols * Math.ceil(12 / cols);
+const meta0 = await sharp(files[0]).metadata();
+const cellH = Math.round(cell * meta0.height / meta0.width);
+for (let s = 0; s * per < files.length; s++) {
+ const chunk = files.slice(s * per, (s + 1) * per);
+ const rows = Math.ceil(chunk.length / cols);
+ const comps = [];
+ for (let i = 0; i < chunk.length; i++) {
+ const f = chunk[i];
+ const img = await sharp(f).resize(cell, cellH, { fit: 'contain', background: '#ffffff' }).toBuffer();
+ const x = (i % cols) * cell, y = Math.floor(i / cols) * (cellH + 22);
+ comps.push({ input: img, left: x, top: y + 22 });
+ const label = Buffer.from(`<svg width="${cell}" height="22"><rect width="100%" height="100%" fill="#111"/><text x="6" y="16" font-family="monospace" font-size="14" fill="#fff">${path.basename(f)}</text></svg>`);
+ comps.push({ input: label, left: x, top: y });
+ }
+ await sharp({ create: { width: cols * cell, height: rows * (cellH + 22), channels: 3, background: '#222' } }).composite(comps).jpeg({ quality: 82 }).toFile(`${out}-${s}.jpg`);
+ console.log(`${out}-${s}.jpg`);
+}
diff --git a/scripts/errors.mjs b/scripts/errors.mjs
new file mode 100644
index 0000000..b0f7b25
--- /dev/null
+++ b/scripts/errors.mjs
@@ -0,0 +1,9 @@
+// Print full console errors for a page: node scripts/errors.mjs <url> [waitMs]
+import { chromium } from 'playwright';
+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=d3d11', '--ignore-gpu-blocklist', '--enable-gpu'] });
+const p = await b.newPage({ viewport: { width: 1440, height: 900 } });
+p.on('console', m => { if (m.type() === 'error') console.log('[error]', m.text().slice(0, 3000)); });
+p.on('pageerror', e => console.log('[pageerror]', e.message));
+await p.goto(process.argv[2], { waitUntil: 'load' });
+await p.waitForTimeout(+(process.argv[3] ?? 4000));
+await b.close();
diff --git a/scripts/fal.mjs b/scripts/fal.mjs
new file mode 100644
index 0000000..8a22bf5
--- /dev/null
+++ b/scripts/fal.mjs
@@ -0,0 +1,50 @@
+// Shared fal client. Reads FAL_KEY from the environment or a .env file in the project root.
+import { config } from 'dotenv';
+import { fal } from '@fal-ai/client';
+import fs from 'node:fs';
+import path from 'node:path';
+
+config({ quiet: true });
+if (!process.env.FAL_KEY) throw new Error('FAL_KEY missing: copy .env.example to .env and add your fal key');
+fal.config({ credentials: process.env.FAL_KEY });
+
+export { fal };
+
+export const ROOT = path.resolve(import.meta.dirname, '..');
+const MANIFEST = path.join(ROOT, 'assets', 'manifest.json');
+
+export function readManifest() {
+ try { return JSON.parse(fs.readFileSync(MANIFEST, 'utf8')); } catch { return { images: {}, meshes: {} }; }
+}
+// Serialize manifest writes so concurrent jobs never clobber each other.
+let chain = Promise.resolve();
+export function updateManifest(fn) {
+ chain = chain.then(() => {
+ const m = readManifest();
+ fn(m);
+ fs.writeFileSync(MANIFEST, JSON.stringify(m, null, 2));
+ });
+ return chain;
+}
+
+export async function download(url, dest) {
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
+ for (let attempt = 0; attempt < 4; attempt++) {
+ try {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ fs.writeFileSync(dest, Buffer.from(await res.arrayBuffer()));
+ return dest;
+ } catch (e) {
+ if (attempt === 3) throw e;
+ await new Promise(r => setTimeout(r, 2000 * (attempt + 1)));
+ }
+ }
+}
+
+export async function uploadFile(file) {
+ const buf = fs.readFileSync(file);
+ const ext = path.extname(file).slice(1).toLowerCase();
+ const type = ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : ext === 'webp' ? 'image/webp' : 'image/png';
+ return fal.storage.upload(new Blob([buf], { type }));
+}
diff --git a/scripts/fetch-rig.mjs b/scripts/fetch-rig.mjs
new file mode 100644
index 0000000..3feb26e
--- /dev/null
+++ b/scripts/fetch-rig.mjs
@@ -0,0 +1,12 @@
+import { fal, readManifest, download } from './fal.mjs';
+const id = process.argv[2];
+const m = readManifest().meshes[id];
+const r = await fal.queue.result(m.endpoint, { requestId: m.request_id });
+const d = r.data;
+const out = {};
+for (const k of ['rigged_character_glb', 'animation_glb']) if (d[k]?.url) { await download(d[k].url, `assets/raw/${id}.${k}.glb`); out[k] = d[k].file_size; }
+if (d.basic_animations) {
+ console.log('basic_animations keys', Object.keys(d.basic_animations));
+ for (const [k, v] of Object.entries(d.basic_animations)) if (v?.url && /glb/i.test(k + v.url)) { await download(v.url, `assets/raw/${id}.${k}.glb`); out[k] = v.file_size; }
+}
+console.log(out);
diff --git a/scripts/gen.mjs b/scripts/gen.mjs
new file mode 100644
index 0000000..57d3c39
--- /dev/null
+++ b/scripts/gen.mjs
@@ -0,0 +1,130 @@
+// Asset generation pipeline: Nano Banana 2 (clean reference images) -> Meshy 7.1 (image to 3D).
+//
+// node scripts/gen.mjs images assets/jobs/foo.json [--force id,id]
+// node scripts/gen.mjs meshes assets/jobs/foo.json [--force id,id]
+// node scripts/gen.mjs all assets/jobs/foo.json
+//
+// Every request id is written to assets/manifest.json before polling, so a crashed run resumes
+// instead of paying for the same model twice.
+import fs from 'node:fs';
+import path from 'node:path';
+import { fal, ROOT, readManifest, updateManifest, download, uploadFile } from './fal.mjs';
+
+const NB2 = 'fal-ai/nano-banana-2';
+const NB2_EDIT = 'fal-ai/nano-banana-2/edit';
+const MESHY = 'meshy/v7.1/image-to-3d';
+const MESHY_MULTI = 'meshy/v7.1/multi-image-to-3d';
+
+const [, , mode, jobFile, ...rest] = process.argv;
+const forceIdx = rest.indexOf('--force');
+const force = new Set(forceIdx >= 0 ? rest[forceIdx + 1].split(',') : []);
+const onlyIdx = rest.indexOf('--only');
+const only = onlyIdx >= 0 ? new Set(rest[onlyIdx + 1].split(',')) : null;
+const jobs = JSON.parse(fs.readFileSync(jobFile, 'utf8'));
+const log = (...a) => console.log(new Date().toISOString().slice(11, 19), ...a);
+
+async function pool(items, n, fn) {
+ const out = [];
+ let i = 0;
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, async () => {
+ while (i < items.length) {
+ const idx = i++;
+ try { out[idx] = await fn(items[idx]); } catch (e) { log('FAIL', items[idx].id, e.message, JSON.stringify(e.body ?? '').slice(0, 400)); }
+ }
+ }));
+ return out;
+}
+
+const STYLE_SUFFIX = ' Single isolated object, centered, full object visible with generous margin, three-quarter view from slightly above, ' +
+ 'plain pure white seamless studio background, soft even diffuse lighting, no cast shadows on background, no text, no watermark, ' +
+ 'ultra detailed, sharp focus, product-render clarity, physically plausible materials.';
+
+async function genImage(job) {
+ const m = readManifest();
+ const dest = path.join(ROOT, 'assets', 'src', `${job.id}.png`);
+ if (m.images[job.id] && fs.existsSync(dest) && !force.has(job.id)) { log('skip image', job.id); return; }
+ const prompt = job.raw ? job.prompt : job.prompt + STYLE_SUFFIX;
+ const input = {
+ prompt,
+ aspect_ratio: job.aspect_ratio ?? '1:1',
+ resolution: job.resolution ?? '2K',
+ output_format: 'png',
+ num_images: 1,
+ safety_tolerance: '5',
+ };
+ if (job.thinking) input.thinking_level = job.thinking;
+ let endpoint = NB2;
+ if (job.edit_from) {
+ endpoint = NB2_EDIT;
+ input.image_urls = job.edit_from.map(id => readManifest().images[id].url);
+ }
+ log('image ->', job.id);
+ const r = await fal.subscribe(endpoint, { input });
+ const url = r.data.images[0].url;
+ await download(url, dest);
+ await updateManifest(mm => { mm.images[job.id] = { url, prompt: job.prompt, endpoint, at: new Date().toISOString() }; });
+ log('image OK', job.id);
+}
+
+async function genMesh(job) {
+ const dest = path.join(ROOT, 'assets', 'raw', `${job.id}.glb`);
+ let m = readManifest();
+ if (fs.existsSync(dest) && !force.has(job.id)) { log('skip mesh', job.id); return; }
+ const entry = m.meshes[job.id];
+ const multi = Array.isArray(job.images) && job.images.length > 1;
+ const endpoint = multi ? MESHY_MULTI : MESHY;
+ let requestId = entry?.request_id && !force.has(job.id) && entry.status !== 'failed' ? entry.request_id : null;
+
+ if (!requestId) {
+ const imgIds = multi ? job.images : [job.image ?? job.id];
+ const urls = [];
+ for (const id of imgIds) {
+ const local = path.join(ROOT, 'assets', 'src', `${id}.png`);
+ // Prefer a locally edited reference (e.g. background-cleaned) when it has been re-saved.
+ const known = readManifest().images[id]?.url;
+ urls.push(job.upload || !known ? await uploadFile(local) : known);
+ }
+ const input = {
+ topology: 'triangle',
+ target_polycount: job.polycount ?? 150000,
+ symmetry_mode: job.symmetry ?? 'auto',
+ should_remesh: job.remesh ?? true,
+ should_texture: true,
+ enable_pbr: job.pbr ?? true,
+ enable_safety_checker: false,
+ ...(job.opts ?? {}),
+ };
+ if (!multi) { input.geometry_resolution = job.geometry ?? '4k'; input.model_type = job.model_type ?? 'standard'; }
+ if (multi) input.image_urls = urls; else input.image_url = urls[0];
+ if (job.texture_prompt) input.texture_prompt = job.texture_prompt;
+ const sub = await fal.queue.submit(endpoint, { input });
+ requestId = sub.request_id;
+ await updateManifest(mm => { mm.meshes[job.id] = { request_id: requestId, endpoint, input, status: 'queued', at: new Date().toISOString() }; });
+ log('mesh submitted', job.id, requestId);
+ }
+
+ const t0 = Date.now();
+ for (;;) {
+ const st = await fal.queue.status(endpoint, { requestId, logs: false });
+ if (st.status === 'COMPLETED') break;
+ if (Date.now() - t0 > 40 * 60e3) throw new Error('timeout');
+ await new Promise(r => setTimeout(r, 10000));
+ }
+ let res;
+ try {
+ res = await fal.queue.result(endpoint, { requestId });
+ } catch (e) {
+ await updateManifest(mm => { mm.meshes[job.id].status = 'failed'; mm.meshes[job.id].error = String(e.message); });
+ throw e;
+ }
+ const d = res.data;
+ await download(d.model_glb.url, dest);
+ if (d.thumbnail?.url) await download(d.thumbnail.url, path.join(ROOT, 'assets', 'raw', `${job.id}.thumb.png`));
+ await updateManifest(mm => { Object.assign(mm.meshes[job.id], { status: 'done', glb: d.model_glb.url, size: d.model_glb.file_size, done: new Date().toISOString() }); });
+ log('mesh OK', job.id, `${(d.model_glb.file_size / 1e6).toFixed(1)}MB`, `${((Date.now() - t0) / 60e3).toFixed(1)}min`);
+}
+
+const filt = arr => (arr ?? []).filter(j => !only || only.has(j.id));
+if (mode === 'images' || mode === 'all') await pool(filt(jobs.images), 6, genImage);
+if (mode === 'meshes' || mode === 'all') await pool(filt(jobs.meshes), 20, genMesh);
+log('done');
diff --git a/scripts/model-sheet.mjs b/scripts/model-sheet.mjs
new file mode 100644
index 0000000..f7c710e
--- /dev/null
+++ b/scripts/model-sheet.mjs
@@ -0,0 +1,19 @@
+// Render every optimised model in the viewer (one browser) -> shots/models/<page>-<name>.png
+import { chromium } from 'playwright';
+import fs from 'node:fs';
+const files = [];
+for (const d of fs.readdirSync('public/models')) for (const f of fs.readdirSync(`public/models/${d}`)) if (f.endsWith('.glb') && !f.includes('-lo')) files.push(`models/${d}/${f}`);
+const only = process.argv[2];
+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=d3d11', '--ignore-gpu-blocklist', '--enable-gpu'] });
+const p = await b.newPage({ viewport: { width: 900, height: 900 } });
+fs.mkdirSync('shots/models', { recursive: true });
+for (const f of files) {
+ const out = `shots/models/${f.split('/').slice(1).join('-').replace('.glb', '')}.png`;
+ if (only ? !f.includes(only) : fs.existsSync(out)) continue;
+ await p.goto(`http://127.0.0.1:5190/examples/_viewer/?m=${f}&rot=-25&d=4.4&h=1.6&env=1.3`, { waitUntil: 'load' });
+ await p.waitForFunction(() => document.getElementById('i').textContent.length > 0, null, { timeout: 60000 }).catch(() => {});
+ await p.waitForTimeout(1200);
+ await p.screenshot({ path: out });
+ console.log(out);
+}
+await b.close();
diff --git a/scripts/optimize-all.mjs b/scripts/optimize-all.mjs
new file mode 100644
index 0000000..b5cda2a
--- /dev/null
+++ b/scripts/optimize-all.mjs
@@ -0,0 +1,28 @@
+// Optimise every finished raw mesh into public/models/<page>/<name>.glb (skips up-to-date outputs).
+import fs from 'node:fs';
+import path from 'node:path';
+import { execFile } from 'node:child_process';
+import { promisify } from 'node:util';
+const run = promisify(execFile);
+const PAGE = { reliq: 'reliquary', abyss: 'abyssal', ember: 'ember', terra: 'terrarium', koi: 'koi', flora: 'florae', velo: 'velocity',
+ hangar: 'hangar', sucre: 'sucre', mono: 'monolith', lf: 'lowfreq', gambit: 'gambit', atlas: 'atlas', lithos: 'lithos', artemis: 'artemis',
+ keeper: 'keeper', koen: 'koen', noct: 'nocturne', racer: 'racer', horo: 'horologie' };
+const raw = fs.readdirSync('assets/raw').filter(f => f.endsWith('.glb') && !f.startsWith('pilot'));
+const jobs = [];
+for (const f of raw) {
+ const id = f.replace('.glb', '');
+ const [pre, ...rest] = id.split('-');
+ const page = PAGE[pre]; if (!page) continue;
+ const out = `public/models/${page}/${rest.join('-')}.glb`;
+ const src = `assets/raw/${f}`;
+ if (fs.existsSync(out) && fs.statSync(out).mtimeMs > fs.statSync(src).mtimeMs) continue;
+ jobs.push([src, out]);
+}
+let i = 0;
+await Promise.all(Array.from({ length: 4 }, async () => {
+ while (i < jobs.length) {
+ const [src, out] = jobs[i++];
+ try { const { stdout } = await run('node', ['scripts/optimize.mjs', src, out, ...process.argv.slice(2)]); console.log(stdout.trim().split('\n').pop()); }
+ catch (e) { console.log('FAIL', src, e.message.slice(0, 200)); }
+ }
+}));
diff --git a/scripts/optimize.mjs b/scripts/optimize.mjs
new file mode 100644
index 0000000..0d074f4
--- /dev/null
+++ b/scripts/optimize.mjs
@@ -0,0 +1,34 @@
+// Compress a Meshy GLB for the web: weld, optional simplify, meshopt geometry, WebP textures.
+// node scripts/optimize.mjs <in.glb> <out.glb> [--ratio 0.5] [--tex 2048] [--q 88]
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { dedup, weld, simplify, meshopt, textureCompress, prune, reorder, quantize } from '@gltf-transform/functions';
+import { MeshoptSimplifier, MeshoptEncoder } from 'meshoptimizer';
+import sharp from 'sharp';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const [, , input, output, ...rest] = process.argv;
+const opt = (k, d) => { const i = rest.indexOf('--' + k); return i >= 0 ? rest[i + 1] : d; };
+const ratio = +opt('ratio', 1);
+const tex = +opt('tex', 2048);
+const q = +opt('q', 88);
+
+await MeshoptSimplifier.ready;
+await MeshoptEncoder.ready;
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({ 'meshopt.encoder': MeshoptEncoder });
+const doc = await io.read(input);
+const ops = [dedup(), weld()];
+if (ratio < 1) ops.push(simplify({ simplifier: MeshoptSimplifier, ratio, error: 0.0008, lockBorder: false }));
+ops.push(
+ textureCompress({ encoder: sharp, targetFormat: 'webp', resize: [tex, tex], quality: q }),
+ prune(),
+ reorder({ encoder: MeshoptEncoder }),
+ quantize({ quantizePosition: 16, quantizeNormal: 10, quantizeTexcoord: 14 }),
+);
+await doc.transform(...ops);
+await doc.transform(meshopt({ encoder: MeshoptEncoder, level: 'medium' }));
+fs.mkdirSync(path.dirname(output), { recursive: true });
+await io.write(output, doc);
+const tris = doc.getRoot().listMeshes().reduce((a, m) => a + m.listPrimitives().reduce((b, p) => b + (p.getIndices()?.getCount() ?? 0) / 3, 0), 0);
+console.log(`${path.basename(output)}: ${(fs.statSync(input).size / 1e6).toFixed(1)}MB -> ${(fs.statSync(output).size / 1e6).toFixed(2)}MB, ${Math.round(tris)} tris`);
diff --git a/scripts/review.mjs b/scripts/review.mjs
new file mode 100644
index 0000000..d872685
--- /dev/null
+++ b/scripts/review.mjs
@@ -0,0 +1,55 @@
+// Lead review battery: node scripts/review.mjs <slug> [stops=0,0.12,0.25,0.4,0.55,0.7,0.85,1]
+// Desktop shots at each stop + a mobile hero, stitched into shots/review/<slug>.jpg, plus console errors and fps.
+import { chromium } from 'playwright';
+import sharp from 'sharp';
+import fs from 'node:fs';
+
+const slug = process.argv[2];
+const stops = (process.argv[3] ?? '0,0.12,0.25,0.4,0.55,0.7,0.85,1').split(',').map(Number);
+const url = `http://127.0.0.1:5190/examples/${slug}/`;
+fs.mkdirSync(`shots/review/${slug}`, { recursive: true });
+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=d3d11', '--ignore-gpu-blocklist', '--enable-gpu'] });
+const errors = [];
+async function run(opts, fn) {
+ const ctx = await b.newContext(opts);
+ const p = await ctx.newPage();
+ p.on('console', m => { if (m.type() === 'error' && !/favicon|404/.test(m.text())) errors.push(m.text().slice(0, 200)); });
+ p.on('pageerror', e => errors.push('pageerror: ' + e.message.slice(0, 200)));
+ await p.goto(url, { waitUntil: 'load', timeout: 90000 });
+ await p.mouse.move(opts.viewport.width * 0.58, opts.viewport.height * 0.42, { steps: 6 });
+ await p.waitForTimeout(8000);
+ const r = await fn(p);
+ await ctx.close();
+ return r;
+}
+const shots = [];
+const fps = await run({ viewport: { width: 1440, height: 900 } }, async p => {
+ let f = [];
+ for (const [i, s] of stops.entries()) {
+ await p.evaluate(v => { const y = v * (document.documentElement.scrollHeight - innerHeight); window.__lenis ? window.__lenis.scrollTo(y, { immediate: true }) : scrollTo(0, y); }, s);
+ await p.mouse.move(1440 * (0.4 + (i % 3) * 0.1), 900 * 0.45, { steps: 4 });
+ await p.waitForTimeout(2200);
+ const path = `shots/review/${slug}/d${i}.png`;
+ await p.screenshot({ path }); shots.push(path);
+ f.push(await p.evaluate(() => window.__fps ?? null));
+ }
+ return f;
+});
+await run({ viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }, async p => {
+ const path = `shots/review/${slug}/m0.png`; await p.screenshot({ path }); shots.push(path);
+ await p.evaluate(() => { const y = 0.35 * (document.documentElement.scrollHeight - innerHeight); window.__lenis ? window.__lenis.scrollTo(y, { immediate: true }) : scrollTo(0, y); });
+ await p.waitForTimeout(2200);
+ const p2 = `shots/review/${slug}/m1.png`; await p.screenshot({ path: p2 }); shots.push(p2);
+});
+await b.close();
+
+// Sheet: desktop 2 columns at 720 wide, mobile pair appended as a row.
+const cw = 720, ch = 450;
+const desk = shots.filter(s => /\/d\d/.test(s)), mob = shots.filter(s => /\/m\d/.test(s));
+const rows = Math.ceil(desk.length / 2);
+const comps = [];
+for (const [i, s] of desk.entries()) comps.push({ input: await sharp(s).resize(cw, ch).toBuffer(), left: (i % 2) * cw, top: Math.floor(i / 2) * ch });
+const mh = 640, mw = Math.round(390 / 844 * mh);
+for (const [i, s] of mob.entries()) comps.push({ input: await sharp(s).resize(mw, mh).toBuffer(), left: i * (mw + 10), top: rows * ch });
+await sharp({ create: { width: cw * 2, height: rows * ch + mh, channels: 3, background: '#222' } }).composite(comps).jpeg({ quality: 80 }).toFile(`shots/review/${slug}.jpg`);
+console.log(JSON.stringify({ slug, fps, errors: [...new Set(errors)].slice(0, 8) }));
diff --git a/scripts/shot.mjs b/scripts/shot.mjs
new file mode 100644
index 0000000..25b9c0b
--- /dev/null
+++ b/scripts/shot.mjs
@@ -0,0 +1,60 @@
+// Headless GPU screenshots for QA.
+// node scripts/shot.mjs <url> <outPrefix> [--w 1440] [--h 900] [--wait 5000] [--scrolls 0,0.25,0.5,1] [--mouse 0.3,0.4] [--mobile]
+// Writes <outPrefix>-<i>.png per scroll stop and prints console errors + a WebGL renderer string.
+import { chromium } from 'playwright';
+import fs from 'node:fs';
+import path from 'node:path';
+
+const args = process.argv.slice(2);
+const url = args[0];
+const out = args[1];
+const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; };
+const flag = k => args.includes('--' + k);
+const mobile = flag('mobile');
+const W = +opt('w', mobile ? 390 : 1440), H = +opt('h', mobile ? 844 : 900);
+const wait = +opt('wait', 5000);
+const scrolls = opt('scrolls', '0').split(',').map(Number);
+const mouse = opt('mouse', null)?.split(',').map(Number);
+const actions = opt('actions', null);
+const click = opt('click', null)?.split(',').map(Number); // click at this NDC-ish (0..1) spot at every stop
+const clickWait = +opt('clickwait', 2600); // JS snippet run after load, e.g. "window.__demo?.()"
+
+fs.mkdirSync(path.dirname(out), { recursive: true });
+const browser = await chromium.launch({
+ channel: 'chrome',
+ headless: true,
+ args: ['--enable-gpu', '--ignore-gpu-blocklist', '--use-angle=d3d11', '--enable-unsafe-webgpu', '--autoplay-policy=no-user-gesture-required'],
+});
+const ctx = await browser.newContext({ viewport: { width: W, height: H }, deviceScaleFactor: 1, isMobile: mobile, hasTouch: mobile });
+const page = await ctx.newPage();
+const errors = [];
+page.on('console', m => { if (m.type() === 'error' || m.type() === 'warning') errors.push(`[${m.type()}] ${m.text()}`.slice(0, 300)); });
+page.on('pageerror', e => errors.push('[pageerror] ' + String(e.message).slice(0, 300)));
+const t0 = Date.now();
+await page.goto(url, { waitUntil: 'load', timeout: 90000 });
+if (mouse) await page.mouse.move(mouse[0] * W, mouse[1] * H, { steps: 8 });
+await page.waitForTimeout(wait);
+if (actions) await page.evaluate(actions);
+const info = await page.evaluate(() => {
+ const c = document.createElement('canvas').getContext('webgl2');
+ const ext = c?.getExtension('WEBGL_debug_renderer_info');
+ return { gl: ext ? c.getParameter(ext.UNMASKED_RENDERER_WEBGL) : 'none', docH: document.documentElement.scrollHeight, fps: window.__fps ?? null };
+});
+let i = 0;
+for (const s of scrolls) {
+ if (s > 0 || scrolls.length > 1) {
+ await page.evaluate(f => {
+ const y = f * (document.documentElement.scrollHeight - innerHeight);
+ if (window.__lenis) window.__lenis.scrollTo(y, { immediate: true }); else window.scrollTo(0, y);
+ }, s);
+ await page.waitForTimeout(+opt('settle', 1800));
+ }
+ if (mouse) await page.mouse.move(mouse[0] * W + 20, mouse[1] * H + 10, { steps: 4 });
+ if (click) { await page.mouse.move(click[0] * W, click[1] * H, { steps: 6 }); await page.waitForTimeout(400); await page.mouse.down(); await page.mouse.up(); await page.waitForTimeout(clickWait); }
+ await page.screenshot({ path: `${out}-${i}.png` });
+ i++;
+}
+const fps = await page.evaluate(() => window.__fps ?? null);
+console.log(JSON.stringify({ ...info, fps, loadMs: Date.now() - t0 }));
+if (errors.length) console.log(errors.slice(0, 15).join('\n'));
+await browser.close();
diff --git a/scripts/spot.mjs b/scripts/spot.mjs
new file mode 100644
index 0000000..cddc177
--- /dev/null
+++ b/scripts/spot.mjs
@@ -0,0 +1,17 @@
+// Quick hero spot-check of many pages in one browser: node scripts/spot.mjs slug,slug [scroll]
+import { chromium } from 'playwright';
+const slugs = process.argv[2].split(','); const sc = +(process.argv[3] ?? 0);
+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=d3d11', '--ignore-gpu-blocklist', '--enable-gpu'] });
+for (const s of slugs) {
+ const ctx = await b.newContext({ viewport: { width: 1440, height: 900 } }); const p = await ctx.newPage();
+ const errs = []; p.on('pageerror', e => errs.push(e.message.slice(0, 120)));
+ try {
+ await p.goto(`${process.env.BASE ?? 'http://127.0.0.1:5190'}/examples/${s}/`, { waitUntil: 'load', timeout: 60000 });
+ await p.mouse.move(830, 380, { steps: 5 }); await p.waitForTimeout(9000);
+ if (sc) { await p.evaluate(v => { const y = v * (document.documentElement.scrollHeight - innerHeight); window.__lenis ? window.__lenis.scrollTo(y, { immediate: true }) : scrollTo(0, y); }, sc); await p.waitForTimeout(2000); }
+ await p.screenshot({ path: `shots/spot/${process.env.TAG ?? ''}${s}-${sc}.png` });
+ console.log(s, 'ok', await p.evaluate(() => window.__fps), errs.join(' | '));
+ } catch (e) { console.log(s, 'fail', e.message.slice(0, 100)); }
+ await ctx.close();
+}
+await b.close();
diff --git a/scripts/thumbs.mjs b/scripts/thumbs.mjs
new file mode 100644
index 0000000..7d1db1e
--- /dev/null
+++ b/scripts/thumbs.mjs
@@ -0,0 +1,35 @@
+// Capture each world's hero as the gallery thumbnail: node scripts/thumbs.mjs [slug,slug]
+// A page can steer its own capture by defining window.__thumb = { mouse:[x,y], scroll: 0..1, wait: ms, js: 'code' } before load finishes.
+import { chromium } from 'playwright';
+import sharp from 'sharp';
+import fs from 'node:fs';
+
+const WORLDS = (await import('../src/core/worlds.js')).WORLDS;
+const only = process.argv[2]?.split(',');
+// Worlds whose best still is not the untouched hero.
+const OVERRIDE = { hangar: { scroll: 0.12, wait: 4000 }, lithos: { scroll: 0.25, wait: 4500 } };
+const b = await chromium.launch({ channel: 'chrome', headless: true, args: ['--use-angle=d3d11', '--ignore-gpu-blocklist', '--enable-gpu'] });
+fs.mkdirSync('shots/thumbs', { recursive: true });
+for (const w of WORLDS) {
+ if (only && !only.includes(w.slug)) continue;
+ if (!fs.existsSync(`examples/${w.slug}/index.html`)) { console.log('missing', w.slug); continue; }
+ const ctx = await b.newContext({ viewport: { width: 1440, height: 900 } });
+ const p = await ctx.newPage();
+ try {
+ await p.goto(`http://127.0.0.1:5190/examples/${w.slug}/`, { waitUntil: 'load', timeout: 90000 });
+ await p.mouse.move(820, 400, { steps: 5 });
+ await p.waitForTimeout(8000);
+ const cfg = OVERRIDE[w.slug] ?? await p.evaluate(() => window.__thumb ?? null);
+ if (cfg?.mouse) await p.mouse.move(cfg.mouse[0] * 1440, cfg.mouse[1] * 900, { steps: 10 });
+ if (cfg?.scroll) await p.evaluate(f => { const y = f * (document.documentElement.scrollHeight - innerHeight); window.__lenis ? window.__lenis.scrollTo(y, { immediate: true }) : scrollTo(0, y); }, cfg.scroll);
+ if (cfg?.js) await p.evaluate(cfg.js);
+ await p.waitForTimeout(cfg?.wait ?? 2500);
+ await p.evaluate(() => document.querySelectorAll('.tw-nav,.tw-cursor').forEach(e => e.style.display = 'none'));
+ const png = `shots/thumbs/${w.slug}.png`;
+ await p.screenshot({ path: png });
+ await sharp(png).resize(1280, 800).webp({ quality: 86 }).toFile(`public/img/index/${w.slug}.webp`);
+ console.log('ok', w.slug);
+ } catch (e) { console.log('fail', w.slug, e.message.slice(0, 120)); }
+ await ctx.close();
+}
+await b.close();
diff --git a/src/core/assets.js b/src/core/assets.js
new file mode 100644
index 0000000..fe354cd
--- /dev/null
+++ b/src/core/assets.js
@@ -0,0 +1,112 @@
+// Asset loading with one shared progress stream for the preloader.
+import * as THREE from 'three';
+import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
+import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
+import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
+import { RGBELoader } from 'three/examples/jsm/loaders/RGBELoader.js';
+import { MeshSurfaceSampler } from 'three/examples/jsm/math/MeshSurfaceSampler.js';
+
+export const BASE = import.meta.env.BASE_URL;
+export const url = p => (p.startsWith('http') ? p : BASE + p.replace(/^\//, ''));
+
+export class Assets {
+ constructor(onProgress) {
+ this.manager = new THREE.LoadingManager();
+ this.progress = 0;
+ this._listeners = onProgress ? [onProgress] : [];
+ // Byte-weighted progress: GLBs dominate load time, so count bytes where the server reports them.
+ this._bytes = new Map();
+ this.manager.onProgress = () => this._emit();
+ this.gltfLoader = new GLTFLoader(this.manager);
+ this.gltfLoader.setMeshoptDecoder(MeshoptDecoder);
+ this.tex = new THREE.TextureLoader(this.manager);
+ this.cache = new Map();
+ this._pending = 0;
+ this._done = 0;
+ }
+
+ onProgress(f) { this._listeners.push(f); }
+ _emit() {
+ let loaded = 0, total = 0;
+ for (const v of this._bytes.values()) { loaded += v.loaded; total += v.total || v.loaded || 1; }
+ const byteP = total ? loaded / total : 0;
+ const countP = this._pending ? this._done / this._pending : 1;
+ this.progress = Math.min(byteP * 0.8 + countP * 0.2, 1);
+ for (const f of this._listeners) f(this.progress);
+ }
+
+ gltf(path) {
+ const u = url(path);
+ if (this.cache.has(u)) return this.cache.get(u);
+ this._pending++;
+ this._bytes.set(u, { loaded: 0, total: 0 });
+ const p = new Promise((res, rej) => this.gltfLoader.load(u, g => { this._done++; this._emit(); res(g); },
+ e => { this._bytes.set(u, { loaded: e.loaded, total: e.total }); this._emit(); }, rej));
+ this.cache.set(u, p);
+ return p;
+ }
+
+ texture(path, { srgb = true, repeat = null, flipY = true } = {}) {
+ const u = url(path);
+ this._pending++;
+ return new Promise((res, rej) => this.tex.load(u, t => {
+ this._done++; this._emit();
+ if (srgb) t.colorSpace = THREE.SRGBColorSpace;
+ t.flipY = flipY;
+ if (repeat) { t.wrapS = t.wrapT = THREE.RepeatWrapping; t.repeat.set(...repeat); }
+ t.anisotropy = 8;
+ res(t);
+ }, undefined, rej));
+ }
+
+ hdr(path) {
+ const u = url(path);
+ this._pending++;
+ return new Promise((res, rej) => new RGBELoader(this.manager).load(u, t => { this._done++; this._emit(); t.mapping = THREE.EquirectangularReflectionMapping; res(t); }, undefined, rej));
+ }
+}
+
+/** First mesh in a glTF scene (Meshy exports a single textured mesh). */
+export function firstMesh(root) {
+ let m = null;
+ root.traverse(o => { if (!m && o.isMesh) m = o; });
+ return m;
+}
+
+/**
+ * Sample N points on a mesh surface, in the mesh's world space, with the texture colour at each point.
+ * Returns { position: Float32Array(3N), normal, color, uv }.
+ */
+export function sampleSurface(mesh, count, { colors = true } = {}) {
+ mesh.updateMatrixWorld(true);
+ const sampler = new MeshSurfaceSampler(mesh).build();
+ const pos = new Float32Array(count * 3), nor = new Float32Array(count * 3), col = new Float32Array(count * 3), uvs = new Float32Array(count * 2);
+ const p = new THREE.Vector3(), n = new THREE.Vector3(), c = new THREE.Color(), uv = new THREE.Vector2();
+ const nm = new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld);
+ let pixels = null, tw = 0, th = 0;
+ const map = mesh.material?.map;
+ if (colors && map?.image) {
+ const img = map.image;
+ tw = Math.min(img.width, 1024); th = Math.min(img.height, 1024);
+ const cv = document.createElement('canvas'); cv.width = tw; cv.height = th;
+ const cx = cv.getContext('2d', { willReadFrequently: true });
+ cx.drawImage(img, 0, 0, tw, th);
+ pixels = cx.getImageData(0, 0, tw, th).data;
+ }
+ for (let i = 0; i < count; i++) {
+ sampler.sample(p, n, c, uv);
+ p.applyMatrix4(mesh.matrixWorld);
+ n.applyMatrix3(nm).normalize();
+ pos.set([p.x, p.y, p.z], i * 3);
+ nor.set([n.x, n.y, n.z], i * 3);
+ uvs.set([uv.x, uv.y], i * 2);
+ if (pixels) {
+ const u = ((uv.x % 1) + 1) % 1, v = ((uv.y % 1) + 1) % 1;
+ const x = Math.floor(u * (tw - 1)), y = Math.floor((map.flipY ? 1 - v : v) * (th - 1));
+ const k = (y * tw + x) * 4;
+ c.setRGB(pixels[k] / 255, pixels[k + 1] / 255, pixels[k + 2] / 255, THREE.SRGBColorSpace);
+ col.set([c.r, c.g, c.b], i * 3);
+ } else col.set([1, 1, 1], i * 3);
+ }
+ return { position: pos, normal: nor, color: col, uv: uvs };
+}
diff --git a/src/core/engine.js b/src/core/engine.js
new file mode 100644
index 0000000..9e25aa7
--- /dev/null
+++ b/src/core/engine.js
@@ -0,0 +1,213 @@
+// Shared render core: renderer, camera, HDR post stack, frame loop.
+// Every page builds on this so tone mapping, AO and bloom behave identically across the collection.
+import * as THREE from 'three';
+import {
+ EffectComposer, RenderPass, EffectPass, BloomEffect, ToneMappingEffect, ToneMappingMode,
+ SMAAEffect, VignetteEffect, NoiseEffect, ChromaticAberrationEffect, BlendFunction,
+} from 'postprocessing';
+import { N8AOPostPass } from 'n8ao';
+
+export { THREE };
+
+const TONE = {
+ agx: ToneMappingMode.AGX, aces: ToneMappingMode.ACES_FILMIC, neutral: ToneMappingMode.NEUTRAL,
+ reinhard: ToneMappingMode.REINHARD2, linear: ToneMappingMode.LINEAR,
+};
+
+export class Engine {
+ constructor({
+ canvas, fov = 35, near = 0.1, far = 400, dpr = 1.75, exposure = 1, background = 0x000000,
+ shadows = true, alpha = false, post = {}, fixedSize = null,
+ } = {}) {
+ this.canvas = canvas;
+ this.maxDpr = dpr;
+ this.fixedSize = fixedSize;
+ this.renderer = new THREE.WebGLRenderer({
+ canvas, antialias: false, alpha, stencil: false, depth: true, powerPreference: 'high-performance',
+ });
+ const r = this.renderer;
+ r.outputColorSpace = THREE.SRGBColorSpace;
+ r.toneMapping = THREE.NoToneMapping; // tone mapping happens in the post stack (HDR bloom first)
+ r.shadowMap.enabled = shadows;
+ r.shadowMap.type = THREE.PCFShadowMap;
+ if (background !== null && !alpha) r.setClearColor(background, 1);
+
+ this.scene = new THREE.Scene();
+ this.camera = new THREE.PerspectiveCamera(fov, 1, near, far);
+ this.clock = new THREE.Clock();
+ this.time = 0;
+ this.ticks = [];
+ this.afters = [];
+ this.resizers = [];
+ this.paused = false;
+ this.exposure = exposure;
+ this.running = false;
+ this._frames = 0;
+ this._fpsT = performance.now();
+
+ this.post = post === false ? null : this._buildPost(post);
+ this.resize = this.resize.bind(this);
+ addEventListener('resize', this.resize);
+ this.resize();
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) this.clock.stop(); else { this.clock.start(); }
+ });
+ }
+
+ _buildPost(p) {
+ const composer = new EffectComposer(this.renderer, { frameBufferType: THREE.HalfFloatType, multisampling: 0 });
+ const renderPass = new RenderPass(this.scene, this.camera);
+ composer.addPass(renderPass);
+ let ao = null;
+ if (p.ao !== false) {
+ ao = new N8AOPostPass(this.scene, this.camera, 1, 1);
+ Object.assign(ao.configuration, {
+ aoRadius: 1.2, distanceFalloff: 1.0, intensity: 2.2, denoiseSamples: 8, denoiseRadius: 12,
+ aoSamples: 16, halfRes: true, gammaCorrection: false, ...(p.ao ?? {}),
+ });
+ composer.addPass(ao);
+ }
+ const effects = [];
+ const bloom = p.bloom === false ? null : new BloomEffect({
+ intensity: 0.9, luminanceThreshold: 0.85, luminanceSmoothing: 0.3, mipmapBlur: true, radius: 0.72, levels: 8,
+ ...(p.bloom ?? {}),
+ });
+ if (bloom) effects.push(bloom);
+ for (const e of (typeof p.pre === 'function' ? p.pre(this.camera, this.scene) : p.pre ?? [])) effects.push(e); // HDR-space effects (before tone mapping)
+ const tone = new ToneMappingEffect({ mode: TONE[p.tone ?? 'agx'] });
+ effects.push(tone);
+ for (const e of (typeof p.extra === 'function' ? p.extra(this.camera, this.scene) : p.extra ?? [])) effects.push(e); // display-space effects
+ let ca = null;
+ if (p.ca) {
+ // Own pass: CA samples its input buffer directly, so inside the main pass it would read un-tone-mapped HDR.
+ ca = new ChromaticAberrationEffect({ offset: new THREE.Vector2(p.ca, p.ca), radialModulation: true, modulationOffset: 0.35 });
+ }
+ const vignette = p.vignette === false ? null : new VignetteEffect({ offset: 0.3, darkness: 0.62, ...(p.vignette ?? {}) });
+ if (vignette) effects.push(vignette);
+ const noise = p.noise === false ? null : new NoiseEffect({ premultiply: false, blendFunction: BlendFunction.OVERLAY });
+ if (noise) { noise.blendMode.opacity.value = p.noise ?? 0.06; effects.push(noise); }
+ composer.addPass(new EffectPass(this.camera, ...effects));
+ if (ca) composer.addPass(new EffectPass(this.camera, ca));
+ if (p.smaa !== false) composer.addPass(new EffectPass(this.camera, new SMAAEffect()));
+ return { composer, renderPass, ao, bloom, tone, vignette, noise, ca };
+ }
+
+ get size() { return { w: this._w, h: this._h, dpr: this._dpr }; }
+
+ resize() {
+ const w = this.fixedSize?.w ?? this.canvas.clientWidth ?? innerWidth;
+ const h = this.fixedSize?.h ?? this.canvas.clientHeight ?? innerHeight;
+ this._w = w || innerWidth; this._h = h || innerHeight;
+ this._dpr = Math.min(devicePixelRatio || 1, this.maxDpr);
+ this.renderer.setPixelRatio(this._dpr);
+ this.renderer.setSize(this._w, this._h, false);
+ this.camera.aspect = this._w / this._h;
+ this.camera.updateProjectionMatrix();
+ if (this.post) {
+ this.post.composer.setSize(this._w, this._h, false);
+ }
+ for (const f of this.resizers) f(this._w, this._h, this._dpr);
+ }
+
+ onTick(fn) { this.ticks.push(fn); return () => { this.ticks = this.ticks.filter(f => f !== fn); }; }
+ onAfterRender(fn) { this.afters.push(fn); }
+ onResize(fn) { this.resizers.push(fn); fn(this._w, this._h, this._dpr); }
+
+ start() {
+ if (this.running) return;
+ this.running = true;
+ const loop = () => {
+ if (!this.running) return;
+ requestAnimationFrame(loop);
+ if (document.hidden) return;
+ const dt = Math.min(this.clock.getDelta(), 1 / 20);
+ this.time += dt;
+ for (const f of this.ticks) f(dt, this.time);
+ if (this.paused) return;
+ this.render(dt);
+ for (const f of this.afters) f(dt, this.time);
+ this._frames++;
+ const now = performance.now();
+ if (now - this._fpsT > 1000) { window.__fps = Math.round(this._frames * 1000 / (now - this._fpsT)); this._frames = 0; this._fpsT = now; }
+ };
+ this.clock.start();
+ requestAnimationFrame(loop);
+ }
+
+ render(dt) {
+ if (this.post) this.post.composer.render(dt);
+ else this.renderer.render(this.scene, this.camera);
+ }
+}
+
+/** Soft studio lighting baked into a PMREM env map: a dim gradient dome with bright softbox panels. */
+export function studioEnvironment(renderer, {
+ top = 0x1a1a1f, bottom = 0x050506, panels = [
+ { pos: [0, 6, 4], size: [8, 3], intensity: 6, color: 0xffffff },
+ { pos: [-7, 2, -2], size: [3, 6], intensity: 3, color: 0xfff1e0 },
+ { pos: [7, 3, -3], size: [2, 7], intensity: 2.5, color: 0xe0ecff },
+ ], blur = 0.04,
+} = {}) {
+ const s = new THREE.Scene();
+ const dome = new THREE.Mesh(
+ new THREE.SphereGeometry(20, 48, 24),
+ new THREE.ShaderMaterial({
+ side: THREE.BackSide, depthWrite: false,
+ uniforms: { top: { value: new THREE.Color(top) }, bottom: { value: new THREE.Color(bottom) } },
+ vertexShader: 'varying vec3 vP; void main(){ vP = normalize(position); gl_Position = projectionMatrix*modelViewMatrix*vec4(position,1.); }',
+ fragmentShader: 'uniform vec3 top; uniform vec3 bottom; varying vec3 vP; void main(){ gl_FragColor = vec4(mix(bottom, top, smoothstep(-0.4, 0.8, vP.y)), 1.); }',
+ }),
+ );
+ s.add(dome);
+ for (const p of panels) {
+ const m = new THREE.Mesh(new THREE.PlaneGeometry(p.size[0], p.size[1]),
+ new THREE.MeshBasicMaterial({ color: new THREE.Color(p.color).multiplyScalar(p.intensity), side: THREE.DoubleSide }));
+ m.position.set(...p.pos);
+ m.lookAt(0, 0, 0);
+ s.add(m);
+ }
+ const pm = new THREE.PMREMGenerator(renderer);
+ const rt = pm.fromScene(s, blur);
+ pm.dispose();
+ return rt.texture;
+}
+
+/** Fit an object into a box of the given size and rest it on y=0 (or centre it). */
+export function normalize(obj, size = 2, { ground = true, axis = 'max' } = {}) {
+ obj.updateMatrixWorld(true);
+ const box = new THREE.Box3().setFromObject(obj);
+ const dim = box.getSize(new THREE.Vector3());
+ const ref = axis === 'y' ? dim.y : axis === 'x' ? dim.x : Math.max(dim.x, dim.y, dim.z);
+ const s = size / ref;
+ obj.scale.multiplyScalar(s);
+ obj.updateMatrixWorld(true);
+ box.setFromObject(obj);
+ const c = box.getCenter(new THREE.Vector3());
+ obj.position.x -= c.x; obj.position.z -= c.z;
+ obj.position.y -= ground ? box.min.y : c.y;
+ return obj;
+}
+
+/** Walk a loaded model: shadows, anisotropy, env intensity, optional material tweaks. */
+export function prepModel(obj, renderer, { cast = true, receive = true, env = 1, rough = null, metal = null, onMat = null } = {}) {
+ const aniso = renderer.capabilities.getMaxAnisotropy();
+ obj.traverse(o => {
+ if (!o.isMesh) return;
+ o.castShadow = cast; o.receiveShadow = receive;
+ const mats = Array.isArray(o.material) ? o.material : [o.material];
+ for (const m of mats) {
+ for (const k of ['map', 'normalMap', 'roughnessMap', 'metalnessMap', 'emissiveMap', 'aoMap']) if (m[k]) m[k].anisotropy = aniso;
+ if ('envMapIntensity' in m) m.envMapIntensity = env;
+ if (rough !== null) m.roughness = rough;
+ if (metal !== null) m.metalness = metal;
+ onMat?.(m, o);
+ }
+ });
+ return obj;
+}
+
+export const damp = (a, b, lambda, dt) => a + (b - a) * (1 - Math.exp(-lambda * dt));
+export const clamp = (v, a = 0, b = 1) => Math.min(b, Math.max(a, v));
+export const lerp = (a, b, t) => a + (b - a) * t;
+export const smooth = (a, b, v) => { const t = clamp((v - a) / (b - a)); return t * t * (3 - 2 * t); };
+export const range = (v, a, b) => clamp((v - a) / (b - a));
diff --git a/src/core/input.js b/src/core/input.js
new file mode 100644
index 0000000..71aa344
--- /dev/null
+++ b/src/core/input.js
@@ -0,0 +1,41 @@
+// Pointer state shared by scenes: raw + damped NDC, pixel position, velocity, press state.
+import { damp } from './engine.js';
+
+export class Pointer {
+ constructor({ lambda = 6, target = window } = {}) {
+ this.x = 0; this.y = 0; // raw NDC (-1..1, y up)
+ this.sx = 0; this.sy = 0; // damped NDC
+ this.px = innerWidth / 2; this.py = innerHeight / 2; // pixels
+ this.vx = 0; this.vy = 0; // NDC velocity per second (damped)
+ this.down = false;
+ this.active = false; // pointer has moved at least once
+ this.lambda = lambda;
+ this._lx = 0; this._ly = 0;
+ this.listeners = { down: [], up: [], move: [] };
+ const move = e => {
+ const t = e.touches?.[0] ?? e;
+ this.px = t.clientX; this.py = t.clientY;
+ this.x = (t.clientX / innerWidth) * 2 - 1;
+ this.y = -(t.clientY / innerHeight) * 2 + 1;
+ this.active = true;
+ for (const f of this.listeners.move) f(e, this);
+ };
+ target.addEventListener('pointermove', move, { passive: true });
+ target.addEventListener('pointerdown', e => { move(e); this.down = true; for (const f of this.listeners.down) f(e, this); });
+ addEventListener('pointerup', e => { this.down = false; for (const f of this.listeners.up) f(e, this); });
+ addEventListener('pointercancel', () => { this.down = false; });
+ addEventListener('blur', () => { this.down = false; });
+ }
+
+ on(type, f) { this.listeners[type].push(f); }
+
+ update(dt) {
+ const nx = damp(this.sx, this.x, this.lambda, dt);
+ const ny = damp(this.sy, this.y, this.lambda, dt);
+ if (dt > 0) {
+ this.vx = damp(this.vx, (nx - this.sx) / dt, 10, dt);
+ this.vy = damp(this.vy, (ny - this.sy) / dt, 10, dt);
+ }
+ this.sx = nx; this.sy = ny;
+ }
+}
diff --git a/src/core/reflector.js b/src/core/reflector.js
new file mode 100644
index 0000000..c0ba766
--- /dev/null
+++ b/src/core/reflector.js
@@ -0,0 +1,114 @@
+// Planar reflections for glossy floors (polished stone, wet asphalt, lacquered boards).
+// Renders a mirrored camera into a mipmapped HDR target; the floor samples it with a roughness-driven LOD,
+// so blur is essentially free and follows the material's roughness map.
+import * as THREE from 'three';
+
+export class PlanarReflection {
+ constructor(renderer, { resolution = 0.5, normal = new THREE.Vector3(0, 1, 0), point = new THREE.Vector3(), clipBias = 0.003 } = {}) {
+ this.renderer = renderer;
+ this.resolution = resolution;
+ this.normal = normal.clone().normalize();
+ this.point = point.clone();
+ this.clipBias = clipBias;
+ this.rt = new THREE.WebGLRenderTarget(2, 2, {
+ type: THREE.HalfFloatType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, magFilter: THREE.LinearFilter,
+ colorSpace: THREE.LinearSRGBColorSpace, samples: 0,
+ });
+ this.cam = new THREE.PerspectiveCamera();
+ this.texMatrix = new THREE.Matrix4();
+ this.hidden = [];
+ this.enabled = true;
+ this.uniforms = { uRefl: { value: this.rt.texture }, uReflMat: { value: this.texMatrix } };
+ this._v = { rp: new THREE.Vector3(), cp: new THREE.Vector3(), rot: new THREE.Matrix4(), look: new THREE.Vector3(), view: new THREE.Vector3(), target: new THREE.Vector3(), plane: new THREE.Plane(), clip: new THREE.Vector4(), q: new THREE.Vector4() };
+ }
+
+ setSize(w, h, dpr) {
+ this.rt.setSize(Math.max(2, Math.round(w * dpr * this.resolution)), Math.max(2, Math.round(h * dpr * this.resolution)));
+ }
+
+ update(scene, camera) {
+ if (!this.enabled) return;
+ // Shadow maps are created by the first main render; rendering before that binds an empty shadow sampler.
+ if ((this._n = (this._n ?? 0) + 1) < 3) return;
+ const { rp, cp, rot, look, view, target, plane, clip, q } = this._v;
+ const n = this.normal;
+ rp.copy(this.point);
+ cp.setFromMatrixPosition(camera.matrixWorld);
+ view.subVectors(rp, cp);
+ if (view.dot(n) > 0) return;
+ view.reflect(n).negate().add(rp);
+ rot.extractRotation(camera.matrixWorld);
+ look.set(0, 0, -1).applyMatrix4(rot).add(cp);
+ target.subVectors(rp, look).reflect(n).negate().add(rp);
+ const vc = this.cam;
+ vc.position.copy(view);
+ vc.up.set(0, 1, 0).applyMatrix4(rot).reflect(n);
+ vc.lookAt(target);
+ vc.far = camera.far; vc.near = camera.near;
+ vc.updateMatrixWorld();
+ vc.projectionMatrix.copy(camera.projectionMatrix);
+ this.texMatrix.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1);
+ this.texMatrix.multiply(vc.projectionMatrix).multiply(vc.matrixWorldInverse);
+ // Oblique near plane so nothing below the floor leaks into the reflection.
+ plane.setFromNormalAndCoplanarPoint(n, rp).applyMatrix4(vc.matrixWorldInverse);
+ clip.set(plane.normal.x, plane.normal.y, plane.normal.z, plane.constant);
+ const e = vc.projectionMatrix.elements;
+ q.x = (Math.sign(clip.x) + e[8]) / e[0];
+ q.y = (Math.sign(clip.y) + e[9]) / e[5];
+ q.z = -1; q.w = (1 + e[10]) / e[14];
+ clip.multiplyScalar(2 / clip.dot(q));
+ e[2] = clip.x; e[6] = clip.y; e[10] = clip.z + 1 - this.clipBias; e[14] = clip.w;
+ vc.projectionMatrixInverse.copy(vc.projectionMatrix).invert();
+
+ const r = this.renderer;
+ const prevRT = r.getRenderTarget();
+ const prevShadow = r.shadowMap.autoUpdate;
+ r.shadowMap.autoUpdate = false;
+ for (const o of this.hidden) o.visible = false;
+ r.setRenderTarget(this.rt);
+ r.clear();
+ r.render(scene, vc);
+ for (const o of this.hidden) o.visible = true;
+ r.setRenderTarget(prevRT);
+ r.shadowMap.autoUpdate = prevShadow;
+ }
+
+ /** Patch a MeshStandard/Physical material so it reflects this target. */
+ patch(material, { strength = 1, distort = 0.04, lodScale = 7, lodBias = 0.5, f0 = 0.04, tint = new THREE.Color(1, 1, 1) } = {}) {
+ const u = this.uniforms;
+ material.userData.reflUniforms = Object.assign(u, {
+ uReflStrength: { value: strength }, uReflDistort: { value: distort }, uReflLod: { value: lodScale }, uReflBias: { value: lodBias },
+ uReflF0: { value: f0 }, uReflTint: { value: tint },
+ });
+ material.onBeforeCompile = sh => {
+ Object.assign(sh.uniforms, material.userData.reflUniforms);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vReflW;')
+ .replace('#include <project_vertex>', '#include <project_vertex>\nvReflW = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+ varying vec3 vReflW; uniform sampler2D uRefl; uniform mat4 uReflMat; uniform float uReflStrength, uReflDistort, uReflLod, uReflBias, uReflF0; uniform vec3 uReflTint;`)
+ .replace('#include <opaque_fragment>', `
+ {
+ vec4 rp = uReflMat * vec4(vReflW, 1.0);
+ vec2 ruv = rp.xy / rp.w + normal.xy * uReflDistort;
+ float lod = uReflBias + roughnessFactor * uReflLod;
+ vec2 texel = exp2(lod) / vec2(textureSize(uRefl, 0));
+ float l1 = max(lod - 1.0, 0.0);
+ vec3 refl = textureLod(uRefl, ruv, l1).rgb * 0.28
+ + textureLod(uRefl, ruv + vec2( 0.9, 0.5) * texel, l1).rgb * 0.18
+ + textureLod(uRefl, ruv + vec2(-0.9, -0.5) * texel, l1).rgb * 0.18
+ + textureLod(uRefl, ruv + vec2(-0.5, 0.9) * texel, l1).rgb * 0.18
+ + textureLod(uRefl, ruv + vec2( 0.5, -0.9) * texel, l1).rgb * 0.18;
+ float ndv = clamp(dot(normal, normalize(vViewPosition)), 0.0, 1.0);
+ float fres = uReflF0 + (1.0 - uReflF0) * pow(1.0 - ndv, 5.0);
+ float edge = smoothstep(0.0, 0.04, ruv.x) * smoothstep(1.0, 0.96, ruv.x) * smoothstep(0.0, 0.04, ruv.y) * smoothstep(1.0, 0.96, ruv.y);
+ outgoingLight += refl * uReflTint * uReflStrength * fres * (1.0 - roughnessFactor * 0.6) * edge;
+ }
+ #include <opaque_fragment>`);
+ };
+ material.customProgramCacheKey = () => 'planar-refl';
+ material.needsUpdate = true;
+ return material;
+ }
+}
diff --git a/src/core/scroll.js b/src/core/scroll.js
new file mode 100644
index 0000000..cd3652d
--- /dev/null
+++ b/src/core/scroll.js
@@ -0,0 +1,48 @@
+// Lenis smooth scrolling bound to GSAP ScrollTrigger, plus helpers for scroll-driven 3D.
+import Lenis from 'lenis';
+import { gsap } from 'gsap';
+import { ScrollTrigger } from 'gsap/ScrollTrigger';
+import { SplitText } from 'gsap/SplitText';
+
+gsap.registerPlugin(ScrollTrigger, SplitText);
+export { gsap, ScrollTrigger, SplitText };
+
+export function smoothScroll({ lerp = 0.085, wheelMultiplier = 1, ...rest } = {}) {
+ const lenis = new Lenis({ lerp, wheelMultiplier, smoothWheel: true, syncTouch: false, ...rest });
+ lenis.on('scroll', ScrollTrigger.update);
+ gsap.ticker.add(t => lenis.raf(t * 1000));
+ gsap.ticker.lagSmoothing(0);
+ window.__lenis = lenis;
+ return lenis;
+}
+
+/** Normalised page progress (0..1) and progress through an element's scroll span. */
+export function pageProgress() {
+ const max = document.documentElement.scrollHeight - innerHeight;
+ return max > 0 ? scrollY / max : 0;
+}
+
+export function elementProgress(el, { start = 'top top', end = 'bottom bottom' } = {}) {
+ const r = el.getBoundingClientRect();
+ const vh = innerHeight;
+ const s = start === 'top bottom' ? r.top - vh : start === 'top center' ? r.top - vh / 2 : r.top;
+ const e = end === 'bottom top' ? r.bottom : end === 'bottom center' ? r.bottom - vh / 2 : r.bottom - vh;
+ const span = e - s || 1;
+ return Math.min(1, Math.max(0, -s / span));
+}
+
+/** Reveal text by lines/words/chars when it scrolls into view. */
+export function reveal(selector, { type = 'lines', stagger = 0.08, y = '110%', duration = 1.1, ease = 'expo.out', start = 'top 85%', scrub = false, mask = true } = {}) {
+ const els = typeof selector === 'string' ? document.querySelectorAll(selector) : [selector].flat();
+ const out = [];
+ els.forEach(el => {
+ const split = SplitText.create(el, { type, mask: mask ? type.split(',').pop().trim() : undefined, autoSplit: true,
+ onSplit(self) {
+ const targets = self[type.split(',').pop().trim()];
+ return gsap.from(targets, { yPercent: parseFloat(y), opacity: 0, duration, ease, stagger,
+ scrollTrigger: scrub ? { trigger: el, start, end: 'bottom 40%', scrub: true } : { trigger: el, start, once: true } });
+ } });
+ out.push(split);
+ });
+ return out;
+}
diff --git a/src/core/textures.js b/src/core/textures.js
new file mode 100644
index 0000000..0153326
--- /dev/null
+++ b/src/core/textures.js
@@ -0,0 +1,63 @@
+// Procedural tileable textures rendered on the GPU once at startup (fbm noise, height -> normal).
+import * as THREE from 'three';
+
+const NOISE_GLSL = /* glsl */`
+ // Periodic gradient noise so the textures tile seamlessly.
+ vec2 hash2(vec2 p, float per){ p = mod(p, per); p = vec2(dot(p, vec2(127.1,311.7)), dot(p, vec2(269.5,183.3))); return -1.0 + 2.0*fract(sin(p)*43758.5453123); }
+ float pnoise(vec2 p, float per){
+ vec2 i = floor(p), f = fract(p); vec2 u = f*f*f*(f*(f*6.-15.)+10.);
+ return mix(mix(dot(hash2(i,per), f), dot(hash2(i+vec2(1,0),per), f-vec2(1,0)), u.x),
+ mix(dot(hash2(i+vec2(0,1),per), f-vec2(0,1)), dot(hash2(i+vec2(1,1),per), f-vec2(1,1)), u.x), u.y);
+ }
+ float fbm(vec2 p, float per, int oct, float gain){ float a = .5, s = 0.; for(int i=0;i<10;i++){ if(i>=oct) break; s += a*pnoise(p, per); p *= 2.; per *= 2.; a *= gain; } return s; }
+ float ridge(vec2 p, float per, int oct){ float a=.5, s=0.; for(int i=0;i<10;i++){ if(i>=oct) break; s += a*(1.-abs(pnoise(p,per))); p*=2.; per*=2.; a*=.5; } return s; }
+`;
+
+function bake(renderer, size, frag, uniforms = {}) {
+ const rt = new THREE.WebGLRenderTarget(size, size, { type: THREE.UnsignedByteType, generateMipmaps: true, minFilter: THREE.LinearMipmapLinearFilter, wrapS: THREE.RepeatWrapping, wrapT: THREE.RepeatWrapping });
+ const mat = new THREE.ShaderMaterial({
+ uniforms,
+ vertexShader: 'varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }',
+ fragmentShader: `precision highp float; varying vec2 vUv; ${NOISE_GLSL}\n${frag}`,
+ depthTest: false, depthWrite: false,
+ });
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat);
+ const scene = new THREE.Scene(); scene.add(quad);
+ const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ const prev = renderer.getRenderTarget();
+ renderer.setRenderTarget(rt);
+ renderer.render(scene, cam);
+ renderer.setRenderTarget(prev);
+ mat.dispose(); quad.geometry.dispose();
+ rt.texture.wrapS = rt.texture.wrapT = THREE.RepeatWrapping;
+ rt.texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
+ return rt.texture;
+}
+
+/** Greyscale fbm. `frag` override lets a page write its own height function h(uv). */
+export function fbmTexture(renderer, { size = 1024, scale = 6, octaves = 6, gain = 0.5, contrast = 1, bias = 0.5, ridged = false } = {}) {
+ return bake(renderer, size, `
+ void main(){
+ float n = ${ridged ? 'ridge(vUv*' + scale.toFixed(1) + ',' + scale.toFixed(1) + ',' + octaves + ')' : 'fbm(vUv*' + scale.toFixed(1) + ',' + scale.toFixed(1) + ',' + octaves + ',' + gain.toFixed(2) + ')'};
+ float v = clamp(${bias.toFixed(3)} + n * ${contrast.toFixed(3)}, 0., 1.);
+ gl_FragColor = vec4(vec3(v), 1.);
+ }`);
+}
+
+/** Tangent-space normal map from an fbm height field. */
+export function fbmNormal(renderer, { size = 1024, scale = 6, octaves = 6, strength = 2, ridged = false, gain = 0.5 } = {}) {
+ const h = ridged ? `ridge(p*${scale.toFixed(1)}, ${scale.toFixed(1)}, ${octaves})` : `fbm(p*${scale.toFixed(1)}, ${scale.toFixed(1)}, ${octaves}, ${gain.toFixed(2)})`;
+ return bake(renderer, size, `
+ float H(vec2 p){ return ${h}; }
+ void main(){
+ float e = 1.0 / ${size.toFixed(1)};
+ float hx = H(vUv + vec2(e,0.)) - H(vUv - vec2(e,0.));
+ float hy = H(vUv + vec2(0.,e)) - H(vUv - vec2(0.,e));
+ vec3 n = normalize(vec3(-hx * ${strength.toFixed(2)} * ${size.toFixed(1)} * 0.02, -hy * ${strength.toFixed(2)} * ${size.toFixed(1)} * 0.02, 1.));
+ gl_FragColor = vec4(n * 0.5 + 0.5, 1.);
+ }`);
+}
+
+/** Bake any custom shader to a texture: body must set gl_FragColor from vUv; noise helpers available. */
+export function bakeTexture(renderer, size, body, uniforms) { return bake(renderer, size, body, uniforms); }
+export { NOISE_GLSL };
diff --git a/src/core/ui.css b/src/core/ui.css
new file mode 100644
index 0000000..70b3662
--- /dev/null
+++ b/src/core/ui.css
@@ -0,0 +1,29 @@
+.tw-has-cursor, .tw-has-cursor * { cursor: none !important; }
+.tw-cursor { position: fixed; inset: 0; pointer-events: none; z-index: 9999; }
+.tw-cursor-dot, .tw-cursor-ring { position: absolute; left: 0; top: 0; will-change: transform; }
+.tw-cursor-dot { width: 6px; height: 6px; margin: -3px 0 0 -3px; border-radius: 50%; background: var(--c); transition: opacity .3s; }
+.tw-cursor-ring { width: var(--s); height: var(--s); margin: calc(var(--s) / -2) 0 0 calc(var(--s) / -2); }
+.tw-cursor-ring::before { content: ''; position: absolute; inset: 0; border: 1px solid var(--c); border-radius: 50%; opacity: .55;
+ transition: transform .45s cubic-bezier(.2,.8,.2,1), opacity .3s, background .3s; }
+.tw-cursor-label { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); font: 600 10px/1 ui-sans-serif, system-ui, sans-serif;
+ letter-spacing: .14em; text-transform: uppercase; white-space: nowrap; color: var(--c); opacity: 0; transition: opacity .3s; }
+.tw-cursor[data-state="link"] .tw-cursor-ring::before { transform: scale(1.7); opacity: .9; }
+.tw-cursor[data-state="link"] .tw-cursor-dot { opacity: 0; }
+.tw-cursor[data-state="drag"] .tw-cursor-ring::before, .tw-cursor[data-state="label"] .tw-cursor-ring::before { transform: scale(2.6); opacity: 1; }
+.tw-cursor[data-state="drag"] .tw-cursor-label, .tw-cursor[data-state="label"] .tw-cursor-label { opacity: 1; }
+.tw-cursor[data-state="hidden"] { opacity: 0; }
+
+.tw-nav { position: fixed; z-index: 9000; display: flex; align-items: center; gap: 2px; padding: 5px; border-radius: 999px;
+ font: 500 11px/1 ui-monospace, 'SF Mono', Menlo, Consolas, monospace; letter-spacing: .04em;
+ backdrop-filter: blur(14px) saturate(1.4); -webkit-backdrop-filter: blur(14px) saturate(1.4); transition: opacity .4s; }
+.tw-nav-bl { left: 16px; bottom: 16px; } .tw-nav-br { right: 16px; bottom: 16px; }
+.tw-nav-tl { left: 16px; top: 16px; } .tw-nav-tr { right: 16px; top: 16px; }
+.tw-nav-dark { background: rgba(12,12,14,.55); color: rgba(255,255,255,.86); box-shadow: inset 0 0 0 1px rgba(255,255,255,.1); }
+.tw-nav-light { background: rgba(255,255,255,.6); color: rgba(10,10,12,.86); box-shadow: inset 0 0 0 1px rgba(0,0,0,.08); }
+.tw-nav a { color: inherit; text-decoration: none; display: grid; place-items: center; height: 28px; min-width: 28px; border-radius: 999px; transition: background .25s; }
+.tw-nav a:hover { background: color-mix(in srgb, currentColor 14%, transparent); }
+.tw-nav-home svg { width: 16px; height: 16px; }
+.tw-nav-step { font-size: 16px; line-height: 1; padding-bottom: 2px; }
+.tw-nav-count { padding: 0 6px; font-variant-numeric: tabular-nums; }
+.tw-nav-count em { font-style: normal; opacity: .45; }
+@media (max-width: 640px) { .tw-nav { transform: scale(.92); transform-origin: left bottom; } }
diff --git a/src/core/ui.js b/src/core/ui.js
new file mode 100644
index 0000000..1f1f031
--- /dev/null
+++ b/src/core/ui.js
@@ -0,0 +1,103 @@
+// Page chrome shared by every world: preloader, cursor, magnetic buttons, collection navigator.
+import { gsap } from 'gsap';
+import { WORLDS } from './worlds.js';
+import './ui.css';
+
+/**
+ * Preloader bound to an Assets instance. Returns a promise that resolves after the exit animation.
+ * `el` is the page's own loader element (each world styles its own); `onValue(v)` updates it.
+ */
+export function preloader({ assets, el, onValue, minTime = 900, exit = null }) {
+ const t0 = performance.now();
+ let shown = 0;
+ const state = { v: 0 };
+ const tick = () => {
+ shown += (assets.progress - shown) * 0.12;
+ onValue?.(shown);
+ if (!state.done) requestAnimationFrame(tick);
+ };
+ tick();
+ return {
+ async finish() {
+ const wait = Math.max(0, minTime - (performance.now() - t0));
+ await new Promise(r => setTimeout(r, wait));
+ state.done = true;
+ onValue?.(1);
+ if (exit) await exit();
+ else if (el) await gsap.to(el, { autoAlpha: 0, duration: 0.9, ease: 'power2.inOut' });
+ el?.remove?.();
+ },
+ };
+}
+
+/** Custom cursor: a dot plus a lagging ring that swells over interactive elements. */
+export function cursor({ color = '#fff', blend = 'difference', size = 34, label = true } = {}) {
+ if (matchMedia('(pointer: coarse)').matches) return null;
+ const root = document.createElement('div');
+ root.className = 'tw-cursor';
+ root.style.setProperty('--c', color);
+ root.style.setProperty('--s', size + 'px');
+ root.style.mixBlendMode = blend;
+ root.innerHTML = '<div class="tw-cursor-ring"><span class="tw-cursor-label"></span></div><div class="tw-cursor-dot"></div>';
+ document.body.appendChild(root);
+ document.documentElement.classList.add('tw-has-cursor');
+ const ring = root.firstElementChild, dot = root.lastElementChild, lab = ring.firstElementChild;
+ let x = innerWidth / 2, y = innerHeight / 2, rx = x, ry = y;
+ addEventListener('pointermove', e => { x = e.clientX; y = e.clientY; }, { passive: true });
+ const loop = () => {
+ rx += (x - rx) * 0.18; ry += (y - ry) * 0.18;
+ dot.style.transform = `translate3d(${x}px,${y}px,0)`;
+ ring.style.transform = `translate3d(${rx}px,${ry}px,0)`;
+ requestAnimationFrame(loop);
+ };
+ loop();
+ const api = {
+ root,
+ set(state, text = '') { root.dataset.state = state || ''; lab.textContent = label ? text : ''; },
+ };
+ document.addEventListener('pointerover', e => {
+ const t = e.target.closest?.('a,button,[data-cursor]');
+ if (t) api.set(t.dataset.cursor ?? 'link', t.dataset.cursorLabel ?? '');
+ });
+ document.addEventListener('pointerout', e => {
+ const t = e.target.closest?.('a,button,[data-cursor]');
+ if (t && !t.contains(e.relatedTarget)) api.set('');
+ });
+ return api;
+}
+
+/** Buttons that lean toward the pointer. */
+export function magnetic(selector = '[data-magnetic]', strength = 0.35) {
+ document.querySelectorAll(selector).forEach(el => {
+ const inner = el.querySelector('[data-magnetic-inner]') ?? el;
+ el.addEventListener('pointermove', e => {
+ const r = el.getBoundingClientRect();
+ const dx = e.clientX - (r.left + r.width / 2), dy = e.clientY - (r.top + r.height / 2);
+ gsap.to(el, { x: dx * strength, y: dy * strength, duration: 0.5, ease: 'power3.out' });
+ if (inner !== el) gsap.to(inner, { x: dx * strength * 0.4, y: dy * strength * 0.4, duration: 0.5, ease: 'power3.out' });
+ });
+ el.addEventListener('pointerleave', () => {
+ gsap.to([el, inner], { x: 0, y: 0, duration: 0.9, ease: 'elastic.out(1, 0.4)' });
+ });
+ });
+}
+
+/** Small collection navigator pinned to a corner of every world. */
+export function worldNav(slug, { theme = 'dark', corner = 'bl' } = {}) {
+ const i = WORLDS.findIndex(w => w.slug === slug);
+ const prev = WORLDS[(i - 1 + WORLDS.length) % WORLDS.length];
+ const next = WORLDS[(i + 1) % WORLDS.length];
+ const base = import.meta.env.BASE_URL;
+ const nav = document.createElement('nav');
+ nav.className = `tw-nav tw-nav-${theme} tw-nav-${corner}`;
+ nav.setAttribute('aria-label', 'Twenty Worlds');
+ nav.innerHTML = `
+ <a class="tw-nav-home" href="${base}" title="All twenty worlds">
+ <svg viewBox="0 0 20 20" aria-hidden="true"><g fill="currentColor">${[0, 1, 2, 3].map(r => [0, 1, 2, 3, 4].map(c => `<rect x="${1 + c * 3.8}" y="${2 + r * 4.4}" width="2.2" height="2.2" rx=".6" opacity="${(r * 5 + c) === i ? 1 : 0.38}"/>`).join('')).join('')}</g></svg>
+ </a>
+ <a href="${base}examples/${prev.slug}/" class="tw-nav-step" title="${prev.name}" aria-label="Previous world: ${prev.name}">‹</a>
+ <span class="tw-nav-count">${String(i + 1).padStart(2, '0')}<em>/20</em></span>
+ <a href="${base}examples/${next.slug}/" class="tw-nav-step" title="${next.name}" aria-label="Next world: ${next.name}">›</a>`;
+ document.body.appendChild(nav);
+ return nav;
+}
diff --git a/src/core/volumetric.js b/src/core/volumetric.js
new file mode 100644
index 0000000..4951ea8
--- /dev/null
+++ b/src/core/volumetric.js
@@ -0,0 +1,124 @@
+// Raymarched volumetric spotlights as a post effect. The march stops at scene depth, so beams end on
+// surfaces and pass behind objects correctly; noise gives drifting dust. Up to 4 lights.
+import * as THREE from 'three';
+import { Effect, EffectAttribute, BlendFunction } from 'postprocessing';
+
+const frag = /* glsl */`
+uniform mat4 uProjInv;
+uniform mat4 uCamWorld;
+uniform vec3 uCamPos;
+uniform int uCount;
+uniform vec3 uLPos[4];
+uniform vec3 uLDir[4];
+uniform vec3 uLCol[4];
+uniform vec2 uLCone[4];
+uniform float uLRange[4];
+uniform float uDensity;
+uniform float uTime;
+uniform float uNoise;
+uniform float uNoiseScale;
+uniform float uMaxDist;
+uniform vec3 uWind;
+uniform float uFloorY;
+
+float vhash(vec3 p){ p = fract(p * 0.3183099 + .1); p *= 17.0; return fract(p.x * p.y * p.z * (p.x + p.y + p.z)); }
+float vnoise(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f * f * (3. - 2. * f);
+ return mix(mix(mix(vhash(i), vhash(i + vec3(1,0,0)), f.x), mix(vhash(i + vec3(0,1,0)), vhash(i + vec3(1,1,0)), f.x), f.y),
+ mix(mix(vhash(i + vec3(0,0,1)), vhash(i + vec3(1,0,1)), f.x), mix(vhash(i + vec3(0,1,1)), vhash(i + vec3(1,1,1)), f.x), f.y), f.z);
+}
+
+void mainImage(const in vec4 inputColor, const in vec2 uv, const in float depth, out vec4 outputColor) {
+ vec4 clip = vec4(uv * 2. - 1., depth * 2. - 1., 1.);
+ vec4 vp = uProjInv * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vec4(vp.xyz, 1.)).xyz;
+ vec3 ro = uCamPos;
+ vec3 rd = wp - ro;
+ float len = min(length(rd), uMaxDist);
+ rd = normalize(rd);
+ const int STEPS = 32;
+ float stepL = len / float(STEPS);
+ float jitter = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))));
+ vec3 acc = vec3(0.);
+ for (int i = 0; i < STEPS; i++) {
+ float t = (float(i) + jitter) * stepL;
+ vec3 p = ro + rd * t;
+ vec3 q = p * uNoiseScale + uWind * uTime;
+ float n = vnoise(q) * 0.65 + vnoise(q * 2.7 + 7.1) * 0.35;
+ float dens = uDensity * mix(1.0, n * n * 2.4, uNoise) * smoothstep(uFloorY - 0.2, uFloorY + 0.6, p.y);
+ for (int l = 0; l < 4; l++) {
+ if (l >= uCount) break;
+ vec3 d = p - uLPos[l];
+ float dist = max(length(d), 1e-3);
+ float c = dot(d / dist, uLDir[l]);
+ float cone = smoothstep(uLCone[l].x, uLCone[l].y, c);
+ float att = 1.0 / (1.0 + dist * dist * uLRange[l]);
+ acc += uLCol[l] * cone * att * dens * stepL;
+ }
+ }
+ outputColor = vec4(inputColor.rgb + acc, inputColor.a);
+}`;
+
+export class VolumetricSpotEffect extends Effect {
+ constructor(camera, { density = 0.08, noise = 0.8, noiseScale = 1.4, maxDist = 30, wind = new THREE.Vector3(0.02, 0.05, 0.01), floorY = -100 } = {}) {
+ const vec3s = () => [0, 1, 2, 3].map(() => new THREE.Vector3());
+ super('VolumetricSpotEffect', frag, {
+ attributes: EffectAttribute.DEPTH,
+ blendFunction: BlendFunction.NORMAL,
+ uniforms: new Map([
+ ['uProjInv', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamWorld', new THREE.Uniform(new THREE.Matrix4())],
+ ['uCamPos', new THREE.Uniform(new THREE.Vector3())],
+ ['uCount', new THREE.Uniform(0)],
+ ['uLPos', new THREE.Uniform(vec3s())],
+ ['uLDir', new THREE.Uniform(vec3s())],
+ ['uLCol', new THREE.Uniform(vec3s())],
+ ['uLCone', new THREE.Uniform([0, 1, 2, 3].map(() => new THREE.Vector2(0.9, 0.95)))],
+ ['uLRange', new THREE.Uniform([0.05, 0.05, 0.05, 0.05])],
+ ['uDensity', new THREE.Uniform(density)],
+ ['uTime', new THREE.Uniform(0)],
+ ['uNoise', new THREE.Uniform(noise)],
+ ['uNoiseScale', new THREE.Uniform(noiseScale)],
+ ['uMaxDist', new THREE.Uniform(maxDist)],
+ ['uWind', new THREE.Uniform(wind)],
+ ['uFloorY', new THREE.Uniform(floorY)],
+ ]),
+ });
+ this.camera = camera;
+ this.lights = [];
+ this._d = new THREE.Vector3();
+ this._p = new THREE.Vector3();
+ }
+
+ /** Track a THREE.SpotLight. `scale` multiplies its colour*intensity into the fog; `range` is quadratic falloff. */
+ add(light, { scale = 0.02, range = 0.04, softness = 0.12 } = {}) {
+ this.lights.push({ light, scale, range, softness });
+ return this;
+ }
+
+ update(renderer, inputBuffer, dt) {
+ const u = this.uniforms;
+ const cam = this.camera;
+ u.get('uProjInv').value.copy(cam.projectionMatrixInverse);
+ u.get('uCamWorld').value.copy(cam.matrixWorld);
+ u.get('uCamPos').value.setFromMatrixPosition(cam.matrixWorld);
+ u.get('uTime').value += dt;
+ const n = Math.min(4, this.lights.length);
+ u.get('uCount').value = n;
+ for (let i = 0; i < n; i++) {
+ const { light, scale, range, softness } = this.lights[i];
+ light.updateMatrixWorld();
+ light.target.updateMatrixWorld();
+ this._p.setFromMatrixPosition(light.matrixWorld);
+ this._d.setFromMatrixPosition(light.target.matrixWorld).sub(this._p).normalize();
+ u.get('uLPos').value[i].copy(this._p);
+ u.get('uLDir').value[i].copy(this._d);
+ const on = light.visible ? light.intensity * scale : 0;
+ u.get('uLCol').value[i].set(light.color.r * on, light.color.g * on, light.color.b * on);
+ const outer = Math.cos(light.angle);
+ const inner = Math.cos(light.angle * (1 - Math.max(light.penumbra, softness)));
+ u.get('uLCone').value[i].set(outer, inner);
+ u.get('uLRange').value[i] = range;
+ }
+ }
+}
diff --git a/src/core/worlds.js b/src/core/worlds.js
new file mode 100644
index 0000000..9f48e37
--- /dev/null
+++ b/src/core/worlds.js
@@ -0,0 +1,23 @@
+// The collection, in gallery order. Used by the index and by the cross-page navigator.
+export const WORLDS = [
+ { slug: 'reliquary', name: 'Reliquary', line: 'A museum you can only see by lantern light', hue: '#c9a36a' },
+ { slug: 'abyssal', name: 'Abyssal', line: 'Descend eleven thousand metres', hue: '#3fd6c9' },
+ { slug: 'ember', name: 'Hammer & Ember', line: 'Heat the blade. Strike the steel.', hue: '#ff6a1f' },
+ { slug: 'terrarium', name: 'Bell & Moss', line: 'Wipe the glass. Meet the world inside.', hue: '#8fb57a' },
+ { slug: 'koi', name: 'Still Water', line: 'Touch the pond', hue: '#e0503a' },
+ { slug: 'florae', name: 'Florae', line: 'Two hundred thousand petals, one gesture', hue: '#d6456b' },
+ { slug: 'velocity', name: 'Velocity Lab', line: 'See through the shoe', hue: '#ff8a1f' },
+ { slug: 'hangar', name: 'Hangar Nine', line: 'Power up a forty-ton machine', hue: '#ffb000' },
+ { slug: 'sucre', name: 'Maison Sucre', line: 'A patisserie with gravity', hue: '#f29bb2' },
+ { slug: 'monolith', name: 'Monolith', line: 'Drag the sun across a house', hue: '#d9c7a8' },
+ { slug: 'lowfreq', name: 'Low Frequency', line: 'Put your hand on the record', hue: '#a78bfa' },
+ { slug: 'gambit', name: 'Gambit', line: 'The Immortal Game, replayed in marble', hue: '#e9e4da' },
+ { slug: 'atlas', name: 'Atlas of Drifting Isles', line: 'Travel between floating islands', hue: '#7cc4ff' },
+ { slug: 'lithos', name: 'Lithos', line: 'Crack the stone open', hue: '#9d6bff' },
+ { slug: 'artemis', name: 'Artemis', line: 'Scroll to walk on the Moon', hue: '#dcdcdc' },
+ { slug: 'keeper', name: 'The Keeper', line: 'Hold the light against the storm', hue: '#ffd27a' },
+ { slug: 'koen', name: 'Kōen', line: 'One tree, four seasons', hue: '#d2553b' },
+ { slug: 'nocturne', name: 'Nocturne', line: 'A fragrance you can pour', hue: '#d8b56a' },
+ { slug: 'racer', name: 'Nightshift Motor Co.', line: 'Rev a café racer in the rain', hue: '#ff3b5c' },
+ { slug: 'horologie', name: 'Aurel Horologie', line: 'Take a movement apart', hue: '#c89b6d' },
+];
diff --git a/src/index/main.js b/src/index/main.js
new file mode 100644
index 0000000..e929e79
--- /dev/null
+++ b/src/index/main.js
@@ -0,0 +1,215 @@
+// Twenty Worlds — the gallery. A curved wall of twenty lit windows over black glass.
+import { Engine, THREE, damp, clamp } from '../core/engine.js';
+import { Pointer } from '../core/input.js';
+import { smoothScroll, gsap, elementProgress } from '../core/scroll.js';
+import { cursor } from '../core/ui.js';
+import { PlanarReflection } from '../core/reflector.js';
+import { WORLDS } from '../core/worlds.js';
+
+const BASE = import.meta.env.BASE_URL;
+const N = WORLDS.length;
+const R = 12.2; // ring radius
+const STEP = (Math.PI * 2) / N; // angle between windows
+const CARD = { w: 3.36, h: 2.1 };
+
+const engine = new Engine({
+ canvas: document.getElementById('gl'), fov: 36, near: 0.1, far: 60, dpr: 1.75, background: 0x060607, shadows: false,
+ post: { ao: false, tone: 'linear', bloom: { intensity: 0.55, luminanceThreshold: 0.72, luminanceSmoothing: 0.25, radius: 0.8 }, vignette: { offset: 0.28, darkness: 0.7 }, noise: 0.05 },
+});
+const { scene, camera, renderer } = engine;
+scene.fog = new THREE.Fog(0x060607, 6, 22);
+camera.position.set(0, 0.55, -2.8);
+
+// ─── Windows ─────────────────────────────────────────────────────────────────
+const loader = new THREE.TextureLoader();
+const cardGeo = (() => {
+ const g = new THREE.PlaneGeometry(CARD.w, CARD.h, 32, 1);
+ const p = g.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const a = p.getX(i) / R;
+ p.setXYZ(i, Math.sin(a) * R, p.getY(i), R - Math.cos(a) * R);
+ }
+ g.computeVertexNormals();
+ return g;
+})();
+const cardMat = (tex, hue) => new THREE.ShaderMaterial({
+ transparent: true, fog: true,
+ uniforms: {
+ map: { value: tex }, uActive: { value: 0 }, uHover: { value: 0 }, uHue: { value: new THREE.Color(hue) }, uTime: { value: 0 },
+ uReveal: { value: 0 }, fogColor: { value: scene.fog.color }, fogNear: { value: scene.fog.near }, fogFar: { value: scene.fog.far },
+ },
+ vertexShader: `
+ varying vec2 vUv; varying vec3 vView;
+ #include <fog_pars_vertex>
+ void main(){ vUv = uv; vec4 mvPosition = modelViewMatrix * vec4(position, 1.); vView = -mvPosition.xyz; gl_Position = projectionMatrix * mvPosition;
+ #include <fog_vertex>
+ }`,
+ fragmentShader: `
+ uniform sampler2D map; uniform float uActive, uHover, uTime, uReveal; uniform vec3 uHue; varying vec2 vUv; varying vec3 vView;
+ #include <fog_pars_fragment>
+ float rbox(vec2 p, vec2 b, float r){ vec2 q = abs(p) - b + r; return length(max(q, 0.)) + min(max(q.x, q.y), 0.) - r; }
+ void main(){
+ vec2 p = (vUv - .5) * vec2(${CARD.w.toFixed(2)}, ${CARD.h.toFixed(2)});
+ float d = rbox(p, vec2(${(CARD.w / 2).toFixed(3)}, ${(CARD.h / 2).toFixed(3)}), 0.08);
+ float a = smoothstep(0.012, 0.0, d);
+ // Gentle zoom-in when active: the world "opens" a little.
+ vec2 uv = (vUv - .5) * (1. - uActive * 0.05 - uHover * 0.02) + .5;
+ vec3 c = texture2D(map, uv).rgb;
+ float l = dot(c, vec3(.299, .587, .114));
+ c = mix(vec3(l) * 0.55, c, 0.35 + 0.65 * max(uActive, uHover * .7));
+ c *= 0.34 + 0.66 * max(uActive, uHover * 0.8);
+ float rim = smoothstep(0.014, 0.0, abs(d + 0.006)) * (0.12 + uActive * 0.9);
+ c += uHue * rim * 1.2;
+ c *= uReveal;
+ gl_FragColor = vec4(c, a * uReveal);
+ #include <fog_fragment>
+ }`,
+});
+
+const cards = WORLDS.map((w, i) => {
+ const tex = loader.load(`${BASE}img/index/${w.slug}.webp`);
+ tex.colorSpace = THREE.SRGBColorSpace;
+ tex.anisotropy = 8;
+ const pivot = new THREE.Group();
+ const mesh = new THREE.Mesh(cardGeo, cardMat(tex, w.hue));
+ mesh.position.set(0, 0.05, -R);
+ mesh.userData.i = i;
+ pivot.add(mesh);
+ scene.add(pivot);
+ return { w, i, pivot, mesh, active: 0, hover: 0 };
+});
+
+// Black glass floor.
+const floorMat = new THREE.MeshStandardMaterial({ color: 0x020203, roughness: 0.14, metalness: 0 });
+const floor = new THREE.Mesh(new THREE.CircleGeometry(30, 64), floorMat);
+floor.rotation.x = -Math.PI / 2; floor.position.y = -1.05;
+scene.add(floor);
+const refl = new PlanarReflection(renderer, { resolution: 0.5, point: new THREE.Vector3(0, -1.05, 0) });
+refl.hidden.push(floor);
+refl.patch(floorMat, { strength: 1.6, distort: 0, lodScale: 3, lodBias: 0.8, f0: 0.18 });
+engine.onResize((w, h, d) => refl.setSize(w, h, d));
+
+// Drifting motes for depth.
+{
+ const n = 900, pos = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) { const a = Math.random() * Math.PI * 2, r = 2 + Math.random() * 10; pos.set([Math.sin(a) * r, -1 + Math.random() * 4, -Math.cos(a) * r], i * 3); }
+ const g = new THREE.BufferGeometry(); g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ const m = new THREE.PointsMaterial({ size: 0.022, color: 0xbfb8a8, transparent: true, opacity: 0.5, depthWrite: false, blending: THREE.AdditiveBlending });
+ const pts = new THREE.Points(g, m); scene.add(pts);
+ engine.onTick((dt, t) => { pts.rotation.y = t * 0.01; });
+}
+
+// ─── State ───────────────────────────────────────────────────────────────────
+const pointer = new Pointer({ lambda: 5 });
+const ringEl = document.querySelector('.ring-section');
+const ui = {
+ num: document.querySelector('.active-num .n'), name: document.querySelector('.active-name'),
+ line: document.querySelector('.active-line'), enter: document.querySelector('.enter'),
+ bar: document.querySelector('.progress i'), root: document.documentElement,
+};
+let rot = 0, drag = 0, dragV = 0, dragging = false, lastX = 0, activeIdx = -1, hoverIdx = -1, clickStart = null;
+const ray = new THREE.Raycaster();
+
+function setActive(i) {
+ if (i === activeIdx) return;
+ activeIdx = i;
+ const w = WORLDS[i];
+ ui.root.style.setProperty('--hue', w.hue);
+ gsap.to([ui.name, ui.line], { opacity: 0, y: -8, duration: 0.18, onComplete: () => {
+ ui.num.textContent = String(i + 1).padStart(2, '0');
+ ui.name.textContent = w.name; ui.line.textContent = w.line;
+ ui.enter.href = `${BASE}examples/${w.slug}/`;
+ gsap.fromTo([ui.name, ui.line], { opacity: 0, y: 10 }, { opacity: 1, y: 0, duration: 0.5, ease: 'power3.out', stagger: 0.05 });
+ } });
+}
+
+function go(slug) {
+ gsap.to('.wipe', { opacity: 1, duration: 0.55, ease: 'power2.in', onComplete: () => { location.href = `${BASE}examples/${slug}/`; } });
+}
+ui.enter.addEventListener('click', e => { e.preventDefault(); go(WORLDS[activeIdx].slug); });
+
+addEventListener('pointerdown', e => {
+ if (e.button !== 0 || e.target.closest('a,button,.list,.about')) return;
+ dragging = true; lastX = e.clientX; clickStart = { x: e.clientX, y: e.clientY, t: performance.now() };
+});
+addEventListener('pointermove', e => {
+ if (!dragging) return;
+ const dx = e.clientX - lastX; lastX = e.clientX;
+ drag -= dx / innerWidth * 5.5; dragV = -dx / innerWidth * 5.5;
+});
+addEventListener('pointerup', e => {
+ if (!dragging) return;
+ dragging = false;
+ const moved = clickStart && Math.hypot(e.clientX - clickStart.x, e.clientY - clickStart.y) > 6;
+ if (!moved && hoverIdx >= 0) {
+ if (hoverIdx === activeIdx) go(WORLDS[hoverIdx].slug);
+ else scrollToIndex(hoverIdx);
+ } else {
+ drag += dragV * 4; // throw
+ }
+});
+function scrollToIndex(i) {
+ const span = ringEl.offsetHeight - innerHeight;
+ const cur = (target() % N + N) % N;
+ let delta = i - cur; if (delta > N / 2) delta -= N; if (delta < -N / 2) delta += N;
+ drag += delta;
+ void span;
+}
+addEventListener('keydown', e => {
+ if (e.key === 'ArrowRight') drag += 1;
+ if (e.key === 'ArrowLeft') drag -= 1;
+ if (e.key === 'Enter' && activeIdx >= 0) go(WORLDS[activeIdx].slug);
+});
+const target = () => elementProgress(ringEl) * (N - 1) + drag;
+
+engine.onTick((dt, t) => {
+ pointer.update(dt);
+ if (!dragging) { const snap = Math.round(target()) - target(); drag += snap * (1 - Math.exp(-4 * dt)); }
+ rot = damp(rot, target(), 6, dt);
+ const idx = ((Math.round(rot) % N) + N) % N;
+ setActive(idx);
+ ui.bar.style.width = `${((idx + 1) / N) * 100}%`;
+
+ // Hover pick.
+ ray.setFromCamera(new THREE.Vector2(pointer.x, pointer.y), camera);
+ const hit = ray.intersectObjects(cards.map(c => c.mesh), false)[0];
+ hoverIdx = hit && pointer.active ? hit.object.userData.i : -1;
+ document.body.style.cursor = hoverIdx >= 0 ? 'pointer' : '';
+
+ for (const c of cards) {
+ let a = c.i * STEP - rot * STEP;
+ c.pivot.rotation.y = -a;
+ const d = Math.abs(((c.i - rot) % N + N + N / 2) % N - N / 2);
+ c.active = damp(c.active, d < 0.5 ? 1 : 0, 6, dt);
+ c.hover = damp(c.hover, hoverIdx === c.i ? 1 : 0, 8, dt);
+ const u = c.mesh.material.uniforms;
+ u.uActive.value = c.active; u.uHover.value = c.hover; u.uTime.value = t;
+ c.mesh.position.z = -R + c.active * 0.9 + c.hover * 0.25;
+ c.mesh.position.y = 0.05 + Math.sin(t * 0.6 + c.i) * 0.03;
+ }
+ camera.position.x = pointer.sx * 0.3;
+ camera.position.y = 0.5 + pointer.sy * 0.12;
+ camera.lookAt(pointer.sx * 0.4, 0.12, -R);
+ refl.update(scene, camera);
+ engine.paused = document.querySelector('.list').getBoundingClientRect().top < 0;
+});
+
+// ─── The list ────────────────────────────────────────────────────────────────
+const rows = document.querySelector('.rows');
+const preview = document.querySelector('.preview');
+const pimg = preview.querySelector('img');
+rows.innerHTML = WORLDS.map((w, i) => `<li><a href="${BASE}examples/${w.slug}/" data-i="${i}">
+ <span class="num">${String(i + 1).padStart(2, '0')}</span><span class="name">${w.name}</span><span class="line">${w.line}</span><span class="dot" style="color:${w.hue};background:${w.hue}"></span></a></li>`).join('');
+let px = 0, py = 0, tx = 0, ty = 0;
+rows.addEventListener('pointerover', e => { const a = e.target.closest('a'); if (!a) return; pimg.src = `${BASE}img/index/${WORLDS[+a.dataset.i].slug}.webp`; preview.classList.add('on'); });
+rows.addEventListener('pointerleave', () => preview.classList.remove('on'));
+addEventListener('pointermove', e => { tx = e.clientX + 24; ty = e.clientY - 110; });
+(function loop() { px += (tx - px) * 0.15; py += (ty - py) * 0.15; preview.style.transform = `translate3d(${px}px,${py}px,0) rotate(${(tx - px) * 0.02}deg)`; requestAnimationFrame(loop); })();
+
+// ─── Boot ────────────────────────────────────────────────────────────────────
+smoothScroll({ lerp: 0.09 });
+cursor({ color: '#f1efe9', blend: 'difference', size: 30 });
+renderer.compile(scene, camera);
+engine.start();
+cards.forEach((c, i) => gsap.to(c.mesh.material.uniforms.uReveal, { value: 1, duration: 1.6, delay: 0.2 + Math.abs(i < N / 2 ? i : N - i) * 0.07, ease: 'power2.out' }));
+gsap.from('.intro h1, .intro .kicker, .active', { opacity: 0, y: 24, duration: 1.4, ease: 'expo.out', stagger: 0.08, delay: 0.2 });
diff --git a/src/index/style.css b/src/index/style.css
new file mode 100644
index 0000000..600c792
--- /dev/null
+++ b/src/index/style.css
@@ -0,0 +1,75 @@
+:root {
+ --bg: #060607; --ink: #f1efe9; --muted: #8d8a83; --faint: rgba(241,239,233,.1);
+ --serif: 'Instrument Serif', Georgia, serif; --sans: 'Inter Tight', system-ui, sans-serif; --mono: 'JetBrains Mono', ui-monospace, monospace;
+ --hue: #c9a36a;
+}
+* { box-sizing: border-box; margin: 0; padding: 0; }
+html { background: var(--bg); color: var(--ink); -webkit-font-smoothing: antialiased; }
+body { font: 400 16px/1.55 var(--sans); overflow-x: hidden; background: var(--bg); }
+a { color: inherit; text-decoration: none; }
+.mono { font-family: var(--mono); font-size: 11px; letter-spacing: .12em; text-transform: uppercase; }
+#gl { position: fixed; inset: 0; width: 100vw; height: 100vh; display: block; }
+
+.top { position: fixed; inset: 0 0 auto; z-index: 10; display: flex; justify-content: space-between; align-items: center; padding: 22px clamp(16px, 4vw, 44px); }
+.mark { display: flex; align-items: center; gap: 11px; font: 500 14px/1 var(--sans); letter-spacing: -.01em; }
+.mark svg { width: 20px; height: 20px; }
+.top nav { display: flex; gap: 28px; font: 500 13px/1 var(--sans); color: var(--muted); }
+.top nav a:hover { color: var(--ink); }
+
+.ring-section { position: relative; height: 560vh; z-index: 2; pointer-events: none; }
+.ring-sticky { position: sticky; top: 0; height: 100vh; }
+.intro { position: absolute; left: clamp(16px, 4vw, 44px); top: 10vh; }
+.kicker { color: var(--muted); }
+.intro h1 { font: 400 clamp(60px, 8vw, 132px)/.86 var(--serif); letter-spacing: -.035em; margin-top: 12px; }
+.intro h1 em { font-style: italic; color: var(--hue); transition: color .8s; }
+.active { position: absolute; left: clamp(16px, 4vw, 44px); bottom: 9vh; max-width: 30rem; pointer-events: auto; }
+.active-num { color: var(--muted); }
+.active-num .n { color: var(--hue); transition: color .6s; }
+.active-name { font: 400 clamp(36px, 4.2vw, 62px)/1 var(--serif); letter-spacing: -.02em; margin: 12px 0 10px; }
+.active-line { color: #b9b5ad; font-size: 17px; }
+.enter { display: inline-flex; gap: 12px; align-items: center; margin-top: 24px; height: 46px; padding: 0 22px; border-radius: 999px;
+ background: var(--ink); color: #0a0a0b; font: 600 14px/1 var(--sans); transition: background .3s, transform .3s; }
+.enter:hover { background: var(--hue); transform: translateY(-1px); }
+.ring-hint { position: absolute; right: clamp(16px, 4vw, 44px); bottom: 9vh; color: var(--muted); }
+.progress { position: absolute; left: 50%; bottom: 4.5vh; width: min(360px, 60vw); height: 1px; transform: translateX(-50%); background: var(--faint); }
+.progress i { position: absolute; inset: 0 auto 0 0; width: 5%; background: var(--hue); transition: background .6s; }
+
+.list { position: relative; z-index: 3; background: var(--bg); padding: 16vh clamp(16px, 5vw, 80px) 10vh; }
+.list-head { display: grid; grid-template-columns: 1fr 1fr; gap: 40px; align-items: end; margin-bottom: 8vh; }
+.list-head h2 { font: 400 clamp(56px, 7vw, 120px)/.9 var(--serif); letter-spacing: -.03em; }
+.list-head p { color: #aaa69e; max-width: 34em; font-size: 17px; }
+.rows { list-style: none; border-top: 1px solid var(--faint); }
+.rows li a { display: grid; grid-template-columns: 70px 1.1fr 1.4fr 40px; align-items: center; gap: 24px; padding: 22px 6px; border-bottom: 1px solid var(--faint);
+ transition: background .35s, padding .35s; }
+.rows li a:hover { background: rgba(255,255,255,.03); padding-left: 18px; }
+.rows .num { color: var(--muted); font: 400 12px/1 var(--mono); }
+.rows .name { font: 400 clamp(26px, 2.6vw, 40px)/1 var(--serif); letter-spacing: -.01em; }
+.rows .line { color: #a19d95; }
+.rows .dot { width: 10px; height: 10px; border-radius: 50%; justify-self: end; box-shadow: 0 0 18px currentColor; }
+.preview { position: fixed; left: 0; top: 0; z-index: 20; width: 340px; aspect-ratio: 16/10; border-radius: 6px; overflow: hidden; pointer-events: none;
+ opacity: 0; transform: translate3d(-9999px,0,0); transition: opacity .3s; box-shadow: 0 30px 80px rgba(0,0,0,.6); }
+.preview.on { opacity: 1; }
+.preview img { width: 100%; height: 100%; object-fit: cover; display: block; }
+
+.about { position: relative; z-index: 3; background: var(--bg); padding: 12vh clamp(16px, 5vw, 80px) 6vh; border-top: 1px solid var(--faint); }
+.about-grid { display: grid; grid-template-columns: 1fr 1.2fr; gap: 60px; }
+.about h2 { font: 400 clamp(44px, 5vw, 84px)/.95 var(--serif); letter-spacing: -.025em; margin-top: 14px; }
+.about h2 em { color: var(--muted); }
+.about-cols { display: grid; gap: 24px; color: #b1ada5; font-size: 16px; }
+.about-cols b { color: var(--ink); font-weight: 600; }
+.foot { display: flex; justify-content: space-between; margin-top: 14vh; color: var(--muted); padding-top: 24px; border-top: 1px solid var(--faint); }
+.wipe { position: fixed; inset: 0; z-index: 50; background: var(--bg); opacity: 0; pointer-events: none; }
+
+@media (max-width: 860px) {
+ .list-head, .about-grid { grid-template-columns: 1fr; }
+ .rows li a { grid-template-columns: 44px 1fr 20px; }
+ .rows .line { display: none; }
+ .ring-hint { display: none; }
+ .preview { display: none; }
+ .intro { top: 11vh; }
+}
+.ring-sticky::before { content: ''; position: absolute; inset: auto 0 0 0; height: 46vh; pointer-events: none;
+ background: linear-gradient(180deg, rgba(6,6,7,0) 0%, rgba(6,6,7,.55) 45%, rgba(6,6,7,.88) 100%); }
+.ring-sticky::after { content: ''; position: absolute; inset: 0 auto 0 0; width: 42vw; pointer-events: none;
+ background: linear-gradient(90deg, rgba(6,6,7,.6), rgba(6,6,7,0)); }
+.intro, .active, .ring-hint, .progress { z-index: 1; }
diff --git a/vite.config.js b/vite.config.js
new file mode 100644
index 0000000..b7f26d5
--- /dev/null
+++ b/vite.config.js
@@ -0,0 +1,20 @@
+import { defineConfig } from 'vite';
+import fs from 'node:fs';
+
+const examples = fs.readdirSync('examples').filter(d => fs.existsSync(`examples/${d}/index.html`));
+
+export default defineConfig({
+ appType: 'mpa',
+ // HMR off: many examples are edited in parallel; each save would otherwise reload every open tab.
+ server: { host: '127.0.0.1', port: 5190, strictPort: true, hmr: false },
+ preview: { host: '127.0.0.1', port: 5191 },
+ build: {
+ target: 'es2022',
+ assetsInlineLimit: 0,
+ chunkSizeWarningLimit: 4000,
+ rollupOptions: {
+ input: { index: 'index.html', ...Object.fromEntries(examples.map(p => [p, `examples/${p}/index.html`])) },
+ },
+ },
+ optimizeDeps: { exclude: ['@dimforge/rapier3d-compat'] },
+});