# Recreate this site as a single HTML file: Night Shift — a studio portfolio inside a planetarium dome

You are an expert creative front-end developer. Produce one self-contained `index.html` that reproduces the site below exactly: same views, copy, shaders, transitions, sound and working UI. Pure HTML/CSS/JS, no build step, no framework. One `<script type="module">`. three.js is the only library, and it is loaded with dynamic `import()` inside a try/catch, so the site still works as a list if it fails. Hardcode every value given here.

## What it is

The portfolio of **Night Shift**, a fictional creative technology studio that works 19:00–05:00 from a retired planetarium. The home page *is* the inside of the dome at night. The visitor stands at the centre of a live WebGL sky: 320k GPU stars, a baked Milky Way, a treeline horizon and **ten projects hung as constellations**, each one drawn in the shape of the project (a ship, a rain boot, a lantern, a pocket watch, binoculars, a boombox, a whale, a rubber duck, a film projector, a compass rose).

**Signature:** three linked effects.
1. **Drag turns the dome** with inertia, and the cursor drives a **real-time GPU stable-fluids simulation** (ping-pong render targets) whose velocity field smears the starlight like a hand through mist.
2. **Hover a constellation** and it brightens and takes its accent colour, its lines **draw in segment by segment**, a soft bell chime plays, and its project name **decodes in** from star-chart glyphs.
3. **Click** and the camera swings to centre it, then **warps in**: stars stretch into radial streaks with chromatic splitting, a white flash, and you arrive in that project's own **live 3D scene** (a real CC0 model on a lit plinth, or a code-built ferry on a shader ocean) with a case-study panel. Back reverses the warp.

Views: **Preloader · Dome (home) · Project ×10 · Index · About · Services · Lab (3 experiments) · Contact.** Hash routing: `#work/<slug>`, `#index`, `#about`, `#services`, `#lab`, `#contact`, empty = dome.

## Page shell & libraries

```html
<link href="https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&family=Schibsted+Grotesk:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/" } }
</script>
```

- Addons (same version, loaded with `Promise.all` of dynamic imports): `postprocessing/EffectComposer.js`, `RenderPass.js`, `UnrealBloomPass.js`, `ShaderPass.js`, `OutputPass.js`, `loaders/GLTFLoader.js`, `environments/RoomEnvironment.js`.
- `<title>Night Shift — a creative studio that works after dark</title>`, `theme-color #05070d`, `viewport-fit=cover`.
- Layer order (z-index): `#stage` canvas 0 (fixed, inset 0, `touch-action:none`, cursor grab/grabbing/pointer), `.grain` 1 (SVG feTurbulence overlay, opacity .035 with GL, `mix-blend-mode:overlay`), `#labels` 5, cardinal letters 6, hero + HUD 10, project view 15, sheets 20, header 30, preloader 90.
- `html, body { overflow:hidden }` in GL mode; the list mode switches the document to `overflow:auto`.

## Tokens

```css
--night:#05070d; --night-2:#0a0e18; --night-3:#121828;
--star:#ece6d8; --star-dim:#a9adb8; --muted:#8d93a1;
--sodium:#f2a65a (warm accent, streetlight orange); --phosphor:#8fd3c8 (cool accent for eyebrows/status);
--line:rgba(236,230,216,.14); --line-2:rgba(236,230,216,.28);
--gutter:clamp(16px,3.2vw,40px); --r:2px; --ease:cubic-bezier(.2,.7,.1,1);
```

- **Instrument Serif** 400 (roman + italic) for every display line: hero h1 `clamp(44px,6.4vw,96px)/.92`, sheet h2 `clamp(40px,5vw,68px)/.95`, project h2 `clamp(44px,4.6vw,72px)/.92`, tracking −.02em. The italic phrase of each headline is `--sodium`.
- **Schibsted Grotesk** 400–600 for body, 16px/1.55. **IBM Plex Mono** 500 for every eyebrow, label, HUD readout and button (10–13px, uppercase, tracking .08–.16em).
- Focus: `2px solid --sodium`, offset 3px. Headings focused programmatically (`tabindex=-1`) show no outline.
- Per-project accents (used for hovered constellation, plinth ring, rim light, particles, project eyebrow): ferry `#f2a65a`, boot `#e7c44a`, lantern `#ffb36b`, watch `#d9b77a`, binoculars `#9fd0b8`, boombox `#ff7a5c`, whale `#5fc4d9`, duck `#f5d25c`, projector `#efdcb0`, compass `#9db8ff`.

## Layout & structure

**Header** (fixed, pointer-events only on children): left the wordmark — a 26px SVG of a dome arc on a horizon line with three tiny stars joined by lines (one `--sodium`) — and "Night *Shift*" in Instrument Serif 26px (*Shift* italic sodium). Right: mono links Sky · Index · About · Services · Lab · Contact (current link gets a 5px glowing sodium dot), a **Sound** button with three animated EQ bars (`aria-pressed`), and a "Menu" button that only shows under 860px and opens the links as a dropdown panel.

**Hero overlay** (bottom-left, `max-width:min(620px,62vw)`, pointer-events none): phosphor eyebrow with a 22px rule "Creative technology · open 19:00–05:00"; h1 "We do our best work *after dark.*"; paragraph "Night Shift is a small studio in a retired planetarium. Ten of our projects hang above you as constellations. Turn the dome, find a shape, and fly inside."; hint row of mono `kbd` chips "Drag turn the sky · Hover wake a constellation · Click fly in". After the first drag the hero drops to opacity .55; in a project or sheet it fades out.

**HUD** (bottom-right, mono 11px): "AZ 014° · ALT 22°" updated live from the camera, the local time + "studio open" (19:00–04:59) or "studio asleep · leave a note", and a "View as a list" link to `#index`.

**Labels**: one real `<button>` per constellation, positioned every frame at a point 0.32 shape-units below the shape's lowest star (`translate3d`, centred). It shows the two-digit number always; the name (Instrument Serif 22px) and "Shape · Year" (sodium mono) fade in when on. Hidden (`.off`) when the anchor is behind the camera or off-screen. Cardinal letters N/E/S/W sit just above the horizon in dim sodium.

**Project view**: canvas shows the project scene; a right panel `width:min(560px,42vw)` scrolls the case study over a 270° gradient from `rgba(5,7,13,.96)` to transparent. Panel: eyebrow "Constellation 03 of 10 · Lantern" (accent colour), h2 title, a meta `dl` (Client full width; Our role; Year) between hairlines, the first paragraph at 18px, still 1 with caption, paragraphs 2–3, still 2 with caption, then Previous / Next links with the neighbouring titles. A fixed pill "← Back to the sky" top-left (top 80px) and "Drag to turn the object · Esc back" bottom-left. Under 860px the panel becomes a bottom sheet starting at `top:46vh`, and the 3D object sits in the top half.

**Sheets** (About, Services, Lab, Contact, Index): left-anchored `width:min(760px,100%)`, gradient from `rgba(5,7,13,.97)` to transparent on the right so the dimmed dome shows through. They slide in from −24px over .6s, with a round 40px close button that is sticky at the top. The dome dims 55% behind them.
- **About**: "Nine people, one dome, *no daylight.*", the story (the lease on the harbour planetarium in 2016; hours 7pm–5am; first clients a ferry, a radio station, an open-air cinema), still `about.webp` with caption "Under the dome, 02:40. The old projector still runs on Thursdays.", a three-column facts row (Founded 2016 · People 9 · Shows shipped 64), and the client list in two mono columns.
- **Services**: "What happens *between seven and five.*", presented as a night timetable, not cards. Six rows with a sodium time and a moon whose phase grows down the list: 19:00 Concept & story · 21:00 Real-time 3D & WebGL · 23:00 Sound design · 01:00 Projection & spaces · 03:00 Apps & tools · 05:00 Launch & care. Each has one specific sentence and pill tags.
- **Lab**: "Things we made *at 4am.*", three bordered experiment cards (EXP 01–03, see Behaviour).
- **Contact**: "Tell us what happens *at night.*" with the form (name, email, a "What is it?" select, budget radio chips Under 20k / 20–60k (default) / 60k+ / Not sure yet, message) and the submit button "Send it to the night desk".
- **Index**: "Every constellation, *in order.*" with the 10 projects as rows: a 44px SVG of the constellation shape (lines + dots generated from the same data), title in serif 30px, mono subline "02 · Boot · Galoshe & Co. · 2024", and a 120px thumbnail on desktop.

**Preloader**: full-screen night with a 180×96 SVG dome arc that draws in sodium (`stroke-dashoffset`, glow), a serif percentage at 54px and a mono step line.

## The ten projects (data)

Each project has a slug, title, client, role, year, shape, accent, model, particle mode, two stills, a sky position (azimuth°, altitude°, angular radius°) and polylines in a −1…1 shape space (x right, y up). Stars are the unique polyline vertices; edges are consecutive vertex pairs.

| # | Title (slug) | Client · role · year | Shape · az / alt / size | Model · particles |
|---|---|---|---|---|
| 01 | Last Ferry Out (`last-ferry`) | Kestrel Sound Ferries · Campaign site, hull projection, live crossing tracker · 2025 | Ship · −8 / 24 / 9.1 | code-built ferry on shader ocean · `spray` |
| 02 | Puddle Season (`puddle-season`) | Galoshe & Co. · WebGL boot configurator, launch film, rain sound · 2024 | Boot · 28 / 38 / 8.4 | `rubber_boots` · `rain` |
| 03 | The Lamplighters (`lamplighters`) | Old Town Heritage Trust · Night-walk app, AR wayfinding, spatial audio · 2025 | Lantern · 64 / 24 / 8.4 | `Lantern_01` · `embers` |
| 04 | Third Shift (`third-shift`) | Hollis Watchworks · Brand film, macro product site, sound design · 2023 | Pocket watch · 100 / 38 / 7.7 | `vintage_pocket_watch` · `dust` |
| 05 | Nightjar Count (`nightjar-count`) | Fenland Bird Observatory · Citizen-science app, sound ID, live migration map · 2024 | Binoculars · 136 / 24 / 8.4 | `binoculars` · `migrate` |
| 06 | Graveyard Radio (`graveyard-radio`) | WNOX 98.3 Overnight · Rebrand, audio-reactive player, station idents · 2023 | Boombox · 172 / 38 / 9.1 | `boombox` · `pulse` |
| 07 | Deep Listening (`deep-listening`) | Harbourside Aquarium · Sound installation, projection, late-opening tickets · 2025 | Whale · 208 / 24 / 9.1 | `bronze_whale_statue` · `bubbles` |
| 08 | Bathwater Stories (`bathwater-stories`) | Hush Audiobooks · Bedtime audio app, character design, sleep timer · 2024 | Duck · 244 / 38 / 7.7 | `rubber_duck_toy` (fit 1.1) · `bubbles` |
| 09 | Moth Cinema (`moth-cinema`) | Orchard Lane Film Club · Festival identity, ticketing, projection rig · 2022 | Projector · 280 / 24 / 9.1 | `filmstrip_projector_8mm` · `moths` |
| 10 | True North Club (`true-north`) | Ridgeline Outfitters · Night-hike guide, star-navigation microsite · 2025 | Compass · 316 / 38 / 8.4 | `seadogs_compass` · `snow` |

Shape polylines (draw them as given):
- **Ship**: hull `(-1,-.25)(-.72,-.55)(.72,-.55)(1.05,-.2)(-1,-.25)`; cabin `(-.5,-.24)(-.5,.08)(.42,.08)(.42,-.22)`; funnel `(.05,.08)(.1,.45)(.32,.45)(.3,.08)`; mast and flag `(-.5,.08)(-.5,.72)(-.2,.6)`.
- **Boot**: outline `(-.45,1)(.15,1)(.15,-.1)(.75,-.4)(.85,-.75)(-.5,-.75)(-.5,-.1)(-.45,1)`; top band `(-.47,.72)(.15,.72)`; sole `(-.5,-.52)(.83,-.52)`.
- **Lantern**: ring `(0,.85)(-.15,1.05)(.15,1.05)(0,.85)`; roof `(-.45,.55)(0,.85)(.45,.55)(-.45,.55)`; glass `(-.45,.55)(-.35,-.6)(.35,-.6)(.45,.55)`; base `(-.35,-.6)(-.45,-.82)(.45,-.82)(.35,-.6)`; flame diamond `(0,-.25)(.09,0)(0,.22)(-.09,0)(0,-.25)`.
- **Pocket watch**: a 12-point ring of radius ≈.7 centred at (0,−.15) starting at (0,.55); crown `(0,.55)(0,.75)`; bow loop `(0,.75)(-.15,.9)(0,1.05)(.15,.9)(0,.75)`; hands `(0,-.15)(0,.3)` and `(0,-.15)(.32,-.3)`.
- **Binoculars**: two barrels `(-.75,.6)(-.25,.6)(-.2,-.7)(-.85,-.7)` closed and its mirror; bridge `(-.22,.1)(.22,.1)`; focus wheel `(0,.1)(0,.48)`.
- **Boombox**: body `(±1, .35/−.55)` rectangle; handle `(-.7,.35)(-.6,.75)(.6,.75)(.7,.35)`; two hexagonal speakers centred at (±.55,−.17) with radius ≈.3; cassette rectangle `(-.18,.05)…(.18,-.25)`; antenna `(.6,.75)(1.05,1.12)`.
- **Whale**: body loop `(-1,.05)(-.6,.35)(0,.42)(.5,.26)(.85,0)(.95,-.15)(.6,-.3)(0,-.36)(-.6,-.25)(-1,.05)`; flukes `(-1,.05)(-1.3,.4)(-1.15,.05)(-1.3,-.3)(-1,.05)`; fin `(0,-.36)(-.12,-.7)(.25,-.34)`; spout `(.5,.26)(.45,.62)`, then `(.45,.62)(.28,.78)` and `(.45,.62)(.62,.8)`; eye `(.66,.02)`.
- **Duck**: one loop `(.1,.55)(.22,.85)(.5,.92)(.66,.72)(.95,.62)(.62,.52)(.8,.2)(.75,-.3)(.3,-.55)(-.5,-.55)(-.85,-.2)(-.95,.25)(-.55,.05)(-.1,.15)(.1,.55)`; eye `(.44,.74)`; wing `(-.45,-.12)(.1,-.15)(.3,-.32)`.
- **Projector**: body rectangle `(-.6,0)…(.5,-.5)`; two hexagonal reels centred at (−.35,.45) and (.3,.45), radius .3; lens `(.5,-.15)(.8,-.1)(.8,-.35)(.5,-.3)`; light cone `(.8,-.1)(1.4,.25)` and `(.8,-.35)(1.4,-.7)`; legs `(-.5,-.5)(-.6,-.85)` and `(.4,-.5)(.5,-.85)`.
- **Compass**: eight-point star `(0,1)(.18,.18)(1,0)(.18,-.18)(0,-1)(-.18,-.18)(-1,0)(-.18,.18)(0,1)`; a 16-point ring of radius .62; centre star `(0,0)`.

Case-study copy (three paragraphs each, use verbatim; the stills captions follow):
1. **Last Ferry Out**. "Kestrel's 01:40 crossing is the last boat off the island, and most people who live there had never taken it. The brief was to make the night run feel like the reason to stay out late, not the punishment for it." / "For six weeks we projected a slow band of amber light along the hull, synced to a tracker site that drew the ferry as a moving lantern on a black chart. Every crossing became a 38-minute broadcast: tide, wind, the deck playlist and who was out by the rail." / "Night ridership rose 41% over the season. The tracker is still live, and the deck crew asked to keep the light." Captions: "The 01:40 leaving harbour with its amber band." · "Upper deck, second week. People came for the stars."
2. **Puddle Season**. "Galoshe makes one thing: a rubber boot that lasts twenty years. Their customers buy a pair, then disappear for two decades. They needed a launch that made a second colour feel like a reason to come back." / "We built a configurator where it is always raining. Each colour changes the street around the boot, from the reflections in the puddle to the colour of the shop light. Step into the puddle and the splash is simulated, never looped." / "The new mustard pair sold out in nine days, and the original bottle green sold out again behind it. Average time on the configurator was 3 minutes 40, mostly spent jumping in puddles." Captions: "Hero still: the mustard pair, 23:10, Wharf Street." · "Launch film frame. The splash was real; so was the cold."
3. **The Lamplighters**. "Until 1958 the old town's gas lamps were lit by hand, one street at a time. The Trust wanted to bring that walk back without adding a single sign to listed buildings." / "Visitors borrow a brass lantern with a phone inside. As you walk, the app lights the real lamps on your route one by one and tells the lamplighters' stories in spatial audio from the doorways where they happened." / "The walk runs every night from October to March and has been fully booked since launch. Nothing was screwed into a wall." Captions: "Lamp 14, Cooper's Wynd, lit on cue." · "The opening night. We relit the whole lane."
4. **Third Shift**. "Hollis has three watchmakers, and all of them work nights because the street is quiet enough to hear a balance wheel. That was the whole brand, and nobody outside the workshop knew it." / "We filmed one movement being assembled between midnight and six, at macro scale, and built the site around that single film. You scrub through the night by dragging, and the sound of each component seating is the real recording, slowed down." / "The waiting list went from four months to fourteen. Hollis now opens the workshop window to the street on Fridays after midnight." Captions: "Calibre H-3, open back, under the green lamp." · "The workshop window from Cutler Lane, 03:15."
5. **Nightjar Count**. "Most songbirds migrate at night, and you can hear them calling overhead if you know what to listen for. The observatory wanted ten thousand pairs of ears, not ten." / "The app listens with your phone, flags likely flight calls and asks you to confirm them by ear. Every confirmed call drops a point on a live map that shows the night's migration moving across the fens." / "In its first autumn, 6,200 volunteers logged 81,000 calls. Two species were recorded in the county for the first time." Captions: "Count night on Holme Fen, full moon." · "The field kit: phone, binoculars and a pencil tally."
6. **Graveyard Radio**. "WNOX's overnight show has run from midnight to six since 1987. Its listeners are taxi drivers, nurses, bakers and insomniacs, and the old branding looked like a car dealer's." / "We rebuilt the station around the idea of company in the dark. The web player draws the live broadcast as a slow aurora, and each presenter has a sung ident we wrote with them in the studio at 3am." / "Online listening is up 2.3×. The idents are now requested by name on the phone-in." Captions: "Studio B during the 02:00 hour." · "Who's listening: a cab at the lights on Union Street."
7. **Deep Listening**. "The aquarium's whale gallery is empty after five, which is when the real whale recordings they hold are most affecting. The brief: give people a reason to come back after dark and lie down." / "We turned the gallery into a listening room. Hydrophone recordings from the North Atlantic play through 32 speakers, and the tank wall shows a slow projection drawn by the song itself. Lower notes travel further across the glass." / "Late openings now sell out every Thursday, and the average visit is 47 minutes. Most people stay lying down." Captions: "Thursday late: the listening floor." · "The song wall in Gallery 3, drawn live by the recording."
8. **Bathwater Stories**. "Hush makes audiobooks for adults. Parents kept asking for something for the twenty minutes between bath and bed, the hardest twenty minutes of the day." / "We designed an app with one character, a duck who narrates from the side of the bath, and a timer that slows the story down as the minutes pass. Each story's music is written to slow its tempo by a fifth from start to finish." / "It reached the top ten in kids' apps in four countries. The most common review mentions the duck by name." Captions: "The night light setting at 19:42." · "Story six, chapter two. The ceiling stars are part of the app."
9. **Moth Cinema**. "Orchard Lane screens 8mm prints on a bedsheet in an old apple orchard, ten nights a summer, for whoever turns up with a chair. They wanted to grow without losing the bedsheet." / "We gave the festival a moth for a mascot, because the moths always come for the beam. Tickets are free but numbered by seat, so the site shows a hand-drawn orchard where you pick a gap between two trees and bring your own chair." / "Attendance tripled to 400 a night, and the moth was printed on 2,000 tote bags. The bedsheet is the same one." Captions: "Night four: Sherlock Jr. on the sheet." · "The club's 1962 projector, and its regulars."
10. **True North Club**. "Ridgeline sells kit for long walks, and their customers kept getting lost on short ones once the sun went down. The brief was a guide to walking at night that people would actually finish reading." / "We wrote a field guide in twelve short chapters, each one paired with a live sky for wherever you are standing. It teaches one star at a time: Polaris first, then the shapes that point to it, then how to walk a bearing by them." / "The guide is read to the end by 58% of visitors, and Ridgeline's night-hike clubs now run in eleven towns." Captions: "Chapter 4, Black Fell ridge: find north without a phone." · "The kit list, pinned by a compass and lit by a lantern."

## Behaviour & interaction

**Device tiers** (decided before creating the renderer): read `UNMASKED_RENDERER_WEBGL` from a throwaway WebGL2 context. A software rasteriser (SwiftShader/llvmpipe) → tier 0. Touch or a short side under 700px → tier 1. `deviceMemory ≤ 4` or `hardwareConcurrency ≤ 4` → tier 1. Otherwise tier 2. `?tier=N` overrides.
Tiers: 0 = 90k stars, DPR 1 (software: internal DPR .6), fluid 64 / dye 192; 1 = 120k stars (≈37% of desktop), DPR ≤ 1.5, fluid 96 / dye 256; 2 = 320k stars, DPR ≤ 2, fluid 128 / dye 512. An fps monitor (every 2 s) lowers the DPR by .25 down to 1 when fps < 40.

**Renderer**: `antialias:false`, ACES filmic tone mapping, exposure 1, sRGB output. Dome camera: perspective, FOV 56 (72 in portrait), rotation order YXZ, at the origin. Azimuth convention: direction = `(−sin az·cos alt, sin alt, −cos az·cos alt)`, so camera yaw = az and pitch = alt.

**Sky** (rendered as a BackSide sphere r 900, `gl_Position = p.xyww`, no depth):
- Once at startup, bake the Milky Way into an equirect half-float target (2048×1024 on tier 2, 1024×512 otherwise) with 5-octave value-noise fbm. The galactic plane normal is `normalize(.42,.62,.66)`. Band = `exp(−g²/.03)`, cool `(.26,.30,.42)`, modulated by fbm(d·3.6), with dust lanes `smoothstep(.48,.78,fbm(d·8+7.3))` cutting 80%, a warm core `(.42,.30,.20)·exp(−g²/.006)·n²` and faint nebula patches.
- Per frame: gradient horizon `#05070c`-ish `(.018,.026,.048)` to zenith `(.004,.006,.014)`, a sodium light-pollution glow `(.55,.27,.09)·(.015+.32·pol)·exp(−el·6.5)`, plus the baked band ×.16·(1−.9·pol)·reveal.
- A planetarium **alt-az grid** (every 15° altitude and 30° azimuth, `fwidth` anti-aliased, phosphor at 6%) fades in while you drag (+.08 per move event) and out at .6/s.
- **House lights**: at load the sky shows the physical dome interior: warm grey `(.17,.14,.12)` with panel seams every 9° of elevation and 10° of azimuth. `uHouse` fades from 1 to 0 during the intro.
- **Horizon silhouette**: a second BackSide sphere band drawn over the stars. Its height per azimuth comes from a 2048×1 float texture computed on the CPU: rolling hills (`.022 + .014 sin 2a + .009 sin 5a + .005 sin 11a + .003 sin 23a`, radians) and about 130 seeded triangular trees (half-width .006–.018 of a turn, height .018–.048). The edge is anti-aliased with `fwidth`.

**Stars** (`THREE.Points`, additive, no depth): positions on a sphere r 500, y > −.08. 55% are sampled around the galactic great circle with a gaussian offset σ .13, and 45% are uniform. Per star `aData = (size, brightness, phase, temperature)`: brightness `b = U^22` (so ~0.5% are bright and ~90% are dust), size `.55 + b·4.8` px × scale (`clamp(h/900,.75,1.5)`) × DPR. Alpha = `(.028 + 2.7·b^1.6)`. Sub-1.5px stars keep a 1.5px quad and scale their alpha down. Colour comes from temperature: blue `(.62,.74,1)` → white `(1,.97,.92)` → orange `(1,.74,.48)`. Twinkle = `1 + (.28 + .5·(1−smoothstep(0,.35,y)))·sin(t·(1.3+4·phase) + 61·phase)`, stronger near the horizon. Sprite = `exp(−6r) + .06·exp(−1.5r)` with a soft circular cut (no square edges). The reveal sweeps up from the horizon: `smoothstep(y−.12, y, reveal·1.25−.1)`. The light-pollution limit hides stars with `b < uLimit`.

**Constellations** (radius 440): each shape point maps to `normalize(c + x·east·tan(size) + y·north·tan(size))`, where `east = (cos az, 0, −sin az)` and `north = east × c`. In portrait the size is ×.92.
- Stars: a Points layer with `aD = (index, size 4.5–9 px, phase)`. Colour lerps from `(1,.95,.86)` to `accent·1.25+.15` by hover·.8. Intensity `(1.4 + 2.6·hover)·pulse`, where pulse is `.85 + .15 sin(1.7t + 30·phase)`. Size ×(1 + .55·hover).
- Lines: **screen-space quads** (6 vertices per segment, attributes A, B, side ±1, end 0/1, index, t). Project both ends, offset by the perpendicular × (width + 1px AA) with width `(1.1 + .7·hover)·DPR` px, and leave a 7px gap at each star (max 30% of the length). `side: DoubleSide`. `t = (segmentIndex + end)/segmentCount`. Fragment alpha = edge falloff × `(.13·reveal + (.85 + .4·hover)·smoothstep(t−.015, t, draw))`, so they **draw in along the shape**.
- `hover` eases to 1 at 6/s and back at 3/s. `draw` rises at 1/0.9 s and falls at 1/0.45 s.

**Shooting stars**: every 7–16 s, a quad streak spans ~10–25° near the view centre over ~0.7 s (head leads, tail trails .35 behind, alpha `sin(πt)`).

**Navigation**: drag maps pixels to radians as `fov/innerHeight`, so the sky follows the finger 1:1. Pitch is clamped to 0.04–1.32 rad. On release the velocity decays with `exp(−2.6·dt)`. Wheel adds yaw velocity. Arrow keys on the focused stage turn and tilt it. After 5 s idle with nothing hovered, an auto-drift eases toward .012 rad/s. Starting view: desktop yaw 12°, pitch 22°; portrait yaw −8° (on the ship), pitch 11°.

**Hover / pick**: every frame, project each constellation centre and an edge point (1.15 units east) to screen; the hit radius is their distance. Pointer within radius·1.05 → hover (nearest wins). Hover → the label gets `.on`, the name **decodes** (34 ms ticks over 520 ms; each character resolves once `k > .25 + .75·i/len`, otherwise it shows a random glyph from `·+*×◦⁘∴∵✶` plus A–Z and 0–9), a chime plays and the model is prefetched. Click (moved < 7 px, < 500 ms) opens it. On touch the first tap selects and centres a constellation; the second tap opens it.

**GPU fluid** (stable fluids, half-float RGBA ping-pong targets, `LinearFilter`): sim grid = tier size on the short side × aspect; dye grid likewise. Each pointer move with speed > .0005 splats velocity `(dx·5200, −dy·5200)` (dx/dy in screen fractions) with radius .0016 and grey-blue dye `(.5,.52,.56)·min(1.2, speed·30)` with radius .0022. Per frame: curl → vorticity confinement (strength 18) → divergence → pressure ×.8 → 18 Jacobi iterations → gradient subtract → advect velocity (dissipation 1.1) → advect dye (dissipation .9). The sim **sleeps** 6 s after the last splat. Composite pass, after the RenderPass: sample the scene 10 times along `−velocity·.00013·2` (the **starlight smear**), then add mist `uMist(#c9cfd8)·m²·.07` and brighten the stars under it by `·(1 + .8m)`, where `m = |dye|`.

**Post chain**: RenderPass → FluidPass → UnrealBloomPass (half-res; dome: strength .75, radius .5, threshold .32; projects: .38 / .35 / .92) → OutputPass (tone map + sRGB) → GradePass: chromatic aberration radial from `uCenter` (.0012 at rest), vignette `mix(1, smoothstep(1.25,.25,|d·aspect|), .55)`, film grain ±.0225 per pixel per frame, and `uFade`/`uFlash`. With `uWarp > 0` it runs a 20-tap radial zoom blur (scale down to `1 − .55·warp`) with per-channel offsets `ca = .0012 + .022·warp`, brightened ×(1 + 1.4·warp).

**Warp in** (`#work/<slug>`): ease the camera to centre the constellation (520 ms, cubic in-out, 3° low on desktop and 11° low in portrait so the shape sits above centre). Set `uCenter` to its screen position and play the whoosh. Over 950 ms (cubic in), warp 0→1, dome FOV narrows by 34° and a flash rises to .6 in the last 20%. Then swap the RenderPass to the project scene (showing "Tuning in…" if the model is still loading). Over 1100 ms (cubic out), warp 1→0, the flash decays, and the project camera dollies from base+9 to base distance while orbiting 1.2 rad. The panel appears 350 ms into the arrival. **Back** (button, Esc, browser back) reverses it: 750 ms warp-in with the camera pulling 8 units back, swap to the dome, then 1000 ms warp-out with the FOV widening back from −34°. Project to project via Previous/Next: 650 ms warp-in with a dolly forward, then the normal arrival. Programmatic focus moves to the project title on arrival and back to the constellation's label on return.

**Project scenes** (built lazily, cached, `compileAsync` before showing): `RoomEnvironment` PMREM at intensity .35, backdrop BackSide sphere `(.006,.008,.016)` plus an accent horizon glow (.022), 4,000 background stars, key light `#fff1dc` 1.6 from (2.5,3.5,2.8), accent rim light 4.5 from (−3,1.6,−2.5), hemisphere `#2a3550`/`#050608` .6. Model scenes: a metal plinth (r 1.05/1.12, h .32, `#0d1016`, roughness .32, metalness .7), an accent emissive torus ring on its rim (×3, blooms) and a radial contact-shadow decal. The GLB is fitted to 1.45 units on its longest side (duck 1.1) and sits on the plinth top, turning at .18 rad/s. **Ferry** (no model): an extruded hull profile with bevel, a navy waterline, an emissive accent band (×3.2), a cabin with a canvas window texture (emissive), a bridge, a funnel, a mast lamp, two orange lifeboats, rails with 15 posts per side and a warm point light. It bobs on a shader **ocean**: 40×40 plane, 180² segments, four summed sines, analytic normals, Fresnel, moon specular `pow(·,180)`, an accent glow near the hull and distance fade. Plus a moon sphere at (−14,7,−38).
Particles (additive points, one shader, mode uniform): `rain` (1,600 vertical streak sprites falling 5.5 u/s), `embers` (rise .32 u/s with sway and flicker), `dust`, `migrate` (drift sideways in a band), `pulse` (rings expanding from the object), `bubbles` (ring sprites rising .4 u/s), `moths` (orbit a point with 20 Hz flicker), `snow` (falls .35 u/s), `spray` (low drifting mist).
Project camera: FOV 36 (48 in portrait), orbiting (0,.5,0). Drag turns it (yaw −.008 rad/px with inertia `exp(−2.4dt)`, pitch −.05….75) and it auto-orbits at .06 rad/s. Base distance 4.1 desktop / 4.6 tablet / 7.2 portrait. `setViewOffset` shifts the object to the left (x + 19% of the width) on desktop and up (24% of the height) under 860px, so it never sits under the panel.

**Intro**: driven by wall-clock time over 3.4 s (cubic in-out). House lights fade by `k·1.6`, stars and the Milky Way reveal from `k > .15`, constellation stars from `.45` and lines from `.6`. It reads as the planetarium lights going down.

**Sound** (Web Audio, all synthesised): on the first pointerdown or keydown anywhere (except on the Sound button itself), unless the visitor muted it before (`localStorage ns-sound=off`), build the graph. The drone is five oscillators on root 55 Hz: ×1 saw (−6 c), ×1.5 triangle (+4 c), ×2 sine, ×3 triangle (+7 c), ×.5 sine, gains .16/.2/.22/.06/.3, bus .32. They feed a lowpass at 420 Hz (Q .9) with a .045 Hz LFO ±140 Hz, into a 3.4 s generated-noise convolver (wet .55) and a master that fades to .5 with τ 1.2 s. **Chime** on hover: A-minor pentatonic note per project (220…784 Hz), partials ×1 / ×2.76 / ×5.4 at .16 / .05 / .02, 6 ms attack and 2.4 s/partial decay into the reverb. **Whoosh** on warp: white noise through a bandpass (Q 2.2) sweeping 180→3,200 Hz in (reversed out), peak .22 at .8 s, plus a sub sine dropping 90→38 Hz on arrival. The Sound button toggles with a .25 s fade and the choice is stored. The context suspends while the tab is hidden.

**Lab** (works without WebGL):
- **EXP 01 Draw a constellation**: a canvas with seeded background stars. Click to add stars (max 24); each joins the last with a sodium line and a radial-gradient glow, and plays a chime. Keyboard: arrows move a phosphor reticle, Enter/Space place a star. Undo, Clear, and **Name it**, which hashes the points into "The Old Kettle", "The Lost Glove" and so on and draws the name in italic serif. Output: "N stars".
- **EXP 02 Drone tuner**: an XY pad (grid background, glowing sodium dot) bound to two range inputs. Root = 36 + 44·x Hz; filter = 160·16^y Hz. It retunes the live drone with 80 ms smoothing. A status line says whether sound is on.
- **EXP 03 Light pollution**: a Bortle range 1–9 drives the dome live (`uLimit = .02 + (B−1)/8·.72`, sodium glow `pol = .03 + .97·(B−1)/8`). It redraws a 2D preview canvas (1,400 stars filtered by the same limit, a sky gradient warming with B, a treeline) and announces "≈ 1,870 of 90,000 stars still visible on the dome" (computed from the `U^22` distribution).

**Contact form**: `novalidate` with custom rules: name ≥ 2 characters; email regex; type required; message ≥ 20 characters (the error counts down the characters needed). Errors appear on blur or submit, set `aria-invalid`, and focus moves to the first invalid field. Submit shows "Sending…" for 900 ms, then replaces the form with a focused `role=status` card: "Received at 02:14." plus the escaped name, type, budget and email, and "Send another".

**Pausing**: rAF stops while `document.hidden`. The fluid sim sleeps when idle, and the clock resumes without a jump.

## Responsive

- **1440**: hero bottom-left (max 62vw), HUD bottom-right, 2–3 constellations in view, project panel right 42vw (max 560), sheets 760px from the left.
- **768**: the menu collapses (Menu button with dropdown); the hero spans the width above the HUD; the HUD becomes a three-column row at the bottom. The project panel is a bottom sheet from 46vh and the object is framed in the top half.
- **390**: portrait dome FOV 72, constellations ×.92, starting on the ship. Hero h1 `clamp(40px,11vw,64px)`, the "Hover" hint is hidden, the facts grid has 2 columns, services time column 62px, clients 1 column, the Sound label is hidden (bars stay). The project camera is FOV 48 at distance 7.2. Never any horizontal scroll (`scrollWidth ≤ innerWidth` at 390/768/1440).

## Accessibility & reduced motion

- The stage is `role=application`, focusable and labelled with keyboard instructions. Every constellation also exists as a real button in `#labels` (role list/listitem) with an `aria-label` like "Puddle Season. Boot constellation. Galoshe & Co., 2024. Open project". Focusing one centres it and wakes it; Enter opens it.
- Skip link, semantic sections with `aria-labelledby`, the preloader as `role=status`, `aria-pressed` on Sound, `aria-expanded` on Menu, Esc closes any view. Focus moves to the heading of each opened view and back afterwards.
- All text meets AA on `#05070d` (muted `#8d93a1` ≈ 6.5:1).
- `prefers-reduced-motion`: no twinkle, fluid, shooting stars, auto-drift or name scrambling. The intro is instant. Lines show fully on hover. Warps become 220 ms fades (out, swap, in). CSS transitions drop to .15 s.

## Fallbacks

- **No WebGL2**, `?nogl`, a failed three.js import or a renderer error → `body.no-gl`: the hero and HUD become normal flow, followed by "The work, as a list" (the same 10-row index), the document scrolls, and each project opens as a full-page article with still 1 as its hero image. Sheets, form, sound and Lab all still work.
- A failed model load still opens the case-study panel over the dome.
- The preloader measures real steps: fonts (10) → engine imported (30) → stars generated (20) → `renderer.compileAsync(dome)` (30) → two composed frames rendered (10).

## Assets

All local, relative paths.
- `assets/models/<name>.glb` (0.1–0.95 MB each, 5.1 MB total): Poly Haven CC0 models, repacked into single GLBs with WebP textures (`EXT_texture_webp`; colour and normal maps ≤1024 px, ARM maps ≤512 px) and quantised geometry (`KHR_mesh_quantization`: int16 positions with a dequantising node, int8 normals, uint16 UVs where they fit in 0–1). three.js `GLTFLoader` reads both extensions natively. The models are `rubber_boots`, `Lantern_01`, `vintage_pocket_watch`, `binoculars`, `boombox`, `bronze_whale_statue`, `rubber_duck_toy`, `filmstrip_projector_8mm` and `seadogs_compass`. They load lazily per project, and the hovered one is prefetched.
- `assets/stills/*.webp` (1400w, about 50–190 KB each, graded at saturation 86% with levels 2–98%, gamma .97), shot on a "35 mm film at night" brief with no text and no logos:
  `ferry-a` (white ferry crossing a black harbour with an amber light band) · `ferry-b` (upper deck at night, warm bulbs, people at the rail) · `boots-a` (mustard rain boots on wet cobbles under a streetlamp) · `boots-b` (child in a yellow raincoat jumping a puddle at night) · `lamp-a` (cobbled lane lit by hanging brass lanterns) · `lamp-b` (hand lighting a brass street lantern with a pole) · `watch-a` (open pocket-watch movement under a green desk lamp) · `watch-b` (watchmaker's lit window from a rainy street) · `nightjar-a` (two people on a hillside with binoculars, birds across the full moon) · `nightjar-b` (phone with a sound-wave screen, binoculars and a tally notebook on a post) · `radio-a` (late-night radio studio, host from behind) · `radio-b` (taxi driver's hand on the wheel, amber dash radio, rain) · `whale-a` (people lying on cushions before a huge blue aquarium tank) · `whale-b` (wall of blue light lines with one visitor) · `duck-a` (rubber duck glowing on a bath edge at night) · `duck-b` (star projector dots on a bedroom ceiling, a parent's hand on a picture book) · `moth-a` (open-air orchard cinema, moths in the beam) · `moth-b` (8 mm projector on a table outdoors, dusty beam) · `north-a` (hiker with a red headlamp and compass under the Milky Way) · `north-b` (paper star map and brass compass lit by a lantern) · `about` (studio team at desks under a planetarium dome full of stars).

## Make it yours

This prompt rebuilds one exact design. If everyone ships it unchanged, the sites will look alike. Before you paste it, change these lines so the result is yours. Each change is one edit to the prompt, and the structure and interactions stay intact.

1. **Studio and work.** Replace Night Shift and the ten projects with your own studio, its hours and your real case studies. Keep 8–12 projects so the dome stays populated (about one every 30–45° of azimuth). Keep three short paragraphs and two stills per project so the panel scrolls in balance.
2. **The sky's subject.** The dome of constellations is the signature. Re-theme it while keeping drag, inertia, fluid smear, hover draw-in and the warp. Some options: an **underwater** dome where projects are bioluminescent creatures and the smear reads as current; a **city at night** seen from a rooftop, with projects as lit-window patterns in towers; a **microscope slide**, where projects are cell clusters and the warp is a zoom through the objective; a **festival field**, where projects are lantern clusters. Keep the shape-from-the-project rule.
3. **Constellation shapes.** Draw each project's shape from its subject: a cup for a café, a key for a locksmith, a bicycle for a courier app. Keep 8–20 stars and 7–20 lines per shape so they read at 8° radius.
4. **Palette.** Swap `--sodium` (#f2a65a) and `--phosphor` (#8fd3c8) and the ten accents for your brand. Keep the night ground at luminance < 3% and body text ≥ 4.5:1 against it. Avoid purple-indigo by default, and re-tint the light-pollution glow to match the new warm accent.
5. **Type pairing.** Replace Instrument Serif + Schibsted Grotesk + IBM Plex Mono with another display serif or grotesk, a plain body sans and a mono for the HUD. Keep the HUD and labels in mono so the planetarium feel survives.
6. **Project scenes.** Swap the Poly Haven models for CC0 or your own GLBs of your products (one per project, fitted to 1.45 units), or code-built objects like the ferry. Change each particle mode to suit its subject (rain, embers, bubbles, moths, snow and so on).
7. **Stills.** Regenerate or shoot two stills per project with one consistent lens, light and grade ("35 mm film at night, natural grain, no text, no logos"), export as 1400w WebP under 250 KB, and keep the same filenames or update the data.
8. **Voice and sound.** Rewrite the copy in your own voice. Say what the work did ("night ridership rose 41%"), not "unlock your potential". Retune the drone root (36–80 Hz) and the chime scale to your brand.

Tell your AI: *"Build exactly as specified, but with these changes: …"*, then list your edits.

---

## Reference implementation (use verbatim)

The complete working `index.html`. Every number in the spec above is in this file; if the two ever seem to differ, the code wins. Images and models referenced as `assets/...` can be downloaded from https://copytheprompt.design/demos/creative-studio-constellation-portfolio/assets/ or replaced with your own (see Make it yours).

````html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Night Shift — a creative studio that works after dark</title>
<meta name="description" content="Night Shift is a creative technology studio in an old planetarium. Ten projects hang in the sky as constellations: drag the dome, hover a shape, fly inside.">
<meta name="theme-color" content="#05070d">
<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=Schibsted+Grotesk:wght@400;500;600&family=IBM+Plex+Mono:wght@400;500&display=swap" rel="stylesheet">
<script type="importmap">
{ "imports": {
  "three": "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js",
  "three/addons/": "https://cdn.jsdelivr.net/npm/three@0.170.0/examples/jsm/"
} }
</script>
<style>
:root{
  --night:#05070d; --night-2:#0a0e18; --night-3:#121828;
  --star:#ece6d8; --star-dim:#a9adb8; --muted:#8d93a1;
  --sodium:#f2a65a; --phosphor:#8fd3c8; --line:rgba(236,230,216,.14); --line-2:rgba(236,230,216,.28);
  --serif:"Instrument Serif", "Iowan Old Style", Georgia, serif;
  --sans:"Schibsted Grotesk", "Helvetica Neue", Arial, sans-serif;
  --mono:"IBM Plex Mono", ui-monospace, Menlo, monospace;
  --gutter:clamp(16px, 3.2vw, 40px);
  --r:2px;
  --ease:cubic-bezier(.2,.7,.1,1);
  --accent:var(--sodium);
}
*{box-sizing:border-box}
html,body{margin:0;min-height:100%;background:var(--night);color:var(--star);overflow:hidden}
body{font:400 16px/1.55 var(--sans);-webkit-font-smoothing:antialiased;text-rendering:optimizeLegibility}
a{color:inherit}
button,input,select,textarea{font:inherit;color:inherit}
img{max-width:100%;display:block}
:focus-visible{outline:2px solid var(--sodium);outline-offset:3px;border-radius:var(--r)}
[tabindex="-1"]:focus{outline:none}
.sr-only{position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;border:0}
.skip{position:fixed;left:12px;top:-60px;z-index:100;background:var(--star);color:var(--night);padding:10px 14px;font:500 13px var(--mono);text-decoration:none}
.skip:focus{top:12px}

/* ---------- stage ---------- */
#stage{position:fixed;inset:0;z-index:0;touch-action:none;cursor:grab;outline:none}
#stage.dragging{cursor:grabbing}
#stage.hot{cursor:pointer}
#stage canvas{display:block;width:100%;height:100%}
.grain{position:fixed;inset:-50%;z-index:1;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");}
body.gl .grain{opacity:.035}

/* ---------- header ---------- */
.top{position:fixed;left:0;right:0;top:0;z-index:30;display:flex;align-items:center;justify-content:space-between;gap:16px;padding:18px var(--gutter);pointer-events:none}
.top > *{pointer-events:auto}
.mark{display:flex;align-items:center;gap:10px;text-decoration:none}
.mark svg{width:26px;height:26px}
.mark b{font:400 26px/1 var(--serif);letter-spacing:-.01em}
.mark b i{font-style:italic;color:var(--sodium)}
.nav{display:flex;align-items:center;gap:4px}
.nav a,.nav button{font:500 12px/1 var(--mono);letter-spacing:.08em;text-transform:uppercase;text-decoration:none;color:var(--star-dim);padding:10px 10px;border-radius:var(--r);background:none;border:0;cursor:pointer;display:inline-flex;align-items:center;gap:7px}
.nav a:hover,.nav button:hover,.nav a[aria-current="page"]{color:var(--star)}
.nav a[aria-current="page"]::before{content:"";width:5px;height:5px;border-radius:50%;background:var(--sodium);box-shadow:0 0 10px var(--sodium)}
.snd .bars{display:inline-flex;gap:2px;align-items:flex-end;height:11px}
.snd .bars i{width:2px;background:currentColor;height:30%;transition:height .3s}
.snd[aria-pressed="true"] .bars i{animation:eq 1.1s ease-in-out infinite}
.snd[aria-pressed="true"] .bars i:nth-child(2){animation-delay:-.4s}
.snd[aria-pressed="true"] .bars i:nth-child(3){animation-delay:-.75s}
@keyframes eq{0%,100%{height:25%}50%{height:100%}}
.nav .menu-btn{display:none}

/* ---------- hero overlay ---------- */
.hero{position:fixed;left:var(--gutter);bottom:clamp(20px,5vh,56px);z-index:10;max-width:min(620px,62vw);pointer-events:none;transition:opacity .8s var(--ease), transform .8s var(--ease)}
.hero .eyebrow{font:500 11px/1.4 var(--mono);letter-spacing:.16em;text-transform:uppercase;color:var(--phosphor);margin:0 0 14px;display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center}
.hero .eyebrow::before{content:"";width:22px;height:1px;background:currentColor}
.hero h1{font:400 clamp(44px,6.4vw,96px)/.92 var(--serif);letter-spacing:-.02em;margin:0 0 18px;text-wrap:balance}
.hero h1 em{color:var(--sodium);font-style:italic}
.hero p{margin:0;max-width:440px;color:var(--star-dim);font-size:15px}
.hero .hint{margin-top:22px;display:flex;flex-wrap:wrap;gap:8px 18px;font:500 11px/1 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--muted)}
.hero .hint span{display:inline-flex;gap:8px;align-items:center}
.hero .hint kbd{font:inherit;border:1px solid var(--line-2);padding:4px 6px;border-radius:var(--r);color:var(--star-dim)}
body.touched .hero{opacity:.55}
body.view-project .hero,body.view-sheet .hero{opacity:0;transform:translateY(12px)}

.hud{position:fixed;right:var(--gutter);bottom:clamp(20px,5vh,56px);z-index:10;text-align:right;font:500 11px/1.8 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--muted);pointer-events:none;transition:opacity .6s}
.hud b{color:var(--star-dim);font-weight:500}
.hud .open{color:var(--phosphor)}
body.view-project .hud{opacity:0}
.hud .list-link{pointer-events:auto;color:var(--star-dim);text-decoration:none;border-bottom:1px solid var(--line-2)}

/* ---------- constellation labels ---------- */
#labels{position:fixed;inset:0;z-index:5;pointer-events:none;overflow:hidden}
.cl{position:absolute;left:0;top:0;pointer-events:auto;background:none;border:0;padding:6px 8px;cursor:pointer;color:var(--star-dim);
  font:500 10px/1 var(--mono);letter-spacing:.14em;text-transform:uppercase;white-space:nowrap;display:flex;flex-direction:column;align-items:center;gap:7px;will-change:transform;transition:opacity .4s}
.cl .num{opacity:.8}
.cl .name{font:400 22px/1 var(--serif);letter-spacing:0;text-transform:none;color:var(--star);opacity:0;transform:translateY(-4px);transition:opacity .35s, transform .5s var(--ease)}
.cl .meta{opacity:0;transition:opacity .35s .1s;color:var(--sodium)}
.cl.on .name,.cl:focus-visible .name{opacity:1;transform:none}
.cl.on .meta,.cl:focus-visible .meta{opacity:1}
.cl.on .num{color:var(--sodium)}
.cl.off{opacity:0;pointer-events:none}
body.view-project #labels,body.view-sheet #labels{opacity:0;pointer-events:none}
body.view-project #labels .cl,body.view-sheet #labels .cl{pointer-events:none}
.cards{position:fixed;inset:0;z-index:6;pointer-events:none}
.card-dir{position:absolute;font:500 11px/1 var(--mono);letter-spacing:.2em;color:rgba(242,166,90,.55);transform:translate(-50%,-50%)}
body.view-project .cards,body.view-sheet .cards{opacity:0}

/* ---------- preloader ---------- */
#loader{position:fixed;inset:0;z-index:90;background:var(--night);display:grid;place-items:center;transition:opacity .9s var(--ease), visibility 0s .9s}
#loader.done{opacity:0;visibility:hidden}
.ld{display:grid;justify-items:center;gap:18px;text-align:center;padding:0 24px}
.ld svg{width:180px;height:96px;overflow:visible}
.ld .arc-bg{stroke:var(--line);fill:none;stroke-width:1}
.ld .arc{stroke:var(--sodium);fill:none;stroke-width:1.5;stroke-linecap:round;transition:stroke-dashoffset .5s var(--ease);filter:drop-shadow(0 0 6px rgba(242,166,90,.6))}
.ld .pct{font:400 54px/1 var(--serif)}
.ld .step{font:500 11px/1.4 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--muted);min-height:1.4em}

/* ---------- sheets (About / Services / Lab / Contact / Index) ---------- */
.sheet{position:fixed;z-index:20;top:0;bottom:0;left:0;width:min(760px,100%);overflow-y:auto;overscroll-behavior:contain;
  background:linear-gradient(90deg, rgba(5,7,13,.97) 0%, rgba(5,7,13,.93) 78%, rgba(5,7,13,.0) 100%);
  padding:96px calc(var(--gutter) + 40px) 80px var(--gutter);opacity:0;transform:translateX(-24px);transition:opacity .5s var(--ease), transform .6s var(--ease);visibility:hidden}
.sheet.open{opacity:1;transform:none;visibility:visible}
.sheet[hidden]{display:block}
.sheet .close{position:sticky;top:0;float:right;margin:-60px -24px 0 0;background:var(--night-2);border:1px solid var(--line-2);color:var(--star);width:40px;height:40px;border-radius:50%;cursor:pointer;display:grid;place-items:center;z-index:2}
.sheet .close:hover{border-color:var(--sodium)}
.kicker{font:500 11px/1.4 var(--mono);letter-spacing:.16em;text-transform:uppercase;color:var(--phosphor);margin:0 0 14px}
.sheet h2{font:400 clamp(40px,5vw,68px)/.95 var(--serif);letter-spacing:-.02em;margin:0 0 22px;text-wrap:balance}
.sheet h2 em{font-style:italic;color:var(--sodium)}
.sheet h3{font:400 28px/1.1 var(--serif);margin:0 0 8px}
.sheet p{color:#c9c6bf;max-width:58ch}
.lede{font-size:18px;color:var(--star)!important}
.sheet figure{margin:28px 0}
.sheet figure img{width:100%;aspect-ratio:3/2;object-fit:cover;filter:saturate(.9) contrast(1.03)}
.sheet figcaption{font:500 11px/1.5 var(--mono);letter-spacing:.06em;color:var(--muted);margin-top:8px}
.facts{display:grid;grid-template-columns:repeat(3,1fr);gap:0;border-top:1px solid var(--line);border-bottom:1px solid var(--line);margin:30px 0}
.facts div{padding:18px 14px 18px 0}
.facts dt{font:500 10px/1.4 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.facts dd{margin:6px 0 0;font:400 34px/1 var(--serif)}
.clients{font:500 12px/2 var(--mono);letter-spacing:.06em;color:var(--star-dim);columns:2;padding:0;list-style:none}

/* services timetable */
.shift{list-style:none;margin:30px 0 0;padding:0;border-top:1px solid var(--line)}
.shift li{display:grid;grid-template-columns:86px 1fr;gap:18px;padding:22px 0;border-bottom:1px solid var(--line);position:relative}
.shift time{font:500 13px/1.3 var(--mono);color:var(--sodium);padding-top:6px}
.shift p{margin:6px 0 10px}
.shift .tags{display:flex;flex-wrap:wrap;gap:6px}
.shift .tags span{font:500 10.5px/1 var(--mono);letter-spacing:.06em;border:1px solid var(--line-2);padding:6px 8px;border-radius:20px;color:var(--star-dim)}
.shift li .moon{position:absolute;right:0;top:24px;width:26px;height:26px;border-radius:50%;box-shadow:inset -8px 0 0 0 var(--star);opacity:.5}

/* index list */
.work-list{list-style:none;margin:24px 0 0;padding:0;counter-reset:w}
.work-list li{border-top:1px solid var(--line)}
.work-list li:last-child{border-bottom:1px solid var(--line)}
.work-list a{display:grid;grid-template-columns:44px 1fr auto;gap:16px;align-items:center;padding:16px 0;text-decoration:none}
.work-list a:hover .wl-title{color:var(--sodium)}
.wl-n{font:500 12px var(--mono);color:var(--muted)}
.wl-title{font:400 30px/1 var(--serif);transition:color .3s}
.wl-sub{display:block;font:500 11px/1.4 var(--mono);letter-spacing:.06em;color:var(--muted);margin-top:6px}
.wl-thumb{width:120px;aspect-ratio:3/2;object-fit:cover;opacity:.85}
.wl-shape{width:44px;height:44px}
.wl-shape path{stroke:var(--star-dim);stroke-width:1;fill:none}
.wl-shape circle{fill:var(--star)}

/* lab */
.lab-grid{display:grid;gap:22px;margin-top:28px}
.exp{border:1px solid var(--line);padding:20px;border-radius:var(--r);background:rgba(10,14,24,.6)}
.exp header{display:flex;justify-content:space-between;align-items:baseline;gap:12px;margin-bottom:6px}
.exp .no{font:500 11px var(--mono);color:var(--sodium);letter-spacing:.1em}
.exp p{margin:0 0 14px;font-size:14.5px}
.exp canvas{display:block;width:100%;height:240px;background:#03050a;border:1px solid var(--line);border-radius:var(--r);touch-action:none;cursor:crosshair}
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
.btn{font:500 12px/1 var(--mono);letter-spacing:.08em;text-transform:uppercase;border:1px solid var(--line-2);background:transparent;padding:11px 14px;border-radius:var(--r);cursor:pointer;color:var(--star)}
.btn:hover{border-color:var(--star)}
.btn.primary{background:var(--sodium);border-color:var(--sodium);color:#1a0f04}
.btn.primary:hover{background:#ffbd78}
.out{font:500 12px/1.4 var(--mono);color:var(--phosphor);margin-left:auto}
.pad{position:relative;height:200px;border:1px solid var(--line);border-radius:var(--r);background:
  linear-gradient(var(--line) 1px,transparent 1px) 0 0/25% 25%, linear-gradient(90deg,var(--line) 1px,transparent 1px) 0 0/12.5% 25%, #03050a;touch-action:none;cursor:crosshair}
.pad .dot{position:absolute;width:18px;height:18px;margin:-9px 0 0 -9px;border-radius:50%;background:var(--sodium);box-shadow:0 0 18px var(--sodium);pointer-events:none}
.sliders{display:grid;grid-template-columns:auto 1fr auto;gap:8px 12px;align-items:center;margin-top:12px;font:500 11px var(--mono);letter-spacing:.06em;color:var(--star-dim)}
input[type=range]{accent-color:var(--sodium);width:100%}
.bortle-view{height:160px}

/* contact */
form{margin-top:24px;display:grid;gap:18px;max-width:560px}
.field label,.field legend{display:block;font:500 11px/1.4 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--star-dim);margin-bottom:8px}
.field input,.field select,.field textarea{width:100%;background:rgba(3,5,10,.8);border:1px solid var(--line-2);border-radius:var(--r);padding:13px 14px;color:var(--star)}
.field textarea{min-height:120px;resize:vertical}
.field input:focus,.field select:focus,.field textarea:focus{border-color:var(--sodium);outline:none;box-shadow:0 0 0 3px rgba(242,166,90,.18)}
.field [aria-invalid="true"]{border-color:#ff8a7a}
.err{color:#ff9d8f;font-size:13px;margin:6px 0 0;min-height:0}
fieldset{border:0;margin:0;padding:0}
.chips{display:flex;flex-wrap:wrap;gap:8px}
.chips label{margin:0;cursor:pointer}
.chips input{position:absolute;opacity:0;width:1px;height:1px}
.chips span{display:inline-block;font:500 12px/1 var(--mono);letter-spacing:.04em;text-transform:none;border:1px solid var(--line-2);border-radius:30px;padding:10px 14px;color:var(--star-dim)}
.chips input:checked + span{background:var(--star);color:var(--night);border-color:var(--star)}
.chips input:focus-visible + span{outline:2px solid var(--sodium);outline-offset:2px}
.sent{border:1px solid var(--phosphor);padding:22px;border-radius:var(--r);background:rgba(143,211,200,.06)}
.sent h3{color:var(--phosphor)}

/* ---------- project view ---------- */
#project{position:fixed;inset:0;z-index:15;pointer-events:none;visibility:hidden}
#project.open{visibility:visible}
.pj-panel{position:absolute;right:0;top:0;bottom:0;width:min(560px,42vw);overflow-y:auto;overscroll-behavior:contain;pointer-events:auto;
  padding:92px var(--gutter) 60px 40px;background:linear-gradient(270deg, rgba(5,7,13,.96) 0%, rgba(5,7,13,.9) 80%, rgba(5,7,13,0) 100%);
  opacity:0;transform:translateX(30px);transition:opacity .6s var(--ease), transform .8s var(--ease)}
#project.shown .pj-panel{opacity:1;transform:none}
.back{position:fixed;left:var(--gutter);top:80px;pointer-events:auto;display:inline-flex;align-items:center;gap:10px;background:rgba(5,7,13,.6);border:1px solid var(--line-2);border-radius:40px;padding:10px 16px 10px 12px;cursor:pointer;
  font:500 11px/1 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--star);opacity:0;transition:opacity .5s .2s, border-color .2s}
.back:hover{border-color:var(--sodium)}
#project.shown .back{opacity:1}
.pj-num{font:500 11px/1.4 var(--mono);letter-spacing:.16em;text-transform:uppercase;color:var(--accent);margin:0 0 12px}
.pj-panel h2{font:400 clamp(44px,4.6vw,72px)/.92 var(--serif);letter-spacing:-.02em;margin:0 0 22px}
.pj-meta{display:grid;grid-template-columns:1fr 1fr;gap:14px 18px;margin:0 0 26px;padding:18px 0;border-top:1px solid var(--line);border-bottom:1px solid var(--line)}
.pj-meta div:first-child{grid-column:1/-1}
.pj-meta dt{font:500 10px/1.4 var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--muted)}
.pj-meta dd{margin:4px 0 0;font-size:15px}
.pj-panel p{color:#cbc7bf}
.pj-panel p.first{font-size:18px;color:var(--star)}
.pj-panel figure{margin:26px 0}
.pj-panel figure img{width:100%;aspect-ratio:3/2;object-fit:cover}
.pj-panel figcaption{font:500 11px/1.5 var(--mono);color:var(--muted);margin-top:8px}
.pj-nav{display:flex;justify-content:space-between;gap:12px;margin-top:32px;padding-top:20px;border-top:1px solid var(--line)}
.pj-nav a{text-decoration:none;font:500 11px/1.4 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--star-dim)}
.pj-nav a b{display:block;font:400 24px/1.1 var(--serif);letter-spacing:0;text-transform:none;color:var(--star);margin-top:4px}
.pj-nav a:hover b{color:var(--accent)}
.pj-hero{display:none}
.pj-hint{position:fixed;left:var(--gutter);bottom:clamp(20px,5vh,56px);font:500 11px/1.6 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--muted);opacity:0;transition:opacity .6s .4s}
#project.shown .pj-hint{opacity:1}
.pj-loading{position:fixed;left:30%;top:50%;transform:translate(-50%,-50%);font:500 11px var(--mono);letter-spacing:.14em;text-transform:uppercase;color:var(--star-dim);opacity:0;transition:opacity .3s}
.pj-loading.on{opacity:1}

/* ---------- no-WebGL / list mode ---------- */
body.no-gl{overflow:auto}
body.no-gl #stage,body.no-gl #labels,body.no-gl .cards,body.no-gl .hud .az{display:none}
body.no-gl .hero{position:relative;left:auto;bottom:auto;padding:140px var(--gutter) 0;max-width:900px;opacity:1!important;transform:none!important}
body.no-gl .hud{position:relative;right:auto;bottom:auto;text-align:left;padding:18px var(--gutter) 0}
body.no-gl .hero .hint{display:none}
body.no-gl #fallback{display:block}
#fallback{display:none;padding:10px var(--gutter) 80px;max-width:900px}
body.no-gl #project{position:fixed;inset:0;z-index:25;background:var(--night);overflow-y:auto}
body.no-gl .pj-panel{position:relative;inset:auto;width:auto;max-width:760px;margin:0 auto;background:none;padding:120px var(--gutter) 60px}
body.no-gl .pj-hero{display:block}
body.no-gl .pj-hint{display:none}
body.no-gl .sheet{background:var(--night)}

/* ---------- responsive ---------- */
@media (max-width: 860px){
  .nav .nl{display:none}
  .nav .menu-btn{display:inline-flex}
  .nav.open-menu .nl{display:flex}
  .nav.open-menu{position:fixed;top:64px;right:var(--gutter);flex-direction:column;align-items:stretch;background:rgba(5,7,13,.96);border:1px solid var(--line-2);padding:8px;border-radius:var(--r);min-width:200px}
  .nav.open-menu a{padding:14px 12px}
  .hero{max-width:none;right:var(--gutter);bottom:96px}
  .hero h1{font-size:clamp(40px,11vw,64px)}
  .hero p{font-size:14px;max-width:34ch}
  .hud{left:var(--gutter);right:var(--gutter);bottom:18px;text-align:left;display:flex;justify-content:space-between;gap:12px;line-height:1.5}
  .pj-panel{left:0;width:auto;top:46vh;padding:28px var(--gutter) 60px;background:linear-gradient(180deg, rgba(5,7,13,0) 0, rgba(5,7,13,.92) 70px, rgba(5,7,13,.97) 100%)}
  .back{top:72px}
  .pj-hint{display:none}
  .pj-loading{left:50%;top:25%}
  .sheet{width:100%;padding:86px var(--gutter) 70px;background:rgba(5,7,13,.96)}
  .sheet .close{margin:-56px -4px 0 0}
  .facts dd{font-size:26px}
  .work-list a{grid-template-columns:34px 1fr}
  .wl-thumb{display:none}
}
@media (max-width: 520px){
  .hero .hint .k{display:none}
  .facts{grid-template-columns:1fr 1fr}
  .shift li{grid-template-columns:62px 1fr}
  .clients{columns:1}
  .mark b{font-size:22px}
  .nav .snd .lbl{display:none}
}
@media (max-width: 860px){ body.no-gl .pj-panel{top:auto;left:auto;padding-top:110px} }
@media (prefers-reduced-motion: reduce){
  *,*::before,*::after{animation-duration:.001s!important;transition-duration:.15s!important}
}
</style>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>

<div id="stage" tabindex="0" role="application" aria-label="Planetarium sky. Drag or use arrow keys to turn the dome. Each constellation is a project; use the labelled buttons to open one." aria-describedby="hero-copy"></div>
<div class="grain" aria-hidden="true"></div>
<div id="labels" role="list" aria-label="Constellations"></div>
<div class="cards" aria-hidden="true"></div>

<header class="top">
  <a class="mark" href="#" aria-label="Night Shift, back to the sky">
    <svg viewBox="0 0 26 26" aria-hidden="true"><path d="M3 20 A10 10 0 0 1 23 20" fill="none" stroke="#ece6d8" stroke-width="1.2"/><line x1="1" y1="20" x2="25" y2="20" stroke="#ece6d8" stroke-width="1.2"/><circle cx="9" cy="13" r="1.4" fill="#f2a65a"/><circle cx="15" cy="10" r="1" fill="#ece6d8"/><circle cx="18" cy="15" r="1.1" fill="#ece6d8"/><path d="M9 13 L15 10 L18 15" stroke="#ece6d8" stroke-width=".6" fill="none" opacity=".6"/></svg>
    <b>Night <i>Shift</i></b>
  </a>
  <nav class="nav" id="nav" aria-label="Main">
    <a class="nl" href="#" data-route="sky">Sky</a>
    <a class="nl" href="#index" data-route="index">Index</a>
    <a class="nl" href="#about" data-route="about">About</a>
    <a class="nl" href="#services" data-route="services">Services</a>
    <a class="nl" href="#lab" data-route="lab">Lab</a>
    <a class="nl" href="#contact" data-route="contact">Contact</a>
    <button class="snd" type="button" aria-pressed="false" id="snd"><span class="bars" aria-hidden="true"><i></i><i></i><i></i></span><span class="lbl">Sound</span><span class="sr-only" id="snd-state">off</span></button>
    <button class="menu-btn" type="button" aria-expanded="false" aria-controls="nav" id="menu-btn">Menu</button>
  </nav>
</header>

<main id="main">
  <section class="hero" aria-labelledby="hero-title">
    <p class="eyebrow">Creative technology · open 19:00–05:00</p>
    <h1 id="hero-title">We do our best work <em>after dark.</em></h1>
    <p id="hero-copy">Night Shift is a small studio in a retired planetarium. Ten of our projects hang above you as constellations. Turn the dome, find a shape, and fly inside.</p>
    <p class="hint" aria-hidden="true"><span><kbd>Drag</kbd> turn the sky</span><span class="k"><kbd>Hover</kbd> wake a constellation</span><span><kbd>Click</kbd> fly in</span></p>
  </section>

  <div class="hud" aria-live="off">
    <div class="az">AZ <b id="hud-az">000°</b> · ALT <b id="hud-alt">00°</b></div>
    <div><span id="hud-time">--:--</span> · <span id="hud-open" class="open">studio open</span></div>
    <div class="az"><a class="list-link" href="#index">View as a list</a></div>
  </div>

  <!-- List view used when WebGL is unavailable -->
  <section id="fallback" aria-labelledby="fb-title">
    <h2 id="fb-title" class="kicker">The work, as a list</h2>
    <ol class="work-list" id="fb-list"></ol>
  </section>
</main>

<!-- Project view -->
<section id="project" aria-labelledby="pj-title" aria-hidden="true">
  <button class="back" type="button" id="pj-back"><svg width="18" height="10" viewBox="0 0 18 10" aria-hidden="true"><path d="M17 5H2M6 1 2 5l4 4" stroke="currentColor" fill="none" stroke-width="1.3"/></svg>Back to the sky</button>
  <article class="pj-panel" id="pj-panel" tabindex="-1">
    <figure class="pj-hero"><img id="pj-hero-img" alt=""></figure>
    <p class="pj-num" id="pj-num"></p>
    <h2 id="pj-title"></h2>
    <dl class="pj-meta">
      <div><dt>Client</dt><dd id="pj-client"></dd></div>
      <div><dt>Our role</dt><dd id="pj-role"></dd></div>
      <div><dt>Year</dt><dd id="pj-year"></dd></div>
    </dl>
    <div id="pj-body"></div>
    <nav class="pj-nav" aria-label="More projects">
      <a id="pj-prev" href="#">Previous<b></b></a>
      <a id="pj-next" href="#" style="text-align:right">Next<b></b></a>
    </nav>
  </article>
  <p class="pj-hint" aria-hidden="true">Drag to turn the object · <kbd>Esc</kbd> back</p>
  <p class="pj-loading" id="pj-loading" aria-live="polite"></p>
</section>

<!-- Index -->
<section class="sheet" id="index" aria-labelledby="index-title" hidden>
  <button class="close" type="button" aria-label="Close index">✕</button>
  <p class="kicker">Index · 10 projects</p>
  <h2 id="index-title">Every constellation, <em>in order.</em></h2>
  <p>The same work as the sky, laid flat. Each project opens its own small scene.</p>
  <ol class="work-list" id="index-list"></ol>
</section>

<!-- About -->
<section class="sheet" id="about" aria-labelledby="about-title" hidden>
  <button class="close" type="button" aria-label="Close about">✕</button>
  <p class="kicker">About the studio</p>
  <h2 id="about-title">Nine people, one dome, <em>no daylight.</em></h2>
  <p class="lede">We took the lease on the old harbour planetarium in 2016, when the city moved the stars to a new science centre and left the projector behind.</p>
  <p>Our desks sit under the dome. Our hours run from seven in the evening to five in the morning. We didn't plan it that way. The first three clients all needed things that only happen at night: a ferry, a radio station, an open-air cinema. We got good at the dark, and the work kept coming from the people who live in it.</p>
  <figure><img src="assets/stills/about.webp" alt="The studio at night: four people at long desks with glowing monitors under a planetarium dome full of projected stars." loading="lazy" width="1400" height="933"><figcaption>Under the dome, 02:40. The old projector still runs on Thursdays.</figcaption></figure>
  <dl class="facts">
    <div><dt>Founded</dt><dd>2016</dd></div>
    <div><dt>People</dt><dd>9</dd></div>
    <div><dt>Shows shipped</dt><dd>64</dd></div>
  </dl>
  <h3>Who we work with</h3>
  <p>Night-time businesses, cultural institutions and brands with a product that comes alive after sunset.</p>
  <ul class="clients">
    <li>Kestrel Sound Ferries</li><li>Harbourside Aquarium</li><li>WNOX 98.3 Overnight</li><li>Old Town Heritage Trust</li><li>Hollis Watchworks</li><li>Orchard Lane Film Club</li><li>Fenland Bird Observatory</li><li>Ridgeline Outfitters</li>
  </ul>
</section>

<!-- Services -->
<section class="sheet" id="services" aria-labelledby="services-title" hidden>
  <button class="close" type="button" aria-label="Close services">✕</button>
  <p class="kicker">Services · a typical shift</p>
  <h2 id="services-title">What happens <em>between seven and five.</em></h2>
  <p>We don't sell packages. Most projects use four or five of these, in roughly this order, over six to fourteen weeks.</p>
  <ol class="shift">
    <li><time>19:00</time><div><h3>Concept &amp; story</h3><p>One idea strong enough to carry a launch. Usually it's a single object or moment we can build a world around.</p><div class="tags"><span>Workshops</span><span>Narrative</span><span>Art direction</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -3px 0 0 0 var(--star)"></i></li>
    <li><time>21:00</time><div><h3>Real-time 3D &amp; WebGL</h3><p>Sites and configurators that run at 60 fps on a five-year-old laptop. We write the shaders ourselves and ship a list view for anyone who can't run them.</p><div class="tags"><span>three.js</span><span>GPU particles</span><span>Fluid sims</span><span>Fallbacks</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -7px 0 0 0 var(--star)"></i></li>
    <li><time>23:00</time><div><h3>Sound design</h3><p>Synthesised scores that react to what you do. They wake on your first click and mute with one button.</p><div class="tags"><span>Web Audio</span><span>Field recording</span><span>Installations</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -13px 0 0 0 var(--star)"></i></li>
    <li><time>01:00</time><div><h3>Projection &amp; spaces</h3><p>Light on hulls, aquarium glass and orchard sheets. We plan the rig, the content and the night the crowd turns up.</p><div class="tags"><span>Projection mapping</span><span>Show control</span><span>Site surveys</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -19px 0 0 0 var(--star)"></i></li>
    <li><time>03:00</time><div><h3>Apps &amp; tools</h3><p>Small, useful software for people awake at odd hours: counters, trackers, guides that work offline in a field.</p><div class="tags"><span>PWA</span><span>Offline-first</span><span>Data viz</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -23px 0 0 0 var(--star)"></i></li>
    <li><time>05:00</time><div><h3>Launch &amp; care</h3><p>We stay on call for the first month after launch, then hand over everything: source, docs and the shader notes.</p><div class="tags"><span>Monitoring</span><span>Handover</span><span>Training</span></div></div><i class="moon" aria-hidden="true" style="box-shadow:inset -26px 0 0 0 var(--star)"></i></li>
  </ol>
</section>

<!-- Lab -->
<section class="sheet" id="lab" aria-labelledby="lab-title" hidden>
  <button class="close" type="button" aria-label="Close lab">✕</button>
  <p class="kicker">Lab · three small experiments</p>
  <h2 id="lab-title">Things we made <em>at 4am.</em></h2>
  <div class="lab-grid">
    <article class="exp" aria-labelledby="x1">
      <header><h3 id="x1">Draw a constellation</h3><span class="no">EXP 01</span></header>
      <p>Click to place stars. Each one joins the last. With the keyboard, use the arrow keys to move the reticle and Enter to place a star.</p>
      <canvas id="draw" tabindex="0" aria-label="Constellation drawing area" width="640" height="240"></canvas>
      <div class="row"><button class="btn" type="button" id="draw-undo">Undo</button><button class="btn" type="button" id="draw-clear">Clear</button><button class="btn primary" type="button" id="draw-name">Name it</button><output class="out" id="draw-out" aria-live="polite">0 stars</output></div>
    </article>
    <article class="exp" aria-labelledby="x2">
      <header><h3 id="x2">Drone tuner</h3><span class="no">EXP 02</span></header>
      <p>The hum under this site is synthesised live. Drag on the pad to retune it: left and right set the root note, up and down open the filter.</p>
      <div class="pad" id="pad" aria-hidden="true"><span class="dot" id="pad-dot" style="left:40%;top:60%"></span></div>
      <div class="sliders">
        <label for="pad-root">Root</label><input type="range" id="pad-root" min="0" max="100" value="40"><output id="pad-root-out">55 Hz</output>
        <label for="pad-cut">Filter</label><input type="range" id="pad-cut" min="0" max="100" value="40"><output id="pad-cut-out">420 Hz</output>
      </div>
      <p class="out" id="pad-note" style="margin:10px 0 0">Sound is off. Turn it on with the Sound button at the top.</p>
    </article>
    <article class="exp" aria-labelledby="x3">
      <header><h3 id="x3">Light pollution</h3><span class="no">EXP 03</span></header>
      <p>The Bortle scale runs from 1, a truly dark site, to 9, a city centre. Slide it and the dome behind this panel loses its faint stars, just as your own sky does.</p>
      <canvas id="bortle-view" class="bortle-view" width="640" height="160" aria-hidden="true"></canvas>
      <div class="sliders"><label for="bortle">Bortle</label><input type="range" id="bortle" min="1" max="9" value="2" step="1"><output id="bortle-out">2</output></div>
      <p class="out" id="bortle-count" style="margin:10px 0 0" aria-live="polite"></p>
    </article>
  </div>
</section>

<!-- Contact -->
<section class="sheet" id="contact" aria-labelledby="contact-title" hidden>
  <button class="close" type="button" aria-label="Close contact">✕</button>
  <p class="kicker">Contact · replies before sunrise</p>
  <h2 id="contact-title">Tell us what happens <em>at night.</em></h2>
  <p>A few lines are enough. We read everything at the start of the shift and answer by 05:00.</p>
  <div id="form-wrap">
  <form id="form" novalidate>
    <div class="field"><label for="f-name">Your name</label><input id="f-name" name="name" autocomplete="name" required aria-describedby="e-name"><p class="err" id="e-name"></p></div>
    <div class="field"><label for="f-email">Email</label><input id="f-email" name="email" type="email" autocomplete="email" required aria-describedby="e-email"><p class="err" id="e-email"></p></div>
    <div class="field"><label for="f-type">What is it?</label>
      <select id="f-type" name="type" required aria-describedby="e-type"><option value="">Choose one</option><option>A launch site or campaign</option><option>An installation or projection</option><option>An app or tool</option><option>Sound</option><option>Something stranger</option></select><p class="err" id="e-type"></p></div>
    <fieldset class="field"><legend>Rough budget</legend>
      <div class="chips">
        <label><input type="radio" name="budget" value="Under 20k"><span>Under 20k</span></label>
        <label><input type="radio" name="budget" value="20–60k" checked><span>20–60k</span></label>
        <label><input type="radio" name="budget" value="60k+"><span>60k+</span></label>
        <label><input type="radio" name="budget" value="Not sure"><span>Not sure yet</span></label>
      </div></fieldset>
    <div class="field"><label for="f-msg">The idea, in a few lines</label><textarea id="f-msg" name="message" required minlength="20" aria-describedby="e-msg"></textarea><p class="err" id="e-msg"></p></div>
    <div><button class="btn primary" type="submit">Send it to the night desk</button></div>
  </form>
  </div>
</section>

<div id="loader" role="status" aria-live="polite">
  <div class="ld">
    <svg viewBox="0 0 180 96" aria-hidden="true"><path class="arc-bg" d="M6 92 A84 84 0 0 1 174 92"/><path class="arc" id="ld-arc" d="M6 92 A84 84 0 0 1 174 92" pathLength="100" stroke-dasharray="100" stroke-dashoffset="100"/><line x1="0" y1="92.5" x2="180" y2="92.5" stroke="rgba(236,230,216,.28)"/></svg>
    <div class="pct" id="ld-pct">0%</div>
    <div class="step" id="ld-step">Unlocking the dome</div>
  </div>
</div>

<script type="module">
/* =====================================================================
   NIGHT SHIFT — data
   ===================================================================== */
const P = [
 { slug:'last-ferry', title:'Last Ferry Out', client:'Kestrel Sound Ferries', role:'Campaign site, hull projection, live crossing tracker', year:2025, shape:'Ship', accent:'#f2a65a', model:null, fx:'spray', img:'ferry',
   az:-8, alt:24, size:9.1,
   lines:[[-1,-.25,-.72,-.55,.72,-.55,1.05,-.2,-1,-.25],[-.5,-.24,-.5,.08,.42,.08,.42,-.22],[.05,.08,.1,.45,.32,.45,.3,.08],[-.5,.08,-.5,.72,-.2,.6]],
   body:["Kestrel's 01:40 crossing is the last boat off the island, and most people who live there had never taken it. The brief was to make the night run feel like the reason to stay out late, not the punishment for it.",
         "For six weeks we projected a slow band of amber light along the hull, synced to a tracker site that drew the ferry as a moving lantern on a black chart. Every crossing became a 38-minute broadcast: tide, wind, the deck playlist and who was out by the rail.",
         "Night ridership rose 41% over the season. The tracker is still live, and the deck crew asked to keep the light."],
   caps:['The 01:40 leaving harbour with its amber band.','Upper deck, second week. People came for the stars.'] },
 { slug:'puddle-season', title:'Puddle Season', client:'Galoshe & Co.', role:'WebGL boot configurator, launch film, rain sound', year:2024, shape:'Boot', accent:'#e7c44a', model:'rubber_boots', fx:'rain', img:'boots',
   az:28, alt:38, size:8.4,
   lines:[[-.45,1,.15,1,.15,-.1,.75,-.4,.85,-.75,-.5,-.75,-.5,-.1,-.45,1],[-.47,.72,.15,.72],[-.5,-.52,.83,-.52]],
   body:["Galoshe makes one thing: a rubber boot that lasts twenty years. Their customers buy a pair, then disappear for two decades. They needed a launch that made a second colour feel like a reason to come back.",
         "We built a configurator where it is always raining. Each colour changes the street around the boot, from the reflections in the puddle to the colour of the shop light. Step into the puddle and the splash is simulated, never looped.",
         "The new mustard pair sold out in nine days, and the original bottle green sold out again behind it. Average time on the configurator was 3 minutes 40, mostly spent jumping in puddles."],
   caps:['Hero still: the mustard pair, 23:10, Wharf Street.','Launch film frame. The splash was real; so was the cold.'] },
 { slug:'lamplighters', title:'The Lamplighters', client:'Old Town Heritage Trust', role:'Night-walk app, AR wayfinding, spatial audio', year:2025, shape:'Lantern', accent:'#ffb36b', model:'Lantern_01', fx:'embers', img:'lamp',
   az:64, alt:24, size:8.4,
   lines:[[0,.85,-.15,1.05,.15,1.05,0,.85],[-.45,.55,0,.85,.45,.55,-.45,.55],[-.45,.55,-.35,-.6,.35,-.6,.45,.55],[-.35,-.6,-.45,-.82,.45,-.82,.35,-.6],[0,-.25,.09,0,0,.22,-.09,0,0,-.25]],
   body:["Until 1958 the old town's gas lamps were lit by hand, one street at a time. The Trust wanted to bring that walk back without adding a single sign to listed buildings.",
         "Visitors borrow a brass lantern with a phone inside. As you walk, the app lights the real lamps on your route one by one and tells the lamplighters' stories in spatial audio from the doorways where they happened.",
         "The walk runs every night from October to March and has been fully booked since launch. Nothing was screwed into a wall."],
   caps:['Lamp 14, Cooper\'s Wynd, lit on cue.','The opening night. We relit the whole lane.'] },
 { slug:'third-shift', title:'Third Shift', client:'Hollis Watchworks', role:'Brand film, macro product site, sound design', year:2023, shape:'Pocket watch', accent:'#d9b77a', model:'vintage_pocket_watch', fx:'dust', img:'watch',
   az:100, alt:38, size:7.7,
   lines:[[0,.55,.35,.46,.6,.2,.7,-.15,.6,-.5,.35,-.76,0,-.85,-.35,-.76,-.6,-.5,-.7,-.15,-.6,.2,-.35,.46,0,.55],[0,.55,0,.75],[0,.75,-.15,.9,0,1.05,.15,.9,0,.75],[0,-.15,0,.3],[0,-.15,.32,-.3]],
   body:["Hollis has three watchmakers, and all of them work nights because the street is quiet enough to hear a balance wheel. That was the whole brand, and nobody outside the workshop knew it.",
         "We filmed one movement being assembled between midnight and six, at macro scale, and built the site around that single film. You scrub through the night by dragging, and the sound of each component seating is the real recording, slowed down.",
         "The waiting list went from four months to fourteen. Hollis now opens the workshop window to the street on Fridays after midnight."],
   caps:['Calibre H-3, open back, under the green lamp.','The workshop window from Cutler Lane, 03:15.'] },
 { slug:'nightjar-count', title:'Nightjar Count', client:'Fenland Bird Observatory', role:'Citizen-science app, sound ID, live migration map', year:2024, shape:'Binoculars', accent:'#9fd0b8', model:'binoculars', fx:'migrate', img:'nightjar',
   az:136, alt:24, size:8.4,
   lines:[[-.75,.6,-.25,.6,-.2,-.7,-.85,-.7,-.75,.6],[.25,.6,.75,.6,.85,-.7,.2,-.7,.25,.6],[-.22,.1,.22,.1],[0,.1,0,.48]],
   body:["Most songbirds migrate at night, and you can hear them calling overhead if you know what to listen for. The observatory wanted ten thousand pairs of ears, not ten.",
         "The app listens with your phone, flags likely flight calls and asks you to confirm them by ear. Every confirmed call drops a point on a live map that shows the night's migration moving across the fens.",
         "In its first autumn, 6,200 volunteers logged 81,000 calls. Two species were recorded in the county for the first time."],
   caps:['Count night on Holme Fen, full moon.','The field kit: phone, binoculars and a pencil tally.'] },
 { slug:'graveyard-radio', title:'Graveyard Radio', client:'WNOX 98.3 Overnight', role:'Rebrand, audio-reactive player, station idents', year:2023, shape:'Boombox', accent:'#ff7a5c', model:'boombox', fx:'pulse', img:'radio',
   az:172, alt:38, size:9.1,
   lines:[[-1,.35,1,.35,1,-.55,-1,-.55,-1,.35],[-.7,.35,-.6,.75,.6,.75,.7,.35],[-.55,.13,-.32,-.03,-.32,-.31,-.55,-.47,-.78,-.31,-.78,-.03,-.55,.13],[.55,.13,.78,-.03,.78,-.31,.55,-.47,.32,-.31,.32,-.03,.55,.13],[-.18,.05,.18,.05,.18,-.25,-.18,-.25,-.18,.05],[.6,.75,1.05,1.12]],
   body:["WNOX's overnight show has run from midnight to six since 1987. Its listeners are taxi drivers, nurses, bakers and insomniacs, and the old branding looked like a car dealer's.",
         "We rebuilt the station around the idea of company in the dark. The web player draws the live broadcast as a slow aurora, and each presenter has a sung ident we wrote with them in the studio at 3am.",
         "Online listening is up 2.3×. The idents are now requested by name on the phone-in."],
   caps:['Studio B during the 02:00 hour.','Who\'s listening: a cab at the lights on Union Street.'] },
 { slug:'deep-listening', title:'Deep Listening', client:'Harbourside Aquarium', role:'Sound installation, projection, late-opening tickets', year:2025, shape:'Whale', accent:'#5fc4d9', model:'bronze_whale_statue', fx:'bubbles', img:'whale',
   az:208, alt:24, size:9.1,
   lines:[[-1,.05,-.6,.35,0,.42,.5,.26,.85,0,.95,-.15,.6,-.3,0,-.36,-.6,-.25,-1,.05],[-1,.05,-1.3,.4,-1.15,.05,-1.3,-.3,-1,.05],[0,-.36,-.12,-.7,.25,-.34],[.5,.26,.45,.62],[.45,.62,.28,.78],[.45,.62,.62,.8],[.66,.02]],
   body:["The aquarium's whale gallery is empty after five, which is when the real whale recordings they hold are most affecting. The brief: give people a reason to come back after dark and lie down.",
         "We turned the gallery into a listening room. Hydrophone recordings from the North Atlantic play through 32 speakers, and the tank wall shows a slow projection drawn by the song itself. Lower notes travel further across the glass.",
         "Late openings now sell out every Thursday, and the average visit is 47 minutes. Most people stay lying down."],
   caps:['Thursday late: the listening floor.','The song wall in Gallery 3, drawn live by the recording.'] },
 { slug:'bathwater-stories', title:'Bathwater Stories', client:'Hush Audiobooks', role:'Bedtime audio app, character design, sleep timer', year:2024, shape:'Duck', accent:'#f5d25c', model:'rubber_duck_toy', fit:1.1, fx:'bubbles', img:'duck',
   az:244, alt:38, size:7.7,
   lines:[[.1,.55,.22,.85,.5,.92,.66,.72,.95,.62,.62,.52,.8,.2,.75,-.3,.3,-.55,-.5,-.55,-.85,-.2,-.95,.25,-.55,.05,-.1,.15,.1,.55],[.44,.74],[-.45,-.12,.1,-.15,.3,-.32]],
   body:["Hush makes audiobooks for adults. Parents kept asking for something for the twenty minutes between bath and bed, the hardest twenty minutes of the day.",
         "We designed an app with one character, a duck who narrates from the side of the bath, and a timer that slows the story down as the minutes pass. Each story's music is written to slow its tempo by a fifth from start to finish.",
         "It reached the top ten in kids' apps in four countries. The most common review mentions the duck by name."],
   caps:['The night light setting at 19:42.','Story six, chapter two. The ceiling stars are part of the app.'] },
 { slug:'moth-cinema', title:'Moth Cinema', client:'Orchard Lane Film Club', role:'Festival identity, ticketing, projection rig', year:2022, shape:'Projector', accent:'#efdcb0', model:'filmstrip_projector_8mm', fx:'moths', img:'moth',
   az:280, alt:24, size:9.1,
   lines:[[-.6,0,.5,0,.5,-.5,-.6,-.5,-.6,0],[-.35,.75,-.1,.6,-.1,.3,-.35,.15,-.6,.3,-.6,.6,-.35,.75],[.3,.75,.55,.6,.55,.3,.3,.15,.05,.3,.05,.6,.3,.75],[.5,-.15,.8,-.1,.8,-.35,.5,-.3],[.8,-.1,1.4,.25],[.8,-.35,1.4,-.7],[-.5,-.5,-.6,-.85],[.4,-.5,.5,-.85]],
   body:["Orchard Lane screens 8mm prints on a bedsheet in an old apple orchard, ten nights a summer, for whoever turns up with a chair. They wanted to grow without losing the bedsheet.",
         "We gave the festival a moth for a mascot, because the moths always come for the beam. Tickets are free but numbered by seat, so the site shows a hand-drawn orchard where you pick a gap between two trees and bring your own chair.",
         "Attendance tripled to 400 a night, and the moth was printed on 2,000 tote bags. The bedsheet is the same one."],
   caps:['Night four: Sherlock Jr. on the sheet.','The club\'s 1962 projector, and its regulars.'] },
 { slug:'true-north', title:'True North Club', client:'Ridgeline Outfitters', role:'Night-hike guide, star-navigation microsite', year:2025, shape:'Compass', accent:'#9db8ff', model:'seadogs_compass', fx:'snow', img:'north',
   az:316, alt:38, size:8.4,
   lines:[[0,1,.18,.18,1,0,.18,-.18,0,-1,-.18,-.18,-1,0,-.18,.18,0,1],[0,.62,.44,.44,.62,0,.44,-.44,0,-.62,-.44,-.44,-.62,0,-.44,.44,0,.62],[0,0]],
   body:["Ridgeline sells kit for long walks, and their customers kept getting lost on short ones once the sun went down. The brief was a guide to walking at night that people would actually finish reading.",
         "We wrote a field guide in twelve short chapters, each one paired with a live sky for wherever you are standing. It teaches one star at a time: Polaris first, then the shapes that point to it, then how to walk a bearing by them.",
         "The guide is read to the end by 58% of visitors, and Ridgeline's night-hike clubs now run in eleven towns."],
   caps:['Chapter 4, Black Fell ridge: find north without a phone.','The kit list, pinned by a compass and lit by a lantern.'] }
];
const MODEL_ROOT='assets/models/';
const RM = matchMedia('(prefers-reduced-motion: reduce)');
let reduced = RM.matches;
RM.addEventListener?.('change', e=>{ reduced = e.matches; });
const $ = (s,el=document)=>el.querySelector(s);
const $$ = (s,el=document)=>[...el.querySelectorAll(s)];
const isTouch = matchMedia('(hover: none)').matches;

/* =====================================================================
   Audio — synthesised drone, chimes and warp whoosh (Web Audio)
   ===================================================================== */
const Sound = (()=>{
  let ctx=null, master, droneBus, filt, rev, oscs=[], wanted=false;
  try{ wanted = localStorage.getItem('ns-sound') !== 'off'; }catch(e){ wanted=true; }
  const btn=$('#snd'), st=$('#snd-state');
  const notes=[220,261.63,293.66,329.63,392,440,523.25,587.33,659.25,783.99];
  let root=55, cut=420;
  function impulse(sec){ const len=ctx.sampleRate*sec, b=ctx.createBuffer(2,len,ctx.sampleRate);
    for(let c=0;c<2;c++){ const d=b.getChannelData(c); for(let i=0;i<len;i++) d[i]=(Math.random()*2-1)*Math.pow(1-i/len,3.2); } return b; }
  function build(){
    const AC=window.AudioContext||window.webkitAudioContext; if(!AC) return false;
    ctx=new AC();
    master=ctx.createGain(); master.gain.value=0; master.connect(ctx.destination);
    rev=ctx.createConvolver(); rev.buffer=impulse(3.4); const revGain=ctx.createGain(); revGain.gain.value=.55; rev.connect(revGain); revGain.connect(master);
    droneBus=ctx.createGain(); droneBus.gain.value=.32;
    filt=ctx.createBiquadFilter(); filt.type='lowpass'; filt.frequency.value=cut; filt.Q.value=.9;
    droneBus.connect(filt); filt.connect(master); filt.connect(rev);
    const lfo=ctx.createOscillator(), lfoG=ctx.createGain(); lfo.frequency.value=.045; lfoG.gain.value=140; lfo.connect(lfoG); lfoG.connect(filt.frequency); lfo.start();
    [[1,'sawtooth',.16,-6],[1.5,'triangle',.2,4],[2,'sine',.22,0],[3,'triangle',.06,7],[.5,'sine',.3,0]].forEach(([m,t,g,det])=>{
      const o=ctx.createOscillator(), gg=ctx.createGain(); o.type=t; o.frequency.value=root*m; o.detune.value=det; gg.gain.value=g; o.connect(gg); gg.connect(droneBus); o.start(); oscs.push([o,m]); });
    return true;
  }
  function setOn(on){
    wanted=on; try{ localStorage.setItem('ns-sound', on?'on':'off'); }catch(e){}
    btn.setAttribute('aria-pressed', on?'true':'false'); st.textContent=on?'on':'off';
    $('#pad-note').textContent = on? 'Listening. The pad retunes the drone you hear now.' : 'Sound is off. Turn it on with the Sound button at the top.';
    if(on){ if(!ctx && !build()) return; ctx.resume(); master.gain.cancelScheduledValues(ctx.currentTime); master.gain.setTargetAtTime(.5, ctx.currentTime, 1.2); }
    else if(ctx){ master.gain.cancelScheduledValues(ctx.currentTime); master.gain.setTargetAtTime(0, ctx.currentTime, .25); }
  }
  btn.addEventListener('click', ()=>{ const on = !(ctx && ctx.state==='running' && wanted); setOn(on); });
  btn.setAttribute('aria-pressed', 'false');
  // audio can only start after a user gesture: the first click, tap or key press wakes it, unless the visitor muted it before
  const unlock=(e)=>{ if(e.target?.closest?.('#snd')) return; if(wanted) setOn(true); window.removeEventListener('pointerdown',unlock); window.removeEventListener('keydown',unlock); };
  window.addEventListener('pointerdown',unlock); window.addEventListener('keydown',unlock);
  function chime(i){ if(!ctx||!wanted) return; const t=ctx.currentTime, f=notes[i%notes.length];
    [[1,.16],[2.76,.05],[5.4,.02]].forEach(([m,g])=>{ const o=ctx.createOscillator(), e=ctx.createGain(); o.type='sine'; o.frequency.value=f*m; e.gain.setValueAtTime(0,t); e.gain.linearRampToValueAtTime(g,t+.006); e.gain.exponentialRampToValueAtTime(.0001,t+2.4/m+.3); o.connect(e); e.connect(rev); e.connect(master); o.start(t); o.stop(t+3); }); }
  function whoosh(inward=true){ if(!ctx||!wanted) return; const t=ctx.currentTime, len=ctx.sampleRate*1.6, b=ctx.createBuffer(1,len,ctx.sampleRate), d=b.getChannelData(0);
    for(let i=0;i<len;i++) d[i]=Math.random()*2-1;
    const n=ctx.createBufferSource(); n.buffer=b; const bp=ctx.createBiquadFilter(); bp.type='bandpass'; bp.Q.value=2.2;
    bp.frequency.setValueAtTime(inward?180:2800,t); bp.frequency.exponentialRampToValueAtTime(inward?3200:160,t+1.1);
    const g=ctx.createGain(); g.gain.setValueAtTime(0,t); g.gain.linearRampToValueAtTime(.22,t+.8); g.gain.exponentialRampToValueAtTime(.0001,t+1.5);
    n.connect(bp); bp.connect(g); g.connect(master); g.connect(rev); n.start(t); n.stop(t+1.6);
    const s=ctx.createOscillator(), sg=ctx.createGain(); s.frequency.setValueAtTime(inward?90:50,t+.8); s.frequency.exponentialRampToValueAtTime(inward?38:90,t+1.6);
    sg.gain.setValueAtTime(0,t+.75); sg.gain.linearRampToValueAtTime(.25,t+.9); sg.gain.exponentialRampToValueAtTime(.0001,t+2.2); s.connect(sg); sg.connect(master); s.start(t+.75); s.stop(t+2.3); }
  function tune(r,c){ root=r; cut=c; if(!ctx) return; const t=ctx.currentTime; oscs.forEach(([o,m])=>o.frequency.setTargetAtTime(root*m,t,.08)); filt.frequency.setTargetAtTime(cut,t,.08); }
  document.addEventListener('visibilitychange',()=>{ if(!ctx) return; document.hidden? ctx.suspend(): (wanted&&ctx.resume()); });
  return { chime, whoosh, tune, get on(){return wanted;} };
})();

/* =====================================================================
   DOM: lists, labels, routing, sheets, project panel
   ===================================================================== */
function shapeSVG(p){
  let d='', dots='';
  const seen=new Set();
  p.lines.forEach(l=>{ for(let i=0;i<l.length;i+=2){ const x=22+l[i]*15, y=22-l[i+1]*15; d+=(i?'L':'M')+x.toFixed(1)+' '+y.toFixed(1)+' '; const k=x.toFixed(1)+','+y.toFixed(1); if(!seen.has(k)){seen.add(k); dots+=`<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="1.3"/>`;} } });
  return `<svg class="wl-shape" viewBox="0 0 44 44" aria-hidden="true"><path d="${d}"/>${dots}</svg>`;
}
function listHTML(){
  return P.map((p,i)=>`<li><a href="#work/${p.slug}">${shapeSVG(p)}<span><span class="wl-title">${p.title}</span><span class="wl-sub">${String(i+1).padStart(2,'0')} · ${p.shape} · ${p.client} · ${p.year}</span></span><img class="wl-thumb" src="assets/stills/${p.img}-a.webp" alt="" loading="lazy" width="120" height="80"></a></li>`).join('');
}
$('#index-list').innerHTML=listHTML();
$('#fb-list').innerHTML=listHTML();

const labelsEl=$('#labels');
P.forEach((p,i)=>{
  const b=document.createElement('button'); b.className='cl off'; b.type='button'; b.dataset.i=i;
  b.setAttribute('role','listitem');
  b.setAttribute('aria-label',`${p.title}. ${p.shape} constellation. ${p.client}, ${p.year}. Open project`);
  b.innerHTML=`<span class="num">${String(i+1).padStart(2,'0')}</span><span class="name" aria-hidden="true">${p.title}</span><span class="meta" aria-hidden="true">${p.shape} · ${p.year}</span>`;
  b.addEventListener('click',()=>{ location.hash='work/'+p.slug; });
  b.addEventListener('focus',()=>{ GL?.focusConstellation(i); setHover(i,true); });
  b.addEventListener('blur',()=>setHover(-1,true));
  b.addEventListener('pointerenter',()=>setHover(i));
  b.addEventListener('pointerleave',()=>setHover(-1));
  labelsEl.appendChild(b);
});
const labelEls=$$('.cl',labelsEl);

/* name decode: glyphs resolve left to right */
const GLY='·+*×◦⁘∴∵✶ABCDEFGHJKLMNPRSTUVWXYZ0123456789';
const decTimers=new Map();
function decode(el,text){
  clearInterval(decTimers.get(el));
  if(reduced){ el.textContent=text; return; }
  const t0=performance.now(), dur=520;
  const id=setInterval(()=>{ const k=(performance.now()-t0)/dur; let s='';
    for(let i=0;i<text.length;i++){ const r=i/text.length; s += (text[i]===' '||k>r*0.75+0.25)? text[i] : GLY[(Math.random()*GLY.length)|0]; }
    el.textContent=s; if(k>=1){ el.textContent=text; clearInterval(id);} },34);
  decTimers.set(el,id);
}
let hovered=-1;
function setHover(i){
  if(i===hovered) return;
  if(hovered>=0) labelEls[hovered].classList.remove('on');
  hovered=i;
  if(i>=0){ const el=labelEls[i]; el.classList.add('on'); decode($('.name',el),P[i].title); Sound.chime(i); GL?.prefetch(i); }
  GL?.setHover(i);
}

/* --- routing --- */
let route={name:'sky'}, lastFocus=null;
function parse(){ const h=decodeURIComponent(location.hash.slice(1));
  if(h.startsWith('work/')){ const i=P.findIndex(p=>p.slug===h.slice(5)); if(i>=0) return {name:'project',i}; }
  if(['index','about','services','lab','contact'].includes(h)) return {name:'sheet',id:h};
  if(h==='main') return {name:'sky'};
  return {name:'sky'}; }
function applyRoute(){
  const r=parse(), prev=route; route=r;
  $$('.nav a').forEach(a=>a.removeAttribute('aria-current'));
  const cur = r.name==='sheet'? r.id : (r.name==='sky'?'sky':null);
  if(cur) $(`.nav a[data-route="${cur}"]`)?.setAttribute('aria-current','page');
  closeMenu();
  // sheets
  $$('.sheet').forEach(s=>{ const on = r.name==='sheet' && s.id===r.id; if(on){ s.hidden=false; requestAnimationFrame(()=>s.classList.add('open')); } else if(s.classList.contains('open')||!s.hidden){ s.classList.remove('open'); setTimeout(()=>{ if(!s.classList.contains('open')) s.hidden=true; },500);} });
  document.body.classList.toggle('view-sheet', r.name==='sheet');
  GL?.setDim(r.name==='sheet' ? 1 : 0);
  if(r.name==='sheet'){ lastFocus = lastFocus || document.activeElement; setTimeout(()=>$('#'+r.id+' h2')?.setAttribute('tabindex','-1'),0); setTimeout(()=>$('#'+r.id+' h2')?.focus({preventScroll:true}),60); if(r.id==='lab') Lab.open(); }
  // project
  if(r.name==='project'){ openProject(r.i, prev); }
  else if(prev.name==='project'){ closeProject(); }
  if(r.name==='sky' && prev.name==='sheet'){ const t=lastFocus; lastFocus=null; t?.focus?.({preventScroll:true}); }
}
window.addEventListener('hashchange',applyRoute);
$$('.sheet .close').forEach(b=>b.addEventListener('click',()=>{ location.hash=''; }));
document.addEventListener('keydown',e=>{ if(e.key==='Escape'){ if(route.name!=='sky'){ location.hash = ''; } } });
const menuBtn=$('#menu-btn'), nav=$('#nav');
function closeMenu(){ nav.classList.remove('open-menu'); menuBtn.setAttribute('aria-expanded','false'); }
menuBtn.addEventListener('click',()=>{ const o=!nav.classList.contains('open-menu'); nav.classList.toggle('open-menu',o); menuBtn.setAttribute('aria-expanded',String(o)); });

/* --- project panel --- */
const proj=$('#project');
function fillProject(i){
  const p=P[i];
  proj.style.setProperty('--accent',p.accent);
  $('#pj-num').textContent=`Constellation ${String(i+1).padStart(2,'0')} of 10 · ${p.shape}`;
  $('#pj-title').textContent=p.title; $('#pj-client').textContent=p.client; $('#pj-role').textContent=p.role; $('#pj-year').textContent=p.year;
  $('#pj-hero-img').src=`assets/stills/${p.img}-a.webp`; $('#pj-hero-img').alt=p.caps[0];
  $('#pj-body').innerHTML = `<p class="first">${p.body[0]}</p>
    <figure><img src="assets/stills/${p.img}-a.webp" alt="${p.caps[0]}" width="1400" height="933" loading="lazy"><figcaption>${p.caps[0]}</figcaption></figure>
    <p>${p.body[1]}</p><p>${p.body[2]}</p>
    <figure><img src="assets/stills/${p.img}-b.webp" alt="${p.caps[1]}" width="1400" height="933" loading="lazy"><figcaption>${p.caps[1]}</figcaption></figure>`;
  const pr=P[(i+9)%10], nx=P[(i+1)%10];
  $('#pj-prev').href='#work/'+pr.slug; $('#pj-prev b').textContent=pr.title;
  $('#pj-next').href='#work/'+nx.slug; $('#pj-next b').textContent=nx.title;
  $('#pj-panel').scrollTop=0;
}
function showPanel(){ proj.classList.add('shown'); proj.setAttribute('aria-hidden','false'); setTimeout(()=>$('#pj-title').setAttribute('tabindex','-1'),0); setTimeout(()=>$('#pj-title').focus({preventScroll:true}),80); }
function openProject(i, prev){
  document.body.classList.add('view-project');
  proj.classList.add('open');
  if(prev.name==='project' && proj.classList.contains('shown')){ proj.classList.remove('shown'); }
  fillProject(i);
  setHover(-1);
  if(GL){ GL.openProject(i, showPanel); } else { showPanel(); proj.scrollTop=0; }
}
function closeProject(){
  proj.classList.remove('shown'); proj.setAttribute('aria-hidden','true');
  const done=()=>{ proj.classList.remove('open'); document.body.classList.remove('view-project'); };
  if(GL){ GL.closeProject(done); } else done();
  const i=P.findIndex(p=>p.slug===(lastProjSlug)); if(i>=0) setTimeout(()=>labelEls[i].focus({preventScroll:true}),40);
}
let lastProjSlug=null;
window.addEventListener('hashchange',()=>{ const r=parse(); if(r.name==='project') lastProjSlug=P[r.i].slug; });
$('#pj-back').addEventListener('click',()=>{ location.hash=''; });

/* --- HUD clock --- */
function clock(){ const d=new Date(), h=d.getHours(); $('#hud-time').textContent=`${String(h).padStart(2,'0')}:${String(d.getMinutes()).padStart(2,'0')} local`;
  $('#hud-open').textContent = (h>=19||h<5)? 'studio open' : 'studio asleep · leave a note'; }
clock(); setInterval(clock,20000);

/* =====================================================================
   Contact form
   ===================================================================== */
(function form(){
  const f=$('#form'), wrap=$('#form-wrap');
  const rules={ name:v=>v.trim().length>=2||'Tell us what to call you.', email:v=>/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(v.trim())||'That email looks incomplete.', type:v=>!!v||'Pick the closest one.', message:v=>v.trim().length>=20||`A little more, please: ${Math.max(0,20-v.trim().length)} more characters.` };
  function check(el){ const r=rules[el.name]; if(!r) return true; const res=r(el.value); const err=$('#e-'+(el.name==='message'?'msg':el.name));
    if(res===true){ el.removeAttribute('aria-invalid'); err.textContent=''; return true; } el.setAttribute('aria-invalid','true'); err.textContent=res; return false; }
  ['name','email','type','message'].forEach(n=>{ const el=f.elements[n]; el.addEventListener('blur',()=>{ if(el.value) check(el); }); el.addEventListener('input',()=>{ if(el.getAttribute('aria-invalid')) check(el); }); });
  f.addEventListener('submit',e=>{ e.preventDefault(); let first=null;
    ['name','email','type','message'].forEach(n=>{ const el=f.elements[n]; if(!check(el)&&!first) first=el; });
    if(first){ first.focus(); return; }
    const btn=f.querySelector('[type=submit]'); btn.disabled=true; btn.textContent='Sending…';
    const data=Object.fromEntries(new FormData(f));
    setTimeout(()=>{ const t=new Date(); const hh=String(t.getHours()).padStart(2,'0')+':'+String(t.getMinutes()).padStart(2,'0');
      wrap.innerHTML=`<div class="sent" role="status" tabindex="-1"><h3>Received at ${hh}.</h3><p>Thanks, ${data.name.replace(/[<>&"]/g,'')}. Your note about <strong>${data.type.toLowerCase().replace(/[<>&"]/g,'')}</strong> (${data.budget}) is on the night desk. Expect a reply at <strong>${data.email.replace(/[<>&"]/g,'')}</strong> before sunrise.</p><button class="btn" type="button" id="again">Send another</button></div>`;
      $('.sent',wrap).focus(); $('#again').addEventListener('click',()=>{ location.reload(); });
    },900);
  });
})();

/* =====================================================================
   Lab experiments
   ===================================================================== */
const Lab=(()=>{
  let inited=false;
  const STARS_B=[]; // brightness sample for the Bortle preview, shared with GL star field
  function open(){ if(inited){ resizeDraw(); drawBortle(); return; } inited=true; initDraw(); initPad(); initBortle(); }
  // EXP 01 — draw a constellation
  let pts=[], ret={x:.5,y:.5}, dc, dctx;
  const A=['The','Old','Little','Late','Lost','Second','Northern','Quiet'], N=['Kettle','Night Bus','Glove','Ferryman','Heron','Lamp','Key','Teapot','Fox','Bicycle','Ladder','Umbrella'];
  function resizeDraw(){ const r=dc.getBoundingClientRect(), dpr=Math.min(2,devicePixelRatio||1); dc.width=Math.max(10,r.width*dpr); dc.height=Math.max(10,r.height*dpr); dctx.setTransform(dpr,0,0,dpr,0,0); paint(); }
  function paint(name){ const w=dc.width/(Math.min(2,devicePixelRatio||1)), h=dc.height/(Math.min(2,devicePixelRatio||1)); dctx.clearRect(0,0,w,h);
    // backdrop stars (seeded)
    let s=7; const rnd=()=>((s=(s*16807)%2147483647)/2147483647);
    for(let i=0;i<160;i++){ dctx.fillStyle=`rgba(236,230,216,${.25+rnd()*.5})`; const z=rnd()<.15?2:1; dctx.fillRect(rnd()*w,rnd()*h,z,z); }
    dctx.strokeStyle='rgba(242,166,90,.55)'; dctx.lineWidth=1; dctx.beginPath(); pts.forEach((p,i)=>{ const x=p.x*w,y=p.y*h; i?dctx.lineTo(x,y):dctx.moveTo(x,y); }); dctx.stroke();
    pts.forEach(p=>{ const x=p.x*w,y=p.y*h; const g=dctx.createRadialGradient(x,y,0,x,y,9); g.addColorStop(0,'rgba(255,240,215,1)'); g.addColorStop(.25,'rgba(255,220,170,.5)'); g.addColorStop(1,'rgba(255,200,140,0)'); dctx.fillStyle=g; dctx.beginPath(); dctx.arc(x,y,9,0,7); dctx.fill(); });
    if(document.activeElement===dc){ dctx.strokeStyle='rgba(143,211,200,.9)'; dctx.beginPath(); dctx.arc(ret.x*w,ret.y*h,8,0,7); dctx.moveTo(ret.x*w-13,ret.y*h); dctx.lineTo(ret.x*w-4,ret.y*h); dctx.moveTo(ret.x*w+4,ret.y*h); dctx.lineTo(ret.x*w+13,ret.y*h); dctx.stroke(); }
    if(name){ dctx.fillStyle='rgba(236,230,216,.95)'; dctx.font='italic 26px "Instrument Serif", Georgia, serif'; dctx.fillText(name,16,h-18); }
    $('#draw-out').textContent = pts.length+(pts.length===1?' star':' stars');
  }
  function add(x,y){ if(pts.length>=24) pts.shift(); pts.push({x,y}); paint(); Sound.chime(pts.length); }
  function initDraw(){ dc=$('#draw'); dctx=dc.getContext('2d'); resizeDraw(); addEventListener('resize',()=>{ if(!$('#lab').hidden) resizeDraw(); });
    dc.addEventListener('pointerdown',e=>{ const r=dc.getBoundingClientRect(); add((e.clientX-r.left)/r.width,(e.clientY-r.top)/r.height); });
    dc.addEventListener('keydown',e=>{ const st=.04; if(e.key==='ArrowLeft') ret.x=Math.max(0,ret.x-st); else if(e.key==='ArrowRight') ret.x=Math.min(1,ret.x+st); else if(e.key==='ArrowUp') ret.y=Math.max(0,ret.y-st); else if(e.key==='ArrowDown') ret.y=Math.min(1,ret.y+st); else if(e.key==='Enter'||e.key===' ') add(ret.x,ret.y); else return; e.preventDefault(); paint(); });
    dc.addEventListener('focus',()=>paint()); dc.addEventListener('blur',()=>paint());
    $('#draw-undo').onclick=()=>{ pts.pop(); paint(); }; $('#draw-clear').onclick=()=>{ pts=[]; paint(); };
    $('#draw-name').onclick=()=>{ if(pts.length<2){ $('#draw-out').textContent='Place at least two stars first'; return; } const h=pts.reduce((a,p)=>a+p.x*97+p.y*131,0); const nm=A[Math.floor(h*7)%A.length]+' '+N[Math.floor(h*13)%N.length]; paint(nm); $('#draw-out').textContent='Named: '+nm; };
  }
  // EXP 02 — drone tuner
  function initPad(){ const pad=$('#pad'), dot=$('#pad-dot'), r1=$('#pad-root'), r2=$('#pad-cut');
    const apply=()=>{ const a=r1.value/100, b=r2.value/100; const root=Math.round(36+a*44), cut=Math.round(160*Math.pow(16,b));
      $('#pad-root-out').textContent=root+' Hz'; $('#pad-cut-out').textContent=cut+' Hz'; dot.style.left=(a*100)+'%'; dot.style.top=((1-b)*100)+'%'; Sound.tune(root,cut); };
    let down=false; const mv=e=>{ const r=pad.getBoundingClientRect(); r1.value=Math.max(0,Math.min(100,(e.clientX-r.left)/r.width*100)); r2.value=Math.max(0,Math.min(100,(1-(e.clientY-r.top)/r.height)*100)); apply(); };
    pad.addEventListener('pointerdown',e=>{ down=true; pad.setPointerCapture(e.pointerId); mv(e); }); pad.addEventListener('pointermove',e=>{ if(down) mv(e); }); pad.addEventListener('pointerup',()=>down=false);
    r1.oninput=apply; r2.oninput=apply; apply(); }
  // EXP 03 — light pollution
  let bc, bctx;
  function limitFor(b){ return (b-1)/8*0.72; }
  function drawBortle(){ if(!bc) return; const r=bc.getBoundingClientRect(), dpr=Math.min(2,devicePixelRatio||1); bc.width=Math.max(10,r.width*dpr); bc.height=Math.max(10,r.height*dpr);
    const w=bc.width,h=bc.height, b=+$('#bortle').value, lim=limitFor(b);
    const g=bctx.createLinearGradient(0,0,0,h); g.addColorStop(0,'#03050a'); g.addColorStop(1,`rgba(${60+b*14},${35+b*6},${20},1)`); bctx.fillStyle=g; bctx.fillRect(0,0,w,h);
    let s=3; const rnd=()=>((s=(s*16807)%2147483647)/2147483647); let shown=0;
    for(let i=0;i<1400;i++){ const x=rnd()*w,y=rnd()*h, br=Math.pow(rnd(),5); if(br<lim) continue; shown++; const a=Math.min(1,.25+br*1.4); bctx.fillStyle=`rgba(240,236,226,${a})`; const sz=(br>.5?2:1)*dpr; bctx.fillRect(x,y,sz,sz); }
    bctx.fillStyle='#010204'; bctx.beginPath(); bctx.moveTo(0,h); for(let x=0;x<=w;x+=w/40){ bctx.lineTo(x,h-8*dpr-Math.abs(Math.sin(x*.013))*12*dpr-(x%(w/7)<w/40?18*dpr:0)); } bctx.lineTo(w,h); bctx.fill();
    const total=GL?GL.starCount:300000; const frac=1-Math.pow(Math.max(lim,1e-6),1/22); // brightness ~ U^22, fraction with b>lim
    $('#bortle-count').textContent=`≈ ${Math.round(total*frac).toLocaleString('en-GB')} of ${total.toLocaleString('en-GB')} stars still visible on the dome`;
  }
  function initBortle(){ bc=$('#bortle-view'); bctx=bc.getContext('2d'); const s=$('#bortle');
    s.addEventListener('input',()=>{ $('#bortle-out').textContent=s.value; GL?.setPollution(limitFor(+s.value), (+s.value-1)/8); drawBortle(); }); drawBortle(); }
  return { open, drawBortle };
})();

/* =====================================================================
   Preloader (real readiness)
   ===================================================================== */
const Loader=(()=>{ const steps={}; let total=0, done=0;
  const arc=$('#ld-arc'), pct=$('#ld-pct'), lab=$('#ld-step');
  function add(name,w){ steps[name]={w,done:false}; total+=w; }
  function set(name,label){ const s=steps[name]; if(!s||s.done) return; s.done=true; done+=s.w; const k=Math.round(done/total*100); arc.style.strokeDashoffset=100-k; pct.textContent=k+'%'; if(label) lab.textContent=label; }
  function label(t){ lab.textContent=t; }
  function finish(){ arc.style.strokeDashoffset=0; pct.textContent='100%'; setTimeout(()=>$('#loader').classList.add('done'),280); }
  return {add,set,label,finish};
})();
Loader.add('fonts',10); Loader.add('engine',30); Loader.add('sky',20); Loader.add('shaders',30); Loader.add('frame',10);
const fontsReady = (document.fonts?.ready||Promise.resolve()).then(()=>Loader.set('fonts','Fonts in. Loading the engine'));

/* =====================================================================
   WebGL
   ===================================================================== */
let GL=null;
function hasWebGL2(){ try{ const c=document.createElement('canvas'); return !!c.getContext('webgl2'); }catch(e){ return false; } }
function listMode(reason){
  document.body.classList.add('no-gl'); document.body.classList.remove('gl'); document.documentElement.style.overflow='auto';
  Loader.label(reason||'Showing the list view'); Loader.finish(); applyRoute();
}
async function boot(){
  if(!hasWebGL2() || /[?&]nogl\b/.test(location.search)){ await fontsReady; listMode('No WebGL here, so the work is shown as a list'); return; }
  let mods;
  try{
    mods = await Promise.all([ import('three'), import('three/addons/postprocessing/EffectComposer.js'), import('three/addons/postprocessing/RenderPass.js'),
      import('three/addons/postprocessing/UnrealBloomPass.js'), import('three/addons/postprocessing/ShaderPass.js'), import('three/addons/postprocessing/OutputPass.js'),
      import('three/addons/loaders/GLTFLoader.js'), import('three/addons/environments/RoomEnvironment.js') ]);
  }catch(e){ console.warn('3D engine unavailable, falling back to the list view', e); listMode('Could not load the 3D engine; showing the list view'); return; }
  Loader.set('engine','Engine ready. Scattering stars');
  try{ GL = await createGL(mods); }
  catch(e){ console.warn('WebGL init failed', e); GL=null; listMode('This device could not start the sky; showing the list view'); return; }
  document.body.classList.add('gl');
  applyRoute();
}
boot();

async function createGL([THREE, {EffectComposer}, {RenderPass}, {UnrealBloomPass}, {ShaderPass}, {OutputPass}, {GLTFLoader}, {RoomEnvironment}]){
  const stage=$('#stage');
  /* ---- device tier ---- */
  const mem=navigator.deviceMemory||8, cores=navigator.hardwareConcurrency||8, small=Math.min(innerWidth,innerHeight)<700;
  let soft=false; try{ const gl=document.createElement('canvas').getContext('webgl2'); const ext=gl.getExtension('WEBGL_debug_renderer_info'); soft=/swiftshader|llvmpipe|software/i.test(ext? gl.getParameter(ext.UNMASKED_RENDERER_WEBGL):''); gl.getExtension('WEBGL_lose_context')?.loseContext(); }catch(e){}
  const forced=(location.search.match(/[?&]tier=(\d)/)||[])[1];
  const tier = forced!=null ? +forced : soft ? 0 : (isTouch||small) ? 1 : (mem<=4||cores<=4) ? 1 : 2;
  const TIER = [ {stars:90000, dpr:1, sim:64, dye:192, bloom:.4}, {stars:120000, dpr:1.5, sim:96, dye:256, bloom:.5}, {stars:320000, dpr:2, sim:128, dye:512, bloom:.5} ][Math.max(0,Math.min(2,tier))];
  let dprCap = (soft && forced==null) ? .6 : Math.min(devicePixelRatio||1, TIER.dpr); // software rasterisers get a reduced internal resolution

  const renderer = new THREE.WebGLRenderer({ antialias:false, powerPreference:'high-performance', alpha:false });
  renderer.setPixelRatio(dprCap); renderer.setSize(innerWidth, innerHeight);
  renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.0;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  stage.appendChild(renderer.domElement);
  renderer.domElement.setAttribute('aria-hidden','true');

  /* ================= DOME SCENE ================= */
  const dome = new THREE.Scene();
  const cam = new THREE.PerspectiveCamera(innerWidth<innerHeight?72:56, innerWidth/innerHeight, .1, 2000);
  cam.rotation.order='YXZ';
  const DEG=Math.PI/180;
  const GAL = new THREE.Vector3(.42,.62,.66).normalize();

  const NOISE = `
    float h13(vec3 p){ p=fract(p*.1031); p+=dot(p,p.zyx+31.32); return fract((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(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 fbm(vec3 p){ float a=.5, s=0.; for(int i=0;i<5;i++){ s+=a*vnoise(p); p*=2.03; a*=.5; } return s; }
  `;
  // background sky + milky way + grid + house lights
  // Bake the milky way once into an equirect texture (cheap per-frame sky)
  const BW = tier>=2? 2048 : 1024;
  const mwRT = new THREE.WebGLRenderTarget(BW, BW/2, { type:THREE.HalfFloatType, wrapS:THREE.RepeatWrapping, minFilter:THREE.LinearFilter, magFilter:THREE.LinearFilter, depthBuffer:false });
  {
    const bm = new THREE.ShaderMaterial({ uniforms:{ uGal:{value:GAL} }, depthTest:false,
      vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=vec4(position.xy,0.,1.); }`,
      fragmentShader:`varying vec2 vUv; uniform vec3 uGal; ${NOISE}
        void main(){ float az=(vUv.x-.5)*6.2831853, el=(vUv.y-.5)*3.14159265; vec3 d=vec3(-sin(az)*cos(el), sin(el), -cos(az)*cos(el));
          float g=dot(d,uGal); float n=fbm(d*3.6); float dust=smoothstep(.48,.78,fbm(d*8.+7.3)); float band=exp(-g*g/.03);
          vec3 mw = vec3(.26,.30,.42)*band*(.25+.9*n)*(1.-.8*dust*smoothstep(.2,1.,band));
          mw += vec3(.42,.30,.2)*exp(-g*g/.006)*n*n*.9*smoothstep(-.2,.6,dot(d,normalize(vec3(-.6,.3,-.75))));
          mw += vec3(.10,.16,.22)*smoothstep(.55,.95,fbm(d*2.1+3.))*.25;
          gl_FragColor=vec4(mw,1.); }` });
    const q=new THREE.Mesh(new THREE.PlaneGeometry(2,2),bm), sc=new THREE.Scene(); sc.add(q); q.frustumCulled=false;
    renderer.setRenderTarget(mwRT); renderer.render(sc,new THREE.OrthographicCamera(-1,1,1,-1,0,1)); renderer.setRenderTarget(null);
    bm.dispose(); q.geometry.dispose();
  }
  // horizon silhouette heights: rolling hills plus a treeline, computed once on the CPU
  const RW=2048, ridgeData=new Float32Array(RW*4);
  { let seed=11; const rnd=()=>((seed=(seed*16807)%2147483647)/2147483647); const trees=[];
    for(let k=0;k<260;k++) if(rnd()<.5) trees.push([rnd(), .006+rnd()*.012, .018+rnd()*.03]);
    for(let i=0;i<RW;i++){ const u=i/RW, a=u*6.2831853; let h=.022+.014*Math.sin(a*2+1.3)+.009*Math.sin(a*5+.4)+.005*Math.sin(a*11+2.1)+.003*Math.sin(a*23);
      for(const [c,w,ht] of trees){ let du=Math.abs(u-c); du=Math.min(du,1-du); if(du<w) h=Math.max(h, .02+ht*(1-du/w)); }
      ridgeData[i*4]=h; } }
  const ridgeTex=new THREE.DataTexture(ridgeData,RW,1,THREE.RGBAFormat,THREE.FloatType); ridgeTex.wrapS=THREE.RepeatWrapping; ridgeTex.magFilter=ridgeTex.minFilter=THREE.LinearFilter; ridgeTex.needsUpdate=true;
  const skyMat = new THREE.ShaderMaterial({
    uniforms:{ uTime:{value:0}, uHouse:{value:1}, uPol:{value:.03}, uGrid:{value:0}, uReveal:{value:0}, uDim:{value:0}, tMW:{value:mwRT.texture} },
    vertexShader:`varying vec3 vDir; void main(){ vDir=position; vec4 p=projectionMatrix*modelViewMatrix*vec4(position,1.); gl_Position=p.xyww; }`,
    fragmentShader:`varying vec3 vDir; uniform float uTime,uHouse,uPol,uGrid,uReveal,uDim; uniform sampler2D tMW;
      void main(){ vec3 d=normalize(vDir); float el=asin(clamp(d.y,-1.,1.)); float az=atan(-d.x,-d.z);
        vec3 zen=vec3(.004,.006,.014), hor=vec3(.018,.026,.048);
        vec3 col=mix(hor,zen,smoothstep(0.,.9,el));
        col += vec3(.55,.27,.09)*(.015+.32*uPol)*exp(-max(el,0.)*6.5);
        col += texture2D(tMW, vec2(az/6.2831853+.5, el/3.14159265+.5)).rgb*.16*(1.-uPol*.9)*uReveal;
        float ed=el/(15.*.0174533), ad=az/(30.*.0174533);
        float gl = (1.-smoothstep(0.,1.5*fwidth(ed),abs(fract(ed+.5)-.5))) + (1.-smoothstep(0.,1.5*fwidth(ad),abs(fract(ad+.5)-.5)))*smoothstep(1.45,1.2,el);
        col += vec3(.45,.75,.72)*gl*.06*uGrid*step(0.,el);
        if(uHouse>.001){
          float ps = (1.-smoothstep(0.,2.*fwidth(el*40.),abs(fract(el*40./6.2831+.5)-.5)))*.35 + (1.-smoothstep(0.,2.*fwidth(az*36.),abs(fract(az*36./6.2831+.5)-.5)))*.25*smoothstep(1.4,1.,el);
          vec3 house = vec3(.17,.14,.12)*(.55+.45*smoothstep(-.1,1.2,el)) * (1.-ps*.6);
          col = mix(col, house, uHouse); }
        col *= 1.-uDim*.55;
        gl_FragColor=vec4(col,1.); }`,
    side:THREE.BackSide, depthWrite:false, depthTest:false
  });
  const sky = new THREE.Mesh(new THREE.SphereGeometry(900,64,32), skyMat); sky.renderOrder=0; sky.frustumCulled=false; dome.add(sky);

  // GPU star field
  const N = TIER.stars, R=500;
  const sp=new Float32Array(N*3), sd=new Float32Array(N*4);
  const v=new THREE.Vector3(), t1=new THREE.Vector3(), t2=new THREE.Vector3();
  t1.set(1,0,0).cross(GAL).normalize(); t2.copy(GAL).cross(t1).normalize();
  const gauss=()=>{ let u=0,w=0; while(!u) u=Math.random(); w=Math.random(); return Math.sqrt(-2*Math.log(u))*Math.cos(6.2831853*w); };
  for(let i=0;i<N;i++){
    do{
      if(Math.random()<.55){ const a=Math.random()*6.2831853, off=gauss()*.13; v.copy(t1).multiplyScalar(Math.cos(a)).addScaledVector(t2,Math.sin(a)).addScaledVector(GAL,off).normalize(); }
      else{ const z=Math.random()*2-1, a=Math.random()*6.2831853, r=Math.sqrt(1-z*z); v.set(r*Math.cos(a), z, r*Math.sin(a)); }
    } while(v.y<-.08);
    sp[i*3]=v.x*R; sp[i*3+1]=v.y*R; sp[i*3+2]=v.z*R;
    const b=Math.pow(Math.random(),22);
    sd[i*4]=.55+b*4.8; sd[i*4+1]=b; sd[i*4+2]=Math.random(); sd[i*4+3]=Math.random()<.18? Math.random()*.4 : .35+Math.random()*.65;
  }
  const sg=new THREE.BufferGeometry(); sg.setAttribute('position',new THREE.BufferAttribute(sp,3)); sg.setAttribute('aData',new THREE.BufferAttribute(sd,4));
  const starMat=new THREE.ShaderMaterial({
    uniforms:{ uTime:{value:0}, uPR:{value:dprCap}, uScale:{value:1}, uReveal:{value:0}, uLimit:{value:.06}, uTw:{value:1}, uDim:{value:0} },
    vertexShader:`attribute vec4 aData; uniform float uTime,uPR,uScale,uReveal,uLimit,uTw,uDim; varying vec3 vC; varying float vA;
      vec3 tc(float t){ vec3 a=vec3(.62,.74,1.), b=vec3(1.,.97,.92), c=vec3(1.,.74,.48); return t<.5? mix(a,b,t*2.) : mix(b,c,(t-.5)*2.); }
      void main(){ vec3 d=normalize(position); float b=aData.y;
        float vis = smoothstep(uLimit, uLimit+.05, b+.02);
        float rv = smoothstep(d.y-.12, d.y, uReveal*1.25-.1);
        float tw = 1. + uTw*(.28+.5*(1.-smoothstep(0.,.35,d.y)))*sin(uTime*(1.3+aData.z*4.)+aData.z*61.);
        float sz = aData.x*uScale*uPR;
        float a = (.028+2.7*pow(b,1.6))*vis*rv*tw*(1.-uDim*.5);
        if(sz<1.5*uPR){ a*=sz/(1.5*uPR); sz=1.5*uPR; }
        vC=tc(aData.w); vA=a;
        vec4 p=projectionMatrix*modelViewMatrix*vec4(position,1.); gl_Position=p; gl_PointSize=sz; }`,
    fragmentShader:`varying vec3 vC; varying float vA; void main(){ vec2 q=gl_PointCoord-.5; float r=dot(q,q)*4.; float a=(exp(-r*6.)+.06*exp(-r*1.5))*(1.-smoothstep(.55,1.,r)); if(a<.004) discard; gl_FragColor=vec4(vC*vA*a,1.); }`,
    blending:THREE.AdditiveBlending, depthWrite:false, depthTest:false, transparent:true
  });
  const stars=new THREE.Points(sg,starMat); stars.frustumCulled=false; stars.renderOrder=1; dome.add(stars);
  Loader.set('sky','Drawing ten constellations');

  /* constellations */
  const CR=440, consts=[];
  const cPos=[], cData=[]; const lA=[], lB=[], lS=[], lE=[], lC=[], lT=[];
  const accents = P.map(p=>new THREE.Color(p.accent));
  P.forEach((p,ci)=>{
    const az=p.az*DEG, alt=p.alt*DEG, sc=Math.tan((innerWidth<innerHeight? p.size*.92 : p.size)*DEG);
    const c=new THREE.Vector3(-Math.sin(az)*Math.cos(alt), Math.sin(alt), -Math.cos(az)*Math.cos(alt));
    const east=new THREE.Vector3(Math.cos(az),0,-Math.sin(az)), north=new THREE.Vector3().crossVectors(east,c).normalize();
    const map=(x,y)=>c.clone().addScaledVector(east,x*sc).addScaledVector(north,y*sc).normalize().multiplyScalar(CR);
    const key=(x,y)=>x.toFixed(3)+','+y.toFixed(3); const uniq=new Map();
    let segs=[];
    p.lines.forEach(l=>{ for(let i=0;i<l.length;i+=2){ const k=key(l[i],l[i+1]); if(!uniq.has(k)) uniq.set(k,[l[i],l[i+1]]); if(i>=2) segs.push([l[i-2],l[i-1],l[i],l[i+1]]); } });
    let seed=ci*7+3; const rnd=()=>((seed=(seed*16807)%2147483647)/2147483647);
    uniq.forEach(([x,y])=>{ const q=map(x,y); cPos.push(q.x,q.y,q.z); cData.push(ci, 4.5+rnd()*4.5, rnd()); });
    const ns=segs.length;
    segs.forEach((s,si)=>{ const a=map(s[0],s[1]), b=map(s[2],s[3]);
      for(const [side,end] of [[-1,0],[1,0],[-1,1],[1,0],[1,1],[-1,1]]){ lA.push(a.x,a.y,a.z); lB.push(b.x,b.y,b.z); lS.push(side); lE.push(end); lC.push(ci); lT.push((si+end)/ns); } });
    const minY=Math.min(...[...uniq.values()].map(v=>v[1]));
    consts.push({ c, edge:map(1.15,0).clone(), anchor:map(0,minY-.32), center:c.clone().multiplyScalar(CR), az, alt });
  });
  const cg=new THREE.BufferGeometry(); cg.setAttribute('position',new THREE.Float32BufferAttribute(cPos,3)); cg.setAttribute('aD',new THREE.Float32BufferAttribute(cData,3));
  const hoverU={value:new Array(10).fill(0)}, drawU={value:new Array(10).fill(0)}, accU={value:accents};
  const cStarMat=new THREE.ShaderMaterial({
    uniforms:{ uHover:hoverU, uAcc:accU, uTime:{value:0}, uPR:{value:dprCap}, uScale:{value:1}, uReveal:{value:0}, uDim:{value:0} },
    vertexShader:`attribute vec3 aD; uniform float uHover[10]; uniform vec3 uAcc[10]; uniform float uTime,uPR,uScale,uReveal,uDim; varying vec3 vC; varying float vA;
      void main(){ int i=int(aD.x+.5); float h=uHover[i];
        float pulse=.85+.15*sin(uTime*1.7+aD.z*30.);
        vC=mix(vec3(1.,.95,.86), uAcc[i]*1.25+.15, h*.8);
        vA=(1.4+h*2.6)*pulse*uReveal*(1.-uDim*.6);
        gl_PointSize=(aD.y*(1.+h*.55))*uScale*uPR;
        gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
    fragmentShader:`varying vec3 vC; varying float vA; void main(){ vec2 q=gl_PointCoord-.5; float r=dot(q,q)*4.; float a=(exp(-r*7.)*1.3+.35*exp(-r*2.2))*(1.-smoothstep(.5,1.,r)); if(a<.01) discard; gl_FragColor=vec4(vC*vA*a,1.); }`,
    blending:THREE.AdditiveBlending, depthWrite:false, depthTest:false, transparent:true });
  const cStars=new THREE.Points(cg,cStarMat); cStars.frustumCulled=false; cStars.renderOrder=3; dome.add(cStars);

  const lg=new THREE.BufferGeometry();
  lg.setAttribute('position',new THREE.Float32BufferAttribute(lA,3)); lg.setAttribute('aB',new THREE.Float32BufferAttribute(lB,3));
  lg.setAttribute('aSide',new THREE.Float32BufferAttribute(lS,1)); lg.setAttribute('aEnd',new THREE.Float32BufferAttribute(lE,1));
  lg.setAttribute('aC',new THREE.Float32BufferAttribute(lC,1)); lg.setAttribute('aT',new THREE.Float32BufferAttribute(lT,1));
  const lineMat=new THREE.ShaderMaterial({
    uniforms:{ uHover:hoverU, uDraw:drawU, uAcc:accU, uRes:{value:new THREE.Vector2(innerWidth,innerHeight)}, uPR:{value:dprCap}, uReveal:{value:0}, uDim:{value:0} },
    vertexShader:`attribute vec3 aB; attribute float aSide,aEnd,aC,aT; uniform float uHover[10]; uniform float uDraw[10]; uniform vec3 uAcc[10]; uniform vec2 uRes; uniform float uPR;
      varying float vSide,vT,vDraw,vH; varying vec3 vCol;
      void main(){ int i=int(aC+.5); vH=uHover[i]; vDraw=uDraw[i]; vCol=mix(vec3(.93,.9,.84),uAcc[i],vH*.85);
        vec4 ca=projectionMatrix*modelViewMatrix*vec4(position,1.), cb=projectionMatrix*modelViewMatrix*vec4(aB,1.);
        if(ca.w<=0.||cb.w<=0.){ gl_Position=vec4(2.,2.,2.,1.); return; }
        vec2 res=uRes*uPR*.5; vec2 sa=ca.xy/ca.w*res, sb=cb.xy/cb.w*res; vec2 d=sb-sa; float L=length(d); d/=max(L,1e-4); vec2 n=vec2(-d.y,d.x);
        float gap=min(7.*uPR, L*.3); float w=(1.1+vH*.7)*uPR;
        vec2 s=(aEnd<.5? sa+d*gap : sb-d*gap) + n*aSide*(w+1.);
        vec4 c=aEnd<.5?ca:cb; c.xy=s/res*c.w; gl_Position=c; vSide=aSide; vT=aT; }`,
    side:THREE.DoubleSide,
    fragmentShader:`varying float vSide,vT,vDraw,vH; varying vec3 vCol; uniform float uReveal,uDim;
      void main(){ float e=1.-smoothstep(.35,1.,abs(vSide)); float lit=smoothstep(vT-.015,vT,vDraw);
        float a=e*(.13*uReveal + (.85+.4*vH)*lit)*(1.-uDim*.6); gl_FragColor=vec4(vCol*a,1.); }`,
    blending:THREE.AdditiveBlending, depthWrite:false, depthTest:false, transparent:true });
  const lines=new THREE.Mesh(lg,lineMat); lines.frustumCulled=false; lines.renderOrder=2; dome.add(lines);

  // horizon silhouette (treeline + the dome's rim), drawn over the stars
  const silMat=new THREE.ShaderMaterial({ uniforms:{ uHouse:skyMat.uniforms.uHouse, uPol:skyMat.uniforms.uPol, tR:{value:ridgeTex} },
    vertexShader:`varying vec3 vDir; void main(){ vDir=position; vec4 p=projectionMatrix*modelViewMatrix*vec4(position,1.); gl_Position=p.xyww; }`,
    fragmentShader:`varying vec3 vDir; uniform float uHouse,uPol; uniform sampler2D tR;
      void main(){ vec3 d=normalize(vDir); float el=asin(clamp(d.y,-1.,1.)); float az=atan(-d.x,-d.z);
        float h=texture2D(tR,vec2(az/6.2831853+.5,.5)).r; float aa=fwidth(el)*1.2; float a=1.-smoothstep(h-aa,h+aa,el);
        if(a<.004) discard;
        vec3 ground=vec3(.004,.005,.008) + vec3(.06,.035,.015)*uPol*smoothstep(-.1,h,el)*.6;
        ground=mix(ground, vec3(.07,.06,.055), uHouse);
        gl_FragColor=vec4(ground,a); }`,
    side:THREE.BackSide, transparent:true, depthWrite:false, depthTest:false });
  const sil=new THREE.Mesh(new THREE.SphereGeometry(880,96,24,0,Math.PI*2,Math.PI*.38,Math.PI*.62), silMat); sil.renderOrder=4; sil.frustumCulled=false; dome.add(sil);

  // shooting stars (ambient layer)
  const shootMat=new THREE.ShaderMaterial({ uniforms:{ uT:{value:-1}, uA:{value:new THREE.Vector3()}, uB:{value:new THREE.Vector3()}, uRes:lineMat.uniforms.uRes, uPR:{value:dprCap} },
    vertexShader:`attribute float aSide,aEnd; uniform float uT; uniform vec3 uA,uB; uniform vec2 uRes; uniform float uPR; varying float vSide,vE;
      void main(){ float head=clamp(uT*1.3,0.,1.), tail=clamp(uT*1.3-.35,0.,1.); vec3 P0=mix(uA,uB,tail), P1=mix(uA,uB,head);
        vec4 ca=projectionMatrix*modelViewMatrix*vec4(P0,1.), cb=projectionMatrix*modelViewMatrix*vec4(P1,1.);
        if(ca.w<=0.||cb.w<=0.||uT<0.){ gl_Position=vec4(2.,2.,2.,1.); return; }
        vec2 res=uRes*uPR*.5; vec2 sa=ca.xy/ca.w*res, sb=cb.xy/cb.w*res; vec2 d=normalize(sb-sa+1e-4); vec2 n=vec2(-d.y,d.x);
        vec2 s=(aEnd<.5?sa:sb)+n*aSide*1.6*uPR; vec4 c=aEnd<.5?ca:cb; c.xy=s/res*c.w; gl_Position=c; vSide=aSide; vE=aEnd; }`,
    side:THREE.DoubleSide,
    fragmentShader:`varying float vSide,vE; uniform float uT; void main(){ float a=(1.-abs(vSide))*vE*vE*sin(clamp(uT,0.,1.)*3.14159); gl_FragColor=vec4(vec3(1.,.93,.82)*a*2.2,1.); }`,
    blending:THREE.AdditiveBlending, depthWrite:false, depthTest:false, transparent:true });
  const shg=new THREE.BufferGeometry(); const sS=[],sE=[]; for(const [s,e] of [[-1,0],[1,0],[-1,1],[1,0],[1,1],[-1,1]]){ sS.push(s); sE.push(e); }
  shg.setAttribute('position',new THREE.Float32BufferAttribute(new Array(18).fill(0),3)); shg.setAttribute('aSide',new THREE.Float32BufferAttribute(sS,1)); shg.setAttribute('aEnd',new THREE.Float32BufferAttribute(sE,1));
  const shoot=new THREE.Mesh(shg,shootMat); shoot.frustumCulled=false; shoot.renderOrder=2; dome.add(shoot);
  let nextShoot=4;

  /* ================= FLUID SIM (stable fluids, ping-pong) ================= */
  const Fluid=(()=>{
    const fcam=new THREE.OrthographicCamera(-1,1,1,-1,0,1), fscene=new THREE.Scene(), quad=new THREE.Mesh(new THREE.PlaneGeometry(2,2)); fscene.add(quad); quad.frustumCulled=false;
    const rtOpts={ type:THREE.HalfFloatType, format:THREE.RGBAFormat, minFilter:THREE.LinearFilter, magFilter:THREE.LinearFilter, depthBuffer:false, wrapS:THREE.ClampToEdgeWrapping, wrapT:THREE.ClampToEdgeWrapping };
    let simW, simH, dyeW, dyeH;
    const dbl=(w,h)=>{ const o={ a:new THREE.WebGLRenderTarget(w,h,rtOpts), b:new THREE.WebGLRenderTarget(w,h,rtOpts), get read(){return this.a;}, get write(){return this.b;}, swap(){ const t=this.a; this.a=this.b; this.b=t; } }; return o; };
    let vel, dye, prs, div, crl;
    function size(){ const asp=innerWidth/innerHeight; const s=TIER.sim, d=TIER.dye;
      simW=asp>=1? Math.round(s*asp):s; simH=asp>=1? s:Math.round(s/asp); dyeW=asp>=1?Math.round(d*asp):d; dyeH=asp>=1?d:Math.round(d/asp);
      [vel,dye,prs].forEach(x=>{ if(x){ x.a.dispose(); x.b.dispose(); } }); div?.dispose(); crl?.dispose();
      vel=dbl(simW,simH); dye=dbl(dyeW,dyeH); prs=dbl(simW,simH); div=new THREE.WebGLRenderTarget(simW,simH,rtOpts); crl=new THREE.WebGLRenderTarget(simW,simH,rtOpts); }
    size();
    const V=`uniform vec2 texelSize; varying vec2 vUv,vL,vR,vT,vB; void main(){ vUv=position.xy*.5+.5; vL=vUv-vec2(texelSize.x,0.); vR=vUv+vec2(texelSize.x,0.); vT=vUv+vec2(0.,texelSize.y); vB=vUv-vec2(0.,texelSize.y); gl_Position=vec4(position.xy,0.,1.); }`;
    const H=`precision highp float; varying vec2 vUv,vL,vR,vT,vB; uniform vec2 texelSize;`;
    const M=(frag,u)=>new THREE.ShaderMaterial({ uniforms:Object.assign({texelSize:{value:new THREE.Vector2()}},u), vertexShader:V, fragmentShader:H+frag, depthTest:false, depthWrite:false });
    const splatM=M(`uniform sampler2D uTarget; uniform float aspect,radius; uniform vec3 color; uniform vec2 point; void main(){ vec2 p=vUv-point; p.x*=aspect; vec3 s=exp(-dot(p,p)/radius)*color; gl_FragColor=vec4(texture2D(uTarget,vUv).xyz+s,1.); }`,
      { uTarget:{value:null}, aspect:{value:1}, radius:{value:.0012}, color:{value:new THREE.Vector3()}, point:{value:new THREE.Vector2()} });
    const advM=M(`uniform sampler2D uVel,uSrc; uniform float dt,diss; uniform vec2 simTexel; void main(){ vec2 c=vUv-dt*texture2D(uVel,vUv).xy*simTexel; gl_FragColor=vec4(texture2D(uSrc,c).xyz/(1.+diss*dt),1.); }`,
      { uVel:{value:null}, uSrc:{value:null}, dt:{value:.016}, diss:{value:1}, simTexel:{value:new THREE.Vector2()} });
    const divM=M(`uniform sampler2D uVel; void main(){ float L=texture2D(uVel,vL).x, R=texture2D(uVel,vR).x, T=texture2D(uVel,vT).y, B=texture2D(uVel,vB).y; vec2 C=texture2D(uVel,vUv).xy;
      if(vL.x<0.)L=-C.x; if(vR.x>1.)R=-C.x; if(vT.y>1.)T=-C.y; if(vB.y<0.)B=-C.y; gl_FragColor=vec4(.5*(R-L+T-B),0.,0.,1.); }`, { uVel:{value:null} });
    const curlM=M(`uniform sampler2D uVel; void main(){ float L=texture2D(uVel,vL).y, R=texture2D(uVel,vR).y, T=texture2D(uVel,vT).x, B=texture2D(uVel,vB).x; gl_FragColor=vec4(.5*(R-L-T+B),0.,0.,1.); }`, { uVel:{value:null} });
    const vortM=M(`uniform sampler2D uVel,uCurl; uniform float curl,dt; void main(){ float L=texture2D(uCurl,vL).x, R=texture2D(uCurl,vR).x, T=texture2D(uCurl,vT).x, B=texture2D(uCurl,vB).x, C=texture2D(uCurl,vUv).x;
      vec2 f=.5*vec2(abs(T)-abs(B),abs(R)-abs(L)); f/=length(f)+1e-4; f*=curl*C; f.y*=-1.; vec2 v=texture2D(uVel,vUv).xy+f*dt; gl_FragColor=vec4(clamp(v,-1000.,1000.),0.,1.); }`,
      { uVel:{value:null}, uCurl:{value:null}, curl:{value:18}, dt:{value:.016} });
    const prsM=M(`uniform sampler2D uP,uDiv; void main(){ float L=texture2D(uP,vL).x, R=texture2D(uP,vR).x, T=texture2D(uP,vT).x, B=texture2D(uP,vB).x; gl_FragColor=vec4((L+R+B+T-texture2D(uDiv,vUv).x)*.25,0.,0.,1.); }`, { uP:{value:null}, uDiv:{value:null} });
    const gradM=M(`uniform sampler2D uP,uVel; void main(){ float L=texture2D(uP,vL).x, R=texture2D(uP,vR).x, T=texture2D(uP,vT).x, B=texture2D(uP,vB).x; vec2 v=texture2D(uVel,vUv).xy-vec2(R-L,T-B); gl_FragColor=vec4(v,0.,1.); }`, { uP:{value:null}, uVel:{value:null} });
    const clrM=M(`uniform sampler2D uT; uniform float k; void main(){ gl_FragColor=vec4(texture2D(uT,vUv).xyz*k,1.); }`, { uT:{value:null}, k:{value:.8} });
    function blit(mat,target){ quad.material=mat; renderer.setRenderTarget(target); renderer.render(fscene,fcam); }
    const splats=[];
    function splat(x,y,dx,dy,col){ splats.push([x,y,dx,dy,col]); }
    let active=0;
    function step(dt){
      if(!splats.length && active<=0) return; // idle: nothing moving
      active = splats.length? 6 : active-dt;   // keep simulating ~6 s after the last input
      const st=new THREE.Vector2(1/simW,1/simH), dtx=new THREE.Vector2(1/dyeW,1/dyeH);
      const prevAuto=renderer.autoClear; renderer.autoClear=false;
      for(const [x,y,dx,dy,col] of splats.splice(0)){
        splatM.uniforms.aspect.value=innerWidth/innerHeight; splatM.uniforms.point.value.set(x,y);
        splatM.uniforms.texelSize.value.copy(st); splatM.uniforms.uTarget.value=vel.read.texture; splatM.uniforms.color.value.set(dx,dy,0); splatM.uniforms.radius.value=.0016; blit(splatM,vel.write); vel.swap();
        splatM.uniforms.texelSize.value.copy(dtx); splatM.uniforms.uTarget.value=dye.read.texture; splatM.uniforms.color.value.copy(col); splatM.uniforms.radius.value=.0022; blit(splatM,dye.write); dye.swap();
      }
      [curlM,vortM,divM,prsM,gradM,clrM].forEach(m=>m.uniforms.texelSize.value.copy(st));
      curlM.uniforms.uVel.value=vel.read.texture; blit(curlM,crl);
      vortM.uniforms.uVel.value=vel.read.texture; vortM.uniforms.uCurl.value=crl.texture; vortM.uniforms.dt.value=dt; blit(vortM,vel.write); vel.swap();
      divM.uniforms.uVel.value=vel.read.texture; blit(divM,div);
      clrM.uniforms.uT.value=prs.read.texture; clrM.uniforms.k.value=.8; blit(clrM,prs.write); prs.swap();
      prsM.uniforms.uDiv.value=div.texture; for(let i=0;i<18;i++){ prsM.uniforms.uP.value=prs.read.texture; blit(prsM,prs.write); prs.swap(); }
      gradM.uniforms.uP.value=prs.read.texture; gradM.uniforms.uVel.value=vel.read.texture; blit(gradM,vel.write); vel.swap();
      advM.uniforms.texelSize.value.copy(st); advM.uniforms.simTexel.value.copy(st); advM.uniforms.dt.value=dt; advM.uniforms.uVel.value=vel.read.texture; advM.uniforms.uSrc.value=vel.read.texture; advM.uniforms.diss.value=1.1; blit(advM,vel.write); vel.swap();
      advM.uniforms.texelSize.value.copy(dtx); advM.uniforms.uVel.value=vel.read.texture; advM.uniforms.uSrc.value=dye.read.texture; advM.uniforms.diss.value=.9; blit(advM,dye.write); dye.swap();
      renderer.setRenderTarget(null); renderer.autoClear=prevAuto;
    }
    return { step, splat, size, get vel(){return vel.read.texture;}, get dye(){return dye.read.texture;}, get active(){return active>0||splats.length>0;} };
  })();

  /* ================= POST ================= */
  const composer=new EffectComposer(renderer);
  composer.setPixelRatio(dprCap); composer.setSize(innerWidth,innerHeight);
  const renderPass=new RenderPass(dome,cam); composer.addPass(renderPass);
  const fluidPass=new ShaderPass({ uniforms:{ tDiffuse:{value:null}, tVel:{value:null}, tDye:{value:null}, uAmt:{value:1}, uMist:{value:new THREE.Color('#c9cfd8')} },
    vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
    fragmentShader:`uniform sampler2D tDiffuse,tVel,tDye; uniform float uAmt; uniform vec3 uMist; varying vec2 vUv;
      void main(){ vec2 v=texture2D(tVel,vUv).xy; vec2 off=v*.00013*uAmt; vec3 c=vec3(0.);
        for(int i=0;i<10;i++){ float t=float(i)/9.; c+=texture2D(tDiffuse,vUv-off*t*2.).rgb; } c/=10.;
        vec3 dy=texture2D(tDye,vUv).rgb; float m=clamp(length(dy),0.,1.);
        c = c + uMist*m*m*.07*uAmt + c*m*.8*uAmt;
        gl_FragColor=vec4(c,1.); }` });
  composer.addPass(fluidPass);
  const bloom=new UnrealBloomPass(new THREE.Vector2(innerWidth*TIER.bloom,innerHeight*TIER.bloom), .75, .5, .32);
  const BLOOM={ dome:[.75,.5,.32], project:[.38,.35,.92] };
  function bloomFor(m){ const b=BLOOM[m]; bloom.strength=b[0]; bloom.radius=b[1]; bloom.threshold=b[2]; } composer.addPass(bloom);
  composer.addPass(new OutputPass());
  const gradePass=new ShaderPass({ uniforms:{ tDiffuse:{value:null}, uTime:{value:0}, uWarp:{value:0}, uFade:{value:1}, uCenter:{value:new THREE.Vector2(.5,.5)}, uAsp:{value:innerWidth/innerHeight}, uFlash:{value:0} },
    vertexShader:`varying vec2 vUv; void main(){ vUv=uv; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
    fragmentShader:`uniform sampler2D tDiffuse; uniform float uTime,uWarp,uFade,uAsp,uFlash; uniform vec2 uCenter; varying vec2 vUv;
      float h(vec2 p){ return fract(sin(dot(p,vec2(12.9898,78.233)))*43758.5453); }
      void main(){ vec2 d=vUv-uCenter; float ca=.0012+uWarp*.022; vec3 col=vec3(0.);
        if(uWarp>.002){ float w=0.;
          for(int i=0;i<20;i++){ float k=float(i)/19.; float s=1.-uWarp*.55*k; float wt=1.-k*.6;
            col.r+=texture2D(tDiffuse,uCenter+d*s*(1.+ca)).r*wt; col.g+=texture2D(tDiffuse,uCenter+d*s).g*wt; col.b+=texture2D(tDiffuse,uCenter+d*s*(1.-ca)).b*wt; w+=wt; }
          col/=w; col*=1.+uWarp*1.4; }
        else { col.r=texture2D(tDiffuse,uCenter+d*(1.+ca)).r; col.g=texture2D(tDiffuse,vUv).g; col.b=texture2D(tDiffuse,uCenter+d*(1.-ca)).b; }
        col += vec3(1.,.9,.78)*uFlash;
        vec2 q=d*vec2(uAsp,1.); col*=mix(1.,smoothstep(1.25,.25,length(q)),.55);
        col += (h(vUv*1000.+fract(uTime*7.)*100.)-.5)*.045;
        gl_FragColor=vec4(col*uFade,1.); }` });
  composer.addPass(gradePass);

  /* ================= PROJECT SCENES ================= */
  const pmrem=new THREE.PMREMGenerator(renderer);
  const envTex=pmrem.fromScene(new RoomEnvironment(),.04).texture;
  const loader=new GLTFLoader();
  const modelCache=new Map();
  function loadModel(name){ if(!name) return Promise.resolve(null); if(modelCache.has(name)) return modelCache.get(name);
    const pr=new Promise((res,rej)=>loader.load(`${MODEL_ROOT}${name}.glb`, g=>res(g.scene), undefined, rej)); modelCache.set(name,pr); pr.catch(()=>modelCache.delete(name)); return pr; }
  const pcam=new THREE.PerspectiveCamera(36,innerWidth/innerHeight,.05,200);
  const scenes=new Map();
  const softTex=(()=>{ const c=document.createElement('canvas'); c.width=c.height=128; const x=c.getContext('2d'); const g=x.createRadialGradient(64,64,0,64,64,64); g.addColorStop(0,'rgba(0,0,0,.85)'); g.addColorStop(.55,'rgba(0,0,0,.35)'); g.addColorStop(1,'rgba(0,0,0,0)'); x.fillStyle=g; x.fillRect(0,0,128,128); const t=new THREE.CanvasTexture(c); return t; })();
  const FX={spray:0,rain:1,embers:2,dust:3,migrate:4,pulse:5,bubbles:6,moths:7,snow:8};
  function particles(mode,color,count){
    const g=new THREE.BufferGeometry(); const s=new Float32Array(count*3); for(let i=0;i<s.length;i++) s[i]=Math.random();
    g.setAttribute('position',new THREE.BufferAttribute(new Float32Array(count*3),3)); g.setAttribute('aSeed',new THREE.BufferAttribute(s,3));
    const m=new THREE.ShaderMaterial({ uniforms:{ uTime:{value:0}, uMode:{value:mode}, uCol:{value:new THREE.Color(color)}, uPR:{value:dprCap}, uH:{value:innerHeight} },
      vertexShader:`attribute vec3 aSeed; uniform float uTime,uPR,uH; uniform int uMode; varying float vA; varying float vStreak;
        void main(){ vec3 s=aSeed; float t=uTime; vec3 p; float sz=3.; vA=1.; vStreak=0.;
          if(uMode==1){ p=vec3((s.x-.5)*7.,5.-mod(t*5.5+s.y*9.,9.),(s.z-.5)*7.-1.); sz=18.; vStreak=1.; vA=.55; }
          else if(uMode==2){ float y=mod(t*.32+s.y*4.,4.); p=vec3((s.x-.5)*2.4+sin(t*.8+s.z*20.)*.25*y,y-.2,(s.z-.5)*2.4); sz=5.; vA=(1.-y/4.)*(.6+.4*sin(t*9.+s.x*50.)); }
          else if(uMode==4){ float x=mod(t*.18+s.x*8.,8.)-4.; p=vec3(x,1.2+s.y*2.2+sin(x*2.+s.z*6.)*.12,(s.z-.5)*5.-1.5); sz=4.; vA=.8*smoothstep(4.,3.,abs(x)); }
          else if(uMode==5){ float r=mod(t*.5+s.y*3.,3.); float a=s.x*6.2831853; p=vec3(cos(a)*r*1.4,.6+sin(a)*r*.5+(s.z-.5)*.3,-.2+sin(a)*r*.6); sz=4.; vA=(1.-r/3.)*.9; }
          else if(uMode==6){ float y=mod(t*.4+s.y*4.,4.); p=vec3((s.x-.5)*2.6+sin(t*1.3+s.z*30.)*.08,y-.3,(s.z-.5)*2.6); sz=7.+s.z*9.; vA=.75*(1.-y/4.); }
          else if(uMode==7){ float a=t*(1.+s.x*2.)+s.y*30.; float r=.35+s.z*.9; p=vec3(cos(a)*r+.9*sin(t*.3+s.x*9.)*.3,1.5+sin(a*1.7)*.4+s.y*.5,sin(a)*r*.7); sz=5.; vA=.6+.4*sin(t*20.+s.x*90.); }
          else if(uMode==8){ p=vec3((s.x-.5)*7.+sin(t*.4+s.z*9.)*.3,4.5-mod(t*.35+s.y*6.,6.),(s.z-.5)*6.-1.); sz=4.5; vA=.8; }
          else if(uMode==0){ p=vec3((s.x-.5)*9.+mod(t*.25+s.z*9.,9.)-4.5,.05+s.y*.9,(s.z-.5)*7.-1.); sz=6.; vA=.25; }
          else { p=vec3((s.x-.5)*4.+sin(t*.1+s.z*9.)*.2,s.y*3.,(s.z-.5)*4.+cos(t*.13+s.x*7.)*.2); sz=3.5; vA=.55*(.6+.4*sin(t+s.x*40.)); }
          vec4 mv=modelViewMatrix*vec4(p,1.); gl_Position=projectionMatrix*mv; gl_PointSize=sz*uPR*(uH/900.)*(3.5/-mv.z); }`,
      fragmentShader:`uniform vec3 uCol; uniform int uMode; varying float vA; varying float vStreak;
        void main(){ vec2 q=gl_PointCoord-.5; float a;
          if(vStreak>.5) a=exp(-q.x*q.x*900.)*(1.-abs(q.y)*2.);
          else if(uMode==6){ float r=length(q)*2.; a=smoothstep(.65,.9,r)*smoothstep(1.,.9,r)+exp(-r*r*20.)*.15; }
          else { float r=dot(q,q)*4.; a=exp(-r*5.)*(1.-smoothstep(.6,1.,r)); }
          if(a<.01) discard; gl_FragColor=vec4(uCol*a*vA,1.); }`,
      blending:THREE.AdditiveBlending, transparent:true, depthWrite:false });
    const pts=new THREE.Points(g,m); pts.frustumCulled=false; return pts;
  }
  function backdrop(color){
    const m=new THREE.ShaderMaterial({ uniforms:{ uC:{value:new THREE.Color(color)} }, side:THREE.BackSide, depthWrite:false,
      vertexShader:`varying vec3 vD; void main(){ vD=position; gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); }`,
      fragmentShader:`uniform vec3 uC; varying vec3 vD; void main(){ vec3 d=normalize(vD); float g=exp(-pow(d.y-.05,2.)*14.); vec3 c=vec3(.006,.008,.016)+uC*.022*g+uC*.015*exp(-pow(length(d.xz-vec2(0.,-1.)),2.)*2.); gl_FragColor=vec4(c,1.); }` });
    const mesh=new THREE.Mesh(new THREE.SphereGeometry(60,32,16),m); mesh.renderOrder=-1; return mesh;
  }
  function bgStars(){ const n=4000, a=new Float32Array(n*3), d=new Float32Array(n*4); for(let i=0;i<n;i++){ const z=Math.random()*1.2-.2, t=Math.random()*6.283, r=Math.sqrt(1-z*z); a.set([r*Math.cos(t)*50,z*50,r*Math.sin(t)*50],i*3); const b=Math.pow(Math.random(),4); d.set([.8+b*3.5,b,Math.random(),Math.random()],i*4); }
    const g=new THREE.BufferGeometry(); g.setAttribute('position',new THREE.BufferAttribute(a,3)); g.setAttribute('aData',new THREE.BufferAttribute(d,4));
    const m=starMat.clone(); m.uniforms.uReveal.value=1; m.uniforms.uLimit.value=0; m.uniforms.uScale.value=1; m.depthTest=true;
    const p=new THREE.Points(g,m); p.frustumCulled=false; p.renderOrder=0; return p; }
  function ferry(accent){
    const grp=new THREE.Group();
    const hullShape=new THREE.Shape(); hullShape.moveTo(-1.25,.28); hullShape.lineTo(1.3,.3); hullShape.quadraticCurveTo(1.15,-.05,.95,-.22); hullShape.lineTo(-1.1,-.22); hullShape.quadraticCurveTo(-1.25,-.05,-1.25,.28);
    const hull=new THREE.Mesh(new THREE.ExtrudeGeometry(hullShape,{depth:.62,bevelEnabled:true,bevelSize:.04,bevelThickness:.06,bevelSegments:3,curveSegments:16}), new THREE.MeshStandardMaterial({color:'#b9b6af',roughness:.6,metalness:.1}));
    hull.geometry.translate(0,0,-.31); grp.add(hull);
    const band=new THREE.Mesh(new THREE.BoxGeometry(2.3,.07,.7), new THREE.MeshStandardMaterial({color:'#000',emissive:new THREE.Color(accent),emissiveIntensity:3.2})); band.position.set(.02,.09,0); grp.add(band);
    const winC=document.createElement('canvas'); winC.width=256; winC.height=32; const wx=winC.getContext('2d'); wx.fillStyle='#14161c'; wx.fillRect(0,0,256,32); for(let i=0;i<14;i++){ wx.fillStyle=Math.random()<.75?'#ffd39a':'#3a2a18'; wx.fillRect(8+i*17.5,10,11,12); }
    const winT=new THREE.CanvasTexture(winC); winT.colorSpace=THREE.SRGBColorSpace;
    const cabMat=[ new THREE.MeshStandardMaterial({color:'#dcd8cf',roughness:.6}), new THREE.MeshStandardMaterial({color:'#dcd8cf',roughness:.6}), new THREE.MeshStandardMaterial({color:'#cfcac0'}), new THREE.MeshStandardMaterial({color:'#cfcac0'}),
      new THREE.MeshStandardMaterial({color:'#fff',map:winT,emissive:'#ffffff',emissiveMap:winT,emissiveIntensity:1.6,roughness:.4}), new THREE.MeshStandardMaterial({color:'#fff',map:winT,emissive:'#ffffff',emissiveMap:winT,emissiveIntensity:1.6,roughness:.4}) ];
    const cab=new THREE.Mesh(new THREE.BoxGeometry(1.35,.32,.5),cabMat); cab.position.set(-.1,.48,0); grp.add(cab);
    const bridge=new THREE.Mesh(new THREE.BoxGeometry(.45,.2,.42),cabMat); bridge.position.set(.32,.74,0); grp.add(bridge);
    const fun=new THREE.Mesh(new THREE.CylinderGeometry(.08,.1,.36,20), new THREE.MeshStandardMaterial({color:'#20232b',roughness:.4,metalness:.5})); fun.position.set(-.35,.8,0); grp.add(fun);
    const mast=new THREE.Mesh(new THREE.CylinderGeometry(.012,.012,.6,8), new THREE.MeshStandardMaterial({color:'#bbb'})); mast.position.set(.32,1.1,0); grp.add(mast);
    const lamp=new THREE.Mesh(new THREE.SphereGeometry(.03,12,8), new THREE.MeshBasicMaterial({color:new THREE.Color(4,3.2,2.4)})); lamp.position.set(.32,1.42,0); grp.add(lamp);
    const pl=new THREE.PointLight(accent,1.2,3,1.5); pl.position.set(0,.2,.6); grp.add(pl);
    const navy=new THREE.MeshStandardMaterial({color:'#1b2433',roughness:.5,metalness:.2});
    const lower=new THREE.Mesh(new THREE.BoxGeometry(2.24,.07,.72),navy); lower.position.set(-.02,.02,0); grp.add(lower);
    const railM=new THREE.MeshStandardMaterial({color:'#d8d4cc',roughness:.4,metalness:.4});
    for(const z of [-.33,.33]){ const r=new THREE.Mesh(new THREE.BoxGeometry(2.1,.012,.012),railM); r.position.set(.0,.42,z); grp.add(r);
      for(let k=0;k<15;k++){ const post=new THREE.Mesh(new THREE.BoxGeometry(.01,.1,.01),railM); post.position.set(-1.0+k*.145,.37,z); grp.add(post); }
      const boat=new THREE.Mesh(new THREE.CapsuleGeometry(.05,.22,4,12),new THREE.MeshStandardMaterial({color:'#e2683a',roughness:.5})); boat.rotation.z=Math.PI/2; boat.position.set(-.45,.7,z*.85); grp.add(boat); }
    grp.scale.setScalar(.95);
    return grp;
  }
  function ocean(accent){
    const m=new THREE.ShaderMaterial({ uniforms:{ uTime:{value:0}, uC:{value:new THREE.Color(accent)} },
      vertexShader:`uniform float uTime; varying vec3 vW; varying vec3 vN;
        float H(vec2 p){ return .05*sin(p.x*1.3+uTime*.9)+.035*sin(p.y*1.9-uTime*1.1+p.x*.4)+.018*sin((p.x+p.y)*3.7+uTime*1.7)+.01*sin(p.x*7.1-uTime*2.3); }
        void main(){ vec3 p=position; vec2 q=p.xz; float h=H(q); float e=.02; vec3 n=normalize(vec3(-(H(q+vec2(e,0.))-h)/e,1.,-(H(q+vec2(0.,e))-h)/e)); p.y+=h; vN=n; vW=(modelMatrix*vec4(p,1.)).xyz; gl_Position=projectionMatrix*viewMatrix*vec4(vW,1.); }`,
      fragmentShader:`uniform vec3 uC; varying vec3 vW; varying vec3 vN;
        void main(){ vec3 V=normalize(cameraPosition-vW); vec3 N=normalize(vN); float f=pow(1.-max(dot(N,V),0.),4.);
          vec3 Lm=normalize(vec3(-.4,.35,-1.)); vec3 Hh=normalize(Lm+V); float sp=pow(max(dot(N,Hh),0.),180.)*2.5;
          vec3 La=normalize(vec3(0.,.1,0.)-vW); float glow=exp(-length(vW.xz)*.9)*.5;
          vec3 c=vec3(.004,.008,.016)+vec3(.05,.07,.12)*f+vec3(.8,.85,1.)*sp+uC*glow*(.4+f);
          float fade=exp(-length(vW.xz)*.12); gl_FragColor=vec4(c*fade,1.); }` });
    const o=new THREE.Mesh(new THREE.PlaneGeometry(40,40,180,180).rotateX(-Math.PI/2), m); return o;
  }
  async function buildScene(i){
    if(scenes.has(i)) return scenes.get(i);
    const p=P[i]; const s=new THREE.Scene(); s.environment=envTex; s.environmentIntensity=.35;
    s.add(backdrop(p.accent)); s.add(bgStars());
    const key=new THREE.DirectionalLight('#fff1dc',1.6); key.position.set(2.5,3.5,2.8); s.add(key);
    const rim=new THREE.DirectionalLight(p.accent,4.5); rim.position.set(-3,1.6,-2.5); s.add(rim);
    const fill=new THREE.HemisphereLight('#2a3550','#050608',.6); s.add(fill);
    const holder=new THREE.Group(); s.add(holder);
    let upd=[], obj;
    if(!p.model){
      const sea=ocean(p.accent); s.add(sea); obj=ferry(p.accent); obj.position.y=.02; holder.add(obj);
      upd.push((t)=>{ sea.material.uniforms.uTime.value=t; obj.position.y=.02+Math.sin(t*.9)*.03; obj.rotation.z=Math.sin(t*.7)*.025; obj.rotation.x=Math.sin(t*.55)*.02; });
      const moon=new THREE.Mesh(new THREE.SphereGeometry(1.2,32,16), new THREE.MeshBasicMaterial({color:new THREE.Color(2.2,2.15,2)})); moon.position.set(-14,7,-38); s.add(moon);
    } else {
      const plinth=new THREE.Mesh(new THREE.CylinderGeometry(1.05,1.12,.32,96), new THREE.MeshStandardMaterial({color:'#0d1016',roughness:.32,metalness:.7})); plinth.position.y=-.16; s.add(plinth);
      const ring=new THREE.Mesh(new THREE.TorusGeometry(1.06,.006,8,128), new THREE.MeshBasicMaterial({color:new THREE.Color(p.accent).multiplyScalar(3)})); ring.rotation.x=Math.PI/2; ring.position.y=.001; s.add(ring);
      const sh=new THREE.Mesh(new THREE.PlaneGeometry(1.6,1.6), new THREE.MeshBasicMaterial({map:softTex,transparent:true,depthWrite:false})); sh.rotation.x=-Math.PI/2; sh.position.y=.003; s.add(sh);
      const src=await loadModel(p.model); obj=src.clone(true);
      obj.traverse(o=>{ if(o.isMesh){ o.material=o.material.clone(); if('envMapIntensity' in o.material) o.material.envMapIntensity=1.1; } });
      const box=new THREE.Box3().setFromObject(obj), sz=box.getSize(new THREE.Vector3()), ctr=box.getCenter(new THREE.Vector3());
      const sc=(p.fit||1.45)/Math.max(sz.x,sz.y,sz.z); obj.scale.setScalar(sc); obj.position.set(-ctr.x*sc, -box.min.y*sc+.004, -ctr.z*sc);
      const spin=new THREE.Group(); spin.add(obj); holder.add(spin);
      upd.push((t)=>{ spin.rotation.y=t*.18; });
    }
    const fx=particles(FX[p.fx]??3, p.accent, p.fx==='rain'?1600:p.fx==='snow'?1400:700); s.add(fx);
    upd.push((t)=>{ fx.material.uniforms.uTime.value=t; });
    const sc={ scene:s, update:(t)=>upd.forEach(f=>f(t)), holder, isSea:!p.model };
    await renderer.compileAsync(s,pcam).catch(()=>{});
    scenes.set(i,sc); return sc;
  }

  /* ================= state, input ================= */
  let yaw=(P[0].az+20)*DEG, pitch=22*DEG, vYaw=0, vPitch=0, dragging=false, lastX=0, lastY=0, downX=0, downY=0, downT=0, lastMove=0, interacted=false;
  if(innerWidth<innerHeight){ yaw=P[0].az*DEG; pitch=(P[0].alt-13)*DEG; }
  let focusTarget=null; // {yaw,pitch}
  let mode='dome'; // dome | warping | project
  let curScene=null, pYaw=0, pPitch=.18, pvYaw=0, pDist=3.6; const baseDist=()=>innerWidth<innerHeight? 7.2 : innerWidth<=860? 4.6 : 4.1;
  const ptr={x:-1,y:-1,px:0,py:0,has:false};
  let dimT=0, dim=0, warpRun=null;
  const hoverVals=new Array(10).fill(0), drawVals=new Array(10).fill(0);
  let glHover=-1;

  function setDim(d){ dimT=d; }
  function onDown(e){ if(mode!=='dome' && mode!=='project') return; dragging=true; stage.classList.add('dragging'); stage.setPointerCapture?.(e.pointerId); lastX=downX=e.clientX; lastY=downY=e.clientY; downT=performance.now(); vYaw=vPitch=0; pvYaw=0; focusTarget=null;
    if(!interacted){ interacted=true; document.body.classList.add('touched'); } }
  function onMove(e){
    const x=e.clientX, y=e.clientY; const now=performance.now();
    if(ptr.has && !reduced){ const dx=(x-ptr.px)/innerWidth, dy=(y-ptr.py)/innerHeight; const sp=Math.hypot(dx,dy);
      if(sp>0.0005){ const col=new THREE.Vector3(.5,.52,.56).multiplyScalar(Math.min(1.2,sp*30)); Fluid.splat(x/innerWidth,1-y/innerHeight,dx*5200,-dy*5200,col); } }
    ptr.px=x; ptr.py=y; ptr.x=x; ptr.y=y; ptr.has=true; lastMove=now;
    if(dragging){ const k=(cam.fov*DEG)/innerHeight; const dx=x-lastX, dy=y-lastY; lastX=x; lastY=y;
      if(mode==='dome'){ yaw+=dx*k; pitch+=dy*k; pitch=Math.max(.04,Math.min(1.32,pitch)); vYaw=dx*k*60; vPitch=dy*k*60; skyMat.uniforms.uGrid.value=Math.min(1,skyMat.uniforms.uGrid.value+.08); }
      else if(mode==='project'){ pYaw-=dx*.008; pPitch=Math.max(-.05,Math.min(.75,pPitch+dy*.004)); pvYaw=-dx*.008*60; } }
  }
  function onUp(e){ if(!dragging) return; dragging=false; stage.classList.remove('dragging');
    const moved=Math.hypot(e.clientX-downX,e.clientY-downY), dt=performance.now()-downT;
    if(mode==='dome' && moved<7 && dt<500){ const hit=pick(e.clientX,e.clientY);
      if(hit>=0){ if(e.pointerType==='touch' && hovered!==hit){ setHover(hit); focusConstellation(hit); } else location.hash='work/'+P[hit].slug; }
      else if(e.pointerType==='touch') setHover(-1); } }
  stage.addEventListener('pointerdown',onDown); addEventListener('pointermove',onMove,{passive:true}); addEventListener('pointerup',onUp); addEventListener('pointercancel',onUp);
  stage.addEventListener('wheel',e=>{ if(mode!=='dome') return; e.preventDefault(); vYaw += (e.deltaY+e.deltaX)*.0009*(e.deltaMode?30:1)*60*.016*4; focusTarget=null; interacted=true; document.body.classList.add('touched'); },{passive:false});
  stage.addEventListener('keydown',e=>{ if(mode!=='dome') return; const s=.06; if(e.key==='ArrowLeft') vYaw-=s*8; else if(e.key==='ArrowRight') vYaw+=s*8; else if(e.key==='ArrowUp') pitch=Math.min(1.32,pitch+s); else if(e.key==='ArrowDown') pitch=Math.max(.04,pitch-s); else return; e.preventDefault(); focusTarget=null; });

  const tmpV=new THREE.Vector3();
  function toScreen(p){ tmpV.copy(p).applyMatrix4(cam.matrixWorldInverse); if(tmpV.z>-1) return null; tmpV.applyMatrix4(cam.projectionMatrix); return { x:(tmpV.x*.5+.5)*innerWidth, y:(-tmpV.y*.5+.5)*innerHeight }; }
  const scr=new Array(10).fill(null);
  function pick(x,y){ let best=-1, bd=1e9; for(let i=0;i<10;i++){ const s=scr[i]; if(!s) continue; const d=Math.hypot(x-s.x,y-s.y); if(d<s.r*1.05 && d<bd){ bd=d; best=i; } } return best; }
  function wrap(a){ while(a>Math.PI) a-=Math.PI*2; while(a<-Math.PI) a+=Math.PI*2; return a; }
  function focusConstellation(i){ const c=consts[i]; focusTarget={ yaw: yaw+wrap(c.az-yaw), pitch: Math.max(.06, c.alt - (innerWidth<innerHeight? 11 : 3)*DEG) }; }

  /* cardinal markers */
  const cardEl=$('.cards'); const cards=[['N',0],['E',90],['S',180],['W',270]].map(([n,a])=>{ const el=document.createElement('span'); el.className='card-dir'; el.textContent=n; cardEl.appendChild(el); const az=a*DEG; return { el, p:new THREE.Vector3(-Math.sin(az)*880*.999,880*Math.sin(.075),-Math.cos(az)*880) }; });

  /* ================= resize ================= */
  function resize(){ const w=innerWidth,h=innerHeight; renderer.setSize(w,h); composer.setSize(w,h); cam.aspect=w/h; cam.fov=w<h?72:56; baseFov=cam.fov; cam.updateProjectionMatrix();
    pcam.aspect=w/h; pcam.fov=w<h?48:36; pcam.updateProjectionMatrix(); setViewOffset(); bloom.resolution.set(w*TIER.bloom,h*TIER.bloom);
    lineMat.uniforms.uRes.value.set(w,h); gradePass.uniforms.uAsp.value=w/h; const scl=Math.max(.75,Math.min(1.5,h/900)); starMat.uniforms.uScale.value=scl; cStarMat.uniforms.uScale.value=scl;
    Fluid.size(); }
  let baseFov=cam.fov;
  function setViewOffset(){ const w=innerWidth,h=innerHeight; if(w<=860) pcam.setViewOffset(w,h,0,h*.24,w,h); else pcam.setViewOffset(w,h,w*.19,0,w,h); }
  addEventListener('resize',resize); resize();

  /* ================= transitions ================= */
  const ease={ inC:t=>t*t*t, outC:t=>1-Math.pow(1-t,3), io:t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2 };
  function tween(dur,fn){ return new Promise(res=>{ const t0=performance.now(); const tick=()=>{ const k=Math.min(1,(performance.now()-t0)/dur); fn(k); if(k<1) requestAnimationFrame(tick); else res(); }; requestAnimationFrame(tick); }); }
  const pjLoading=$('#pj-loading');
  let token=0;
  async function openProject(i, onShown){
    const my=++token; const fromProject = mode==='project';
    mode='warping'; setHover(-1);
    const scP=buildScene(i).catch(e=>{ console.warn('model load failed',e); return null; });
    if(reduced){ await tween(220,k=>gradePass.uniforms.uFade.value=1-k); }
    else if(fromProject){ Sound.whoosh(true); await tween(650,k=>{ const e=ease.inC(k); gradePass.uniforms.uWarp.value=e; pDist=baseDist()-e*2.6; }); }
    else {
      focusConstellation(i); const fy=focusTarget.yaw, fp=focusTarget.pitch; const y0=yaw, p0=pitch; focusTarget=null;
      await tween(520,k=>{ const e=ease.io(k); yaw=y0+(fy-y0)*e; pitch=p0+(fp-p0)*e; });
      cam.rotation.set(pitch,yaw,0); cam.updateMatrixWorld(); { const sc0=toScreen(consts[i].center); if(sc0) gradePass.uniforms.uCenter.value.set(sc0.x/innerWidth,1-sc0.y/innerHeight); }
      Sound.whoosh(true);
      await tween(950,k=>{ const e=ease.inC(k); gradePass.uniforms.uWarp.value=e; cam.fov=baseFov-e*34; cam.updateProjectionMatrix(); gradePass.uniforms.uFlash.value=Math.max(0,(k-.8)*2.5)*.6; });
    }
    if(my!==token) return;
    pjLoading.textContent='Tuning in…'; pjLoading.classList.add('on');
    const sc=await scP; pjLoading.classList.remove('on');
    if(my!==token) return;
    if(!sc){ pjLoading.textContent=''; gradePass.uniforms.uWarp.value=0; gradePass.uniforms.uFade.value=1; gradePass.uniforms.uFlash.value=0; cam.fov=baseFov; cam.updateProjectionMatrix(); mode='project'; curScene=null; renderPass.scene=dome; onShown(); return; }
    gradePass.uniforms.uCenter.value.set(innerWidth>860? .4 : .5, innerWidth>860? .5 : .62);
    curScene=sc; renderPass.scene=sc.scene; renderPass.camera=pcam; mode='project'; bloomFor('project');
    pYaw=-.5; pPitch=sc.isSea?.12:.2; pvYaw=0; cam.fov=baseFov; cam.updateProjectionMatrix();
    setTimeout(onShown, reduced?0:350);
    if(reduced){ pDist=baseDist(); gradePass.uniforms.uWarp.value=0; await tween(260,k=>gradePass.uniforms.uFade.value=k); }
    else await tween(1100,k=>{ const e=ease.outC(k); gradePass.uniforms.uWarp.value=1-e; gradePass.uniforms.uFlash.value=(1-k)*(1-k)*.5; pDist=baseDist()+(1-e)*9; pYaw=-.5-(1-e)*1.2; });
    gradePass.uniforms.uFlash.value=0;
  }
  async function closeProject(done){
    const my=++token;
    if(mode==='dome'){ done(); return; }
    mode='warping'; Sound.whoosh(false);
    if(reduced) await tween(220,k=>gradePass.uniforms.uFade.value=1-k);
    else await tween(750,k=>{ const e=ease.inC(k); gradePass.uniforms.uWarp.value=e; pDist=baseDist()+e*8; });
    if(my!==token) return;
    renderPass.scene=dome; renderPass.camera=cam; curScene=null; bloomFor('dome'); done();
    if(reduced){ gradePass.uniforms.uWarp.value=0; cam.fov=baseFov; cam.updateProjectionMatrix(); await tween(260,k=>gradePass.uniforms.uFade.value=k); }
    else await tween(1000,k=>{ const e=ease.outC(k); gradePass.uniforms.uWarp.value=1-e; cam.fov=baseFov-(1-e)*34; cam.updateProjectionMatrix(); });
    cam.fov=baseFov; cam.updateProjectionMatrix(); mode='dome';
  }

  /* ================= loop ================= */
  let introT0=0; const clock=new THREE.Clock(); let t=0, raf=0, running=true, revealK=0, intro=0;
  const hudAz=$('#hud-az'), hudAlt=$('#hud-alt');
  let fpsAcc=0, fpsN=0, lowFrames=0;
  function frame(){
    raf=requestAnimationFrame(frame);
    const dt=Math.min(.05,clock.getDelta()); if(!reduced) t+=dt;
    // adaptive resolution
    fpsAcc+=dt; fpsN++; if(fpsAcc>2){ const fps=fpsN/fpsAcc; if(fps<40 && dprCap>1 && !soft){ dprCap=Math.max(1,dprCap-.25); renderer.setPixelRatio(dprCap); composer.setPixelRatio(dprCap); [starMat,cStarMat,lineMat].forEach(m=>m.uniforms.uPR.value=dprCap); } fpsAcc=0; fpsN=0; }
    // intro: house lights dim, stars rise from the horizon
    if(intro<1){ intro=Math.min(1,(performance.now()-introT0)/(reduced?1:3400)); const k=ease.io(intro); skyMat.uniforms.uHouse.value=1-Math.min(1,k*1.6); const r=Math.max(0,(k-.15)/.85); starMat.uniforms.uReveal.value=r; skyMat.uniforms.uReveal.value=r; cStarMat.uniforms.uReveal.value=Math.max(0,(k-.45)/.55); lineMat.uniforms.uReveal.value=Math.max(0,(k-.6)/.4); }
    dim += (dimT-dim)*Math.min(1,dt*4); skyMat.uniforms.uDim.value=dim; starMat.uniforms.uDim.value=dim*.6; cStarMat.uniforms.uDim.value=dim; lineMat.uniforms.uDim.value=dim;
    if(mode==='dome'){
      if(!dragging){
        if(focusTarget){ yaw+=(focusTarget.yaw-yaw)*Math.min(1,dt*4); pitch+=(focusTarget.pitch-pitch)*Math.min(1,dt*4); if(Math.abs(focusTarget.yaw-yaw)<.001) focusTarget=null; }
        else { yaw+=vYaw*dt; pitch+=vPitch*dt; pitch=Math.max(.04,Math.min(1.32,pitch)); const f=Math.exp(-dt*2.6); vYaw*=f; vPitch*=f;
          if(!reduced && performance.now()-lastMove>5000 && glHover<0 && Math.abs(vYaw)<.012) vYaw+=(.012-vYaw)*dt*.5; }
        skyMat.uniforms.uGrid.value=Math.max(0,skyMat.uniforms.uGrid.value-dt*.6);
      }
      cam.rotation.set(pitch,yaw,0); cam.updateMatrixWorld();
      // project constellations to screen
      for(let i=0;i<10;i++){ const c=consts[i]; const s=toScreen(c.center); const e=toScreen(c.edge); const a=toScreen(c.anchor);
        if(s&&e&&a&&starMat.uniforms.uReveal.value>.5){ scr[i]={x:s.x,y:s.y,r:Math.hypot(e.x-s.x,e.y-s.y)}; labelEls[i].style.transform=`translate3d(${a.x}px,${a.y}px,0) translate(-50%,0)`;
          const vis=a.x>-80&&a.x<innerWidth+80&&a.y>-40&&a.y<innerHeight+40; labelEls[i].classList.toggle('off',!vis); }
        else { scr[i]=null; labelEls[i].classList.add('off'); } }
      cards.forEach(c=>{ const s=toScreen(c.p); if(s&&s.x>-20&&s.x<innerWidth+20){ c.el.style.transform=`translate3d(${s.x}px,${s.y}px,0) translate(-50%,-50%)`; c.el.style.opacity=starMat.uniforms.uReveal.value; } else c.el.style.opacity=0; });
      // pointer hover
      if(ptr.has && !dragging && !isTouch && route.name==='sky'){ const h=pick(ptr.x,ptr.y); if(h!==hovered && document.activeElement?.classList?.contains('cl')!==true) setHover(h); stage.classList.toggle('hot',h>=0); }
      let ad=((yaw/DEG)%360+360)%360; hudAz.textContent=String(Math.round(ad)).padStart(3,'0')+'°'; hudAlt.textContent=String(Math.round(pitch/DEG)).padStart(2,'0')+'°';
      // shooting star
      if(!reduced && t>nextShoot){ nextShoot=t+7+Math.random()*9; const a0=yaw+(Math.random()-.5)*1.1, e0=pitch+.15+Math.random()*.3; const A=new THREE.Vector3(-Math.sin(a0)*Math.cos(e0),Math.sin(e0),-Math.cos(a0)*Math.cos(e0)).multiplyScalar(450);
        const a1=a0+(Math.random()<.5?-1:1)*(.18+Math.random()*.2), e1=e0-.12-Math.random()*.12; const B=new THREE.Vector3(-Math.sin(a1)*Math.cos(e1),Math.sin(e1),-Math.cos(a1)*Math.cos(e1)).multiplyScalar(450);
        shootMat.uniforms.uA.value.copy(A); shootMat.uniforms.uB.value.copy(B); shootMat.uniforms.uT.value=0; }
      if(shootMat.uniforms.uT.value>=0){ shootMat.uniforms.uT.value+=dt*1.4; if(shootMat.uniforms.uT.value>1) shootMat.uniforms.uT.value=-1; }
    } else if(mode==='warping'){ cam.rotation.set(pitch,yaw,0); cam.updateMatrixWorld(); }
    if(curScene){ if(!dragging){ pYaw+=pvYaw*dt; pvYaw*=Math.exp(-dt*2.4); if(!reduced) pYaw+=dt*.06; }
      pcam.position.set(Math.sin(pYaw)*Math.cos(pPitch)*pDist, .55+Math.sin(pPitch)*pDist, Math.cos(pYaw)*Math.cos(pPitch)*pDist); pcam.lookAt(0,.5,0); curScene.update(t); }
    // hover / draw-in easing
    for(let i=0;i<10;i++){ const on=(i===glHover)?1:0; hoverVals[i]+=(on-hoverVals[i])*Math.min(1,dt*(on?6:3)); drawVals[i]= on? Math.min(1,drawVals[i]+dt/.9) : Math.max(0,drawVals[i]-dt/.45);
      hoverU.value[i]=hoverVals[i]; drawU.value[i]=reduced? on : drawVals[i]; }
    starMat.uniforms.uTime.value=t; cStarMat.uniforms.uTime.value=t; skyMat.uniforms.uTime.value=t; gradePass.uniforms.uTime.value=t; starMat.uniforms.uTw.value=reduced?0:1;
    // fluid
    if(!reduced) Fluid.step(dt);
    fluidPass.uniforms.tVel.value=Fluid.vel; fluidPass.uniforms.tDye.value=Fluid.dye; fluidPass.uniforms.uAmt.value=reduced?0:1;
    composer.render(dt);
  }

  // prewarm + first frames, then reveal
  Loader.label('Compiling shaders');
  await renderer.compileAsync(dome,cam).catch(()=>{});
  Loader.set('shaders','Dimming the house lights');
  cam.rotation.set(pitch,yaw,0); cam.updateMatrixWorld();
  composer.render(0); composer.render(0);
  await new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)));
  Loader.set('frame','Lights down'); await fontsReady; Loader.finish();
  introT0=performance.now();
  clock.getDelta(); frame();
  // pause when the tab is hidden
  document.addEventListener('visibilitychange',()=>{ if(document.hidden){ cancelAnimationFrame(raf); running=false; } else if(!running){ running=true; clock.getDelta(); frame(); } });
  // prefetch first two models quietly once idle
  setTimeout(()=>{ loadModel(P[1].model).catch(()=>{}); },4000);

  return {
    starCount:N,
    setHover(i){ glHover=i; },
    focusConstellation,
    prefetch(i){ loadModel(P[i].model).catch(()=>{}); },
    setPollution(lim,b){ starMat.uniforms.uLimit.value=.02+lim; skyMat.uniforms.uPol.value=.03+b*.97; },
    setDim, openProject, closeProject
  };
}
</script>
</body>
</html>

````
