Skip to content

A colossal walking Soviet apartment block built entirely in code with three.js (no 3D assets) + a 45 s film rendered from it

Walking Block: procedural three.js walking apartment block and 45 s film

Leonxlnx54bd15b63b76
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..67108dd
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,4 @@
+* text=auto eol=lf
+*.mp3 binary
+*.jpg binary
+*.png binary
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c649c63
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+node_modules/
+out/
+shots/
+refs/
+audio/wave/
+# alternate music candidates are not redistributed here (URLs in audio/CREDITS.md); only the track used in the film
+audio/music/*
+!audio/music/the_long_dark.mp3
+.claude/
+*.log
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..fa1c4f1
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,25 @@
+MIT License
+
+Copyright (c) 2026 Leonxlnx
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+The MIT licence above covers the source code in this repository. The audio in
+`audio/` is third-party material under its own licences (CC-BY 4.0 music,
+CC0 sound effects) — see `audio/CREDITS.md`.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..f1fd991
--- /dev/null
+++ b/README.md
@@ -0,0 +1,63 @@
+# Walking Block
+
+A colossal Soviet panel apartment block on eight mechanical legs, crossing a wet field in blue dusk fog.
+Everything you see is code: procedural geometry, procedural textures and shaders in three.js. No 3D assets,
+no image textures. A 45 s film is rendered from the same scene.
+
+![hero](docs/hero.jpg)
+
+| | |
+|---|---|
+| ![foot](docs/foot.jpg) | ![belly](docs/belly.jpg) |
+| ![puddle](docs/puddle.jpg) | ![life](docs/life.jpg) |
+| ![open](docs/open.jpg) | ![away](docs/away.jpg) |
+
+**The film (1080p30, 45 s, with sound):** see the [latest release](../../releases/latest).
+
+## How it was made
+Built with Claude Fable 5.2 as the main agent and Fable 5.2 / Opus 5.5 subagents, iterating on stills and
+storyboards captured from headless Chrome against a handful of reference images (the references are not part
+of this repo). The scene is about 5.4 million triangles per frame and was rendered offline, frame by frame,
+on an integrated laptop GPU (Radeon 780M).
+
+The only thing that is not code is the sound: music and sound effects are downloaded, freely licensed
+recordings, placed and mixed by a script. See [audio/CREDITS.md](audio/CREDITS.md).
+
+## Run it
+```
+npm install
+npm start # http://127.0.0.1:5177/
+```
+- `/` plays the 45 s film timeline in real time (Space = pause, ←/→ = seek).
+- `/?shot=ref2` shows a single camera preset (`ref1…ref6`, `facade`, `leg`, `foot`, `belly`, `f_hero`, `f_foot`, …).
+- `/?free` gives an orbit camera. Add `&scale=0.5` on slower GPUs — the scene is heavy.
+
+## Render the film yourself
+Needs Chrome and ffmpeg (set `CHROME_PATH` if Chrome is not in the default Windows location).
+```
+npm run audio # soundtrack -> out/audio.wav
+npm run render # 1350 frames -> out/frames (resumable)
+npm run mux # -> out/walking_block_1080p30.mp4
+```
+Other tools: `node tools/shot.mjs --shots f_hero --ts 13.4 --mb 4 --prefix x` (stills),
+`npm run storyboard` (contact sheet of the timeline).
+
+## Layout
+- `src/main.js` – scene bootstrap, lights, module loader, deterministic frame rendering
+- `src/post.js` – ambient occlusion, height fog + sky, depth of field, bloom, grade, film grain, motion-blur accumulation
+- `src/look.js` – colours, fog, lights and grade · `src/gait.js` – stateless walk cycle · `src/shots.js` – cameras and film timeline
+- `src/materials.js`, `src/textures.js` – shared weathering shader (grime, drip streaks, moss, paint chips, rust, wetness)
+- `src/mods/building.js` – the apartment block (interior-mapped windows, loggias, laundry, roof)
+- `src/mods/legs.js` – the eight legs (IK rig, hydraulics, hoses, claws)
+- `src/mods/chassis.js` – the mechanical belly · `src/mods/env.js` – ground, vegetation, puddles, footprints
+- `src/mods/fx.js`, `src/mods/atmo.js` – footfall debris and spray, fog banks, smoke, rain, birds
+- `src/mods/README.md` – the module contract the agents worked from
+- `tools/` – capture, render, soundtrack and encode scripts
+
+Everything is a pure function of time, so any frame can be rendered in any order.
+
+## Licence
+Code: MIT (see [LICENSE](LICENSE)).
+Audio: third-party, under its own licences — music "The Long Dark" by Scott Buckley, released under
+CC-BY 4.0 (www.scottbuckley.com.au); sound effects from freesound.org under CC0. Details in
+[audio/CREDITS.md](audio/CREDITS.md).
diff --git a/audio/CREDITS.md b/audio/CREDITS.md
new file mode 100644
index 0000000..5862047
--- /dev/null
+++ b/audio/CREDITS.md
@@ -0,0 +1,55 @@
+# Audio credits
+
+Everything in the soundtrack is downloaded, freely licensed material that is only edited, layered, filtered and
+pitch/time-shifted by `tools/audio.mjs`. Nothing is synthesized.
+
+## Music (Scott Buckley, CC-BY 4.0 — www.scottbuckley.com.au)
+- **Used in the film:** "The Long Dark" by Scott Buckley — released under CC-BY 4.0. www.scottbuckley.com.au
+ (https://www.scottbuckley.com.au/library/the-long-dark/) — one continuous excerpt, 5:02.4–5:47.4
+ (the full-ensemble entry at 5:13.4 lands on the cut to the hero shot), fades only.
+ File: `music/the_long_dark.mp3`.
+- Downloaded as alternates / evaluated, not used in the film (all by Scott Buckley, CC-BY 4.0):
+ "Penumbra" (https://www.scottbuckley.com.au/library/penumbra/ — the previous choice, still selectable with
+ `--music penumbra`), "Decoherence", "Katabasis I", "Permafrost" (…/library/permafrost/),
+ "I Walk With Ghosts" (…/library/i-walk-with-ghosts/), "Hiraeth" (…/library/hiraeth/),
+ "There Was a Time" (…/library/there-was-a-time/), "Tears in Rain" (…/library/tears-in-rain/).
+
+## Sound effects (all from freesound.org, Creative Commons 0 licence; file -> freesound sound id,
+## i.e. https://freesound.org/s/<id>/)
+
+Footfalls, impacts, debris
+step1..5 -> 813056, 815039, 813053, 813055, 813054 (AudioPapkin "Big robot footstep")
+bassimpact -> 512389 · subdrop -> 856174 · giantstomp -> 622737 · distantboom -> 142598
+metaldoor1..3 -> 814976, 814977, 814881 · gravelfall -> 569745 · debris -> 675728
+bigdebris -> 703247 ("Big falling debris (crash)")
+
+Mechanism: hydraulics, servos, pneumatics, chains
+hydraulics_long -> 342463 · trunkmotor -> 759976 ("Motors_SUV_Trunk_autoclose") · mechclamp -> 123253 ("MechanicalClamp")
+mechdoor -> 739197 ("Sci-Fi Mechanical Door") · airrelease -> 416080 · pressurehiss -> 211096 · steamrelease -> 457294
+chain1 -> 387240 ("chain") · chainrattle -> 108265 ("ChainsRattling")
+
+Structure stress
+metalgroan -> 496836 · longcreak -> 878048 · creakslow -> 172411 · gangplank -> 500008 · bendmetal -> 556714
+windmillgroan -> 585061 · shipcreak -> 31574 · gaterattle -> 274766 ("Rattling at an iron gate")
+metalrattle -> 71283 ("Metal_Rattle")
+
+Mud and water
+mudsquelch -> 207142 · squelch -> 167927 · muddysteps -> 376809 ("MUDDY AND WET FOOTSTEPS") · mudsplat -> 445109 ("Mud Splat")
+slimy -> 445968 ("So slimy!") · splashstomps -> 861370 ("Splashing Stomps Impacts Shallow Water")
+watersplashes -> 207371 ("Water Splashes") · dripcave -> 177958 ("Water Dripping in Cave")
+dripmetal -> 166324 ("Water dripping on metal")
+
+Air and field
+windnight -> 217884 · windsoft -> 352721 · windgust -> 146932 ("Wind Gust") · fieldamb -> 620099 ("Field ambience 01")
+lowrumble -> 638914
+
+Life: facade, birds, dogs
+clothflap -> 245839 · aptchatter -> 406619 ("Apartment Chatter_Muffled_Near_Mono")
+cutleryclinks -> 848942 ("Cup Glasses And Cutlery Clinks") · plates -> 797581 ("Tableware - Handle plates")
+dogbark -> 516904 ("Dog Barking in Neighborhood") · dogsfar -> 705299
+pigeonflock -> 616623 ("Pigeon flock fly away, wing flaps") · crowcalls -> 26959 ("crow-calls") · crowsingle -> 548100
+
+Downloaded but not used in the current mix (CC0, freesound.org)
+robotsteps -> 342235 · mechwalk -> 557594 · walker3 -> 231347 · hydraulics -> 212941 · hoist -> 403075
+ominousrumble -> 593785 · giantforest -> 588655 · muffledexpl -> 149966 · distantexpl -> 372086 · earthrumble -> 217657
+dinostep -> 77027 · monstergravel -> 712066 · chains2 -> 348974 · doveswings -> 574656 · mudsteps2 -> 770097
diff --git a/audio/music/the_long_dark.mp3 b/audio/music/the_long_dark.mp3
new file mode 100644
index 0000000..58b0305
Binary files /dev/null and b/audio/music/the_long_dark.mp3 differ
diff --git a/audio/sfx/airrelease.mp3 b/audio/sfx/airrelease.mp3
new file mode 100644
index 0000000..11f4d1f
Binary files /dev/null and b/audio/sfx/airrelease.mp3 differ
diff --git a/audio/sfx/aptchatter.mp3 b/audio/sfx/aptchatter.mp3
new file mode 100644
index 0000000..b843e1f
Binary files /dev/null and b/audio/sfx/aptchatter.mp3 differ
diff --git a/audio/sfx/bassimpact.mp3 b/audio/sfx/bassimpact.mp3
new file mode 100644
index 0000000..8dd7e59
Binary files /dev/null and b/audio/sfx/bassimpact.mp3 differ
diff --git a/audio/sfx/bendmetal.mp3 b/audio/sfx/bendmetal.mp3
new file mode 100644
index 0000000..5f091ae
Binary files /dev/null and b/audio/sfx/bendmetal.mp3 differ
diff --git a/audio/sfx/bigdebris.mp3 b/audio/sfx/bigdebris.mp3
new file mode 100644
index 0000000..3a3f65d
Binary files /dev/null and b/audio/sfx/bigdebris.mp3 differ
diff --git a/audio/sfx/chain1.mp3 b/audio/sfx/chain1.mp3
new file mode 100644
index 0000000..b943884
Binary files /dev/null and b/audio/sfx/chain1.mp3 differ
diff --git a/audio/sfx/chainrattle.mp3 b/audio/sfx/chainrattle.mp3
new file mode 100644
index 0000000..46eff37
Binary files /dev/null and b/audio/sfx/chainrattle.mp3 differ
diff --git a/audio/sfx/chains2.mp3 b/audio/sfx/chains2.mp3
new file mode 100644
index 0000000..f45820f
Binary files /dev/null and b/audio/sfx/chains2.mp3 differ
diff --git a/audio/sfx/clothflap.mp3 b/audio/sfx/clothflap.mp3
new file mode 100644
index 0000000..cc14359
Binary files /dev/null and b/audio/sfx/clothflap.mp3 differ
diff --git a/audio/sfx/creakslow.mp3 b/audio/sfx/creakslow.mp3
new file mode 100644
index 0000000..757b6c0
Binary files /dev/null and b/audio/sfx/creakslow.mp3 differ
diff --git a/audio/sfx/crowcalls.mp3 b/audio/sfx/crowcalls.mp3
new file mode 100644
index 0000000..cb0e21f
Binary files /dev/null and b/audio/sfx/crowcalls.mp3 differ
diff --git a/audio/sfx/crowsingle.mp3 b/audio/sfx/crowsingle.mp3
new file mode 100644
index 0000000..626a80a
Binary files /dev/null and b/audio/sfx/crowsingle.mp3 differ
diff --git a/audio/sfx/cutleryclinks.mp3 b/audio/sfx/cutleryclinks.mp3
new file mode 100644
index 0000000..3f89dfb
Binary files /dev/null and b/audio/sfx/cutleryclinks.mp3 differ
diff --git a/audio/sfx/debris.mp3 b/audio/sfx/debris.mp3
new file mode 100644
index 0000000..9cb743a
Binary files /dev/null and b/audio/sfx/debris.mp3 differ
diff --git a/audio/sfx/dinostep.mp3 b/audio/sfx/dinostep.mp3
new file mode 100644
index 0000000..bbf8957
Binary files /dev/null and b/audio/sfx/dinostep.mp3 differ
diff --git a/audio/sfx/distantboom.mp3 b/audio/sfx/distantboom.mp3
new file mode 100644
index 0000000..81c96c0
Binary files /dev/null and b/audio/sfx/distantboom.mp3 differ
diff --git a/audio/sfx/distantexpl.mp3 b/audio/sfx/distantexpl.mp3
new file mode 100644
index 0000000..9ad7c34
Binary files /dev/null and b/audio/sfx/distantexpl.mp3 differ
diff --git a/audio/sfx/dogbark.mp3 b/audio/sfx/dogbark.mp3
new file mode 100644
index 0000000..6b1cc1c
Binary files /dev/null and b/audio/sfx/dogbark.mp3 differ
diff --git a/audio/sfx/dogsfar.mp3 b/audio/sfx/dogsfar.mp3
new file mode 100644
index 0000000..b3c4aea
Binary files /dev/null and b/audio/sfx/dogsfar.mp3 differ
diff --git a/audio/sfx/doveswings.mp3 b/audio/sfx/doveswings.mp3
new file mode 100644
index 0000000..cb32dae
Binary files /dev/null and b/audio/sfx/doveswings.mp3 differ
diff --git a/audio/sfx/dripcave.mp3 b/audio/sfx/dripcave.mp3
new file mode 100644
index 0000000..96f24c9
Binary files /dev/null and b/audio/sfx/dripcave.mp3 differ
diff --git a/audio/sfx/dripmetal.mp3 b/audio/sfx/dripmetal.mp3
new file mode 100644
index 0000000..44bbc59
Binary files /dev/null and b/audio/sfx/dripmetal.mp3 differ
diff --git a/audio/sfx/earthrumble.mp3 b/audio/sfx/earthrumble.mp3
new file mode 100644
index 0000000..361999e
Binary files /dev/null and b/audio/sfx/earthrumble.mp3 differ
diff --git a/audio/sfx/fieldamb.mp3 b/audio/sfx/fieldamb.mp3
new file mode 100644
index 0000000..5624da8
Binary files /dev/null and b/audio/sfx/fieldamb.mp3 differ
diff --git a/audio/sfx/gangplank.mp3 b/audio/sfx/gangplank.mp3
new file mode 100644
index 0000000..394b820
Binary files /dev/null and b/audio/sfx/gangplank.mp3 differ
diff --git a/audio/sfx/gaterattle.mp3 b/audio/sfx/gaterattle.mp3
new file mode 100644
index 0000000..5ee7bcd
Binary files /dev/null and b/audio/sfx/gaterattle.mp3 differ
diff --git a/audio/sfx/giantforest.mp3 b/audio/sfx/giantforest.mp3
new file mode 100644
index 0000000..b500c08
Binary files /dev/null and b/audio/sfx/giantforest.mp3 differ
diff --git a/audio/sfx/giantstomp.mp3 b/audio/sfx/giantstomp.mp3
new file mode 100644
index 0000000..1038bc1
Binary files /dev/null and b/audio/sfx/giantstomp.mp3 differ
diff --git a/audio/sfx/gravelfall.mp3 b/audio/sfx/gravelfall.mp3
new file mode 100644
index 0000000..deacabd
Binary files /dev/null and b/audio/sfx/gravelfall.mp3 differ
diff --git a/audio/sfx/hoist.mp3 b/audio/sfx/hoist.mp3
new file mode 100644
index 0000000..a5c017b
Binary files /dev/null and b/audio/sfx/hoist.mp3 differ
diff --git a/audio/sfx/hydraulics.mp3 b/audio/sfx/hydraulics.mp3
new file mode 100644
index 0000000..6933079
Binary files /dev/null and b/audio/sfx/hydraulics.mp3 differ
diff --git a/audio/sfx/hydraulics_long.mp3 b/audio/sfx/hydraulics_long.mp3
new file mode 100644
index 0000000..5e74d7b
Binary files /dev/null and b/audio/sfx/hydraulics_long.mp3 differ
diff --git a/audio/sfx/longcreak.mp3 b/audio/sfx/longcreak.mp3
new file mode 100644
index 0000000..3836a1b
Binary files /dev/null and b/audio/sfx/longcreak.mp3 differ
diff --git a/audio/sfx/lowrumble.mp3 b/audio/sfx/lowrumble.mp3
new file mode 100644
index 0000000..94c9fc5
Binary files /dev/null and b/audio/sfx/lowrumble.mp3 differ
diff --git a/audio/sfx/mechclamp.mp3 b/audio/sfx/mechclamp.mp3
new file mode 100644
index 0000000..26b60d3
Binary files /dev/null and b/audio/sfx/mechclamp.mp3 differ
diff --git a/audio/sfx/mechdoor.mp3 b/audio/sfx/mechdoor.mp3
new file mode 100644
index 0000000..b30e24b
Binary files /dev/null and b/audio/sfx/mechdoor.mp3 differ
diff --git a/audio/sfx/mechwalk.mp3 b/audio/sfx/mechwalk.mp3
new file mode 100644
index 0000000..736a0e2
Binary files /dev/null and b/audio/sfx/mechwalk.mp3 differ
diff --git a/audio/sfx/metaldoor1.mp3 b/audio/sfx/metaldoor1.mp3
new file mode 100644
index 0000000..08dc61c
Binary files /dev/null and b/audio/sfx/metaldoor1.mp3 differ
diff --git a/audio/sfx/metaldoor2.mp3 b/audio/sfx/metaldoor2.mp3
new file mode 100644
index 0000000..ae4081a
Binary files /dev/null and b/audio/sfx/metaldoor2.mp3 differ
diff --git a/audio/sfx/metaldoor3.mp3 b/audio/sfx/metaldoor3.mp3
new file mode 100644
index 0000000..0539d07
Binary files /dev/null and b/audio/sfx/metaldoor3.mp3 differ
diff --git a/audio/sfx/metalgroan.mp3 b/audio/sfx/metalgroan.mp3
new file mode 100644
index 0000000..a38571c
Binary files /dev/null and b/audio/sfx/metalgroan.mp3 differ
diff --git a/audio/sfx/metalrattle.mp3 b/audio/sfx/metalrattle.mp3
new file mode 100644
index 0000000..922f5ed
Binary files /dev/null and b/audio/sfx/metalrattle.mp3 differ
diff --git a/audio/sfx/monstergravel.mp3 b/audio/sfx/monstergravel.mp3
new file mode 100644
index 0000000..20d6d12
Binary files /dev/null and b/audio/sfx/monstergravel.mp3 differ
diff --git a/audio/sfx/muddysteps.mp3 b/audio/sfx/muddysteps.mp3
new file mode 100644
index 0000000..140240e
Binary files /dev/null and b/audio/sfx/muddysteps.mp3 differ
diff --git a/audio/sfx/mudsplat.mp3 b/audio/sfx/mudsplat.mp3
new file mode 100644
index 0000000..e8194fb
Binary files /dev/null and b/audio/sfx/mudsplat.mp3 differ
diff --git a/audio/sfx/mudsquelch.mp3 b/audio/sfx/mudsquelch.mp3
new file mode 100644
index 0000000..4dde3d4
Binary files /dev/null and b/audio/sfx/mudsquelch.mp3 differ
diff --git a/audio/sfx/mudsteps2.mp3 b/audio/sfx/mudsteps2.mp3
new file mode 100644
index 0000000..7d29f28
Binary files /dev/null and b/audio/sfx/mudsteps2.mp3 differ
diff --git a/audio/sfx/muffledexpl.mp3 b/audio/sfx/muffledexpl.mp3
new file mode 100644
index 0000000..ca6d907
Binary files /dev/null and b/audio/sfx/muffledexpl.mp3 differ
diff --git a/audio/sfx/ominousrumble.mp3 b/audio/sfx/ominousrumble.mp3
new file mode 100644
index 0000000..d7e4968
Binary files /dev/null and b/audio/sfx/ominousrumble.mp3 differ
diff --git a/audio/sfx/pigeonflock.mp3 b/audio/sfx/pigeonflock.mp3
new file mode 100644
index 0000000..880b3da
Binary files /dev/null and b/audio/sfx/pigeonflock.mp3 differ
diff --git a/audio/sfx/plates.mp3 b/audio/sfx/plates.mp3
new file mode 100644
index 0000000..7624bf4
Binary files /dev/null and b/audio/sfx/plates.mp3 differ
diff --git a/audio/sfx/pressurehiss.mp3 b/audio/sfx/pressurehiss.mp3
new file mode 100644
index 0000000..e55aa4c
Binary files /dev/null and b/audio/sfx/pressurehiss.mp3 differ
diff --git a/audio/sfx/robotsteps.mp3 b/audio/sfx/robotsteps.mp3
new file mode 100644
index 0000000..e18da26
Binary files /dev/null and b/audio/sfx/robotsteps.mp3 differ
diff --git a/audio/sfx/shipcreak.mp3 b/audio/sfx/shipcreak.mp3
new file mode 100644
index 0000000..7d00772
Binary files /dev/null and b/audio/sfx/shipcreak.mp3 differ
diff --git a/audio/sfx/slimy.mp3 b/audio/sfx/slimy.mp3
new file mode 100644
index 0000000..81ffea1
Binary files /dev/null and b/audio/sfx/slimy.mp3 differ
diff --git a/audio/sfx/splashstomps.mp3 b/audio/sfx/splashstomps.mp3
new file mode 100644
index 0000000..d932bae
Binary files /dev/null and b/audio/sfx/splashstomps.mp3 differ
diff --git a/audio/sfx/squelch.mp3 b/audio/sfx/squelch.mp3
new file mode 100644
index 0000000..9d1851d
Binary files /dev/null and b/audio/sfx/squelch.mp3 differ
diff --git a/audio/sfx/steamrelease.mp3 b/audio/sfx/steamrelease.mp3
new file mode 100644
index 0000000..7d0b6c6
Binary files /dev/null and b/audio/sfx/steamrelease.mp3 differ
diff --git a/audio/sfx/step1.mp3 b/audio/sfx/step1.mp3
new file mode 100644
index 0000000..6afcfa3
Binary files /dev/null and b/audio/sfx/step1.mp3 differ
diff --git a/audio/sfx/step2.mp3 b/audio/sfx/step2.mp3
new file mode 100644
index 0000000..79e7384
Binary files /dev/null and b/audio/sfx/step2.mp3 differ
diff --git a/audio/sfx/step3.mp3 b/audio/sfx/step3.mp3
new file mode 100644
index 0000000..9b45257
Binary files /dev/null and b/audio/sfx/step3.mp3 differ
diff --git a/audio/sfx/step4.mp3 b/audio/sfx/step4.mp3
new file mode 100644
index 0000000..af65fbe
Binary files /dev/null and b/audio/sfx/step4.mp3 differ
diff --git a/audio/sfx/step5.mp3 b/audio/sfx/step5.mp3
new file mode 100644
index 0000000..ce2d1b7
Binary files /dev/null and b/audio/sfx/step5.mp3 differ
diff --git a/audio/sfx/subdrop.mp3 b/audio/sfx/subdrop.mp3
new file mode 100644
index 0000000..0399298
Binary files /dev/null and b/audio/sfx/subdrop.mp3 differ
diff --git a/audio/sfx/trunkmotor.mp3 b/audio/sfx/trunkmotor.mp3
new file mode 100644
index 0000000..28ddb25
Binary files /dev/null and b/audio/sfx/trunkmotor.mp3 differ
diff --git a/audio/sfx/walker3.mp3 b/audio/sfx/walker3.mp3
new file mode 100644
index 0000000..48a6145
Binary files /dev/null and b/audio/sfx/walker3.mp3 differ
diff --git a/audio/sfx/watersplashes.mp3 b/audio/sfx/watersplashes.mp3
new file mode 100644
index 0000000..aaf9120
Binary files /dev/null and b/audio/sfx/watersplashes.mp3 differ
diff --git a/audio/sfx/windgust.mp3 b/audio/sfx/windgust.mp3
new file mode 100644
index 0000000..24c4500
Binary files /dev/null and b/audio/sfx/windgust.mp3 differ
diff --git a/audio/sfx/windmillgroan.mp3 b/audio/sfx/windmillgroan.mp3
new file mode 100644
index 0000000..00820dc
Binary files /dev/null and b/audio/sfx/windmillgroan.mp3 differ
diff --git a/audio/sfx/windnight.mp3 b/audio/sfx/windnight.mp3
new file mode 100644
index 0000000..e58738d
Binary files /dev/null and b/audio/sfx/windnight.mp3 differ
diff --git a/audio/sfx/windsoft.mp3 b/audio/sfx/windsoft.mp3
new file mode 100644
index 0000000..80b3624
Binary files /dev/null and b/audio/sfx/windsoft.mp3 differ
diff --git a/docs/away.jpg b/docs/away.jpg
new file mode 100644
index 0000000..c76047e
Binary files /dev/null and b/docs/away.jpg differ
diff --git a/docs/belly.jpg b/docs/belly.jpg
new file mode 100644
index 0000000..a080aa9
Binary files /dev/null and b/docs/belly.jpg differ
diff --git a/docs/foot.jpg b/docs/foot.jpg
new file mode 100644
index 0000000..f56cbb5
Binary files /dev/null and b/docs/foot.jpg differ
diff --git a/docs/hero.jpg b/docs/hero.jpg
new file mode 100644
index 0000000..cd882be
Binary files /dev/null and b/docs/hero.jpg differ
diff --git a/docs/life.jpg b/docs/life.jpg
new file mode 100644
index 0000000..6d1e467
Binary files /dev/null and b/docs/life.jpg differ
diff --git a/docs/open.jpg b/docs/open.jpg
new file mode 100644
index 0000000..c7fb20e
Binary files /dev/null and b/docs/open.jpg differ
diff --git a/docs/puddle.jpg b/docs/puddle.jpg
new file mode 100644
index 0000000..6bfc2ac
Binary files /dev/null and b/docs/puddle.jpg differ
diff --git a/docs/side.jpg b/docs/side.jpg
new file mode 100644
index 0000000..fa48769
Binary files /dev/null and b/docs/side.jpg differ
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..4938887
--- /dev/null
+++ b/index.html
@@ -0,0 +1,22 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Walking Block</title>
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<style>
+ html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
+ body { display: flex; align-items: center; justify-content: center; }
+ canvas { display: block; }
+ #hud { position: fixed; left: 8px; bottom: 6px; color: #9ab; font: 11px/1.3 monospace; opacity: .7; pointer-events: none; max-width: 90vw; white-space: pre-wrap; }
+</style>
+<script type="importmap">
+{ "imports": { "three": "/node_modules/three/build/three.module.js", "three/addons/": "/node_modules/three/examples/jsm/" } }
+</script>
+</head>
+<body>
+<canvas id="c"></canvas>
+<div id="hud"></div>
+<script type="module" src="/src/main.js"></script>
+</body>
+</html>
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..1999f1d
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,1017 @@
+{
+ "name": "walking-block",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "walking-block",
+ "version": "1.0.0",
+ "license": "ISC",
+ "dependencies": {
+ "puppeteer-core": "^23.11.1",
+ "three": "^0.170.0"
+ }
+ },
+ "node_modules/@puppeteer/browsers": {
+ "version": "2.6.1",
+ "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-2.6.1.tgz",
+ "integrity": "sha512-aBSREisdsGH890S2rQqK82qmQYU3uFpSH8wcZWHgHzl3LfzsxAKbLNiAG9mO8v1Y0UICBeClICxPJvyr0rcuxg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "extract-zip": "^2.0.1",
+ "progress": "^2.0.3",
+ "proxy-agent": "^6.5.0",
+ "semver": "^7.6.3",
+ "tar-fs": "^3.0.6",
+ "unbzip2-stream": "^1.4.3",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "browsers": "lib/cjs/main-cli.js"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@tootallnate/quickjs-emscripten": {
+ "version": "0.23.0",
+ "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz",
+ "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==",
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.6",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz",
+ "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@types/yauzl": {
+ "version": "2.10.3",
+ "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
+ "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@types/node": "*"
+ }
+ },
+ "node_modules/agent-base": {
+ "version": "7.1.4",
+ "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
+ "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/ast-types": {
+ "version": "0.13.4",
+ "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz",
+ "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==",
+ "license": "MIT",
+ "dependencies": {
+ "tslib": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/b4a": {
+ "version": "1.9.0",
+ "resolved": "https://registry.npmjs.org/b4a/-/b4a-1.9.0.tgz",
+ "integrity": "sha512-dpfcF9fDNR6++cthXR67iyhgqWy9CBouAvIWhIntzBG6cvK/cnIPiZQjBwi/ZqjjBEDGfoNDtmB0kTjroOJ3pQ==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "react-native-b4a": "*"
+ },
+ "peerDependenciesMeta": {
+ "react-native-b4a": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-buffer": {
+ "version": "3.7.2",
+ "resolved": "https://registry.npmjs.org/bare-buffer/-/bare-buffer-3.7.2.tgz",
+ "integrity": "sha512-kI35SYpVg0JCk+a+gkUEJZY39mt+g71y1NRwBrEj7SbxLnwngYYMf0T/kouYIujlJwelvPZ9TTbBCbCSPw059Q==",
+ "license": "Apache-2.0",
+ "engines": {
+ "bare": ">=1.20.0"
+ }
+ },
+ "node_modules/bare-events": {
+ "version": "2.9.2",
+ "resolved": "https://registry.npmjs.org/bare-events/-/bare-events-2.9.2.tgz",
+ "integrity": "sha512-AIPKioV7/Y/8KfZ3AAhjPJxLLbY49S64Ym5DakZlUg75qQiTgUq9hEJoEwa4eUezPUlXRy/i5NpsKvo9jgKmoA==",
+ "license": "Apache-2.0",
+ "peerDependencies": {
+ "bare-abort-controller": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-fs": {
+ "version": "4.8.4",
+ "resolved": "https://registry.npmjs.org/bare-fs/-/bare-fs-4.8.4.tgz",
+ "integrity": "sha512-MPC2eyrpbk3A873sK4y6rk+Iv4o2enxTjHZ8zH3HO0mjrpm5XjnguY2XmfidIsDV6vnjpbMBKUAJpV0ISD2SsQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.5.4",
+ "bare-path": "^3.0.0",
+ "bare-stream": "^2.6.4",
+ "bare-url": "^2.2.2",
+ "fast-fifo": "^1.3.2"
+ },
+ "engines": {
+ "bare": ">=1.28.0"
+ },
+ "peerDependencies": {
+ "bare-buffer": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-buffer": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-path": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/bare-path/-/bare-path-3.1.3.tgz",
+ "integrity": "sha512-8r+FVU/o4zcFmpCDqbqAYhHHbtXPP+cyZKo7DRGRWc7OLlNs4TMaSQEpXL/sIdzyEG0M7RHw4B7xYMGrTc+qrg==",
+ "license": "Apache-2.0"
+ },
+ "node_modules/bare-stream": {
+ "version": "2.13.4",
+ "resolved": "https://registry.npmjs.org/bare-stream/-/bare-stream-2.13.4.tgz",
+ "integrity": "sha512-PcrQ8lVLbiJscNm1Kez+Yp4Gy4AHGcN1lzwjvf5NybWen7VvEgUfyfnXYJ2zNqWnzOfCb1Abq6lH8ti0syQszA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.8.1",
+ "streamx": "^2.25.0",
+ "teex": "^1.0.1"
+ },
+ "peerDependencies": {
+ "bare-abort-controller": "*",
+ "bare-buffer": "*",
+ "bare-events": "*"
+ },
+ "peerDependenciesMeta": {
+ "bare-abort-controller": {
+ "optional": true
+ },
+ "bare-buffer": {
+ "optional": true
+ },
+ "bare-events": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/bare-url": {
+ "version": "2.5.7",
+ "resolved": "https://registry.npmjs.org/bare-url/-/bare-url-2.5.7.tgz",
+ "integrity": "sha512-pWAiECRdNYPJAXYKVOb4HuTQedQyRjtGBUu86kO/vOt4GM7e45PghHXQ/Erm5NumaDSWNBzehIfpc768esW7gA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-buffer": "^3.0.0",
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/base64-js": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz",
+ "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT"
+ },
+ "node_modules/basic-ftp": {
+ "version": "5.3.1",
+ "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz",
+ "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ }
+ },
+ "node_modules/buffer": {
+ "version": "5.7.1",
+ "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz",
+ "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "base64-js": "^1.3.1",
+ "ieee754": "^1.1.13"
+ }
+ },
+ "node_modules/buffer-crc32": {
+ "version": "0.2.13",
+ "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
+ "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
+ "license": "MIT",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/chromium-bidi": {
+ "version": "0.11.0",
+ "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.11.0.tgz",
+ "integrity": "sha512-6CJWHkNRoyZyjV9Rwv2lYONZf1Xm0IuDyNq97nwSsxxP3wf5Bwy15K5rOvVKMtJ127jJBmxFUanSAOjgFRxgrA==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "mitt": "3.0.1",
+ "zod": "3.23.8"
+ },
+ "peerDependencies": {
+ "devtools-protocol": "*"
+ }
+ },
+ "node_modules/cliui": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.1",
+ "wrap-ansi": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "license": "MIT"
+ },
+ "node_modules/data-uri-to-buffer": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz",
+ "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/degenerator": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz",
+ "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ast-types": "^0.13.4",
+ "escodegen": "^2.1.0",
+ "esprima": "^4.0.1"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/devtools-protocol": {
+ "version": "0.0.1367902",
+ "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1367902.tgz",
+ "integrity": "sha512-XxtPuC3PGakY6PD7dG66/o8KwJ/LkH2/EKe19Dcw58w53dv4/vSQEkn/SzuyhHE2q4zPgCkxQBxus3VV4ql+Pg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "license": "MIT"
+ },
+ "node_modules/end-of-stream": {
+ "version": "1.4.5",
+ "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz",
+ "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==",
+ "license": "MIT",
+ "dependencies": {
+ "once": "^1.4.0"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/escodegen": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz",
+ "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "esprima": "^4.0.1",
+ "estraverse": "^5.2.0",
+ "esutils": "^2.0.2"
+ },
+ "bin": {
+ "escodegen": "bin/escodegen.js",
+ "esgenerate": "bin/esgenerate.js"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "optionalDependencies": {
+ "source-map": "~0.6.1"
+ }
+ },
+ "node_modules/esprima": {
+ "version": "4.0.1",
+ "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz",
+ "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==",
+ "license": "BSD-2-Clause",
+ "bin": {
+ "esparse": "bin/esparse.js",
+ "esvalidate": "bin/esvalidate.js"
+ },
+ "engines": {
+ "node": ">=4"
+ }
+ },
+ "node_modules/estraverse": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz",
+ "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=4.0"
+ }
+ },
+ "node_modules/esutils": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz",
+ "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==",
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/events-universal": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/events-universal/-/events-universal-1.0.1.tgz",
+ "integrity": "sha512-LUd5euvbMLpwOF8m6ivPCbhQeSiYVNb8Vs0fQ8QjXo0JTkEHpz8pxdQf0gStltaPpw0Cca8b39KxvK9cfKRiAw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "bare-events": "^2.7.0"
+ }
+ },
+ "node_modules/extract-zip": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
+ "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
+ "license": "BSD-2-Clause",
+ "dependencies": {
+ "debug": "^4.1.1",
+ "get-stream": "^5.1.0",
+ "yauzl": "^2.10.0"
+ },
+ "bin": {
+ "extract-zip": "cli.js"
+ },
+ "engines": {
+ "node": ">= 10.17.0"
+ },
+ "optionalDependencies": {
+ "@types/yauzl": "^2.9.1"
+ }
+ },
+ "node_modules/fast-fifo": {
+ "version": "1.3.2",
+ "resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",
+ "integrity": "sha512-/d9sfos4yxzpwkDkuN7k2SqFKtYNmCTzgfEpz82x34IM9/zc8KGxQoXg1liNC/izpRM/MBdt44Nmx41ZWqk+FQ==",
+ "license": "MIT"
+ },
+ "node_modules/fd-slicer": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
+ "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
+ "license": "MIT",
+ "dependencies": {
+ "pend": "~1.2.0"
+ }
+ },
+ "node_modules/get-caller-file": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
+ "license": "ISC",
+ "engines": {
+ "node": "6.* || 8.* || >= 10.*"
+ }
+ },
+ "node_modules/get-stream": {
+ "version": "5.2.0",
+ "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
+ "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/get-uri": {
+ "version": "6.0.5",
+ "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz",
+ "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==",
+ "license": "MIT",
+ "dependencies": {
+ "basic-ftp": "^5.0.2",
+ "data-uri-to-buffer": "^6.0.2",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/http-proxy-agent": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
+ "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.0",
+ "debug": "^4.3.4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/https-proxy-agent": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
+ "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "4"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/ieee754": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz",
+ "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/feross"
+ },
+ {
+ "type": "patreon",
+ "url": "https://www.patreon.com/feross"
+ },
+ {
+ "type": "consulting",
+ "url": "https://feross.org/support"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.6",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz",
+ "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "7.18.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
+ "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/mitt": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.1.tgz",
+ "integrity": "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==",
+ "license": "MIT"
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/netmask": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz",
+ "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4.0"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/pac-proxy-agent": {
+ "version": "7.2.0",
+ "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz",
+ "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==",
+ "license": "MIT",
+ "dependencies": {
+ "@tootallnate/quickjs-emscripten": "^0.23.0",
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "get-uri": "^6.0.1",
+ "http-proxy-agent": "^7.0.0",
+ "https-proxy-agent": "^7.0.6",
+ "pac-resolver": "^7.0.1",
+ "socks-proxy-agent": "^8.0.5"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/pac-resolver": {
+ "version": "7.0.1",
+ "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz",
+ "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==",
+ "license": "MIT",
+ "dependencies": {
+ "degenerator": "^5.0.0",
+ "netmask": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/pend": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
+ "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
+ "license": "MIT"
+ },
+ "node_modules/progress": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/progress/-/progress-2.0.3.tgz",
+ "integrity": "sha512-7PiHtLll5LdnKIMw100I+8xJXR5gW2QwWYkT6iJva0bXitZKa/XMrSbdmg3r2Xnaidz9Qumd0VPaMrZlF9V9sA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
+ "node_modules/proxy-agent": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz",
+ "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "http-proxy-agent": "^7.0.1",
+ "https-proxy-agent": "^7.0.6",
+ "lru-cache": "^7.14.1",
+ "pac-proxy-agent": "^7.1.0",
+ "proxy-from-env": "^1.1.0",
+ "socks-proxy-agent": "^8.0.5"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/proxy-from-env": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
+ "license": "MIT"
+ },
+ "node_modules/pump": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz",
+ "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==",
+ "license": "MIT",
+ "dependencies": {
+ "end-of-stream": "^1.1.0",
+ "once": "^1.3.1"
+ }
+ },
+ "node_modules/puppeteer-core": {
+ "version": "23.11.1",
+ "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-23.11.1.tgz",
+ "integrity": "sha512-3HZ2/7hdDKZvZQ7dhhITOUg4/wOrDRjyK2ZBllRB0ZCOi9u0cwq1ACHDjBB+nX+7+kltHjQvBRdeY7+W0T+7Gg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@puppeteer/browsers": "2.6.1",
+ "chromium-bidi": "0.11.0",
+ "debug": "^4.4.0",
+ "devtools-protocol": "0.0.1367902",
+ "typed-query-selector": "^2.12.0",
+ "ws": "^8.18.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.6",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
+ "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/smart-buffer": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz",
+ "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks": {
+ "version": "2.8.10",
+ "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.10.tgz",
+ "integrity": "sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ip-address": "^10.1.1",
+ "smart-buffer": "^4.2.0"
+ },
+ "engines": {
+ "node": ">= 10.0.0",
+ "npm": ">= 3.0.0"
+ }
+ },
+ "node_modules/socks-proxy-agent": {
+ "version": "8.0.5",
+ "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz",
+ "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==",
+ "license": "MIT",
+ "dependencies": {
+ "agent-base": "^7.1.2",
+ "debug": "^4.3.4",
+ "socks": "^2.8.3"
+ },
+ "engines": {
+ "node": ">= 14"
+ }
+ },
+ "node_modules/source-map": {
+ "version": "0.6.1",
+ "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
+ "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
+ "license": "BSD-3-Clause",
+ "optional": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/streamx": {
+ "version": "2.28.1",
+ "resolved": "https://registry.npmjs.org/streamx/-/streamx-2.28.1.tgz",
+ "integrity": "sha512-zEzXb0s5Cds7tqMH6rhZ05lcJydCWiQPEwiNngVqzsxCc962vLY4Uw+mW7od8kDH258k2Uz/JrOkdIAAhSh9VA==",
+ "license": "MIT",
+ "dependencies": {
+ "events-universal": "^1.0.0",
+ "fast-fifo": "^1.3.2",
+ "text-decoder": "^1.1.0"
+ }
+ },
+ "node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/tar-fs": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-3.1.3.tgz",
+ "integrity": "sha512-/hU4AXnIdZu+Gvl1pk0oI5f5HxWsCJRtY2aFaJdk9VvyL48DWU6iU5WAIPG+wIi1YvWA6eTJvIviP/tMAZZNwQ==",
+ "license": "MIT",
+ "dependencies": {
+ "pump": "^3.0.0",
+ "tar-stream": "^3.1.5"
+ },
+ "optionalDependencies": {
+ "bare-fs": "^4.0.1",
+ "bare-path": "^3.0.0"
+ }
+ },
+ "node_modules/tar-stream": {
+ "version": "3.2.2",
+ "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-3.2.2.tgz",
+ "integrity": "sha512-+8NeqHRjQWH9nYlwo2gamAMImZCVzI4UoEgDpWorBt9OEfppiZn+uSkskzQKPWIZyji/C8fpWO7u69G0DX0tbg==",
+ "license": "MIT",
+ "dependencies": {
+ "b4a": "^1.9.0",
+ "bare-fs": "^4.8.2",
+ "fast-fifo": "^1.3.2",
+ "streamx": "^2.28.1"
+ }
+ },
+ "node_modules/teex": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/teex/-/teex-1.0.1.tgz",
+ "integrity": "sha512-eYE6iEI62Ni1H8oIa7KlDU6uQBtqr4Eajni3wX7rpfXD8ysFx8z0+dri+KWEPWpBsxXfxu58x/0jvTVT1ekOSg==",
+ "license": "MIT",
+ "dependencies": {
+ "streamx": "^2.12.5"
+ }
+ },
+ "node_modules/text-decoder": {
+ "version": "1.2.7",
+ "resolved": "https://registry.npmjs.org/text-decoder/-/text-decoder-1.2.7.tgz",
+ "integrity": "sha512-vlLytXkeP4xvEq2otHeJfSQIRyWxo/oZGEbXrtEEF9Hnmrdly59sUbzZ/QgyWuLYHctCHxFF4tRQZNQ9k60ExQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "b4a": "^1.6.4"
+ }
+ },
+ "node_modules/three": {
+ "version": "0.170.0",
+ "resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
+ "integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ==",
+ "license": "MIT"
+ },
+ "node_modules/through": {
+ "version": "2.3.8",
+ "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz",
+ "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==",
+ "license": "MIT"
+ },
+ "node_modules/tslib": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz",
+ "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==",
+ "license": "0BSD"
+ },
+ "node_modules/typed-query-selector": {
+ "version": "2.12.3",
+ "resolved": "https://registry.npmjs.org/typed-query-selector/-/typed-query-selector-2.12.3.tgz",
+ "integrity": "sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==",
+ "license": "MIT"
+ },
+ "node_modules/unbzip2-stream": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz",
+ "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer": "^5.2.1",
+ "through": "^2.3.8"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "license": "MIT",
+ "optional": true
+ },
+ "node_modules/wrap-ansi": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/ws": {
+ "version": "8.23.0",
+ "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz",
+ "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10.0.0"
+ },
+ "peerDependencies": {
+ "bufferutil": "^4.0.1",
+ "utf-8-validate": ">=5.0.2"
+ },
+ "peerDependenciesMeta": {
+ "bufferutil": {
+ "optional": true
+ },
+ "utf-8-validate": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yargs": {
+ "version": "17.7.3",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",
+ "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",
+ "license": "MIT",
+ "dependencies": {
+ "cliui": "^8.0.1",
+ "escalade": "^3.1.1",
+ "get-caller-file": "^2.0.5",
+ "require-directory": "^2.1.1",
+ "string-width": "^4.2.3",
+ "y18n": "^5.0.5",
+ "yargs-parser": "^21.1.1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/yargs-parser": {
+ "version": "21.1.1",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/yauzl": {
+ "version": "2.10.0",
+ "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
+ "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
+ "license": "MIT",
+ "dependencies": {
+ "buffer-crc32": "~0.2.3",
+ "fd-slicer": "~1.1.0"
+ }
+ },
+ "node_modules/zod": {
+ "version": "3.23.8",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
+ "integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..4425316
--- /dev/null
+++ b/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "walking-block",
+ "version": "1.0.0",
+ "description": "A colossal walking Soviet apartment block, built procedurally in three.js (no 3D assets), with a 45 s film rendered from it.",
+ "scripts": {
+ "start": "node server.mjs",
+ "storyboard": "node tools/shot.mjs --board --prefix sb",
+ "audio": "node tools/audio.mjs",
+ "render": "node tools/render.mjs --w 1920 --h 1080 --mb 5 --dir out/frames",
+ "mux": "bash tools/mux.sh"
+ },
+ "keywords": [],
+ "author": "",
+ "license": "MIT",
+ "dependencies": {
+ "puppeteer-core": "^23.11.1",
+ "three": "^0.170.0"
+ },
+ "type": "module",
+ "private": true
+}
diff --git a/server.mjs b/server.mjs
new file mode 100644
index 0000000..9ab8b76
--- /dev/null
+++ b/server.mjs
@@ -0,0 +1,30 @@
+// Tiny zero-dependency static server. `node server.mjs [port]`
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const ROOT = path.dirname(fileURLToPath(import.meta.url));
+const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.json': 'application/json', '.css': 'text/css', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp', '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', '.mp4': 'video/mp4', '.wasm': 'application/wasm' };
+
+export function startServer(port = 0) {
+ const server = http.createServer((req, res) => {
+ try {
+ let p = decodeURIComponent(new URL(req.url, 'http://x').pathname);
+ if (p === '/') p = '/index.html';
+ const file = path.normalize(path.join(ROOT, p));
+ if (!file.startsWith(ROOT)) { res.writeHead(403); res.end(); return; }
+ fs.readFile(file, (err, data) => {
+ if (err) { res.writeHead(404); res.end('not found'); return; }
+ res.writeHead(200, { 'Content-Type': MIME[path.extname(file).toLowerCase()] || 'application/octet-stream', 'Cache-Control': 'no-store' });
+ res.end(data);
+ });
+ } catch (e) { res.writeHead(500); res.end(String(e)); }
+ });
+ return new Promise((resolve) => server.listen(port, '127.0.0.1', () => resolve({ server, port: server.address().port })));
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ const port = +process.argv[2] || +process.env.PORT || 5177;
+ startServer(port).then(({ port }) => console.log(`http://127.0.0.1:${port}/`));
+}
diff --git a/src/config.js b/src/config.js
new file mode 100644
index 0000000..a10a8f5
--- /dev/null
+++ b/src/config.js
@@ -0,0 +1,18 @@
+// Shared dimensions (meters). Walker travels along +X. Y is up.
+// The walker root group sits at the BASE of the apartment block (bottom of the lowest floor slab).
+// Building occupies local y >= 0, chassis (mechanical underside) occupies local y in [-CHASSIS_H, 0].
+export const CFG = {
+ BODY_LEN: 88, // building length along X (local x in [-44, 44])
+ BODY_DEPTH: 15, // building depth along Z (local z in [-7.5, 7.5])
+ FLOOR_H: 3.0,
+ FLOORS: 6, // nominal floor count (sections may vary 5..7)
+ RIDE_H: 17.0, // world y of walker root at rest
+ CHASSIS_H: 4.5, // thickness of the mechanical underside
+ LEG_X: [-33, -11, 11, 33], // hip x positions (per side)
+ HIP_Y: -2.6, // hip joint local y (inside chassis band)
+ HIP_Z: 9.2, // hip joint |z|
+ FOOT_Z: 23.0, // foot home |z| (legs splay outward)
+ ANKLE_H: 1.9, // ankle joint height above ground when planted
+ THIGH: 12.5, // hip -> knee length
+ SHIN: 18.0, // knee -> ankle length
+};
diff --git a/src/gait.js b/src/gait.js
new file mode 100644
index 0000000..4a2c874
--- /dev/null
+++ b/src/gait.js
@@ -0,0 +1,137 @@
+// Stateless walking gait: everything is a pure function of time t (seconds),
+// so any frame can be rendered deterministically in any order.
+import { CFG } from './config.js';
+
+export const GAIT = {
+ T: 6.4, // full leg cycle (s)
+ duty: 0.70, // fraction of the cycle a foot is planted
+ stride: 13.0, // meters travelled by the body during one stance
+ lift: 4.6, // max ankle lift during swing (m)
+};
+export const SPEED = GAIT.stride / (GAIT.duty * GAIT.T); // m/s (~2.9)
+export const NSIDE = CFG.LEG_X.length;
+export const NLEGS = NSIDE * 2;
+
+const fract = (x) => x - Math.floor(x);
+const TAU = Math.PI * 2;
+
+// leg index i: 0..NSIDE-1 => +Z side (side=+1), NSIDE..2*NSIDE-1 => -Z side (side=-1)
+export function legInfo(i) {
+ const side = i < NSIDE ? 1 : -1;
+ const k = i % NSIDE;
+ const group = (k + (side > 0 ? 0 : 1)) % 2; // alternating tetrapod
+ const phase = fract(group * 0.5 + k * 0.035 + (side < 0 ? 0.02 : 0));
+ return {
+ i, side, k, group, phase,
+ hip: [CFG.LEG_X[k], CFG.HIP_Y, side * CFG.HIP_Z], // walker-local
+ // foot home x (path frame): feet splay away from the centre for a wide A-frame stance (ref 4)
+ homeX: CFG.LEG_X[k] + 1.5 + Math.sign(CFG.LEG_X[k]) * (Math.abs(CFG.LEG_X[k]) > 20 ? 5.0 : 2.2),
+ homeZ: side * CFG.FOOT_Z,
+ };
+}
+export const LEGS = Array.from({ length: NLEGS }, (_, i) => legInfo(i));
+
+// Foot (ankle joint) state for leg i at time t.
+// Returns world-space ankle position + swing info.
+// swing: 0 while planted, (0..1] progress while in the air
+// plantAge: seconds since this foot last touched down
+// liftAge: seconds since lift-off (only meaningful while swinging)
+// pitch: foot pitch (rad) around Z-ish axis, toe-down positive, for swing animation
+export function footState(i, t, out = {}) {
+ const L = LEGS[i];
+ const { T, duty, stride, lift } = GAIT;
+ const u = fract(t / T + L.phase);
+ let rx, y = 0, swing = 0, pitch = 0;
+ if (u < duty) {
+ rx = stride * (0.5 - u / duty);
+ } else {
+ const s = (u - duty) / (1 - duty);
+ swing = s;
+ // horizontal: slow start (peeling the foot off), fast middle, decelerate before slam
+ const e = s * s * (3 - 2 * s);
+ rx = stride * (-0.5 + e);
+ // vertical: quick rise, hang, then a heavy drop
+ const up = Math.min(1, s / 0.38), dn = Math.max(0, (s - 0.62) / 0.38);
+ const rise = 1 - (1 - up) * (1 - up);
+ const fall = dn * dn * dn;
+ y = lift * (rise - fall) * (1 - 0.0);
+ y = Math.max(0, y);
+ pitch = Math.sin(Math.PI * Math.min(1, s * 1.5)) * 0.22 - dn * 0.10;
+ }
+ out.x = SPEED * t + L.homeX + rx;
+ out.y = CFG.ANKLE_H + y;
+ out.z = L.homeZ;
+ out.swing = swing;
+ out.pitch = pitch;
+ out.plantAge = u * T;
+ out.liftAge = swing > 0 ? (u - duty) * T : -1;
+ out.plantX = SPEED * (t - u * T) + L.homeX + stride * 0.5; // where it last planted
+ return out;
+}
+
+// Body (walker root) pose at time t, world space.
+export function bodyPose(t, out = {}) {
+ const { T } = GAIT;
+ const ph2 = 2 * t / T;
+ // two group touchdowns per cycle; body sinks a little just after each
+ let y = CFG.RIDE_H - 0.34 * Math.cos(TAU * (ph2 - 0.13));
+ // damped shudder after each touchdown
+ const age = fract(ph2) * (T / 2);
+ y += 0.07 * Math.exp(-age * 2.6) * Math.sin(age * 15.0);
+ out.x = SPEED * t + 0.35 * Math.sin(TAU * (ph2 - 0.3)); // slight surge
+ out.y = y;
+ out.z = 0.28 * Math.sin(TAU * (t / T) + 0.4);
+ out.roll = 0.013 * Math.sin(TAU * (t / T) - 0.5) + 0.004 * Math.exp(-age * 2.0) * Math.sin(age * 11.0);
+ out.pitch = 0.006 * Math.sin(TAU * ph2 + 1.0);
+ out.yaw = 0.004 * Math.sin(TAU * (t / T) + 2.0);
+ return out;
+}
+
+// Recent footfalls: [{x, z, age, i}] world-space plant positions, age in seconds.
+const _fs = {};
+export function impacts(t) {
+ const res = [];
+ for (let i = 0; i < NLEGS; i++) {
+ footState(i, t, _fs);
+ res.push({ i, x: _fs.plantX, z: _fs.z, age: _fs.plantAge });
+ }
+ return res;
+}
+
+// Camera shake offset (meters) from footfalls near the camera.
+export function shake(t, cx, cz, out = [0, 0, 0]) {
+ let sx = 0, sy = 0;
+ for (let i = 0; i < NLEGS; i++) {
+ footState(i, t, _fs);
+ const a = _fs.plantAge;
+ if (a > 2.5) continue;
+ const d = Math.hypot(_fs.plantX - cx, _fs.z - cz);
+ const amp = 0.16 / (1 + d / 14) * Math.exp(-a * 2.8);
+ sy += amp * Math.sin(a * 34 + i);
+ sx += amp * 0.5 * Math.sin(a * 27 + i * 2.1);
+ }
+ out[0] = sx; out[1] = sy; out[2] = sx * 0.6;
+ return out;
+}
+
+// Analytic two-bone IK. hip, foot: [x,y,z]; pole: direction the knee should bend toward.
+// Returns knee position [x,y,z]. Clamps reach.
+export function solveKnee(hip, foot, pole, l1, l2, out = [0, 0, 0]) {
+ let dx = foot[0] - hip[0], dy = foot[1] - hip[1], dz = foot[2] - hip[2];
+ let d = Math.hypot(dx, dy, dz);
+ const maxR = (l1 + l2) * 0.999, minR = Math.abs(l1 - l2) * 1.001 + 1e-3;
+ const dc = Math.min(maxR, Math.max(minR, d));
+ dx /= d; dy /= d; dz /= d;
+ // distance along hip->foot axis to the knee projection
+ const a = (l1 * l1 - l2 * l2 + dc * dc) / (2 * dc);
+ const h = Math.sqrt(Math.max(0, l1 * l1 - a * a));
+ // pole component perpendicular to the axis
+ const pd = pole[0] * dx + pole[1] * dy + pole[2] * dz;
+ let px = pole[0] - pd * dx, py = pole[1] - pd * dy, pz = pole[2] - pd * dz;
+ const pl = Math.hypot(px, py, pz) || 1;
+ px /= pl; py /= pl; pz /= pl;
+ out[0] = hip[0] + dx * a + px * h;
+ out[1] = hip[1] + dy * a + py * h;
+ out[2] = hip[2] + dz * a + pz * h;
+ return out;
+}
diff --git a/src/look.js b/src/look.js
new file mode 100644
index 0000000..e1309ec
--- /dev/null
+++ b/src/look.js
@@ -0,0 +1,51 @@
+// Global look parameters (linear HDR values, pre-tonemap). Tuned against refs/*.webp.
+import * as THREE from 'three';
+
+export const LOOK = {
+ // sky
+ zenith: new THREE.Color(0.040, 0.092, 0.218),
+ horizon: new THREE.Color(0.066, 0.132, 0.262),
+ skyGlowDir: new THREE.Vector3(-0.6, 0.12, -0.8).normalize(), // faint brighter side of the dusk sky
+ skyGlow: 0.35,
+ // fog
+ fogColor: new THREE.Color(0.066, 0.130, 0.252),
+ mistColor: new THREE.Color(0.105, 0.150, 0.225), // paler, greyer ground mist,
+ fogDensity: 0.0027, // homogeneous extinction per meter
+ mistDensity: 0.022, // extra ground mist extinction at y=0
+ mistHeight: 2.8, // e-folding height of ground mist (m)
+ mistNoise: 1.15, // wispiness
+ // lights
+ hemiSky: new THREE.Color(0.70, 0.74, 0.82),
+ hemiGround: new THREE.Color(0.035, 0.042, 0.040),
+ hemiIntensity: 2.2,
+ keyColor: new THREE.Color(0.90, 0.93, 1.0),
+ keyIntensity: 1.25,
+ keyDir: new THREE.Vector3(-0.35, 1.0, 0.45).normalize(),
+ envIntensity: 0.6,
+ ao: 0.85, // ambient obscurance strength
+ aoRadius: 1.8, // world-space radius (m)
+ // post
+ exposure: 1.0,
+ bloom: 0.62,
+ bloomThreshold: 0.75,
+ saturation: 1.06,
+ contrast: 1.10,
+ lift: new THREE.Color(0.002, 0.004, 0.009),
+ vignette: 0.30,
+ grain: 0.024,
+ chroma: 0.0006,
+};
+
+// GLSL sky function shared by the fog pass and the environment-map sky dome.
+export const SKY_GLSL = /* glsl */`
+uniform vec3 uZenith, uHorizon, uSkyGlowDir;
+uniform float uSkyGlow;
+vec3 skyColor(vec3 d) {
+ float h = clamp(d.y, -0.2, 1.0);
+ float t = 1.0 - exp(-max(h, 0.0) * 3.2);
+ vec3 c = mix(uHorizon, uZenith, t);
+ float g = max(dot(normalize(vec3(d.x, 0.0, d.z) + 1e-5), normalize(vec3(uSkyGlowDir.x, 0.0, uSkyGlowDir.z))), 0.0);
+ c += uHorizon * uSkyGlow * g * g * exp(-max(h, 0.0) * 5.0);
+ return c;
+}
+`;
diff --git a/src/main.js b/src/main.js
new file mode 100644
index 0000000..d7b9f46
--- /dev/null
+++ b/src/main.js
@@ -0,0 +1,230 @@
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { CFG } from './config.js';
+import * as gait from './gait.js';
+import { LOOK, SKY_GLSL } from './look.js';
+import { createPost } from './post.js';
+import { Mats, weathered, applyWeather } from './materials.js';
+import * as TEX from './textures.js';
+import { evalShot, DURATION, TIMELINE } from './shots.js';
+
+const Q = new URLSearchParams(location.search);
+const FIXED_W = +Q.get('w') || 0, FIXED_H = +Q.get('h') || 0;
+const MODS = (Q.get('mods') || 'env,building,chassis,legs,fx,atmo').split(',').filter(Boolean);
+const state = {
+ t: +Q.get('t') || 0, shot: Q.get('shot') || '', playing: !Q.has('still') && !FIXED_W,
+ free: Q.has('free'), camOverride: null, frame: 0,
+};
+if (Q.get('cam')) {
+ const v = Q.get('cam').split(',').map(Number);
+ state.camOverride = { pos: v.slice(0, 3), tgt: v.slice(3, 6), fov: v[6] || 45 };
+}
+
+// look-dev overrides: ?look=bloom:0.5,grain:0.02
+if (Q.get('look')) for (const kv of Q.get('look').split(',')) { const [k, v] = kv.split(':'); if (k in LOOK && typeof LOOK[k] === 'number') LOOK[k] = +v; }
+const canvas = document.getElementById('c');
+const renderer = new THREE.WebGLRenderer({ canvas, antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true });
+renderer.setPixelRatio(1);
+renderer.outputColorSpace = THREE.SRGBColorSpace;
+renderer.toneMapping = THREE.NoToneMapping;
+renderer.shadowMap.enabled = true;
+renderer.shadowMap.type = THREE.PCFSoftShadowMap;
+renderer.autoClear = true;
+renderer.info.autoReset = false;
+
+function targetSize() {
+ if (FIXED_W) return [FIXED_W, FIXED_H];
+ const sc = +Q.get('scale') || 1;
+ let w = window.innerWidth, h = window.innerHeight;
+ if (w / h > 16 / 9) w = Math.round(h * 16 / 9); else h = Math.round(w * 9 / 16);
+ return [Math.max(320, Math.round(w * sc)), Math.max(180, Math.round(h * sc))];
+}
+let [W, H] = targetSize();
+renderer.setSize(W, H, false);
+canvas.style.width = FIXED_W ? W + 'px' : Math.round(W / (+Q.get('scale') || 1)) + 'px';
+canvas.style.height = FIXED_W ? H + 'px' : Math.round(H / (+Q.get('scale') || 1)) + 'px';
+
+const scene = new THREE.Scene();
+const camera = new THREE.PerspectiveCamera(45, W / H, 0.3, 3000);
+const post = createPost(renderer, W, H);
+
+// --- environment map from the dusk sky (for wet specular reflections) ---
+{
+ const skyScene = new THREE.Scene();
+ const skyMat = new THREE.ShaderMaterial({
+ side: THREE.BackSide,
+ uniforms: { uZenith: { value: LOOK.zenith }, uHorizon: { value: LOOK.horizon }, uSkyGlowDir: { value: LOOK.skyGlowDir }, uSkyGlow: { value: LOOK.skyGlow }, uFogCol: { value: LOOK.fogColor } },
+ vertexShader: `varying vec3 vD; void main(){ vD = position; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); }`,
+ fragmentShader: `varying vec3 vD; uniform vec3 uFogCol; ${SKY_GLSL}
+ void main(){ vec3 d = normalize(vD); vec3 c = skyColor(d);
+ // below the horizon: dark wet field
+ c = mix(c, vec3(0.012,0.02,0.022), smoothstep(0.02, -0.15, d.y));
+ c = mix(c, uFogCol, 0.35 * exp(-abs(d.y) * 6.0));
+ gl_FragColor = vec4(c * 1.6, 1.0); }`,
+ });
+ skyScene.add(new THREE.Mesh(new THREE.SphereGeometry(50, 32, 16), skyMat));
+ const pm = new THREE.PMREMGenerator(renderer);
+ scene.environment = pm.fromScene(skyScene, 0.02).texture;
+ scene.environmentIntensity = LOOK.envIntensity;
+ pm.dispose();
+}
+
+// --- lights ---
+const hemi = new THREE.HemisphereLight(LOOK.hemiSky, LOOK.hemiGround, LOOK.hemiIntensity);
+scene.add(hemi);
+const key = new THREE.DirectionalLight(LOOK.keyColor, LOOK.keyIntensity);
+key.castShadow = true;
+key.shadow.mapSize.set(4096, 4096);
+key.shadow.camera.left = -78; key.shadow.camera.right = 78;
+key.shadow.camera.top = 60; key.shadow.camera.bottom = -60;
+key.shadow.camera.near = 10; key.shadow.camera.far = 260;
+key.shadow.bias = -0.0006; key.shadow.normalBias = 0.12;
+key.shadow.radius = 5;
+scene.add(key, key.target);
+
+// --- walker root ---
+const walker = new THREE.Group();
+walker.name = 'walker';
+scene.add(walker);
+
+const ctx = { THREE, scene, walker, CFG, gait, LOOK, Mats, weathered, applyWeather, TEX, renderer, camera, post, Q, rng: TEX.mulberry32 };
+const modules = [];
+const buildMs = {};
+const errors = [];
+
+async function loadModules() {
+ for (const name of MODS) {
+ try {
+ const t0 = performance.now();
+ const m = await import(`./mods/${name}.js?v=${Date.now()}`);
+ const inst = await m.create(ctx);
+ modules.push({ name, inst });
+ buildMs[name] = Math.round(performance.now() - t0);
+ } catch (e) {
+ console.error(`[module ${name}]`, e);
+ errors.push(`${name}: ${e && e.stack ? e.stack : e}`);
+ }
+ }
+}
+
+let controls = null;
+if (state.free) {
+ controls = new OrbitControls(camera, canvas);
+ camera.position.set(-78, 6, 58); controls.target.set(0, 20, 0);
+}
+
+const _pose = {}, _sh = [0, 0, 0], _v = new THREE.Vector3();
+const frameInfo = { t: 0, dt: 1 / 30, camera, pose: _pose, shot: null, frame: 0 };
+
+function renderAt(t, opts = {}) {
+ state.t = t;
+ renderer.info.reset();
+ const frame = Math.round((opts.frameT ?? t) * 30);
+ gait.bodyPose(t, _pose);
+ walker.position.set(_pose.x, _pose.y, _pose.z);
+ walker.rotation.set(_pose.roll, _pose.yaw, _pose.pitch);
+ walker.updateMatrixWorld(true);
+
+ let shot = null;
+ if (!state.free) {
+ shot = state.camOverride
+ ? { pos: [state.camOverride.pos[0] + gait.SPEED * t, state.camOverride.pos[1], state.camOverride.pos[2]], tgt: [state.camOverride.tgt[0] + gait.SPEED * t, state.camOverride.tgt[1], state.camOverride.tgt[2]], fov: state.camOverride.fov, roll: 0, dof: null, shake: 1, post: {}, near: 0.3 }
+ : evalShot(state.shot, t);
+ gait.shake(t, shot.pos[0], shot.pos[2], _sh);
+ camera.position.set(shot.pos[0] + _sh[0] * shot.shake, Math.max(0.15, shot.pos[1] + _sh[1] * shot.shake), shot.pos[2] + _sh[2] * shot.shake);
+ camera.up.set(Math.sin(shot.roll), Math.cos(shot.roll), 0);
+ // subtle handheld / operator drift (deterministic): ~0.12 degrees of slow wander
+ const hd = Math.hypot(shot.tgt[0] - shot.pos[0], shot.tgt[1] - shot.pos[1], shot.tgt[2] - shot.pos[2]) * 0.0021 * (shot.handheld ?? 1);
+ const hx = (Math.sin(t * 0.83 + 1.3) + 0.5 * Math.sin(t * 2.17 + 0.4)) * hd;
+ const hy = (Math.sin(t * 1.07 + 2.9) + 0.5 * Math.sin(t * 2.63 + 1.7)) * hd * 0.7;
+ camera.lookAt(shot.tgt[0] + hx, shot.tgt[1] + hy + _sh[1] * 0.5 * shot.shake, shot.tgt[2] + hx * 0.6);
+ camera.fov = shot.fov; camera.near = shot.near;
+ // sub-pixel jitter per accumulated sub-frame = free supersampling on top of MSAA
+ if (opts.accum && opts.accum.n > 1) {
+ const i = opts.accum.i + 1;
+ const hal = (b) => { let f = 1, r = 0, k = i; while (k > 0) { f /= b; r += f * (k % b); k = Math.floor(k / b); } return r; };
+ camera.setViewOffset(W, H, hal(2) - 0.5, hal(3) - 0.5, W, H);
+ } else if (camera.view) camera.clearViewOffset();
+ camera.updateProjectionMatrix();
+ } else {
+ controls.target.x += 0; controls.update();
+ }
+ camera.updateMatrixWorld(true);
+
+ // key light follows the walker
+ key.target.position.set(_pose.x, 10, 0);
+ key.position.copy(key.target.position).addScaledVector(LOOK.keyDir, 150);
+ key.target.updateMatrixWorld();
+
+ frameInfo.t = t; frameInfo.frame = frame; frameInfo.shot = shot; frameInfo.dt = opts.dt ?? 1 / 30;
+ for (const m of modules) {
+ try { m.inst && m.inst.update && m.inst.update(t, frameInfo); }
+ catch (e) { if (!m.err) { m.err = true; console.error(`[update ${m.name}]`, e); errors.push(`${m.name}.update: ${e.stack || e}`); } }
+ }
+
+ // volumetric warm halos: along the facades + under the belly
+ let gi = 0;
+ const addGlow = (lx, ly, lz, rad, r, g, b) => {
+ _v.set(lx, ly, lz).applyMatrix4(walker.matrixWorld);
+ post.glowPos[gi].set(_v.x, _v.y, _v.z, rad); post.glowCol[gi].setRGB(r, g, b); gi++;
+ };
+ for (let k = -1; k <= 1; k++) {
+ addGlow(k * 28, 9, 10, 7, 1.0, 0.55, 0.22);
+ addGlow(k * 28, 9, -10, 7, 1.0, 0.55, 0.22);
+ addGlow(k * 28, -4, 0, 5, 0.8, 0.42, 0.16);
+ }
+
+ const sp = shot ? shot.post : {};
+ post.render(scene, camera, {
+ t, frame, dof: shot ? shot.dof : null, glowN: gi,
+ fade: opts.fade ?? sp.fade ?? 1, exposureMul: sp.exposureMul, fogMul: sp.fogMul, mistMul: sp.mistMul,
+ letterbox: sp.letterbox ?? 0, accum: opts.accum,
+ });
+ state.frame++;
+}
+
+// motion blur: average n sub-frames across the shutter interval [t, t + shutter]
+function renderBlur(t, n = 4, shutter = 1 / 60) {
+ // forward shutter [t, t + shutter); never let sub-frames cross a cut of the film timeline
+ let lo = -1e9, hi = 1e9;
+ if (!state.shot && !state.camOverride && !state.free) for (const s of TIMELINE) if (t >= s.start && t < s.end) { lo = s.start; hi = s.end - 1e-4; }
+ for (let i = 0; i < n; i++) renderAt(Math.min(hi, Math.max(lo, t + shutter * (i + 0.5) / n)), { accum: { i, n }, frameT: t });
+ state.t = t;
+}
+
+const ready = (async () => {
+ await loadModules();
+ // warm-up render compiles shaders
+ renderAt(state.t);
+ return { errors };
+})();
+
+window.__app = {
+ ready, renderAt, renderBlur, state, scene, camera, renderer, walker, errors, LOOK, post, modules,
+ setShot(name) { state.shot = name; state.camOverride = null; },
+ setCam(pos, tgt, fov = 45) { state.camOverride = { pos, tgt, fov }; },
+ info() { return { W, H, gl: renderer.getContext().getParameter(renderer.getContext().getExtension('WEBGL_debug_renderer_info')?.UNMASKED_RENDERER_WEBGL ?? 0x1F01), calls: renderer.info.render.calls, tris: renderer.info.render.triangles, errors, buildMs }; },
+};
+
+// --- live preview loop ---
+if (!FIXED_W) {
+ let last = performance.now();
+ const hud = document.getElementById('hud');
+ ready.then(() => {
+ function loop(now) {
+ const dt = Math.min(0.1, (now - last) / 1000); last = now;
+ if (state.playing) state.t += dt;
+ if (!state.shot && !state.free && !state.camOverride && state.t > DURATION) state.t = 0;
+ renderAt(state.t);
+ if (hud) hud.textContent = `t=${state.t.toFixed(2)} shot=${state.shot || 'timeline'} ${(1 / dt).toFixed(0)}fps ${errors.length ? 'ERR ' + errors[0].slice(0, 200) : ''}`;
+ requestAnimationFrame(loop);
+ }
+ requestAnimationFrame(loop);
+ });
+ window.addEventListener('keydown', (e) => {
+ if (e.code === 'Space') state.playing = !state.playing;
+ if (e.code === 'ArrowRight') state.t += 1;
+ if (e.code === 'ArrowLeft') state.t = Math.max(0, state.t - 1);
+ });
+ window.addEventListener('resize', () => location.reload());
+}
diff --git a/src/materials.js b/src/materials.js
new file mode 100644
index 0000000..d18995f
--- /dev/null
+++ b/src/materials.js
@@ -0,0 +1,192 @@
+// Shared material library. All "weathered" materials get procedural grime, drip streaks,
+// moss, paint chips, rust and wetness injected into MeshStandardMaterial — triplanar in
+// MESH-LOCAL space (after instanceMatrix), so NO UVs are required and nothing swims when
+// the walker moves. Use `offset` to decorrelate identical meshes.
+import * as THREE from 'three';
+import { detailTexture } from './textures.js';
+
+const W_DEFAULTS = {
+ tex: 0.33, // detail tiles per meter
+ grain: 0.8, // fine albedo grain amount
+ dirt: 0.6, // large-scale blotchy darkening
+ streak: 0.7, // vertical drip streaks (along local -Y)
+ moss: 0.25, // green algae / moss
+ chip: 0.0, // paint chipping revealing bare metal (0..1)
+ rust: 0.0, // rust coverage (0..1)
+ wet: 0.35, // wet sheen (lowers roughness in patches)
+ bump: 0.010, // bump height in meters
+ mossColor: 0x2a3a1c,
+ offset: null, // THREE.Vector3 added to local position for noise lookup
+};
+
+const PARS_V = /* glsl */`
+varying vec3 vWp; varying vec3 vWn;
+uniform vec3 uWOff;
+`;
+const MAIN_V = /* glsl */`
+{
+ vec4 wP_ = vec4(transformed, 1.0);
+ vec3 wN_ = objectNormal;
+ #ifdef USE_INSTANCING
+ wP_ = instanceMatrix * wP_;
+ wN_ = mat3(instanceMatrix) * wN_;
+ #endif
+ vWp = wP_.xyz + uWOff;
+ vWn = normalize(wN_);
+}
+`;
+const PARS_F = /* glsl */`
+varying vec3 vWp; varying vec3 vWn;
+uniform sampler2D uWDetail;
+uniform float uWTex, uWGrain, uWDirt, uWStreak, uWMoss, uWChip, uWRust, uWWet, uWBump;
+uniform vec3 uWMossCol;
+float wRustA = 0.0, wWetA = 0.0, wHeightA = 0.0;
+vec4 wTri(vec3 p, vec3 n) {
+ vec3 w = abs(n); w = w * w * w * w; w /= (w.x + w.y + w.z + 1e-5);
+ return texture2D(uWDetail, p.zy) * w.x + texture2D(uWDetail, p.xz) * w.y + texture2D(uWDetail, p.xy) * w.z;
+}
+vec3 wPerturb(vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDir) {
+ vec3 vSigmaX = dFdx(surf_pos), vSigmaY = dFdy(surf_pos);
+ vec3 vN = surf_norm;
+ vec3 R1 = cross(vSigmaY, vN), R2 = cross(vN, vSigmaX);
+ float fDet = dot(vSigmaX, R1) * faceDir;
+ vec3 vGrad = sign(fDet) * (dHdxy.x * R1 + dHdxy.y * R2);
+ return normalize(abs(fDet) * surf_norm - vGrad);
+}
+`;
+const ALBEDO_F = /* glsl */`
+{
+ vec3 wp = vWp;
+ vec3 wn = normalize(vWn);
+ vec4 d1 = wTri(wp * uWTex, wn);
+ vec4 d2 = wTri(wp * uWTex * 0.137 + 0.37, wn);
+ float up = wn.y;
+ float vert = 1.0 - abs(up);
+ float grain = d1.r;
+ diffuseColor.rgb *= mix(1.0, 0.70 + 0.60 * grain, uWGrain);
+ // micro layer (4x finer): pores, pits, hairline scratches and speckle so surfaces hold up in close-ups
+ vec4 d0 = wTri(wp * uWTex * 4.1 + 0.19, wn);
+ diffuseColor.rgb *= mix(1.0, 0.80 + 0.40 * d0.r, uWGrain * 0.42);
+ float pits = smoothstep(0.30, 0.12, d0.r) * smoothstep(0.42, 0.7, d1.a);
+ diffuseColor.rgb *= 1.0 - 0.24 * pits * uWGrain;
+ float hair = smoothstep(0.74, 0.92, d0.g) * (0.4 + 0.6 * d1.b);
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * (uWChip > 0.001 ? 1.4 : 0.68), hair * 0.4);
+ float macro = d2.b * 0.62 + d2.a * 0.38; // metres-scale tone variation (no small cloudy blobs)
+ diffuseColor.rgb *= mix(1.0, 0.45 + 1.0 * macro, uWDirt);
+ // vertical drip streaks, stretched along local Y
+ vec2 sUV = vec2((wp.x + wp.z) * 0.55, wp.y * 0.028) * (uWTex * 3.0);
+ float st = texture2D(uWDetail, sUV).b * 0.6 + texture2D(uWDetail, sUV * vec2(3.1, 1.7) + 0.5).b * 0.4;
+ float streak = smoothstep(0.50, 0.78, st) * vert;
+ diffuseColor.rgb *= 1.0 - uWStreak * streak * 0.62;
+ // thin secondary runs between the broad streaks
+ float stF = texture2D(uWDetail, vec2((wp.x + wp.z) * 2.3, wp.y * 0.05) * (uWTex * 3.0) + 0.13).a;
+ diffuseColor.rgb *= 1.0 - uWStreak * smoothstep(0.62, 0.8, stF) * vert * 0.3;
+ float st2 = texture2D(uWDetail, sUV * vec2(1.7, 1.0) + vec2(0.31, 0.77)).b;
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * 1.3 + 0.025, uWStreak * 0.45 * smoothstep(0.62, 0.85, st2) * vert);
+ // moss / algae: likes up-facing surfaces and damp blotches
+ float ms = smoothstep(0.50, 0.72, d2.a * 0.7 + d1.a * 0.25 + max(up, 0.0) * 0.22) * uWMoss;
+ diffuseColor.rgb = mix(diffuseColor.rgb, uWMossCol * (0.55 + 0.9 * grain), ms * 0.75);
+ // paint chips -> bare metal (small flakes, clustered by a broad mask)
+ vec4 d3 = wTri(wp * uWTex * 0.41 + 0.71, wn);
+ float broad = smoothstep(0.30, 0.72, d2.r * 0.55 + d2.a * 0.45);
+ float chipN = d1.g * 0.58 + d3.g * 0.34 + broad * 0.26;
+ float cth = 1.10 - uWChip * 0.62;
+ float chip = smoothstep(cth, cth + 0.05, chipN) * step(0.001, uWChip);
+ // rust: mottled patches with speckled edges, heavier where the broad mask says so
+ float rustN = d3.b * 0.46 + d3.a * 0.22 + d1.a * 0.30 + broad * 0.30 + chip * 0.22;
+ float rth = 1.06 - uWRust * 0.56;
+ float rust = smoothstep(rth, rth + 0.11, rustN) * step(0.001, uWRust);
+ vec3 rustCol = mix(vec3(0.060, 0.026, 0.014), vec3(0.235, 0.105, 0.045), d1.a * 0.7 + d3.r * 0.3);
+ rustCol = mix(rustCol, vec3(0.30, 0.17, 0.07), smoothstep(0.75, 0.95, d1.r) * 0.6); // few orange flecks
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.06, 0.063, 0.068), chip * 0.9);
+ diffuseColor.rgb = mix(diffuseColor.rgb, rustCol * (0.65 + 0.7 * grain), rust);
+ // thin rusty halo around rust + rusty tint running down in the streaks
+ float halo = smoothstep(rth - 0.10, rth + 0.02, rustN) * (1.0 - rust) * step(0.001, uWRust);
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.86, 0.66, 0.50), halo * 0.75);
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.92, 0.70, 0.52), uWRust * streak * 0.65);
+ wRustA = max(rust, chip * 0.35);
+ wHeightA = grain * 0.6 + (1.0 - chip) * 0.5 * step(0.001, uWChip) + rust * d1.a * 0.5 + d0.r * 0.22 - pits * 0.35 - hair * 0.15;
+ wWetA = uWWet * (0.30 + 0.70 * smoothstep(0.35, 0.7, d2.b)) * (0.6 + 0.4 * max(up, 0.0)) * (0.8 + 0.4 * d0.a);
+}
+`;
+const ROUGH_F = /* glsl */`
+roughnessFactor = mix(roughnessFactor, 0.96, wRustA);
+roughnessFactor = clamp(roughnessFactor * (1.0 - 0.72 * wWetA) + (wHeightA - 0.5) * 0.12, 0.06, 1.0);
+metalnessFactor = mix(metalnessFactor, 0.05, wRustA * 0.9);
+`;
+const NORMAL_F = /* glsl */`
+{
+ vec2 dH = vec2(dFdx(wHeightA), dFdy(wHeightA)) * uWBump;
+ normal = wPerturb(-vViewPosition, normal, dH, faceDirection);
+}
+`;
+
+export function applyWeather(mat, w = {}) {
+ const o = { ...W_DEFAULTS, ...w };
+ const u = {
+ uWDetail: { value: detailTexture() },
+ uWTex: { value: o.tex }, uWGrain: { value: o.grain }, uWDirt: { value: o.dirt },
+ uWStreak: { value: o.streak }, uWMoss: { value: o.moss }, uWChip: { value: o.chip },
+ uWRust: { value: o.rust }, uWWet: { value: o.wet }, uWBump: { value: o.bump },
+ uWMossCol: { value: new THREE.Color(o.mossColor) },
+ uWOff: { value: o.offset ? o.offset.clone() : new THREE.Vector3() },
+ };
+ mat.userData.weather = u;
+ const prev = mat.onBeforeCompile;
+ mat.onBeforeCompile = (shader, renderer) => {
+ if (prev) prev(shader, renderer);
+ Object.assign(shader.uniforms, u);
+ shader.vertexShader = shader.vertexShader
+ .replace('#include <common>', '#include <common>\n' + PARS_V)
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\n' + MAIN_V);
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\n' + PARS_F)
+ .replace('#include <color_fragment>', '#include <color_fragment>\n' + ALBEDO_F)
+ .replace('#include <metalnessmap_fragment>', '#include <metalnessmap_fragment>\n' + ROUGH_F)
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n' + NORMAL_F);
+ };
+ const prevKey = mat.customProgramCacheKey ? mat.customProgramCacheKey.bind(mat) : null;
+ mat.customProgramCacheKey = () => 'weather4' + (prev && prevKey ? prevKey() : '');
+ return mat;
+}
+
+// params: MeshStandardMaterial params; w: weathering options (see W_DEFAULTS)
+export function weathered(params = {}, w = {}) {
+ return applyWeather(new THREE.MeshStandardMaterial(params), w);
+}
+
+// ---- Presets (each call returns a NEW material; cache them yourself) ----
+export const Mats = {
+ // prefab concrete panel, grey with a cool cast
+ concrete: (o = {}) => weathered(
+ { color: o.color ?? 0x8d8f92, roughness: 0.93, metalness: 0.0 },
+ { tex: 0.33, grain: 0.85, dirt: 0.75, streak: 0.9, moss: 0.3, wet: 0.22, bump: 0.012, ...o.w }),
+ // darker structural concrete (slabs, undersides)
+ concreteDark: (o = {}) => weathered(
+ { color: o.color ?? 0x5d5f62, roughness: 0.95, metalness: 0.0 },
+ { tex: 0.33, grain: 0.9, dirt: 0.85, streak: 0.8, moss: 0.35, wet: 0.25, bump: 0.014, ...o.w }),
+ // painted armor plating (legs): pale, chipped, rusty
+ paintedMetal: (o = {}) => weathered(
+ { color: o.color ?? 0xa9aba6, roughness: 0.5, metalness: 0.35 },
+ { tex: 0.30, grain: 0.45, dirt: 0.7, streak: 0.8, moss: 0.08, chip: 0.55, rust: 0.5, wet: 0.55, bump: 0.008, ...o.w }),
+ // dark structural steel
+ steel: (o = {}) => weathered(
+ { color: o.color ?? 0x3c4046, roughness: 0.48, metalness: 0.85 },
+ { tex: 0.35, grain: 0.5, dirt: 0.6, streak: 0.5, moss: 0.03, chip: 0.0, rust: 0.42, wet: 0.5, bump: 0.006, ...o.w }),
+ // heavily rusted steel
+ rust: (o = {}) => weathered(
+ { color: o.color ?? 0x5a3a26, roughness: 0.85, metalness: 0.3 },
+ { tex: 0.4, grain: 0.8, dirt: 0.7, streak: 0.6, moss: 0.05, rust: 0.85, wet: 0.2, bump: 0.012, ...o.w }),
+ // polished hydraulic rod
+ chrome: (o = {}) => weathered(
+ { color: o.color ?? 0xcfd6dc, roughness: 0.14, metalness: 1.0 },
+ { tex: 0.5, grain: 0.15, dirt: 0.25, streak: 0.25, moss: 0, rust: 0.12, wet: 0.2, bump: 0.002, ...o.w }),
+ // cables, hoses, rubber
+ rubber: (o = {}) => new THREE.MeshStandardMaterial({ color: o.color ?? 0x0c0d0f, roughness: 0.62, metalness: 0.0 }),
+ // generic painted surface (window frames, railings)
+ paint: (o = {}) => weathered(
+ { color: o.color ?? 0xb9bcb8, roughness: 0.6, metalness: 0.1 },
+ { tex: 0.5, grain: 0.4, dirt: 0.6, streak: 0.6, moss: 0.08, chip: 0.25, rust: 0.3, wet: 0.3, bump: 0.004, ...o.w }),
+ // unlit-looking emitter (lamps); bloom picks it up. intensity ~ 2..12
+ lamp: (o = {}) => new THREE.MeshBasicMaterial({ color: new THREE.Color(o.color ?? 0xffb060).multiplyScalar(o.intensity ?? 4), toneMapped: false }),
+};
diff --git a/src/mods/README.md b/src/mods/README.md
new file mode 100644
index 0000000..1d37a9f
--- /dev/null
+++ b/src/mods/README.md
@@ -0,0 +1,126 @@
+# Module contract (src/mods/*.js)
+
+The scene is a colossal walking Soviet-style panel apartment block on mechanical legs, crossing a wet
+foggy field at blue dusk. Target look: `refs/ref1.jpg … ref6.jpg` (photoreal, gritty, cinematic). LOOK AT THEM.
+
+Each module is an ES module exporting `async function create(ctx)` that builds its objects and returns
+`{ update(t, frame) }`. `main.js` loads modules listed in `?mods=` (default `env,building,chassis,legs,fx`)
+inside try/catch, so a broken module never blocks the others.
+
+## ctx
+- `THREE` – three.js r170 namespace (addons importable via `three/addons/...`, e.g. `BufferGeometryUtils`).
+- `scene` – world scene. `walker` – Group = the moving body (parent building/chassis/legs to it).
+- `CFG` (src/config.js) – shared dimensions. `gait` (src/gait.js) – stateless walk math.
+- `Mats`, `weathered(params, w)`, `applyWeather(mat, w)` (src/materials.js) – shared weathered PBR materials.
+- `TEX` (src/textures.js) – `mulberry32(seed)`, `canvasTexture(w,h,draw,opts)`, `detailTexture()`, `tileFbm`.
+- `rng(seed)` – seeded PRNG factory (same as TEX.mulberry32). `LOOK` – global look constants. `renderer`, `camera`.
+- `frame` passed to update: `{ t, dt, frame, camera, pose:{x,y,z,roll,pitch,yaw}, shot }`.
+
+## Frames & dimensions (meters, Y up, walker travels +X)
+- `walker` origin = centre of the BASE of the apartment block. Rest height above ground: `CFG.RIDE_H` (18.5).
+- Building: local x ∈ [-44, 44], z ∈ [-7.5, 7.5], y ≥ 0. 6 nominal floors × 3.0 m (sections may vary 5–7).
+- Chassis (mechanical belly): local y ∈ [-4.5, 0], may overhang the building footprint by ~1–2 m.
+- Hips: local `(CFG.LEG_X[k], CFG.HIP_Y, ±CFG.HIP_Z)` = x ∈ {-33,-11,11,33}, y=-2.6, z=±9.2. 4 legs per side.
+- Thigh 12.5 m, shin 18 m. Knees bend up and outward (knee ends up around local y≈+3..+6, |z|≈19..21).
+- Feet plant at world |z| = 18. Ankle joint is `CFG.ANKLE_H` = 1.9 m above the ground when planted.
+- Ground is the plane y=0 (world). The walker moves ~2.9 m/s, so over the film it covers ~130 m in +X;
+ anything on the ground must tile / follow the camera.
+
+## Rules
+1. **Determinism**: `update(t)` must be a pure function of `t` (frames are rendered offline in arbitrary
+ order). No accumulated state, no `Math.random()`/`Date.now()` in update; use `rng(seed)` at build time.
+2. **No swimming textures**: the walker moves, so never use world-space noise on walker parts. The shared
+ weathering shader works in mesh-local space (after `instanceMatrix`) and needs NO UVs.
+3. **HDR linear pipeline**: output goes through fog → DOF → bloom (threshold ≈0.75) → ACES → grade → grain.
+ Lit warm windows / lamps should have radiance around `(2.4, 1.1, 0.32)` (bright core) down to
+ `(0.9, 0.38, 0.1)` (dim) — use `MeshBasicMaterial({color: new THREE.Color(r,g,b)})` or emissive. They
+ must read as tungsten ORANGE-AMBER, never white or lemon. Concrete is cool grey, metal pale and rusty.
+4. **Lights**: do NOT add lights, except `chassis` may add ≤ 6 warm PointLights (castShadow=false,
+ decay 2, sensible `distance`). Sky/key/hemi lights and the env map are owned by main.js.
+5. **Shadows**: set `castShadow`/`receiveShadow` on significant geometry (one 4096 shadow map, soft key
+ light from above). Tiny details should not cast.
+6. **Performance (integrated Radeon 780M GPU!)**: use `InstancedMesh` and merged geometries
+ (`BufferGeometryUtils.mergeGeometries`) aggressively. Budgets are per module and listed in your task.
+ No textures above 2048². Dispose temp geometries. Building must finish in a few seconds.
+7. **Only edit your own module file(s)**. Do not touch main.js, post.js, look.js, materials.js,
+ textures.js, gait.js, config.js, shots.js, tools/. If you need something there, say so in your report.
+ Extra materials/shaders/textures you need go inside your module.
+8. Custom `ShaderMaterial`s are fine (fog is applied in post from depth, so just write correct depth;
+ transparent things are not fogged properly — prefer alpha-tested/opaque geometry, or keep transparent
+ things subtle). For Standard-material tweaks use `onBeforeCompile`.
+
+## Materials (src/materials.js)
+`Mats.concrete()`, `Mats.concreteDark()`, `Mats.paintedMetal({color})`, `Mats.steel()`, `Mats.rust()`,
+`Mats.chrome()`, `Mats.rubber()`, `Mats.paint({color})`, `Mats.lamp({color,intensity})`.
+Each returns a NEW MeshStandardMaterial with procedural grime/streaks/moss/chips/rust/wetness. Override
+weathering with `{ w: { tex, grain, dirt, streak, moss, chip, rust, wet, bump, offset } }` (see W_DEFAULTS).
+Streaks run along mesh-local -Y; noise is seeded by mesh-local position, so give identical parts a different
+`w.offset` (THREE.Vector3) or bake different local positions if they must not look cloned.
+
+## Iterating: the capture tool
+```
+node tools/shot.mjs --shots ref1,ref2 --t 2.0 --prefix mytag # -> shots/mytag_ref1.png, ...
+node tools/shot.mjs --shots ref2 --mods env,legs --prefix legsonly # load only some modules
+node tools/shot.mjs --cam "-60,3,40,0,20,0,45" --name close --prefix x # free cam: pos xyz, target xyz, fov
+node tools/shot.mjs --shots ref1,ref2,ref3,ref4,ref5,ref6 --prefix x --sheet # + shots/x_sheet.jpg
+node tools/shot.mjs --shots leg --ts 0,1.6,3.2,4.8 --prefix walk --sheet # several times (animation)
+```
+- Camera coordinates are in the PATH FRAME (origin travels with the walker; building base centre is
+ `[0,18.5,0]`, ground y=0). Presets live in src/shots.js: `ref1..ref6` mimic the reference images; also
+ `facade, facadeClose, roof, leg, foot, knee, belly, end, back, grass`.
+- Default 1280×720. Use a UNIQUE `--prefix` (your module name) so parallel workers don't overwrite files.
+- The tool prints `MODULE ERRORS` / `CONSOLE` output: fix everything that comes from your module (errors
+ from other modules may be someone else's work in progress — ignore them, or use `--mods`).
+- Then `Read` the PNG/JPG and compare critically against `refs/refN.jpg`. Iterate many times.
+- Run captures one at a time (shared integrated GPU), never leave servers/browsers running.
+
+---
+# ROUND 2 — detail wave (read this too)
+
+The scene already works end to end and a 45 s film is cut from it. This round is about **density of believable
+detail**: the owner wants every surface to hold up ~4× closer than it does now — more small parts, more grime
+structure, more life, more atmosphere — while keeping the established look. You are polishing a finished thing,
+not rebuilding it: keep what works, keep every existing API, and leave your module loading without errors at
+every step (other workers capture the full scene while you work).
+
+## What changed since round 1 (facts you must respect)
+- Stance: `CFG.RIDE_H = 17.0`, `CFG.FOOT_Z = 23.0`; feet also splay along X (see `legInfo().homeX` in gait.js).
+ Always read these from `CFG`/`gait`, never hard-code.
+- Look (src/look.js, src/post.js — owned by the lead, do not edit): neutral-cool soft light (surfaces must keep
+ their OWN colour; only the air is blue), darker belly, dense pale ground-mist band over the lowest ~3 m beyond
+ ~40 m, AO pass (1.8 m radius), bloom threshold 0.6, coarse film grain, ACES. Capture with `--mb 4` for
+ final-quality stills (sub-pixel jitter + motion blur).
+- Colour targets measured from the references (sRGB, as rendered): lit concrete ≈ 94,97,104 (neutral warm grey,
+ NOT blue); leg paint ≈ 90–150 grimy grey-beige with dark brown rust (≈ 90,55,35) on edges, rivets and drip
+ streaks — never orange, no hazard stripes; window cores ≈ 242,193,130 amber (never lemon, never salmon);
+ grass ≈ 43,52,28 dark olive with dry khaki tips; belly underside ≈ 31,32,29 with a few large warm lamps.
+- A critic compared renders to the references. Its notes for your module are in your task prompt.
+
+## The film (src/shots.js `TIMELINE`) — spend detail where the camera actually looks
+1. `f_open` 0–5.5 s: lens 0.4 m above wet grass ~100 m ahead of the walker, rack focus from blades to the block.
+2. `f_side` 5.5–11 s: long-lens side elevation of the whole block from ~150 m.
+3. `f_hero` 11–16.5 s: low 3/4 hero from ~95 m (like ref2).
+4. `f_foot` 16.5–20.5 s: worm's-eye 10 m from a foot that slams down (shin, ankle, claws, belly edge, cabins).
+5. `f_belly` 20.5–26 s: on the ground looking straight up as the belly passes overhead.
+6. `f_life` 26–31.5 s: drifting up the +Z facade from ~13 m (balconies, loggias, laundry, interiors).
+7. `f_knee` 31.5–35.5 s: knee/thigh/hip of a leg from ~25 m while it lifts and slams.
+8. `f_puddle` 35.5–40.5 s: 1.3 m above a puddle (world x≈130, z≈35), a foot plants 12 m behind it.
+9. `f_away` 40.5–45 s: crane rising behind the walker as it leaves into the fog (roof visible).
+Capture film shots by name, e.g. `node tools/shot.mjs --shots f_foot --ts 18.9 --mb 4 --prefix mytag`
+(for film shots `--ts` is GLOBAL film time inside that shot's range), or the whole storyboard with
+`node tools/shot.mjs --board --prefix mytag --w 960 --h 540`.
+
+## Budgets for round 2 (integrated GPU; the final render is 1350 frames × several sub-frames)
+Triangles per module (main pass): building ≤ 650k, legs ≤ 900k, chassis ≤ 450k, env ≤ 900k, fx/atmo ≤ 200k.
+Prefer detail that costs nothing per frame: richer procedural textures/shader detail (≤ 2048² textures, a few
+of them), normal/bump detail, vertex colours, decals, instancing. Keep draw calls roughly where they are (+30%).
+Module build time must stay under ~10 s. Shader cost matters too: no heavy per-pixel loops on big surfaces.
+
+## Working rules for this round
+- Time-box: about 40 minutes of wall-clock work, then stop and report, leaving everything working.
+- Capture at 960×540 while iterating (`--w 960 --h 540`), 1280×720 or `--mb 4` only for final checks. One
+ capture at a time; several workers share one integrated GPU, so captures can take a while — be patient.
+- Compare against `refs/ref1.jpg … ref6.jpg` again and again; judge at film-shot framing, not only close-ups.
+- Do not touch files you do not own. Shared weathering shader lines in materials.js are string-patched by
+ legs.js — the lead will not change them.
+- Report (short): what you added, counts (tris/draw calls/build ms), anything risky, what you'd do next.
diff --git a/src/mods/atmo.js b/src/mods/atmo.js
new file mode 100644
index 0000000..eb91cfa
--- /dev/null
+++ b/src/mods/atmo.js
@@ -0,0 +1,451 @@
+// Atmosphere & life module (round 2): local volumetric-looking effects that the post fog cannot give.
+// Everything is a closed-form function of t (uniforms are recomputed from gait.js every frame).
+// - fogBanks : big soft world-stable mist sheets around the legs (alpha-blended; pushed by footfalls,
+// dragged along by lifting feet, warmed under the belly)
+// - glow : additive warm light cones under the belly lamps + haze slabs in front of the lit facades
+// - plumes : roof smoke, belly steam, hydraulic steam at knees/hips after a footfall, mist wake behind
+// a lifting foot. ALPHA-HASHED + depth-writing: the post fog replaces every pixel that has
+// no depth with sky, so blended sprites vanish against the sky; hashed ones do not and get
+// fogged correctly by distance.
+// - streaks : additive rain catching window/lamp light near the facades, belly-edge drips, moths
+// - flock : a few birds flushed out of the grass by some footfalls (opaque, fogged by post)
+export async function create(ctx) {
+ const { THREE, scene, walker, gait, LOOK, CFG, rng } = ctx;
+ const { GAIT, NLEGS, SPEED, LEGS } = gait;
+ const T = GAIT.T, SWING = (1 - GAIT.duty) * T;
+ const NS = 8, DSW = 0.28;
+ const F = (v, d = 2) => Number(v).toFixed(d);
+
+ // ---------------------------------------------------------------- shared uniforms
+ const uTime = { value: 0 }, uCam = { value: new THREE.Vector3() }, uCtr = { value: new THREE.Vector2() };
+ const uJit = { value: new THREE.Vector2() };
+ const uPlant = { value: Array.from({ length: NLEGS }, () => new THREE.Vector4(0, 0, 99, 0)) }; // x, z, age, hash
+ const uFootNow = { value: Array.from({ length: NLEGS }, () => new THREE.Vector4()) }; // ankle xyz, swing
+ const uJoint = { value: Array.from({ length: NLEGS * 2 }, () => new THREE.Vector4(0, 0, 0, 99)) }; // knee/hip at touchdown, age
+ const uLift = { value: new Array(NLEGS).fill(99) };
+ const uFoot = { value: Array.from({ length: NLEGS * NS }, () => new THREE.Vector3()) };
+ const uSpeed = { value: SPEED }, uRide = { value: CFG.RIDE_H };
+
+ // tiling 4-channel fbm noise
+ const tN = { value: (() => {
+ const S = 128, r = rng(4242), data = new Uint8Array(S * S * 4);
+ for (let ch = 0; ch < 4; ch++) {
+ const acc = new Float32Array(S * S);
+ let amp = 0.5;
+ for (let o = 0; o < 5; o++) {
+ const n = 4 << o, g = new Float32Array(n * n);
+ for (let i = 0; i < n * n; i++) g[i] = r();
+ for (let y = 0; y < S; y++) for (let x = 0; x < S; x++) {
+ const fx = x / S * n, fy = y / S * n, ix = Math.floor(fx), iy = Math.floor(fy);
+ let tx = fx - ix, ty = fy - iy; tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);
+ const i1 = (ix + 1) % n, j1 = (iy + 1) % n;
+ const a = g[iy * n + ix], b = g[iy * n + i1], c = g[j1 * n + ix], d = g[j1 * n + i1];
+ acc[y * S + x] += amp * (a + (b - a) * tx + (c - a) * ty + (a - b - c + d) * tx * ty);
+ }
+ amp *= 0.5;
+ }
+ let lo = 1e9, hi = -1e9;
+ for (let i = 0; i < S * S; i++) { lo = Math.min(lo, acc[i]); hi = Math.max(hi, acc[i]); }
+ for (let i = 0; i < S * S; i++) data[i * 4 + ch] = Math.round(255 * (acc[i] - lo) / (hi - lo));
+ }
+ const tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.minFilter = THREE.LinearMipmapLinearFilter; tex.magFilter = THREE.LinearFilter;
+ tex.generateMipmaps = true; tex.needsUpdate = true;
+ return tex;
+ })() };
+
+ const quad = (sx = 1, sy = 1) => { const g = new THREE.PlaneGeometry(1, 1, sx, sy); g.deleteAttribute('normal'); g.deleteAttribute('uv'); return g; };
+ function instanced(base, attrs, n) {
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = base.index; ig.setAttribute('position', base.getAttribute('position'));
+ for (const k in attrs) ig.setAttribute(k, new THREE.InstancedBufferAttribute(attrs[k], attrs[k].length / n));
+ ig.instanceCount = n;
+ return ig;
+ }
+ const add = (m, name, order, parent = scene) => {
+ m.frustumCulled = false; m.name = 'atmo-' + name; m.renderOrder = order; m.userData.noReflect = true;
+ m.castShadow = false; m.receiveShadow = false; parent.add(m); return m;
+ };
+ const mistCol = LOOK.mistColor.clone().lerp(LOOK.fogColor, 0.25);
+
+ // ================================================================ rolling ground-fog banks
+ {
+ const N = 84, WX = 250, WZ = 170, r = rng(1101);
+ const off = new Float32Array(N * 4);
+ for (let i = 0; i < N; i++) { off[i * 4] = r() * WX; off[i * 4 + 1] = r() * WZ; off[i * 4 + 2] = r(); off[i * 4 + 3] = r(); }
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uCam, uCtr, uPlant, uFootNow, tN, uCol: { value: mistCol } },
+ transparent: true, depthWrite: false,
+ vertexShader: `
+uniform float uTime; uniform vec3 uCam; uniform vec2 uCtr;
+uniform vec4 uPlant[${NLEGS}]; uniform vec4 uFootNow[${NLEGS}];
+attribute vec4 aOff;
+varying vec2 vUv; varying float vA; varying float vY; varying vec2 vR; varying float vWarm;
+void main(){
+ vec2 HALF = vec2(${F(WX / 2, 1)}, ${F(WZ / 2, 1)});
+ vec2 drift = vec2(-0.32, 0.2) * uTime * (0.7 + 0.6 * aOff.z);
+ vec2 rel = mod(aOff.xy + drift - uCtr + HALF, HALF * 2.0) - HALF;
+ vec2 xz = uCtr + rel;
+ vec2 er = abs(rel) / HALF;
+ float edge = (1.0 - smoothstep(0.72, 0.98, er.x)) * (1.0 - smoothstep(0.72, 0.98, er.y));
+ // footfalls shove the fog outward and tear a hole; a lifting foot drags it along
+ vec2 push = vec2(0.0); float thin = 0.0;
+ for (int i = 0; i < ${NLEGS}; i++) {
+ vec4 pl = uPlant[i];
+ vec2 v = xz - pl.xy; float d = length(v) + 1e-3;
+ float win = (1.0 - exp(-pl.z * 3.0)) * exp(-pl.z * 0.42) * smoothstep(${F(T)}, ${F(T * 0.6)}, pl.z);
+ push += v / d * 7.0 * exp(-d * d / 200.0) * win;
+ thin += exp(-d * d / 60.0) * win;
+ vec4 f = uFootNow[i];
+ vec2 fv = xz - f.xz;
+ push += vec2(3.0, 0.0) * exp(-dot(fv, fv) / 110.0) * sin(3.14159 * f.w);
+ }
+ xz += push;
+ float w = 24.0 + 30.0 * aOff.w, h = 3.2 + 3.6 * aOff.z;
+ vec3 c = vec3(xz.x, h * 0.40, xz.y);
+ vec3 toCam = uCam - c; float dist = length(toCam);
+ vA = edge * smoothstep(9.0, 36.0, dist) * (0.55 + 0.45 * fract(aOff.w * 7.3)) * (1.0 - 0.7 * min(thin, 1.0));
+ vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), toCam));
+ vec3 p = c + right * position.x * w + vec3(0.0, position.y * h, 0.0);
+ // warm spill from the belly lamps
+ vec3 q = vec3(max(abs(p.x - uCtr.x) - 40.0, 0.0), p.y - 11.0, p.z);
+ vWarm = 1.0 / (1.0 + dot(q, q) / 130.0);
+ vUv = position.xy + 0.5; vY = p.y; vR = aOff.zw;
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ if (vA < 1e-3) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+uniform sampler2D tN; uniform vec3 uCol; uniform float uTime;
+varying vec2 vUv; varying float vA; varying float vY; varying vec2 vR; varying float vWarm;
+void main(){
+ vec2 q = (vUv - 0.5) * 2.0;
+ float env = smoothstep(1.0, 0.15, abs(q.x)) * smoothstep(1.0, -0.4, q.y) * smoothstep(-1.0, -0.6, q.y);
+ vec2 np = vUv * vec2(1.3, 0.38) + vR * 9.0 + vec2(uTime * 0.007, uTime * 0.002);
+ float n = texture2D(tN, np).r * 0.62 + texture2D(tN, np * 2.7 + 0.31).g * 0.38;
+ float a = env * smoothstep(0.30, 0.74, n) * vA * smoothstep(-0.15, 0.9, vY);
+ vec3 col = uCol * (1.06 + 0.2 * n) + vec3(0.42, 0.19, 0.06) * 0.16 * vWarm;
+ gl_FragColor = vec4(col, a * 0.34);
+}`,
+ });
+ add(new THREE.Mesh(instanced(quad(), { aOff: off }, N), mat), 'fogBanks', 1);
+ }
+
+ // ================================================================ additive light cones + facade haze
+ {
+ const list = []; // [x, y, z, kind, len/halfW, width/halfH, intensity, rnd]
+ const r = rng(2202);
+ // cones under the six real belly lights (chassis PointLights)
+ for (const [x, y, z] of [[-36, -6.0, 3.8], [-22, -6.9, 0], [-7.5, -6.2, -3.8], [7.5, -6.2, 3.8], [22, -6.9, 0], [36, -6.0, -3.8]])
+ list.push([x, y + 0.5, z, 0, 9.5 + 2 * r(), 4.2 + 1.2 * r(), 0.075, r()]);
+ // warm haze slabs hugging the facades (seen through mist at distance) and the end walls
+ for (const s of [1, -1]) for (let k = 0; k < 5; k++)
+ list.push([-35 + k * 17.5 + (r() - 0.5) * 5, 9.5 + (r() - 0.5) * 3, s * 10.2, s > 0 ? 1 : 2, 15, 11.5, 0.05 + 0.02 * r(), r()]);
+ for (const s of [1, -1]) list.push([s * 46.0, 10, 0, s > 0 ? 3 : 4, 9.5, 11, 0.05, r()]);
+ const n = list.length, aP = new Float32Array(n * 4), aQ = new Float32Array(n * 4);
+ list.forEach((L, i) => { aP.set(L.slice(0, 4), i * 4); aQ.set(L.slice(4, 8), i * 4); });
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uCam, tN },
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, side: THREE.DoubleSide,
+ vertexShader: `
+uniform vec3 uCam;
+attribute vec4 aP; attribute vec4 aQ;
+varying vec2 vUv; varying float vI; varying float vK; varying float vR;
+void main(){
+ vec3 o = (modelMatrix * vec4(aP.xyz, 1.0)).xyz;
+ vec3 p; float I = aQ.z;
+ if (aP.w < 0.5) {
+ float tt = 0.5 - position.y; // 0 at the lamp, 1 at the far end
+ vec3 c = o - vec3(0.0, tt * aQ.x, 0.0);
+ vec3 toCam = uCam - c;
+ vec3 side = normalize(cross(vec3(0.0, 1.0, 0.0), toCam));
+ p = c + side * position.x * 2.0 * mix(0.35, aQ.y, tt);
+ vec3 mid = o - vec3(0.0, aQ.x * 0.5, 0.0);
+ vec3 vd = normalize(uCam - mid);
+ I *= smoothstep(0.96, 0.7, abs(vd.y)) * smoothstep(5.0, 14.0, length(uCam - mid));
+ } else {
+ vec3 ax = aP.w < 2.5 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 0.0, 1.0);
+ p = o + ax * position.x * 2.0 * aQ.x + vec3(0.0, position.y * 2.0 * aQ.y, 0.0);
+ vec3 nrm = aP.w < 1.5 ? vec3(0.0, 0.0, 1.0) : aP.w < 2.5 ? vec3(0.0, 0.0, -1.0) : aP.w < 3.5 ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 0.0, 0.0) - vec3(1.0, 0.0, 0.0);
+ vec3 toCam = uCam - o; float dist = length(toCam);
+ I *= smoothstep(16.0, 95.0, dist) * smoothstep(0.02, 0.35, dot(toCam / dist, nrm));
+ }
+ vUv = position.xy + 0.5; vI = I; vK = aP.w; vR = aQ.w;
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ if (I < 1e-4) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+uniform sampler2D tN; uniform float uTime;
+varying vec2 vUv; varying float vI; varying float vK; varying float vR;
+void main(){
+ vec2 q = (vUv - 0.5) * 2.0; float a;
+ if (vK < 0.5) {
+ float tt = 1.0 - vUv.y;
+ float core = pow(max(1.0 - q.x * q.x, 0.0), 1.6);
+ float n = texture2D(tN, vec2(q.x * 0.16 + vR * 3.0, tt * 0.22 - uTime * 0.012)).r;
+ tt = clamp(tt, 0.0, 1.0);
+ a = core * smoothstep(0.0, 0.05, tt) * pow(1.0 - tt, 1.4) / (1.0 + 2.5 * tt) * (0.45 + 1.1 * n);
+ } else {
+ float n = texture2D(tN, vUv * 0.55 + vR * 5.0 + vec2(uTime * 0.004, 0.0)).b;
+ float g = exp(-dot(q, q) * 2.6) - 0.0743;
+ a = max(g, 0.0) * (0.55 + 0.9 * n);
+ }
+ gl_FragColor = vec4(vec3(1.0, 0.47, 0.16) * a * vI, 1.0);
+}`,
+ });
+ add(new THREE.Mesh(instanced(quad(2, 8), { aP, aQ }, n), mat), 'glow', 4, walker);
+ }
+
+ // ================================================================ plumes: smoke / steam / hydraulic puffs / foot wake
+ {
+ const list = [], r = rng(3303);
+ const push = (x, y, z, kind, count) => { for (let i = 0; i < count; i++) list.push([x, y, z, kind, r(), (i + r()) / count, r(), r()]); };
+ // roof chimneys (walker-local, above each roof section)
+ for (const [x, y, z] of [[-39, 20.4, 1.5], [-21, 23.5, -2], [-3, 17.5, 2.2], [5.5, 17.3, -2.5], [20, 20.4, -1], [38, 23.5, 1.2]]) push(x, y, z, 0, 14);
+ // belly vents + stern exhaust
+ for (const [x, y, z] of [[-30, -4.9, 5.5], [-4, -5.1, -5], [14, -4.9, 6], [33, -5.1, -4.5], [-45.2, -2.6, 3]]) push(x, y, z, 1, 8);
+ for (let l = 0; l < NLEGS; l++) { push(l * 2, 0, 0, 2, 6); push(l * 2 + 1, 0, 0, 2, 4); push(l, 0, 0, 3, 8); }
+ const steam = new THREE.Color(0.150, 0.180, 0.235), smoke = new THREE.Color(0.105, 0.138, 0.200); // close to the sky so the hash stipple stays low-contrast
+ const mk = (hashed) => new THREE.ShaderMaterial({
+ defines: hashed ? { HASHED: 1 } : {}, transparent: !hashed, depthWrite: hashed,
+ uniforms: { uTime, uCam, uJit, uJoint, uLift, uFoot, uSpeed, uRide, tN, uSteam: { value: steam }, uSmoke: { value: smoke } },
+ vertexShader: `
+uniform float uTime, uSpeed, uRide; uniform vec3 uCam; uniform vec3 uSteam, uSmoke;
+uniform vec4 uJoint[${NLEGS * 2}]; uniform float uLift[${NLEGS}]; uniform vec3 uFoot[${NLEGS * NS}];
+attribute vec4 aEm; attribute vec4 aRnd;
+varying vec2 vUv; varying float vA; varying vec3 vCol; varying vec2 vR;
+void main(){
+ float kind = aEm.w, age, size, alpha; vec3 p; vec3 col = uSteam;
+ if (kind < 0.5) {
+ float life = 11.0;
+ age = fract(uTime / life + aRnd.y) * life;
+ float te = uTime - age;
+ p = vec3(uSpeed * te + aEm.x, uRide + aEm.y, aEm.z);
+ p += vec3(-0.45, 0.0, 0.3) * age;
+ p.y += 1.5 * (1.0 - exp(-0.24 * age)) / 0.24;
+ p += vec3(sin(age * 0.6 + aRnd.x * 6.28), 0.3 * sin(age * 0.9 + aRnd.z * 6.28), cos(age * 0.5 + aRnd.w * 6.28)) * 0.22 * age;
+ size = 0.75 + 0.42 * age;
+ alpha = smoothstep(0.0, 0.5, age) * (1.0 - smoothstep(life * 0.45, life, age)) * 0.85 / (1.0 + 0.14 * age);
+ col = mix(uSmoke, uSteam, 0.35 + 0.4 * aRnd.z);
+ } else if (kind < 1.5) {
+ float life = 4.2;
+ age = fract(uTime / life + aRnd.y) * life;
+ float te = uTime - age;
+ p = vec3(uSpeed * te + aEm.x, uRide + aEm.y, aEm.z);
+ p += vec3(-0.5 + (aRnd.x - 0.5), 0.0, (aRnd.w - 0.5) * 1.2) * age;
+ p.y += -1.5 * (1.0 - exp(-1.3 * age)) + 0.22 * age * age;
+ size = 0.5 + 0.6 * age;
+ alpha = smoothstep(0.0, 0.3, age) * (1.0 - smoothstep(life * 0.4, life, age)) * 0.5;
+ col = uSteam + vec3(0.22, 0.10, 0.03) * exp(-age * 0.8);
+ } else if (kind < 2.5) {
+ // hydraulic steam vented at knee (even) / hip (odd) right after the foot slams down
+ int j = int(aEm.x);
+ float hip = mod(aEm.x, 2.0);
+ float td = aRnd.y * 0.55;
+ age = uJoint[j].w - 0.08 - td;
+ vec3 o = uJoint[j].xyz + vec3(uSpeed * (0.45 + 0.5 * hip) * td, 0.0, 0.0);
+ float sgn = sign(o.z);
+ vec3 dir = normalize(vec3(aRnd.x - 0.6, -0.15 + 0.7 * aRnd.z, sgn * (0.5 + aRnd.w)));
+ p = o + dir * (0.9 + 3.6 * (1.0 - exp(-2.2 * max(age, 0.0))) / 2.2 * (0.6 + aRnd.w)) + vec3(-0.3, 0.55, 0.0) * max(age, 0.0);
+ size = 0.45 + 1.0 * max(age, 0.0);
+ alpha = step(0.0, age) * smoothstep(0.0, 0.12, age) * (1.0 - smoothstep(0.5, 2.6, age)) * 0.36;
+ col = uSteam * 1.08;
+ } else {
+ // ground mist dragged along behind a lifting foot
+ int leg = int(aEm.x);
+ float td = (0.1 + 0.9 * aRnd.y) * ${F(SWING)};
+ float f = clamp(td / ${F(DSW)}, 0.0, ${F(NS - 1.001, 3)});
+ int k = int(floor(f));
+ vec3 a0 = uFoot[leg * ${NS} + k], b0 = uFoot[leg * ${NS} + k + 1];
+ vec3 fv = (b0 - a0) / ${F(DSW)};
+ vec3 fp = mix(a0, b0, fract(f));
+ age = uLift[leg] - td;
+ float e = (1.0 - exp(-1.3 * max(age, 0.0))) / 1.3;
+ p = vec3(fp.x - 2.5 + (aRnd.x - 0.5) * 5.0, 0.5 + 1.3 * aRnd.z, fp.z + (aRnd.w - 0.5) * 6.5);
+ p += vec3(fv.x * 0.42 * e, 0.35 * max(age, 0.0) + min(fp.y, 3.0) * 0.35 * e, (aRnd.w - 0.5) * 1.5 * e);
+ size = 1.5 + 0.9 * max(age, 0.0);
+ alpha = step(0.0, age) * smoothstep(0.0, 0.35, age) * (1.0 - smoothstep(1.0, 3.4, age)) * 0.22;
+ col = uSteam * 0.92;
+ }
+ float dist = length(uCam - p);
+ alpha *= smoothstep(3.0, 8.0, dist);
+ if (kind > 0.5) alpha *= 1.0 - 0.6 * smoothstep(0.08, 0.3, (uCam.y - p.y) / dist); // puffs must not read as discs from above
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ float ang = aRnd.x * 6.28318 + age * (aRnd.z - 0.5) * 0.5;
+ vec2 cr = vec2(cos(ang), sin(ang));
+ mv.xy += (vec2(cr.x * position.x - cr.y * position.y, cr.y * position.x + cr.x * position.y)) * size * 2.0;
+ vUv = position.xy + 0.5; vA = alpha; vCol = col; vR = aRnd.zw;
+ gl_Position = projectionMatrix * mv;
+ if (alpha < 1e-3) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+uniform sampler2D tN; uniform vec2 uJit;
+varying vec2 vUv; varying float vA; varying vec3 vCol; varying vec2 vR;
+float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+void main(){
+ vec2 q = (vUv - 0.5) * 2.0;
+ float r = length(q);
+ vec4 nz = texture2D(tN, vUv * 0.42 + vR * 7.0);
+ float a = smoothstep(1.0, 0.25, r + (nz.r - 0.5) * 0.7) * smoothstep(0.18, 0.62, nz.g * 0.6 + nz.r * 0.4) * vA;
+ vec3 col = vCol * (0.84 + 0.22 * q.y + 0.25 * nz.b);
+#ifdef HASHED
+ if (a <= h12(gl_FragCoord.xy + uJit)) discard;
+ gl_FragColor = vec4(col, 1.0);
+#else
+ gl_FragColor = vec4(col, a * smoothstep(0.3, 0.75, nz.b * 0.5 + nz.g * 0.5));
+#endif
+}`,
+ });
+ const mkMesh = (rows, hashed, name, order) => {
+ const n = rows.length, aEm = new Float32Array(n * 4), aRnd = new Float32Array(n * 4);
+ rows.forEach((L, i) => { aEm.set(L.slice(0, 4), i * 4); aRnd.set(L.slice(4, 8), i * 4); });
+ add(new THREE.Mesh(instanced(quad(), { aEm, aRnd }, n), mk(hashed)), name, order);
+ };
+ mkMesh(list.filter((L) => L[3] === 0), true, 'smoke', 0);
+ mkMesh(list.filter((L) => L[3] !== 0), false, 'steam', 2);
+ }
+
+ // ================================================================ additive streaks: lit rain, belly drips, moths
+ {
+ const list = [], r = rng(4404);
+ for (let i = 0; i < 900; i++) { const s = r() < 0.6 ? 1 : -1; list.push([r() * 92 - 46, r() * 31, s * (8.7 + 4.6 * r() * r()), 0, r(), r(), r(), r()]); }
+ for (let i = 0; i < 170; i++) { const s = r() < 0.5 ? 1 : -1; list.push([r() * 86 - 43, -4.45, s * (8.1 + 0.5 * r()), 1, r(), r(), r(), r()]); }
+ for (const [x, y, z] of [[-36, -6.0, 3.8], [-22, -6.9, 0], [-7.5, -6.2, -3.8], [7.5, -6.2, 3.8], [22, -6.9, 0], [36, -6.0, -3.8]])
+ for (let i = 0; i < 6; i++) list.push([x, y, z, 2, r(), r(), r(), r()]);
+ const n = list.length, aP = new Float32Array(n * 4), aR = new Float32Array(n * 4);
+ list.forEach((L, i) => { aP.set(L.slice(0, 4), i * 4); aR.set(L.slice(4, 8), i * 4); });
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uCam, uSpeed, uRide, tN },
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: `
+uniform float uTime, uSpeed, uRide; uniform vec3 uCam; uniform sampler2D tN;
+attribute vec4 aP; attribute vec4 aR;
+varying vec2 vUv; varying vec3 vC;
+void main(){
+ vec3 lp = aP.xyz, dir = vec3(0.0, -1.0, 0.0); float len, wid, I; vec3 col;
+ if (aP.w < 0.5) {
+ float vy = 7.0 + 2.5 * aR.x;
+ lp.y = mod(aP.y - vy * uTime, 31.0) - 6.5;
+ lp.x = mod(aP.x - (uSpeed + 0.5) * uTime + 46.0, 92.0) - 46.0;
+ dir = normalize(vec3(-(uSpeed + 0.5), -vy, 0.0));
+ len = 0.34; wid = 0.007;
+ // pools of window light along the facade, belly-lamp light below it
+ float lit = smoothstep(0.42, 0.8, texture2D(tN, vec2(lp.x * 0.021, lp.y * 0.034) + 0.37).a);
+ float fac = lp.y > 0.5 ? lit * smoothstep(24.0, 19.0, lp.y) : 0.55 * smoothstep(-7.0, -2.0, lp.y);
+ I = fac * exp(-(abs(lp.z) - 8.6) * 0.45) * 0.55 * smoothstep(0.0, 1.5, lp.y + 6.5);
+ col = vec3(1.0, 0.52, 0.2);
+ } else if (aP.w < 1.5) {
+ float per = 1.3 + 2.8 * aR.x;
+ float tau = fract(uTime / per + aR.y) * per;
+ lp.y = aP.y - 4.9 * tau * tau;
+ float v = 9.8 * tau;
+ len = 0.05 + v * 0.022; wid = 0.012;
+ I = step(-uRide + 0.2, lp.y) * (0.5 + 0.5 * aR.z) * 0.5;
+ col = vec3(0.30, 0.36, 0.48) + vec3(0.5, 0.24, 0.08) * 0.7 * exp(-tau * 2.5);
+ } else {
+ // moths circling the lamps
+ float w = 1.3 + 1.6 * aR.x, R = 0.5 + 1.1 * aR.y;
+ lp += vec3(sin(uTime * w + aR.z * 6.28) * R, -0.5 + 0.55 * sin(uTime * w * 1.37 + aR.w * 6.28) * R, cos(uTime * w * 0.83 + aR.y * 6.28) * R);
+ lp += vec3(sin(uTime * 17.0 + aR.w * 40.0), sin(uTime * 23.0 + aR.x * 40.0), sin(uTime * 19.0 + aR.z * 40.0)) * 0.07;
+ len = 0.05; wid = 0.05;
+ I = 0.8 * (0.45 + 0.55 * sin(uTime * 47.0 + aR.y * 60.0));
+ col = vec3(1.0, 0.6, 0.28);
+ }
+ vec3 wp = (modelMatrix * vec4(lp, 1.0)).xyz;
+ vec3 toCam = uCam - wp; float dist = length(toCam);
+ float pxw = dist * 0.0011; // ~1 px at film framing: keep streaks from aliasing away
+ float w2 = max(wid, pxw);
+ I *= wid / w2 * smoothstep(2.5, 5.0, dist) * (1.0 - smoothstep(60.0, 110.0, dist));
+ vec3 side = normalize(cross(dir, toCam));
+ vec3 pp = wp + dir * position.y * max(len, pxw) + side * position.x * w2;
+ vUv = position.xy + 0.5; vC = col * I;
+ gl_Position = projectionMatrix * viewMatrix * vec4(pp, 1.0);
+ if (I < 1e-3 || wp.y < 0.0) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+varying vec2 vUv; varying vec3 vC;
+void main(){
+ float a = (1.0 - abs(vUv.x - 0.5) * 2.0) * sin(vUv.y * 3.14159);
+ gl_FragColor = vec4(vC * a, 1.0);
+}`,
+ });
+ add(new THREE.Mesh(instanced(quad(), { aP, aR }, n), mat), 'streaks', 5, walker);
+ }
+
+ // ================================================================ birds flushed out of the grass by a footfall
+ {
+ const P = [0, 0, 0.35, 0, 0, -0.3, -1, 0, 0, 0, 0, 0.35, 0, 0, -0.3, 1, 0, 0];
+ const PER = 7, n = NLEGS * PER, r = rng(5505);
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ const aB = new Float32Array(n * 4), aL = new Float32Array(n);
+ for (let i = 0; i < n; i++) { aL[i] = Math.floor(i / PER); for (let q = 0; q < 4; q++) aB[i * 4 + q] = r(); }
+ ig.setAttribute('aB', new THREE.InstancedBufferAttribute(aB, 4));
+ ig.setAttribute('aL', new THREE.InstancedBufferAttribute(aL, 1));
+ ig.instanceCount = n;
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uCam, uPlant }, side: THREE.DoubleSide,
+ vertexShader: `
+uniform float uTime; uniform vec3 uCam; uniform vec4 uPlant[${NLEGS}];
+attribute vec4 aB; attribute float aL;
+void main(){
+ vec4 pl = uPlant[int(aL)];
+ float sgn = sign(pl.y);
+ float a = pl.z - 0.12 - 0.7 * aB.x; // staggered take-off
+ float on = step(pl.w, 0.4) * step(0.0, a);
+ float h1 = fract(pl.w * 37.0), h2 = fract(pl.w * 91.0);
+ vec3 s0 = vec3(pl.x + 5.0 + (h1 - 0.5) * 14.0 + (aB.y - 0.5) * 7.0, 0.35, pl.y + sgn * (10.0 + 7.0 * h2 + 5.0 * aB.z));
+ vec3 dh = normalize(vec3(-0.9 + 1.4 * h2 + (aB.w - 0.5) * 0.5, 0.0, sgn * (0.8 + 0.4 * aB.y)));
+ float aa = max(a, 0.0);
+ float run = (8.0 + 3.0 * aB.w) * (aa - (1.0 - exp(-1.6 * aa)) / 1.6);
+ vec3 c = s0 + dh * run + vec3(0.0, 4.5 * (1.0 - exp(-0.9 * aa)) + (0.9 + 0.8 * aB.z) * aa + 0.4 * sin(aa * 2.3 + aB.x * 9.0), 0.0);
+ c += vec3(-dh.z, 0.0, dh.x) * sin(aa * 1.1 + aB.y * 6.28) * 1.5;
+ vec3 rt = normalize(cross(dh, vec3(0.0, 1.0, 0.0)));
+ float flap = sin(uTime * (17.0 + 6.0 * aB.w) + aB.w * 40.0);
+ float sc = on * smoothstep(0.0, 0.3, a) * (1.0 - smoothstep(4.6, 5.6, a)) * smoothstep(7.0, 16.0, length(uCam - c));
+ vec3 lp = position * 0.34 * sc;
+ lp.y += abs(position.x) * flap * 0.3 * sc;
+ vec3 wp = c + rt * lp.x + vec3(0.0, lp.y, 0.0) + dh * lp.z;
+ gl_Position = projectionMatrix * viewMatrix * vec4(wp, 1.0);
+ if (sc < 1e-3) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `void main(){ gl_FragColor = vec4(0.014, 0.016, 0.022, 1.0); }`,
+ });
+ add(new THREE.Mesh(ig, mat), 'flock', 0);
+ }
+
+ // ================================================================ update (pure function of t)
+ const fs = {}, fs2 = {}, bp = {}, hipA = [0, 0, 0], footA = [0, 0, 0], kneeA = [0, 0, 0], UP = [0, 1, 0];
+ const fract = (x) => x - Math.floor(x);
+ return {
+ update(t, f) {
+ uTime.value = t;
+ uCam.value.setFromMatrixPosition(f.camera.matrixWorld);
+ uCtr.value.set(SPEED * t, 0);
+ uJit.value.set(fract(t * 61.7) * 113.0, fract(t * 37.3) * 71.0);
+ for (let i = 0; i < NLEGS; i++) {
+ const L = LEGS[i];
+ gait.footState(i, t, fs);
+ const nPlant = Math.floor(t / T + L.phase);
+ uPlant.value[i].set(fs.plantX, fs.z, fs.plantAge, fract(Math.sin(nPlant * 12.9898 + i * 78.233) * 43758.5453));
+ uFootNow.value[i].set(fs.x, fs.y, fs.z, fs.swing);
+ // knee / hip where they were at the moment of touchdown
+ const tp = t - fs.plantAge + 1e-4;
+ gait.bodyPose(tp, bp); gait.footState(i, tp, fs2);
+ hipA[0] = bp.x + L.hip[0]; hipA[1] = bp.y + L.hip[1]; hipA[2] = bp.z + L.hip[2];
+ footA[0] = fs2.x; footA[1] = fs2.y; footA[2] = fs2.z;
+ gait.solveKnee(hipA, footA, UP, CFG.THIGH, CFG.SHIN, kneeA);
+ uJoint.value[i * 2].set(kneeA[0], kneeA[1] - 0.6, kneeA[2], fs.plantAge);
+ uJoint.value[i * 2 + 1].set(hipA[0], hipA[1] - 0.4, hipA[2] + L.side * 1.6, fs.plantAge);
+ // foot path after the last lift-off
+ const ageL = fs.swing > 0 ? fs.liftAge : fs.plantAge + SWING;
+ uLift.value[i] = ageL;
+ const tl = t - ageL;
+ for (let k = 0; k < NS; k++) {
+ gait.footState(i, tl + k * DSW + 1e-4, fs2);
+ uFoot.value[i * NS + k].set(fs2.x, Math.max(0, fs2.y - CFG.ANKLE_H), fs2.z);
+ }
+ }
+ },
+ };
+}
diff --git a/src/mods/building.js b/src/mods/building.js
new file mode 100644
index 0000000..5c0abc9
--- /dev/null
+++ b/src/mods/building.js
@@ -0,0 +1,1348 @@
+// Soviet prefab panel apartment block riding on the walker.
+// Everything is generated procedurally in walker-local space and merged into a handful of batches.
+// Facade features are authored in a "facade frame": u = along the wall (to the right when seen from
+// outside), y = up, w = outward from the wall plane.
+export async function create(ctx) {
+ const { THREE, walker, CFG, Mats, LOOK, rng } = ctx;
+ const _t0 = performance.now();
+ const group = new THREE.Group(); group.name = 'building';
+ walker.add(group);
+
+ // ------------------------------------------------------------------ utils
+ const R = rng(20261);
+ const rr = (a, b) => a + R() * (b - a);
+ const chance = (p) => R() < p;
+ const pick = (arr) => arr[Math.floor(R() * arr.length) % arr.length];
+ const lin = (hex) => { const c = new THREE.Color(hex); return [c.r, c.g, c.b]; };
+ const mul = (c, k) => [c[0] * k, c[1] * k, c[2] * k];
+ const WHITE = [1, 1, 1];
+
+ const XF = new THREE.Matrix4();
+ const xfStack = [];
+ const pushXf = (m) => { xfStack.push(XF.clone()); XF.multiply(m); };
+ const popXf = () => { XF.copy(xfStack.pop()); };
+ const frameM = (x, z, ang) => new THREE.Matrix4().makeRotationY(ang).setPosition(x, 0, z);
+ const _m1 = new THREE.Matrix4(), _m2 = new THREE.Matrix4();
+
+ class Batch {
+ constructor(ext = 0) { this.pos = []; this.nor = []; this.col = []; this.idx = []; this.ext = ext ? [] : null; this.count = 0; }
+ v(x, y, z, nx, ny, nz, c, e0 = 0, e1 = 0, e2 = 0) {
+ const e = XF.elements;
+ this.pos.push(e[0] * x + e[4] * y + e[8] * z + e[12], e[1] * x + e[5] * y + e[9] * z + e[13], e[2] * x + e[6] * y + e[10] * z + e[14]);
+ this.nor.push(e[0] * nx + e[4] * ny + e[8] * nz, e[1] * nx + e[5] * ny + e[9] * nz, e[2] * nx + e[6] * ny + e[10] * nz);
+ this.col.push(c[0], c[1], c[2]);
+ if (this.ext) this.ext.push(e0, e1, e2);
+ return this.count++;
+ }
+ q(a, b, c, d) { this.idx.push(a, b, c, a, c, d); }
+ // axis-aligned box given min/max; cb = optional colour for bottom vertices (fake AO)
+ box(x0, x1, y0, y1, z0, z1, c, cb) {
+ const b = cb || c;
+ let i;
+ i = this.v(x1, y0, z1, 1, 0, 0, b); this.v(x1, y0, z0, 1, 0, 0, b); this.v(x1, y1, z0, 1, 0, 0, c); this.v(x1, y1, z1, 1, 0, 0, c); this.q(i, i + 1, i + 2, i + 3);
+ i = this.v(x0, y0, z0, -1, 0, 0, b); this.v(x0, y0, z1, -1, 0, 0, b); this.v(x0, y1, z1, -1, 0, 0, c); this.v(x0, y1, z0, -1, 0, 0, c); this.q(i, i + 1, i + 2, i + 3);
+ i = this.v(x0, y1, z1, 0, 1, 0, c); this.v(x1, y1, z1, 0, 1, 0, c); this.v(x1, y1, z0, 0, 1, 0, c); this.v(x0, y1, z0, 0, 1, 0, c); this.q(i, i + 1, i + 2, i + 3);
+ i = this.v(x0, y0, z0, 0, -1, 0, b); this.v(x1, y0, z0, 0, -1, 0, b); this.v(x1, y0, z1, 0, -1, 0, b); this.v(x0, y0, z1, 0, -1, 0, b); this.q(i, i + 1, i + 2, i + 3);
+ i = this.v(x0, y0, z1, 0, 0, 1, b); this.v(x1, y0, z1, 0, 0, 1, b); this.v(x1, y1, z1, 0, 0, 1, c); this.v(x0, y1, z1, 0, 0, 1, c); this.q(i, i + 1, i + 2, i + 3);
+ i = this.v(x1, y0, z0, 0, 0, -1, b); this.v(x0, y0, z0, 0, 0, -1, b); this.v(x0, y1, z0, 0, 0, -1, c); this.v(x1, y1, z0, 0, 0, -1, c); this.q(i, i + 1, i + 2, i + 3);
+ }
+ // cylinder / cone between two points
+ cyl(ax, ay, az, bx, by, bz, r, sides, c, cap = false, r2 = r) {
+ let wx = bx - ax, wy = by - ay, wz = bz - az; const len = Math.hypot(wx, wy, wz) || 1; wx /= len; wy /= len; wz /= len;
+ let hx = 0, hy = 1, hz = 0; if (Math.abs(wy) > 0.9) { hx = 1; hy = 0; }
+ let ux = hy * wz - hz * wy, uy = hz * wx - hx * wz, uz = hx * wy - hy * wx; const ul = Math.hypot(ux, uy, uz); ux /= ul; uy /= ul; uz /= ul;
+ const vx = wy * uz - wz * uy, vy = wz * ux - wx * uz, vz = wx * uy - wy * ux;
+ const base = this.count;
+ for (let i = 0; i <= sides; i++) {
+ const a = (i / sides) * Math.PI * 2, cs = Math.cos(a), sn = Math.sin(a);
+ const dx = ux * cs + vx * sn, dy = uy * cs + vy * sn, dz = uz * cs + vz * sn;
+ this.v(ax + dx * r, ay + dy * r, az + dz * r, dx, dy, dz, c);
+ this.v(bx + dx * r2, by + dy * r2, bz + dz * r2, dx, dy, dz, c);
+ }
+ for (let i = 0; i < sides; i++) { const a = base + i * 2; this.idx.push(a, a + 2, a + 3, a, a + 3, a + 1); }
+ if (cap) {
+ const c0 = this.count;
+ for (let i = 0; i < sides; i++) { const a = (i / sides) * Math.PI * 2, cs = Math.cos(a), sn = Math.sin(a); this.v(bx + (ux * cs + vx * sn) * r2, by + (uy * cs + vy * sn) * r2, bz + (uz * cs + vz * sn) * r2, wx, wy, wz, c); }
+ for (let i = 1; i < sides - 1; i++) this.idx.push(c0, c0 + i, c0 + i + 1);
+ const c1 = this.count;
+ for (let i = 0; i < sides; i++) { const a = (i / sides) * Math.PI * 2, cs = Math.cos(a), sn = Math.sin(a); this.v(ax + (ux * cs + vx * sn) * r, ay + (uy * cs + vy * sn) * r, az + (uz * cs + vz * sn) * r, -wx, -wy, -wz, c); }
+ for (let i = 1; i < sides - 1; i++) this.idx.push(c1, c1 + i + 1, c1 + i);
+ }
+ }
+ // free quad (p = [x,y,z]) with one normal; optional per-vertex extras
+ quad(p0, p1, p2, p3, n, c, e) {
+ const pv = Array.isArray(n[0]), n0 = pv ? n[0] : n, n1 = pv ? n[1] : n, n2 = pv ? n[2] : n, n3 = pv ? n[3] : n;
+ const cv = Array.isArray(c[0]);
+ const i = this.v(p0[0], p0[1], p0[2], n0[0], n0[1], n0[2], cv ? c[0] : c, ...(e ? e[0] : []));
+ this.v(p1[0], p1[1], p1[2], n1[0], n1[1], n1[2], cv ? c[1] : c, ...(e ? e[1] : []));
+ this.v(p2[0], p2[1], p2[2], n2[0], n2[1], n2[2], cv ? c[2] : c, ...(e ? e[2] : []));
+ this.v(p3[0], p3[1], p3[2], n3[0], n3[1], n3[2], cv ? c[3] : c, ...(e ? e[3] : []));
+ this.q(i, i + 1, i + 2, i + 3);
+ }
+ geometry(glowArr) {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(this.pos), 3));
+ g.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(this.nor), 3));
+ g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(this.col), 3));
+ if (this.ext) g.setAttribute('aSway', new THREE.BufferAttribute(new Float32Array(this.ext), 3));
+ if (glowArr) g.setAttribute('glow', new THREE.BufferAttribute(glowArr, 3));
+ g.setIndex(new THREE.BufferAttribute(new Uint32Array(this.idx), 1));
+ g.computeBoundingSphere(); g.computeBoundingBox();
+ return g;
+ }
+ }
+
+ // batches
+ const conc = new Batch(); // concrete panels, slabs
+ const core = new Batch(); // dark backing behind the panel seams
+ const paint = new Batch(); // painted stuff: frames, parapets, clutter, AC units
+ const metal = new Batch(); // steel: railings, antennas, pipes, brackets
+ const tar = new Batch(); // roofing
+ const cloth = new Batch(); // static fabric: loggia curtains, awnings
+ const laundry = new Batch(3); // swaying laundry
+ const plant = new Batch(); // greenery
+ const glass = new Batch(); // loggia glazing
+ const wire = new Batch(); // black cables & wires
+ const emis = new Batch(); // tiny emissive bulbs (HDR vertex colours)
+ const puddle = new Batch(); // standing water on the roofs
+
+ // subdivided box (so baked per-vertex glow has something to interpolate); colour blends c (top) -> cb (bottom)
+ function sbox(b, x0, x1, y0, y1, z0, z1, c, cb, nx = 1, ny = 1, nz = 1) {
+ const bb = cb || c, mixc = (k) => [bb[0] + (c[0] - bb[0]) * k, bb[1] + (c[1] - bb[1]) * k, bb[2] + (c[2] - bb[2]) * k];
+ for (let i = 0; i < nx; i++) for (let j = 0; j < ny; j++) for (let k = 0; k < nz; k++)
+ b.box(x0 + (x1 - x0) * i / nx, x0 + (x1 - x0) * (i + 1) / nx, y0 + (y1 - y0) * j / ny, y0 + (y1 - y0) * (j + 1) / ny, z0 + (z1 - z0) * k / nz, z0 + (z1 - z0) * (k + 1) / nz, mixc((j + 1) / ny), mixc(j / ny));
+ }
+ // weathering decals: quads in the current facade frame (u/y plane at depth w) that MULTIPLY what is behind them.
+ // type 0 fine drip streaks, 1 broad soak / rising damp, 2 hairline crack, 3 repair patch. v runs 0 (yA) -> 1 (yB).
+ const decal = { pos: [], uv: [], par: [], col: [], idx: [], count: 0 };
+ function addDecal(u0, u1, yA, yB, w, type, strength, tint) {
+ const e = XF.elements, seed = R() * 100, W = Math.abs(u1 - u0), H = Math.abs(yA - yB);
+ const P = [[u0, yA, 0, 0], [u1, yA, 1, 0], [u1, yB, 1, 1], [u0, yB, 0, 1]];
+ for (const [x, y, a, b] of P) {
+ decal.pos.push(e[0] * x + e[4] * y + e[8] * w + e[12], e[1] * x + e[5] * y + e[9] * w + e[13], e[2] * x + e[6] * y + e[10] * w + e[14]);
+ decal.uv.push(a, b, W, H); decal.par.push(type, seed, strength, 0); decal.col.push(tint[0], tint[1], tint[2]);
+ }
+ const i = decal.count; decal.count += 4; decal.idx.push(i, i + 1, i + 2, i, i + 2, i + 3);
+ }
+ const D_WATER = [0.50, 0.50, 0.49], D_RUST = [0.66, 0.43, 0.29], D_MOSS = [0.50, 0.60, 0.40], D_SOOT = [0.36, 0.36, 0.37], D_PATCH = [1.28, 1.27, 1.24];
+
+ // window instances
+ const winM = [], winA = [], winT = [];
+ const lights = []; // warm light sources for baked "glow" spill
+ const beacons = [];
+ const _p = new THREE.Vector3();
+ const addLight = (u, y, w, tint, I) => { _p.set(u, y, w).applyMatrix4(XF); const cold = tint[2] > tint[0]; lights.push({ x: _p.x, y: _p.y, z: _p.z, r: cold ? 0.3 : 1.0, g: cold ? 0.5 : 0.43 + 0.3 * (tint[1] - 0.42), b: cold ? 1.0 : 0.13 + 0.3 * (tint[2] - 0.14), I }); };
+ function addWindow(uc, yc, w, ow, oh, seed, lit, curtain, kind, tint) {
+ _m1.makeScale(ow, oh, 1).setPosition(uc, yc, w);
+ _m2.multiplyMatrices(XF, _m1);
+ winM.push(_m2.clone()); winA.push(seed, lit, curtain, kind); winT.push(tint[0], tint[1], tint[2]);
+ }
+
+ // smooth 2D noise for clustering lit flats
+ const NT = new Float32Array(64 * 32); for (let i = 0; i < NT.length; i++) NT[i] = R();
+ const sn2 = (x, y) => {
+ const ix = Math.floor(x), iy = Math.floor(y); let fx = x - ix, fy = y - iy; fx = fx * fx * (3 - 2 * fx); fy = fy * fy * (3 - 2 * fy);
+ const g = (a, b) => NT[(((b % 32) + 32) % 32) * 64 + (((a % 64) + 64) % 64)];
+ return g(ix, iy) * (1 - fx) * (1 - fy) + g(ix + 1, iy) * fx * (1 - fy) + g(ix, iy + 1) * (1 - fx) * fy + g(ix + 1, iy + 1) * fx * fy;
+ };
+
+ // ------------------------------------------------------------------ palettes
+ const desat = (c, k, m = 1) => { const l = c[0] * 0.3 + c[1] * 0.5 + c[2] * 0.2; return [(l + (c[0] - l) * k) * m, (l + (c[1] - l) * k) * m, (l + (c[2] - l) * k) * m]; };
+ const FRAME_COLS = [lin(0xc9cbc4), lin(0xc9cbc4), lin(0xbdbfb8), lin(0xd8dad6), lin(0x9aa3a0), lin(0x5b3b26), lin(0x6f4a30), lin(0x51656b)].map((c) => mul(c, 0.72));
+ const PARAPET_PAINT = [lin(0x5e7f7c), lin(0x8a7748), lin(0xa39a80), lin(0x6e3a2c), lin(0x5b7890), lin(0x8f9490), lin(0x7c8c72), lin(0xb0aca0)].map((c) => desat(c, 0.36, 0.8));
+ const SHEET_COLS = [lin(0x4f6652), lin(0x8d9295), lin(0x6b4a34), lin(0x55708a), lin(0x9a9684), lin(0x7a3b2b)].map((c) => desat(c, 0.36, 0.8));
+ const CLUTTER = [lin(0x5a4632), lin(0x6c6f72), lin(0x2f4a66), lin(0x7a6a50), lin(0x8a3a2a), lin(0x40484a), lin(0x9a927c), lin(0x35523d)].map((c) => desat(c, 0.6, 0.9));
+ const LAUNDRY = [
+ [lin(0xcfcdc6), null], [lin(0xd2d0c8), null], [lin(0xc8c6ba), null], [lin(0xd4d1c6), null], [lin(0xc2bca8), null], [lin(0xbcbab2), null], [lin(0xa9a8a2), null],
+ [lin(0x7c221f), null], [lin(0xb9b6ac), null], [lin(0x9a7c30), null], [lin(0x33486e), null], [lin(0xb59094), null], [lin(0x7890a0), null], [lin(0x55604a), null],
+ [lin(0xcdcbc4), lin(0x8b96a8)], [lin(0xcdcbc4), lin(0xb08a86)], [lin(0xc4b693), lin(0x9c8660)], [lin(0xd0cec8), lin(0x94a3a8)], [lin(0x8a8f9a), lin(0x6c7482)],
+ ];
+ const CURTAIN_COLS = [lin(0xe7dfc8), lin(0xe9e2d2), lin(0xd9b276), lin(0xcf8f4a), lin(0xd8c9a4), lin(0xc7b9a0)].map((c) => mul(c, 0.5));
+ const STEEL = lin(0x4a4e52), STEEL_D = lin(0x2c2f33), RUSTY = lin(0x6b4630);
+ const PLANT_G = [lin(0x2d4a22), lin(0x3a5a26), lin(0x25401f), lin(0x4a6230), lin(0x33502c)].map((c) => desat(c, 0.75, 0.5));
+ const TINTS = [[1.0, 0.335, 0.10], [1.0, 0.35, 0.108], [1.0, 0.36, 0.116], [1.0, 0.375, 0.124], [1.0, 0.39, 0.132], [1.0, 0.40, 0.14], [1.0, 0.415, 0.15], [1.0, 0.43, 0.16]]; // amber (renders ~242,193,130), no salmon / lemon
+ const LAMPC = [2.3, 1.15, 0.4];
+ const REC = 1.0, PROJ = 0.45; // loggia recess behind the facade plane / projection in front of it
+
+ // ------------------------------------------------------------------ layout
+ const Y0 = 0.7, FH = CFG.FLOOR_H, TH = 0.3, TW = 3.0;
+ const BAYS = [4, 5, 6, 5, 4], FL = [6, 7, 5, 6, 7];
+ const ZF = [7.5, 7.9, 7.3, 7.9, 7.6], ZB = [7.8, 7.5, 7.9, 7.4, 7.8];
+ const SEC_TINT = [[1.0, 0.985, 0.95], [0.95, 0.99, 0.985], [1.0, 1.0, 1.0], [1.03, 1.0, 0.94], [0.94, 0.97, 1.0]];
+ const NB = BAYS.reduce((a, b) => a + b, 0);
+ const BW = (CFG.BODY_LEN - 4 * TW) / NB;
+ const TZF = 8.5, TZB = 8.05;
+ const sections = [], towers = [];
+ {
+ let x = -CFG.BODY_LEN / 2, bay = 0;
+ for (let s = 0; s < BAYS.length; s++) {
+ const x1 = x + BAYS[s] * BW;
+ sections.push({ s, x0: x, x1, bays: BAYS[s], floors: FL[s], zf: ZF[s], zb: ZB[s], bay0: bay, roofY: Y0 + FL[s] * FH, tint: SEC_TINT[s] });
+ bay += BAYS[s]; x = x1;
+ if (s < BAYS.length - 1) { towers.push({ x0: x, x1: x + TW, floors: Math.max(FL[s], FL[s + 1]) + 1, i: s }); x += TW; }
+ }
+ }
+
+ // ------------------------------------------------------------------ small generators
+ const ICO = new THREE.IcosahedronGeometry(1, 0).attributes.position.array;
+ function blob(b, x, y, z, r, c, sy = 1) {
+ const base = b.count;
+ for (let i = 0; i < ICO.length; i += 3) b.v(x + ICO[i] * r, y + ICO[i + 1] * r * sy, z + ICO[i + 2] * r, ICO[i], ICO[i + 1], ICO[i + 2], c);
+ for (let i = 0; i < ICO.length / 3; i += 3) b.idx.push(base + i, base + i + 1, base + i + 2);
+ }
+ function bush(x, y, z, r, n = 4) {
+ for (let i = 0; i < n; i++) blob(plant, x + rr(-r, r) * 0.7, y + rr(0, r) * 0.9, z + rr(-r, r) * 0.5, r * rr(0.45, 0.8), mul(pick(PLANT_G), rr(0.7, 1.2)), rr(0.7, 1.1));
+ }
+ function vine(x, y, z, len) {
+ const c = mul(pick(PLANT_G), rr(0.6, 1.0));
+ plant.box(x - 0.012, x + 0.012, y - len, y, z - 0.012, z + 0.012, c);
+ const n = Math.max(2, Math.round(len / 0.22));
+ for (let i = 0; i < n * 2; i++) blob(plant, x + rr(-0.09, 0.09), y - rr(0, len), z + rr(-0.06, 0.06), rr(0.03, 0.075), mul(c, rr(0.8, 1.5)), 0.6);
+ }
+ // sagging wire between two points
+ function catenary(b, a, c, sag, r, col, segs = 8) {
+ let px = a[0], py = a[1], pz = a[2];
+ for (let i = 1; i <= segs; i++) {
+ const k = i / segs;
+ const x = a[0] + (c[0] - a[0]) * k, y = a[1] + (c[1] - a[1]) * k - sag * 4 * k * (1 - k), z = a[2] + (c[2] - a[2]) * k;
+ b.cyl(px, py, pz, x, y, z, r, 3, col);
+ px = x; py = y; pz = z;
+ }
+ }
+ // satellite dish at local position, facing local +z rotated by yaw, tilted up
+ function dish(x, y, z, r, yaw, tilt) {
+ pushXf(_m1.makeRotationY(yaw).setPosition(x, y, z).clone());
+ pushXf(new THREE.Matrix4().makeRotationX(-tilt));
+ const c = mul(lin(0xb9bbb6), rr(0.6, 1.0)), seg = 10, rings = 3, k = 0.28;
+ const ring = (side) => {
+ const base = paint.count;
+ for (let j = 0; j <= rings; j++) for (let i = 0; i <= seg; i++) {
+ const rho = r * j / rings, a = (i / seg) * Math.PI * 2, cs = Math.cos(a), sn = Math.sin(a);
+ const zz = k * r * (rho / r) * (rho / r) + (side < 0 ? -0.012 : 0);
+ const s = 2 * k * rho / r; const nl = Math.hypot(s, 1);
+ paint.v(rho * cs, rho * sn, zz, side * -s * cs / nl, side * -s * sn / nl, side / nl, side > 0 ? c : mul(c, 0.7));
+ }
+ for (let j = 0; j < rings; j++) for (let i = 0; i < seg; i++) {
+ const a = base + j * (seg + 1) + i, b2 = a + 1, c2 = a + seg + 1, d2 = c2 + 1;
+ if (side > 0) paint.idx.push(a, c2, d2, a, d2, b2); else paint.idx.push(a, d2, c2, a, b2, d2);
+ }
+ };
+ ring(1); ring(-1);
+ metal.cyl(0, -r * 0.95, k * r, 0, 0, r * 0.95, 0.012, 3, STEEL);
+ metal.box(-0.04, 0.04, -0.04, 0.04, r * 0.9, r * 1.02, STEEL_D);
+ metal.cyl(0, 0, -0.02, 0, -0.1, -0.28, 0.025, 4, STEEL);
+ popXf(); popXf();
+ }
+ // a piece of hanging laundry (plane in the u/y plane at depth w), swaying
+ const PEGS = [lin(0x8a6a44), lin(0x8a6a44), lin(0x9a7a50), lin(0x7a2a22), lin(0x2f5a7a), lin(0x9a8a2a), lin(0x3a6a3a)];
+ function hang(u, yTop, w, width, height, colSpec, shape = 0) {
+ const [c0, c1] = colSpec; const ph = rr(0, 40), amp = rr(0.6, 1.25) * Math.min(1.3, 0.5 + height * 0.6);
+ const lean = rr(-0.05, 0.08);
+ const fk = rr(7, 13), fa = rr(0.028, 0.06), fk2 = fk * rr(1.9, 2.7), ph2 = rr(0, 6);
+ const fold = (x) => Math.sin(x * fk + ph) + 0.45 * Math.sin(x * fk2 + ph2);
+ const dfold = (x) => fk * Math.cos(x * fk + ph) + 0.45 * fk2 * Math.cos(x * fk2 + ph2);
+ const grow = (p) => Math.min(1, p * 1.4 + 0.12);
+ const rect = (ua, ub, ya, yb, stripeDir, noStripe, o = {}) => {
+ const st = c1 && !noStripe, sag = o.sag || 0, hem = o.hem === undefined ? 0.02 : o.hem, taper = o.taper || 0, cm = o.cm || 1, dw = o.dw || 0;
+ const nx = Math.max(2, Math.round((ub - ua) / (st && stripeDir ? 0.07 : 0.085))), ny = Math.max(2, Math.round((ya - yb) / (st && !stripeDir ? 0.07 : 0.2)));
+ const um = (ua + ub) / 2;
+ const V = (i, j) => {
+ const fx = i / nx, fy = j / ny;
+ const x = um + (ua + (ub - ua) * fx - um) * (1 + taper * fy);
+ const y = ya - (ya - yb) * fy - sag * Math.sin(fx * Math.PI) * (1 - fy) + hem * Math.sin(x * fk * 0.7 + ph) * fy;
+ const p = Math.max(0, (yTop - y) / 1.3), g = grow(p);
+ const dx = -fa * dfold(x) * g * 1.3, l = Math.hypot(dx, 1);
+ const k = cm * (0.80 + 0.20 * Math.sin(x * fk + ph + 0.9)) * (0.96 + 0.04 * Math.sin(p * 9 + ph)) * (1 - 0.12 * Math.min(1, p));
+ return { p: [x, y, w + dw + lean * p + fa * fold(x) * g], n: [dx / l, 0, 1 / l], k, e: [p, ph, amp] };
+ };
+ for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
+ let c = c0;
+ if (st) { const sI = stripeDir ? i : j; if (sI % 3 === 1) c = c1; }
+ const A = V(i, j + 1), B = V(i + 1, j + 1), C = V(i + 1, j), D = V(i, j);
+ laundry.quad(A.p, B.p, C.p, D.p, [A.n, B.n, C.n, D.n], [mul(c, A.k), mul(c, B.k), mul(c, C.k), mul(c, D.k)], [A.e, B.e, C.e, D.e]);
+ }
+ };
+ const peg = (x) => paint.box(x - 0.012, x + 0.012, yTop - 0.045, yTop + 0.03, w - 0.014, w + 0.014, pick(PEGS));
+ if (shape === 0) { rect(u, u + width, yTop, yTop - height, chance(0.5), false, { sag: width > 0.7 ? 0.035 : 0.01, taper: rr(-0.06, 0.02) }); if (width > 0.9) peg(u + width / 2); }
+ else if (shape === 1) { // shirt
+ rect(u + width * 0.22, u + width * 0.78, yTop, yTop - height, true, true, { taper: 0.08 });
+ rect(u, u + width * 0.24, yTop - 0.02, yTop - height * 0.5, true, true, { taper: -0.2, cm: 0.92 });
+ rect(u + width * 0.76, u + width, yTop - 0.02, yTop - height * 0.5, true, true, { taper: -0.2, cm: 0.92 });
+ } else if (shape === 2) { // trousers
+ rect(u, u + width, yTop, yTop - height * 0.25, true, true, { hem: 0 });
+ rect(u, u + width * 0.46, yTop - height * 0.25, yTop - height, true, true, { taper: -0.15 });
+ rect(u + width * 0.54, u + width, yTop - height * 0.25, yTop - height, true, true, { taper: -0.15 });
+ } else if (shape === 3) { // pair of socks
+ rect(u, u + width * 0.4, yTop, yTop - height, true, true, { hem: 0 }); rect(u + width * 0.6, u + width, yTop, yTop - height * rr(0.85, 1), true, true, { hem: 0 });
+ } else if (shape === 4) { // big sheet folded over the line: two layers
+ rect(u, u + width, yTop + 0.01, yTop - height * rr(0.55, 0.8), false, false, { cm: 0.72, dw: -0.035, sag: 0.02 });
+ rect(u, u + width, yTop + 0.012, yTop - height, false, false, { sag: 0.02, taper: rr(-0.05, 0.03) });
+ } else if (shape === 5) { // T-shirt / dress
+ rect(u + width * 0.14, u + width * 0.86, yTop, yTop - height, false, true, { taper: rr(0.1, 0.35) });
+ rect(u, u + width * 0.2, yTop - 0.01, yTop - 0.2, true, true, { hem: 0, cm: 0.9 }); rect(u + width * 0.8, u + width, yTop - 0.01, yTop - 0.2, true, true, { hem: 0, cm: 0.9 });
+ } else { // small things
+ rect(u, u + width, yTop, yTop - height, true, true, { taper: -0.55, hem: 0 });
+ }
+ peg(u + 0.04); peg(u + width - 0.04);
+ }
+ // a washing line from ua to ub at height y / depth w, filled with laundry
+ function washLine(ua, ub, y, w, density = 1) {
+ wire.cyl(ua, y, w, ub, y, w, 0.009, 3, [0.25, 0.25, 0.25]);
+ let u = ua + rr(0.03, 0.25);
+ while (u < ub - 0.25) {
+ if (!chance(0.8 * density)) { u += rr(0.2, 0.7); continue; }
+ const t = R(); let wd, ht, shape = 0;
+ if (t < 0.16) { wd = rr(0.9, 1.5); ht = rr(0.8, 1.25); shape = chance(0.5) ? 4 : 0; } // sheet
+ else if (t < 0.40) { wd = rr(0.3, 0.6); ht = rr(0.45, 0.9); } // towel
+ else if (t < 0.56) { wd = rr(0.5, 0.64); ht = rr(0.5, 0.68); shape = 1; }
+ else if (t < 0.68) { wd = rr(0.36, 0.44); ht = rr(0.75, 0.98); shape = 2; }
+ else if (t < 0.80) { wd = rr(0.2, 0.26); ht = rr(0.22, 0.36); shape = 3; }
+ else if (t < 0.92) { wd = rr(0.42, 0.56); ht = rr(0.5, 0.95); shape = 5; }
+ else { wd = rr(0.26, 0.36); ht = rr(0.16, 0.24); shape = 6; }
+ if (u + wd > ub - 0.03) { if (shape !== 0 && shape !== 4) break; wd = ub - 0.03 - u; }
+ if (wd < 0.2) break;
+ hang(u, y - 0.01, w, wd, ht, pick(LAUNDRY), shape);
+ u += wd + rr(0.03, 0.22);
+ }
+ }
+ // rug / blanket thrown over a parapet (outer face at depth w, top at y)
+ const RUGS = [[lin(0x6a1f1a), lin(0x2a1a14), lin(0xa08050)], [lin(0x5a2a1e), lin(0x8a7a5a), lin(0x23303c)], [lin(0x3a4a3a), lin(0x8a8470), lin(0x5a2a22)], [lin(0x7a7468), lin(0x4a4a50), lin(0x8a3a2e)], [lin(0x2c3c58), lin(0x8a8a84), lin(0x6a2a26)]];
+ function rug(u, y, w, wd, ht, wIn) {
+ const [ca, cb2, cc] = pick(RUGS).map((c) => mul(c, rr(0.5, 0.8)));
+ const z = w + 0.03;
+ cloth.quad([u, y - ht, z + 0.01], [u + wd, y - ht, z + 0.01], [u + wd, y + 0.02, z], [u, y + 0.02, z], [0, 0, 1], [mul(ca, 0.8), mul(ca, 0.8), ca, ca]);
+ const b1 = 0.07, b2 = 0.16;
+ cloth.quad([u + b1, y - ht + b1, z + 0.016], [u + wd - b1, y - ht + b1, z + 0.016], [u + wd - b1, y + 0.02, z + 0.006], [u + b1, y + 0.02, z + 0.006], [0, 0, 1], cb2);
+ cloth.quad([u + b2, y - ht + b2, z + 0.022], [u + wd - b2, y - ht + b2, z + 0.022], [u + wd - b2, y + 0.02, z + 0.012], [u + b2, y + 0.02, z + 0.012], [0, 0, 1], cc);
+ const n = Math.max(2, Math.round(wd / 0.3));
+ for (let i = 0; i < n; i++) { const x = u + b2 + (wd - 2 * b2) * (i + 0.5) / n, s = 0.07; cloth.quad([x, y - ht * 0.55 - s, z + 0.026], [x + s, y - ht * 0.55, z + 0.026], [x, y - ht * 0.55 + s, z + 0.026], [x - s, y - ht * 0.55, z + 0.026], [0, 0, 1], cb2); }
+ cloth.quad([u, y + 0.02, z], [u + wd, y + 0.02, z], [u + wd, y + 0.02, wIn], [u, y + 0.02, wIn], [0, 1, 0], ca);
+ }
+ // bicycle in the u/y plane (hung on a wall or leaning), wheel centres at height y
+ function bike(u, y, w) {
+ const c = mul(pick(CLUTTER), rr(0.5, 0.9)), r = 0.31, wb = 1.0, seg = 10;
+ for (const cx of [u, u + wb]) for (let i = 0; i < seg; i++) {
+ const a0 = i / seg * Math.PI * 2, a1 = (i + 1) / seg * Math.PI * 2;
+ wire.cyl(cx + Math.cos(a0) * r, y + Math.sin(a0) * r, w, cx + Math.cos(a1) * r, y + Math.sin(a1) * r, w, 0.018, 3, [0.05, 0.05, 0.05]);
+ }
+ const bb = [u + 0.42, y - 0.02], seat = [u + 0.3, y + 0.5], head = [u + 0.8, y + 0.5];
+ const L = (p, q, rad = 0.016) => metal.cyl(p[0], p[1], w, q[0], q[1], w, rad, 3, c);
+ L([u, y], bb); L(bb, seat); L(seat, head); L(bb, head); L([u, y], seat, 0.011); L(head, [u + wb, y]); L(head, [u + 0.78, y + 0.66]);
+ metal.box(u + 0.72, u + 0.84, y + 0.65, y + 0.68, w - 0.2, w + 0.2, STEEL_D); paint.box(u + 0.2, u + 0.4, y + 0.52, y + 0.57, w - 0.05, w + 0.05, [0.03, 0.03, 0.03]);
+ }
+ function skis(u, y, w) {
+ const c = mul(pick(CLUTTER), rr(0.6, 1.1)), h = rr(1.7, 2.0);
+ for (const k of [0, 0.09]) { pushXf(new THREE.Matrix4().makeRotationZ(rr(-0.08, 0.02)).setPosition(u + k, y, w)); paint.box(-0.035, 0.035, 0, h, -0.008, 0.008, c); paint.box(-0.03, 0.03, h, h + 0.1, 0.0, 0.03, c); popXf(); }
+ metal.cyl(u + 0.2, y, w, u + 0.22, y + 1.25, w + 0.02, 0.008, 3, STEEL);
+ }
+ function pigeons(ua, ub, y, w, n) {
+ for (let i = 0; i < n; i++) { const x = rr(ua, ub), c = mul([0.16, 0.17, 0.19], rr(0.6, 1.3)); blob(paint, x, y + 0.07, w, 0.075, c, 0.85); blob(paint, x + rr(-0.05, 0.05), y + 0.16, w + 0.04, 0.035, mul(c, 0.8)); }
+ }
+ function spikes(ua, ub, y, w) { for (let x = ua; x < ub; x += 0.07) { metal.box(x, x + 0.006, y, y + 0.09, w - 0.02, w - 0.014, STEEL); metal.box(x + 0.03, x + 0.036, y, y + 0.08, w + 0.014, w + 0.02, STEEL); } }
+ // outdoor AC unit hung on a wall (in the facade frame), with condensate stain
+ function acUnit(au, ay, w0) {
+ const c = mul(lin(0xc4c6c0), rr(0.55, 1));
+ paint.box(au, au + 0.8, ay, ay + 0.55, w0 + 0.03, w0 + 0.33, c, mul(c, 0.8));
+ paint.box(au + 0.1, au + 0.52, ay + 0.07, ay + 0.48, w0 + 0.33, w0 + 0.34, [0.03, 0.03, 0.035]);
+ for (let k = 0; k < 4; k++) paint.box(au + 0.1, au + 0.52, ay + 0.12 + k * 0.09, ay + 0.135 + k * 0.09, w0 + 0.34, w0 + 0.347, mul(c, 0.7));
+ metal.box(au + 0.05, au + 0.09, ay - 0.06, ay, w0, w0 + 0.3, STEEL_D); metal.box(au + 0.71, au + 0.75, ay - 0.06, ay, w0, w0 + 0.3, STEEL_D);
+ wire.cyl(au + 0.7, ay + 0.3, w0 + 0.05, au + 0.95, ay + 0.9, w0 + 0.02, 0.015, 3, [0.1, 0.1, 0.1]);
+ wire.cyl(au + 0.74, ay + 0.2, w0 + 0.04, au + 0.78, ay - rr(0.3, 1.2), w0 + 0.03, 0.008, 3, [0.5, 0.5, 0.48]);
+ addDecal(au + 0.1, au + 0.95, ay - 0.02, ay - rr(1.2, 3.2), w0 + 0.007, 0, 0.8, chance(0.5) ? D_RUST : D_WATER);
+ }
+
+ // one prefab wall panel with an optional opening; seams are real gaps
+ let curStains = [];
+ const stainAt = (u, y) => { let m = 1; for (const s of curStains) { const du = (u - s.u) / s.w, dy = s.top - y; if (dy < -0.5 || dy > s.len) continue; m *= 1 - s.k * Math.exp(-du * du) * (1 - Math.max(0, dy) / s.len); } return m; };
+ const makeStains = (uA, uB, top, n) => { curStains = []; for (let i = 0; i < n; i++) curStains.push({ u: rr(uA, uB), w: rr(0.35, 1.3), top, len: rr(4, 15), k: rr(0.22, 0.5) }); };
+ function panel(u0, y0, bw, fh, op, c0) {
+ let c = c0;
+ const g = 0.03, a0 = u0 + g, a1 = u0 + bw - g, b0 = y0 + g, b1 = y0 + fh - g;
+ if (!op) {
+ const n = Math.max(1, Math.round(bw / 1.1)), cbm = 0.8;
+ for (let i = 0; i < n; i++) { const ua = a0 + (a1 - a0) * i / n, ub = a0 + (a1 - a0) * (i + 1) / n, um = (ua + ub) / 2;
+ conc.box(ua, ub, b0, b1, -TH, 0, mul(c, stainAt(um, b1)), mul(c, cbm * stainAt(um, b0))); }
+ return;
+ }
+ const us = [a0, op.a, op.b, a1], ys = [b0, op.c, op.d, b1];
+ for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) {
+ if (i === 1 && j === 1) continue;
+ if (us[i + 1] - us[i] < 0.02 || ys[j + 1] - ys[j] < 0.02) continue;
+ const k0 = 0.8 + 0.2 * (ys[j] - b0) / (b1 - b0), k1 = 0.8 + 0.2 * (ys[j + 1] - b0) / (b1 - b0);
+ const um = (us[i] + us[i + 1]) / 2, s0 = stainAt(um, ys[j]), s1 = stainAt(um, ys[j + 1]);
+ if (i === 1 && j === 0) conc.box(us[i], us[i + 1], ys[j], ys[j + 1], -TH, 0, mul(c, 0.66 * s1), mul(c, 0.86 * s0));
+ else conc.box(us[i], us[i + 1], ys[j], ys[j + 1], -TH, 0, mul(c, k1 * s1), mul(c, k0 * s0));
+ }
+ }
+ const panelCol = (tint, k = 1) => { const t = rr(0.84, 1.1) * (chance(0.07) ? rr(0.72, 0.85) : 1) * k; return [t * tint[0] * rr(0.98, 1.02), t * tint[1], t * tint[2] * rr(0.98, 1.03)]; };
+
+ const WZ0 = -0.2, FZ0 = -0.19, FZ1 = -0.11; // glass plane / frame depth
+ function frameRect(a, b, c, d, fc, t = 0.06) {
+ paint.box(a, b, c, c + t, FZ0, FZ1, fc); paint.box(a, b, d - t, d, FZ0, FZ1, fc);
+ paint.box(a, a + t, c + t, d - t, FZ0, FZ1, fc); paint.box(b - t, b, c + t, d - t, FZ0, FZ1, fc);
+ }
+ const vbar = (u, c, d, fc, t = 0.05) => paint.box(u - t / 2, u + t / 2, c, d, FZ0, FZ1 - 0.01, fc);
+ const hbar = (a, b, y, fc, t = 0.045) => paint.box(a, b, y - t / 2, y + t / 2, FZ0, FZ1 - 0.01, fc);
+
+ function litState(gx, gy, side, p = 0.6) {
+ const n = sn2(gx * 0.45 + side * 17.3, gy * 0.6 + side * 5.1);
+ const lit = R() < (p - 0.38) + 0.76 * n;
+ let tint = pick(TINTS), bright = chance(0.28) ? rr(0.4, 0.7) : rr(0.75, 1.3), kind = 0;
+ if (lit && chance(0.05)) { tint = [0.30, 0.5, 1.0]; bright = 0.55; kind = 3; } // TV glow
+ else if (lit && chance(0.06)) { tint = [1.0, 0.66, 0.36]; bright = rr(0.7, 1.0); } // bare bulb, a bit whiter
+ return { lit, tint, bright, kind };
+ }
+ // weathering of a blank stretch of wall u0..u1 (no openings) of one panel row
+ function weatherBlank(u0, u1, y0, isTop, isBase) {
+ const wdt = u1 - u0; if (wdt < 0.3) return;
+ if (isTop) addDecal(u0, u1, y0 + FH - 0.02, y0 + FH - rr(1.2, 7.5), 0.007, 1, rr(0.45, 0.85), chance(0.8) ? D_WATER : D_MOSS);
+ if (isBase) addDecal(u0, u1, y0 - 0.02, y0 + rr(0.5, 2.2), 0.007, 1, rr(0.5, 0.85), chance(0.6) ? D_WATER : D_MOSS);
+ if (chance(0.10)) { const x = rr(u0, Math.max(u0, u1 - 0.5)); addDecal(x, x + Math.min(0.5, wdt), y0 + FH - 0.05, y0 + rr(0.1, 1.6), 0.008, 2, 0.8, D_SOOT); }
+ if (chance(0.07) && wdt > 0.5) { const pw2 = rr(0.35, Math.min(1.2, wdt - 0.1)), x = rr(u0 + 0.05, u1 - pw2 - 0.05), y = y0 + rr(0.2, FH - 1.2); addDecal(x, x + pw2, y + rr(0.4, 0.9), y, 0.008, 3, 1, mul(D_PATCH, rr(0.9, 1.05))); }
+ if (chance(0.14)) addDecal(u0, u1, y0 - 0.04, y0 + rr(0.12, 0.4), 0.008, 1, 0.85, D_MOSS);
+ if (chance(0.10)) addDecal(u0, u1, y0 + FH + 0.03, y0 + FH - rr(0.3, 1.0), 0.008, 0, 0.6, D_WATER);
+ }
+
+ // --------------------------------------------------------------- one flat's bay
+ function unit(u0, y0, type, o) {
+ const { tint, gx, gy, side, isTop, back } = o;
+ const bw = o.bw || BW;
+ const uc = u0 + bw / 2;
+ const st = litState(gx, gy, side, back ? 0.62 : 0.72);
+ const fc = mul(pick(FRAME_COLS), rr(0.8, 1.05));
+ const seed = rr(1, 900);
+ const curtain = chance(0.2) ? 0 : rr(0.15, 0.95);
+ const isL = type === 'L', isBalc = type === 'B' || isL, isBase = gy === 0;
+ let ow, oh, sill;
+ if (type === 'W') { ow = 1.72; oh = 1.58; sill = 0.9; }
+ else if (type === 'WW') { ow = 2.4; oh = 1.58; sill = 0.9; }
+ else if (type === 'K') { ow = 1.2; oh = 1.38; sill = 1.05; }
+ else { ow = 2.3; oh = 2.15; sill = 0.12; }
+ const a = uc - ow / 2, b = uc + ow / 2, c = y0 + sill, d = c + oh;
+ if (isL) pushXf(new THREE.Matrix4().makeTranslation(0, 0, -REC));
+ const BD = isL ? REC + PROJ : 1.2;
+ panel(u0, y0, bw, FH, { a, b, c, d }, panelCol(tint, isBalc ? 0.82 : 1));
+ addWindow(uc, (c + d) / 2, WZ0, ow, oh, seed, st.lit ? st.bright : 0, curtain, st.kind, st.tint);
+ if (st.lit) addLight(uc, (c + d) / 2 + (isBalc ? 0.25 : 0), isBalc ? BD * 0.42 : 0.3, st.tint, st.bright * (st.kind === 3 ? 0.5 : isBalc ? 1.4 : 0.9));
+
+ if (!isBalc) {
+ frameRect(a, b, c, d, fc);
+ let leafW = ow * 0.5;
+ if (type === 'W') {
+ const m = chance(0.6) ? uc : a + ow * 0.36; vbar(m, c, d, fc); leafW = m - a;
+ if (chance(0.6)) hbar(m, b, c + oh * 0.72, fc);
+ } else if (type === 'WW') { vbar(a + ow / 3, c, d, fc); vbar(a + 2 * ow / 3, c, d, fc); leafW = ow / 3; if (chance(0.5)) hbar(a + ow / 3, a + 2 * ow / 3, c + oh * 0.72, fc); }
+ else { vbar(a + ow * 0.4, c, d, fc); leafW = ow * 0.4; }
+ if (chance(0.09)) { // one casement left ajar
+ const lw = leafW - 0.07, y1 = c + 0.06, y2 = d - 0.06, t = 0.05;
+ pushXf(new THREE.Matrix4().makeRotationY(-rr(0.25, 1.0)).setPosition(a + 0.05, 0, FZ1 + 0.01));
+ paint.box(0, lw, y1, y1 + t, -0.02, 0.02, fc); paint.box(0, lw, y2 - t, y2, -0.02, 0.02, fc); paint.box(0, t, y1 + t, y2 - t, -0.02, 0.02, fc); paint.box(lw - t, lw, y1 + t, y2 - t, -0.02, 0.02, fc);
+ glass.quad([0, y1, 0], [lw, y1, 0], [lw, y2, 0], [0, y2, 0], [0, 0, 1], [seed * 0.01, 0, 0]);
+ popXf();
+ }
+ // sill + staining below it
+ paint.box(a - 0.05, b + 0.05, c - 0.05, c - 0.01, -0.12, 0.09, mul(lin(0x9da1a3), rr(0.6, 1)));
+ addDecal(a - 0.12, a + 0.16, c - 0.04, c - rr(0.7, 3.2), 0.006, 0, rr(0.5, 0.95), chance(0.25) ? D_RUST : D_WATER);
+ addDecal(b - 0.16, b + 0.12, c - 0.04, c - rr(0.7, 3.2), 0.006, 0, rr(0.5, 0.95), chance(0.25) ? D_RUST : D_WATER);
+ if (chance(0.75)) addDecal(a - 0.04, b + 0.04, c - 0.05, y0 + 0.03, 0.006, 0, rr(0.3, 0.75), D_WATER);
+ weatherBlank(u0 + 0.03, a - 0.03, y0, isTop, isBase); weatherBlank(b + 0.03, u0 + bw - 0.03, y0, isTop, isBase);
+ if (isTop) addDecal(a, b, y0 + FH - 0.02, d + 0.02, 0.007, 1, rr(0.4, 0.8), D_WATER);
+ if (isBase) addDecal(a - 0.05, b + 0.05, y0 - 0.02, c - 0.06, 0.007, 1, rr(0.4, 0.8), D_WATER);
+ if (chance(0.06)) pigeons(a, b, c - 0.01, 0.03, 1 + Math.floor(R() * 3));
+ else if (chance(0.06)) spikes(a, b, c - 0.01, 0.05);
+ if (chance(0.12)) { const x = chance(0.5) ? a - 0.1 : b + 0.1; wire.box(x, x + 0.02, c + rr(0.2, 1.2), y0 + FH + rr(0.5, 4), 0.0, 0.02, [0.07, 0.07, 0.07]); }
+ const t = R();
+ if (t < 0.17) acUnit(a + rr(0.0, ow - 0.8), c - rr(0.75, 0.85), 0);
+ else if (t < 0.29) { // flower box
+ const fu = uc - rr(0.4, 0.7), fw = rr(0.8, 1.3);
+ paint.box(fu, fu + fw, c - 0.26, c - 0.07, 0.06, 0.26, mul(pick(CLUTTER), 0.8));
+ for (let i = 0; i < 4; i++) bush(fu + (i + 0.5) * fw / 4, c - 0.08, 0.16, rr(0.1, 0.2), 3);
+ if (chance(0.6)) for (let i = 0; i < 3; i++) vine(fu + rr(0, fw), c - 0.24, 0.27, rr(0.3, 1.1));
+ addDecal(fu, fu + fw, c - 0.25, c - rr(0.8, 1.8), 0.007, 0, 0.7, D_MOSS);
+ } else if (t < 0.50) { // washing lines under the window
+ const la = a - rr(0.1, 0.5), lb = b + rr(0.1, 0.5), ly = c - 0.12;
+ metal.box(la - 0.015, la + 0.015, ly - 0.015, ly + 0.015, 0, 0.5, STEEL); metal.box(lb - 0.015, lb + 0.015, ly - 0.015, ly + 0.015, 0, 0.5, STEEL);
+ washLine(la, lb, ly, 0.24, 1); if (chance(0.6)) washLine(la, lb, ly, 0.46, 0.85);
+ addDecal(la - 0.06, la + 0.06, ly, ly - rr(0.5, 1.5), 0.007, 0, 0.9, D_RUST); addDecal(lb - 0.06, lb + 0.06, ly, ly - rr(0.5, 1.5), 0.007, 0, 0.9, D_RUST);
+ } else if (t < 0.54) { // awning
+ const n = 7, ay0 = d + 0.18, ay1 = d - 0.28, aw = 0.75, ca = pick(LAUNDRY);
+ for (let i = 0; i < n; i++) {
+ const ua = a - 0.1 + (ow + 0.2) * i / n, ub = a - 0.1 + (ow + 0.2) * (i + 1) / n;
+ const cc = mul(i % 2 && ca[1] ? ca[1] : ca[0], 0.75);
+ cloth.quad([ua, ay1, aw], [ub, ay1, aw], [ub, ay0, 0.02], [ua, ay0, 0.02], [0, 0.85, 0.52], cc);
+ cloth.quad([ua, ay1 - 0.16, aw], [ub, ay1 - 0.16, aw], [ub, ay1, aw], [ua, ay1, aw], [0, 0, 1], cc);
+ }
+ metal.cyl(a - 0.1, ay1, aw, a - 0.1, ay1 - 0.5, 0.02, 0.012, 3, STEEL); metal.cyl(b + 0.1, ay1, aw, b + 0.1, ay1 - 0.5, 0.02, 0.012, 3, STEEL);
+ } else if (t < 0.63) {
+ const du = chance(0.5) ? a - 0.35 : b + 0.35, dy = c + rr(0.2, 1.2);
+ dish(du, dy, 0.3, rr(0.28, 0.4), rr(-0.9, 0.9), rr(0.25, 0.5));
+ addDecal(du - 0.1, du + 0.1, dy - 0.1, dy - rr(0.8, 2.2), 0.007, 0, 0.9, D_RUST);
+ wire.box(du - 0.01, du + 0.01, dy - 0.1, dy - rr(0.3, 0.9), 0.0, 0.02, [0.06, 0.06, 0.06]);
+ }
+ return;
+ }
+
+ // ---- balcony / loggia door + window
+ const doorL = chance(0.5), dw = 0.8;
+ const da = doorL ? a : b - dw, db = da + dw, wa = doorL ? db : a, wb = doorL ? b : da;
+ frameRect(a, b, c, d, fc);
+ vbar(doorL ? db : da, c, d, fc, 0.08);
+ conc.box(wa, wb, c, y0 + 0.92, WZ0 - 0.02, -0.06, panelCol(tint, 0.8)); // spandrel under the window part
+ hbar(wa, wb, y0 + 0.95, fc, 0.06); vbar((wa + wb) / 2, y0 + 0.95, d, fc);
+ hbar(da, db, y0 + 0.98, fc, 0.06);
+ paint.box(da + 0.05, db - 0.05, c + 0.05, y0 + 0.96, FZ0 + 0.01, FZ1 - 0.03, mul(fc, 0.9));
+
+ // ---- slab, cheek walls, ceiling
+ const inset = isL ? 0.14 : 0.1;
+ const ua = u0 + inset, ub = u0 + bw - inset, yS = y0 + 0.05, yT = y0 + 1.1, yC = y0 + FH - 0.1;
+ const slabC = panelCol(tint, 0.85);
+ sbox(conc, ua, ub, y0 - 0.1, yS, 0, BD, slabC, mul(slabC, 0.7), 4, 1, 2);
+ metal.box(ua - 0.01, ub + 0.01, y0 - 0.1, y0 - 0.05, BD, BD + 0.015, RUSTY);
+ if (isL) {
+ const cc = panelCol(tint, 0.92), wEnd = o.fin ? BD + 0.04 : REC;
+ sbox(conc, u0 + 0.015, u0 + inset, y0, y0 + FH, 0, wEnd, cc, mul(cc, 0.82), 1, 3, 3);
+ sbox(conc, u0 + bw - inset, u0 + bw - 0.015, y0, y0 + FH, 0, wEnd, cc, mul(cc, 0.82), 1, 3, 3);
+ if (isTop) sbox(conc, ua, ub, y0 + FH - 0.16, y0 + FH - 0.05, 0, REC + 0.02, cc, mul(cc, 0.8), 4, 1, 2);
+ }
+ const glazed = chance(back ? 0.5 : 0.52);
+ let ptype = Math.floor(R() * 3); if (glazed && ptype === 2 && chance(0.7)) ptype = Math.floor(R() * 2);
+ const pcBase = chance(0.45) ? null : pick(PARAPET_PAINT);
+ if (ptype === 0) {
+ const B_ = pcBase ? paint : conc, pc = pcBase ? mul(pcBase, rr(0.6, 1.0)) : panelCol(tint, 0.95);
+ B_.box(ua, ub, yS, yT, BD - 0.08, BD, pc, mul(pc, 0.8));
+ B_.box(ua, ua + 0.08, yS, yT, 0, BD - 0.08, pc, mul(pc, 0.8)); B_.box(ub - 0.08, ub, yS, yT, 0, BD - 0.08, pc, mul(pc, 0.8));
+ if (chance(0.5)) paint.box(ua - 0.01, ub + 0.01, yT, yT + 0.035, BD - 0.1, BD + 0.02, mul(lin(0x8a8d8f), 0.8));
+ addDecal(ua, ub, yT, yS - 0.14, BD + 0.005, 0, rr(0.5, 0.95), chance(0.45) ? D_RUST : D_WATER);
+ if (chance(0.4)) addDecal(ua, ub, y0 - 0.1, y0 + rr(0.25, 0.6), BD + 0.006, 1, 0.8, chance(0.5) ? D_MOSS : D_WATER);
+ if (chance(0.12)) { const x = rr(ua, ub - 0.5); addDecal(x, x + 0.45, yT, yS, BD + 0.007, 2, 0.8, D_SOOT); }
+ } else if (ptype === 1) {
+ const pc = mul(pick(SHEET_COLS), rr(0.6, 1.0));
+ paint.box(ua, ub, yS + 0.04, yT, BD - 0.03, BD, pc, mul(pc, 0.75));
+ for (let u = ua + 0.05; u < ub - 0.05; u += 0.17) paint.box(u, u + 0.06, yS + 0.04, yT, BD, BD + 0.022, mul(pc, 1.1), mul(pc, 0.8));
+ paint.box(ua, ua + 0.03, yS + 0.04, yT, 0, BD - 0.03, pc); paint.box(ub - 0.03, ub, yS + 0.04, yT, 0, BD - 0.03, pc);
+ for (let w = 0.1; w < BD - 0.1; w += 0.17) { paint.box(ua - 0.022, ua, yS + 0.04, yT, w, w + 0.06, pc); paint.box(ub, ub + 0.022, yS + 0.04, yT, w, w + 0.06, pc); }
+ metal.box(ua, ub, yT - 0.03, yT + 0.02, BD - 0.05, BD + 0.01, STEEL);
+ addDecal(ua, ub, yT - 0.03, yS - 0.14, BD + 0.026, 0, rr(0.4, 0.8), D_RUST);
+ } else {
+ const rc = mul(chance(0.5) ? STEEL : RUSTY, rr(0.7, 1.1));
+ metal.box(ua, ub, yT - 0.05, yT, BD - 0.05, BD, rc); metal.box(ua, ub, yS + 0.08, yS + 0.12, BD - 0.04, BD - 0.01, rc);
+ metal.box(ua, ua + 0.05, yT - 0.05, yT, 0, BD, rc); metal.box(ub - 0.05, ub, yT - 0.05, yT, 0, BD, rc);
+ for (let u = ua + 0.04; u < ub - 0.03; u += 0.135) metal.box(u, u + 0.022, yS, yT - 0.05, BD - 0.036, BD - 0.014, rc);
+ for (let w = 0.12; w < BD - 0.06; w += 0.135) { metal.box(ua + 0.014, ua + 0.036, yS, yT - 0.05, w, w + 0.022, rc); metal.box(ub - 0.036, ub - 0.014, yS, yT - 0.05, w, w + 0.022, rc); }
+ if (chance(0.55)) { const pc = mul(pick(chance(0.5) ? SHEET_COLS : PARAPET_PAINT), rr(0.55, 0.95)); paint.box(ua + 0.05, ub - 0.05, yS + 0.1, yS + rr(0.6, 0.95), BD - 0.07, BD - 0.045, pc); }
+ addDecal(ua, ub, yS, yS - 0.15, BD + 0.017, 0, 0.9, D_RUST);
+ }
+ if (isTop) { // canopy over the top-floor balcony
+ const cc = mul(pick(SHEET_COLS), 0.7);
+ sbox(paint, ua - 0.06, ub + 0.06, yC + 0.02, yC + 0.07, 0, BD + 0.18, cc, cc, 3, 1, 2);
+ metal.cyl(ua + 0.03, yC + 0.02, BD - 0.03, ua + 0.03, yT, BD - 0.03, 0.02, 4, STEEL); metal.cyl(ub - 0.03, yC + 0.02, BD - 0.03, ub - 0.03, yT, BD - 0.03, 0.02, 4, STEEL);
+ }
+ if (glazed) {
+ const gc = mul(pick(FRAME_COLS), rr(0.75, 1.0)), t = pick([0.035, 0.05, 0.05, 0.075]), gz0 = BD - 0.07, gz1 = BD - 0.01;
+ const yA = yT, yB = yC;
+ paint.box(ua, ub, yA, yA + 0.06, gz0, gz1, gc); paint.box(ua, ub, yB - 0.07, yB, gz0, gz1, gc);
+ const np = Math.max(2, Math.round((ub - ua) / rr(0.45, 1.05)));
+ const tr = chance(0.7) ? yB - rr(0.42, 0.6) : 0, tr2 = chance(0.3) ? yA + rr(0.3, 0.45) : 0;
+ const board = mul(pick(CLUTTER), rr(0.5, 0.9));
+ for (let i = 0; i <= np; i++) {
+ const u = ua + (ub - ua - t) * i / np; paint.box(u, u + t, yA + 0.06, yB - 0.07, gz0, gz1, gc);
+ if (i < np && chance(0.1)) paint.box(u + t, u + (ub - ua - t) / np, tr2 ? tr2 : yA + 0.06, tr ? tr : yB - 0.07, gz0 + 0.01, gz1 - 0.01, board); // pane replaced by a board
+ else if (i < np && tr2 && chance(0.5)) paint.box(u + t, u + (ub - ua - t) / np, yA + 0.06, tr2, gz0 + 0.01, gz1 - 0.01, board);
+ }
+ if (tr) paint.box(ua, ub, tr - 0.02, tr + 0.02, gz0, gz1, gc);
+ if (tr2) paint.box(ua, ub, tr2 - 0.02, tr2 + 0.02, gz0, gz1, gc);
+ if (!isL || !o.fin) for (const su of [ua, ub - 0.06]) {
+ paint.box(su, su + 0.06, yA, yA + 0.06, isL ? REC : 0, gz0, gc); paint.box(su, su + 0.06, yB - 0.07, yB, isL ? REC : 0, gz0, gc);
+ if (!isL) paint.box(su, su + 0.06, yA + 0.06, yB - 0.07, BD * 0.48, BD * 0.48 + t, gc);
+ if (tr) paint.box(su, su + 0.06, tr - 0.02, tr + 0.02, isL ? REC : 0, gz0, gc);
+ }
+ const sd = seed * 0.01, gs = isL ? (o.fin ? BD : REC) : 0;
+ glass.quad([ua, yA, BD - 0.04], [ub, yA, BD - 0.04], [ub, yB, BD - 0.04], [ua, yB, BD - 0.04], [0, 0, 1], [sd, 0, 0]);
+ if (gs < BD - 0.1) {
+ glass.quad([ua + 0.03, yA, BD], [ua + 0.03, yA, gs], [ua + 0.03, yB, gs], [ua + 0.03, yB, BD], [-1, 0, 0], [sd, 0, 0]);
+ glass.quad([ub - 0.03, yA, gs], [ub - 0.03, yA, BD], [ub - 0.03, yB, BD], [ub - 0.03, yB, gs], [1, 0, 0], [sd, 0, 0]);
+ }
+ if (chance(0.55)) { // curtains / tulle inside the glazing
+ const cc = mul(pick(CURTAIN_COLS), rr(0.55, 0.9));
+ const cov = chance(0.3) ? [[0, 1]] : [[0, rr(0.12, 0.4)], [rr(0.65, 0.88), 1]];
+ for (const [f0, f1] of cov) {
+ const ca = ua + 0.08 + (ub - ua - 0.16) * f0, cb = ua + 0.08 + (ub - ua - 0.16) * f1, n = Math.max(2, Math.round((cb - ca) / 0.05));
+ const k = rr(22, 34), p0 = rr(0, 6);
+ for (let i = 0; i < n; i++) {
+ const x0 = ca + (cb - ca) * i / n, x1 = ca + (cb - ca) * (i + 1) / n;
+ const zz = BD - 0.14 + 0.025 * Math.sin(x0 * k + p0), zz2 = BD - 0.14 + 0.025 * Math.sin(x1 * k + p0);
+ const sl = Math.cos((x0 + x1) * 0.5 * k + p0);
+ cloth.quad([x0, yA + 0.08, zz], [x1, yA + 0.08, zz2], [x1, yB - 0.08, zz2], [x0, yB - 0.08, zz], [-0.5 * sl, 0, 0.86], mul(cc, 0.78 + 0.22 * sl));
+ }
+ }
+ }
+ }
+ // loggia / balcony lamp
+ if (chance(st.lit ? 0.3 : 0.07)) {
+ const lu = uc + rr(-0.7, 0.7), lw = BD * rr(0.3, 0.6), ly = y0 + FH - 0.34;
+ emis.box(lu - 0.04, lu + 0.04, ly - 0.06, ly + 0.04, lw - 0.04, lw + 0.04, LAMPC);
+ wire.box(lu - 0.008, lu + 0.008, ly + 0.04, y0 + FH - 0.1, lw - 0.008, lw + 0.008, [0.05, 0.05, 0.05]);
+ addLight(lu, ly - 0.05, lw, [1, 0.42, 0.14], rr(0.8, 1.4));
+ }
+ // clutter
+ const nCl = Math.floor(rr(1, 6));
+ for (let i = 0; i < nCl; i++) {
+ const cu = chance(0.5) ? ua + rr(0.12, 0.5) : ub - rr(0.5, 1.0), cw = rr(0.3, 0.6), chh = chance(0.3) ? rr(0.9, 1.7) : rr(0.25, 0.6), cd = rr(0.3, 0.5), cz = rr(0.1, BD - 0.15 - cd);
+ const cc = mul(pick(CLUTTER), rr(0.5, 1.0));
+ paint.box(cu, cu + cw, yS, yS + chh, cz, cz + cd, cc, mul(cc, 0.7));
+ if (chh < 0.6 && chance(0.4)) { const c2 = mul(pick(CLUTTER), rr(0.5, 1.0)); paint.box(cu + 0.04, cu + cw - 0.06, yS + chh, yS + chh + rr(0.2, 0.4), cz + 0.03, cz + cd - 0.04, c2, mul(c2, 0.7)); }
+ }
+ if (chance(0.16)) bike(uc - 0.5 + rr(-0.3, 0.3), yS + rr(1.45, 1.7), 0.12);
+ if (chance(0.16)) skis(chance(0.5) ? ua + 0.2 : ub - 0.45, yS, rr(0.1, 0.3));
+ if (chance(0.45)) { // pot plants on the parapet / floor
+ const n = Math.floor(rr(1, 5));
+ for (let i = 0; i < n; i++) { const pu = rr(ua + 0.2, ub - 0.2), top = chance(0.6) && !glazed; const py = top ? yT + 0.02 : yS; const pw = top ? BD - 0.1 : rr(0.3, BD - 0.3);
+ paint.box(pu - 0.09, pu + 0.09, py, py + 0.16, pw - 0.09, pw + 0.09, mul(lin(0x7a4a32), rr(0.6, 1))); bush(pu, py + 0.2, pw, rr(0.16, 0.3), 4); }
+ }
+ if (!glazed && chance(0.36)) { // flower box hung outside
+ const fu = rr(ua + 0.1, ub - 1.2), fw = rr(0.8, 1.1);
+ paint.box(fu, fu + fw, yT - 0.24, yT - 0.06, BD, BD + 0.17, mul(pick(CLUTTER), 0.7));
+ for (let i = 0; i < 4; i++) bush(fu + (i + 0.5) * fw / 4, yT - 0.05, BD + 0.09, rr(0.1, 0.2), 3);
+ for (let i = 0; i < 4; i++) if (chance(0.7)) vine(fu + rr(0, fw), yT - 0.2, BD + 0.18, rr(0.3, 1.4));
+ }
+ let lines = false;
+ if (chance(glazed ? 0.3 : 0.74)) { // washing lines outside the parapet
+ const la = ua + 0.06, lb = ub - 0.06, ly = yT + (glazed ? -0.12 : rr(0.0, 0.25)); lines = true;
+ metal.box(la - 0.012, la + 0.012, ly - 0.012, ly + 0.012, BD - 0.05, BD + 0.42, STEEL); metal.box(lb - 0.012, lb + 0.012, ly - 0.012, ly + 0.012, BD - 0.05, BD + 0.42, STEEL);
+ washLine(la, lb, ly, BD + 0.13, 1); if (chance(0.65)) washLine(la, lb, ly, BD + 0.27, 0.9); if (chance(0.3)) washLine(la, lb, ly, BD + 0.4, 0.8);
+ }
+ if (!glazed && chance(0.5)) washLine(ua + 0.05, ub - 0.05, y0 + rr(2.3, 2.55), BD - rr(0.2, 0.5), 0.95); // line across the loggia, high up
+ if (!lines && ptype !== 2 && chance(0.22)) { const rw = rr(0.7, 1.5), ru = rr(ua + 0.05, ub - rw - 0.05); rug(ru, yT + (glazed ? -0.02 : 0.02), BD, rw, rr(0.55, 0.95), BD - 0.2); }
+ if (chance(0.08)) { // someone out on the balcony
+ const pu = rr(ua + 0.4, ub - 0.4), pw = rr(0.45, 0.85), cc = mul(pick(CLUTTER), rr(0.25, 0.5)), hgt = rr(1.28, 1.45);
+ paint.box(pu - 0.2, pu + 0.2, yS + 0.75, yS + hgt, pw - 0.11, pw + 0.11, cc); paint.box(pu - 0.16, pu + 0.16, yS, yS + 0.75, pw - 0.1, pw + 0.1, mul(cc, 0.6));
+ blob(paint, pu, yS + hgt + 0.13, pw, 0.115, [0.2, 0.13, 0.1]);
+ }
+ if (chance(0.16)) dish(chance(0.5) ? ua + 0.25 : ub - 0.25, yT + 0.3, BD + 0.05, rr(0.3, 0.42), rr(-0.9, 0.9), rr(0.25, 0.5));
+ if (chance(0.12)) { const au = chance(0.5) ? ua + 0.15 : ub - 0.95; paint.box(au, au + 0.8, yS + 0.02, yS + 0.57, 0.05, 0.35, mul(lin(0xc4c6c0), rr(0.6, 0.9))); }
+ else if (chance(0.14)) acUnit(chance(0.5) ? ua + 0.1 : ub - 0.9, yS + 0.12, BD);
+ if (!glazed && chance(0.08)) pigeons(ua + 0.2, ub - 0.2, yT, BD - 0.04, 1 + Math.floor(R() * 3));
+ if (chance(0.05)) { const ax = chance(0.5) ? ua + 0.05 : ub - 0.05; antenna(ax, yT, BD + 0.03, rr(1.2, 2.0), Math.floor(R() * 3), false); }
+ if (isL) popXf();
+ }
+
+ // ------------------------------------------------------------------ sections
+ const typesFront = [], typesBack = [], finCol = [];
+ for (let i = 0; i < NB; i++) {
+ const r1 = R(); typesFront.push(r1 < 0.34 ? 'L' : r1 < 0.54 ? 'B' : r1 < 0.84 ? 'W' : 'WW');
+ const r2 = R(); typesBack.push(r2 < 0.22 ? 'L' : r2 < 0.36 ? 'B' : r2 < 0.64 ? 'W' : r2 < 0.86 ? 'K' : 'WW');
+ finCol.push(chance(0.55));
+ }
+ for (const S of sections) {
+ // dark core behind the panels (set back behind recessed loggias)
+ for (let i = 0; i < S.bays; i++) {
+ const gi = S.bay0 + i, xa = i === 0 ? S.x0 + TH - 0.02 : S.x0 + i * BW, xb = i === S.bays - 1 ? S.x1 - TH + 0.02 : S.x0 + (i + 1) * BW;
+ core.box(xa, xb, Y0 - 0.02, S.roofY, -S.zb + TH - 0.02 + (typesBack[gi] === 'L' ? REC : 0), S.zf - TH + 0.02 - (typesFront[gi] === 'L' ? REC : 0), [0.5, 0.5, 0.5]);
+ }
+ for (const side of [1, -1]) {
+ pushXf(side > 0 ? frameM(0, S.zf, 0) : frameM(0, -S.zb, Math.PI));
+ makeStains(side > 0 ? S.x0 : -S.x1, side > 0 ? S.x1 : -S.x0, S.roofY, 2 + Math.floor(R() * 4));
+ for (let i = 0; i < S.bays; i++) {
+ const gi = S.bay0 + i;
+ const type = side > 0 ? typesFront[gi] : typesBack[gi];
+ const xw = S.x0 + i * BW; // bay's low-x edge in world
+ const u0 = side > 0 ? xw : -(xw + BW);
+ for (let f = 0; f < S.floors; f++) {
+ let t = type; if (t === 'B' && chance(0.04)) t = 'W';
+ unit(u0, Y0 + f * FH, t, { tint: S.tint, gx: gi, gy: f, side, isTop: f === S.floors - 1, back: side < 0, fin: finCol[gi] });
+ }
+ }
+ // drips down the base slab
+ {
+ const bz = (side > 0 ? 8.85 - S.zf : 8.45 - S.zb) + 0.006, uA0 = side > 0 ? S.x0 : -S.x1;
+ for (let u = uA0; u < uA0 + S.bays * BW - 0.5; ) { const wd = rr(1.5, 4); addDecal(u, Math.min(u + wd, uA0 + S.bays * BW), Y0 - 0.03, 0.0, bz, chance(0.5) ? 0 : 1, rr(0.5, 0.9), chance(0.3) ? D_RUST : D_WATER); u += wd; }
+ }
+ // faded yellow gas main with risers
+ {
+ const gy = Y0 + FH - 0.22, gA = (side > 0 ? S.x0 : -S.x1) + 0.2, gB = gA + S.bays * BW - 0.4, gc = mul(lin(0x9a8428), rr(0.55, 0.85));
+ metal.cyl(gA, gy, 0.11, gB, gy, 0.11, 0.045, 6, gc);
+ for (let u = gA + 0.6; u < gB; u += BW * (1 + Math.floor(R() * 2))) {
+ const top = Y0 + (1 + Math.floor(R() * (S.floors - 1))) * FH + 1.0;
+ metal.cyl(u, gy, 0.11, u, top, 0.11, 0.03, 5, gc); metal.box(u - 0.05, u + 0.05, gy + 0.6, gy + 0.66, 0, 0.14, STEEL_D);
+ }
+ for (let u = gA + 1.5; u < gB; u += 3.4) metal.box(u - 0.03, u + 0.03, gy - 0.07, gy + 0.07, 0, 0.14, STEEL_D);
+ }
+ // cable bundles clipped under the floor lines
+ for (let k = 0; k < 4; k++) {
+ const cy = Y0 + (1 + Math.floor(R() * (S.floors - 1))) * FH + rr(0.03, 0.12), cA = (side > 0 ? S.x0 : -S.x1) + rr(0, 4), cB = Math.min(cA + rr(6, 16), (side > 0 ? S.x1 : -S.x0));
+ for (let j = 0; j < 3; j++) wire.box(cA, cB, cy + j * 0.03, cy + j * 0.03 + 0.018, 0.0, 0.03 + j * 0.006, [0.07, 0.07, 0.075]);
+ for (let u = cA + 0.4; u < cB; u += rr(1.2, 2.5)) metal.box(u, u + 0.03, cy - 0.02, cy + 0.11, 0.0, 0.045, STEEL_D);
+ if (chance(0.6)) { const jx = rr(cA, cB - 0.3); paint.box(jx, jx + 0.26, cy - 0.1, cy + 0.22, 0.0, 0.1, mul(lin(0x8a8c88), rr(0.5, 0.9))); addDecal(jx, jx + 0.26, cy - 0.1, cy - rr(0.6, 1.6), 0.007, 0, 0.8, D_RUST); }
+ }
+ // long drooping facade cables
+ const uA = side > 0 ? S.x0 : -S.x1, uB = uA + S.bays * BW;
+ for (let k = 0; k < 4 + Math.floor(R() * 4); k++) {
+ const ya = Y0 + rr(1, S.floors) * FH - rr(0.05, 0.3), u1 = rr(uA, uB - 4), u2 = Math.min(uB, u1 + rr(3, 12));
+ catenary(wire, [u1, ya, 0.05], [u2, ya + rr(-0.5, 0.5), 0.05], rr(0.15, 0.6), 0.014, [0.08, 0.08, 0.08], 8);
+ }
+ for (let k = 0; k < 5; k++) { const u = rr(uA + 0.3, uB - 0.3); wire.box(u, u + 0.025, Y0 + rr(0, 4), S.roofY + 0.4, 0.0, 0.025, [0.08, 0.08, 0.08]); }
+ // roof-edge vines
+ if (chance(0.7)) for (let k = 0; k < 6; k++) vine(rr(uA, uB), S.roofY + 0.05, 0.03, rr(0.4, 2.2));
+ popXf();
+ }
+ // side walls (visible above lower neighbours and at the two ends of the block)
+ const depth = S.zf + S.zb;
+ const sideWall = (isEnd, ang, x, uStart) => {
+ const endTypes = x < 0 ? ['', 'K', 'B', 'W', ''] : ['', 'W', '', 'B', 'K'];
+ pushXf(frameM(x, 0, ang));
+ const np = 5, pw = depth / np;
+ makeStains(uStart, uStart + depth, S.roofY, isEnd ? 6 : 2);
+ for (let f = 0; f < S.floors; f++) for (let i = 0; i < np; i++) {
+ const u0 = uStart + i * pw, y0 = Y0 + f * FH;
+ const et = isEnd ? endTypes[i] : '';
+ if (et && (et === 'B' || chance(0.85))) unit(u0, y0, et, { tint: S.tint, gx: 40 + i * 2 + (x > 0 ? 9 : 0), gy: f, side: 3, isTop: f === S.floors - 1, back: true, bw: pw });
+ else { panel(u0, y0, pw, FH, null, panelCol(S.tint)); weatherBlank(u0 + 0.03, u0 + pw - 0.03, y0, f === S.floors - 1, f === 0 && isEnd); }
+ }
+ if (isEnd) {
+ // fire ladder
+ const lu = uStart + pw * 0.5, top = S.roofY + 1.0;
+ metal.box(lu - 0.25, lu - 0.21, Y0 + 0.4, top, 0.14, 0.18, RUSTY); metal.box(lu + 0.21, lu + 0.25, Y0 + 0.4, top, 0.14, 0.18, RUSTY);
+ for (let y = Y0 + 0.6; y < top; y += 0.32) metal.box(lu - 0.21, lu + 0.21, y, y + 0.03, 0.145, 0.175, RUSTY);
+ for (let y = Y0 + 1.5; y < top; y += 3) { metal.box(lu - 0.25, lu - 0.21, y, y + 0.04, 0, 0.16, RUSTY); metal.box(lu + 0.21, lu + 0.25, y, y + 0.04, 0, 0.16, RUSTY); addDecal(lu - 0.32, lu + 0.32, y, y - rr(1, 2.6), 0.007, 0, 0.85, D_RUST); }
+ // drain pipe + conduit
+ const pu = uStart + pw * 4 + (x < 0 ? 0.1 : -pw + 0.1);
+ metal.cyl(pu, Y0 + 0.2, 0.12, pu, S.roofY + 0.3, 0.12, 0.075, 7, RUSTY);
+ for (let y = Y0 + 1.5; y < S.roofY; y += 3) metal.box(pu - 0.11, pu + 0.11, y, y + 0.05, 0, 0.2, STEEL_D);
+ wire.box(uStart + pw * 4.6, uStart + pw * 4.6 + 0.03, Y0 + 2, S.roofY + 0.5, 0, 0.03, [0.08, 0.08, 0.08]);
+ catenary(wire, [uStart + 0.5, S.roofY - 1.2, 0.04], [uStart + depth - 0.5, S.roofY - 2.4, 0.04], 0.5, 0.014, [0.08, 0.08, 0.08], 10);
+ dish(uStart + pw * 4.7, Y0 + FH * (S.floors - 2) + 1.4, 0.3, 0.42, -0.5, 0.4);
+ }
+ popXf();
+ };
+ sideWall(S.s === 0, -Math.PI / 2, S.x0, -S.zb);
+ sideWall(S.s === sections.length - 1, Math.PI / 2, S.x1, -S.zf);
+ }
+
+ // ------------------------------------------------------------------ stair towers
+ for (const T of towers) {
+ const topY = Y0 + T.floors * FH;
+ core.box(T.x0 + TH - 0.02, T.x1 - TH + 0.02, Y0 - 0.02, topY, -TZB + TH - 0.02, TZF - TH + 0.02, [0.5, 0.5, 0.5]);
+ const tint = [0.97, 0.97, 0.99];
+ const face = (side) => {
+ pushXf(side > 0 ? frameM(0, TZF, 0) : frameM(0, -TZB, Math.PI));
+ const u0 = side > 0 ? T.x0 : -T.x1;
+ makeStains(u0, u0 + TW, topY, 2);
+ for (let f = 0; f < T.floors; f++) {
+ const y0 = Y0 + f * FH, top = f === T.floors - 1;
+ if (top) {
+ panel(u0, y0, TW, FH, null, panelCol(tint)); weatherBlank(u0 + 0.03, u0 + TW - 0.03, y0, true, false);
+ if (side > 0) { paint.box(u0 + 0.9, u0 + 2.1, y0 + 1.3, y0 + 2.1, 0, 0.03, [0.05, 0.055, 0.06]); for (let y = y0 + 1.36; y < y0 + 2.08; y += 0.1) metal.box(u0 + 0.9, u0 + 2.1, y, y + 0.04, 0.02, 0.06, STEEL); }
+ continue;
+ }
+ const uc = u0 + TW / 2, ow = side > 0 ? 1.15 : 0.8, oh = side > 0 ? 1.5 : 1.0, a = uc - ow / 2, b = uc + ow / 2, c = y0 + (side > 0 ? 1.15 : 1.5), d = c + oh;
+ panel(u0, y0, TW, FH, { a, b, c, d }, panelCol(tint));
+ const lit = chance(side > 0 ? 0.55 : 0.4), br = rr(0.4, 0.7), tn = [1.0, 0.42, 0.13];
+ addWindow(uc, (c + d) / 2, WZ0, ow, oh, rr(1, 900), lit ? br : 0, 0, 2, tn);
+ if (lit) addLight(uc, (c + d) / 2, 0.28, tn, br * 0.8);
+ const fc = mul(pick(FRAME_COLS), 0.8);
+ frameRect(a, b, c, d, fc); if (side > 0) { vbar(uc, c, d, fc); hbar(a, b, c + oh * 0.5, fc); }
+ paint.box(a - 0.04, b + 0.04, c - 0.05, c - 0.01, -0.12, 0.07, mul(lin(0x9da1a3), rr(0.6, 1)));
+ addDecal(a - 0.1, b + 0.1, c - 0.04, c - rr(0.6, 1.1), 0.006, 0, rr(0.5, 0.9), D_WATER);
+ weatherBlank(u0 + 0.03, a - 0.03, y0, false, f === 0); weatherBlank(b + 0.03, u0 + TW - 0.03, y0, false, f === 0);
+ if (chance(0.3)) { const x = rr(u0 + 0.2, u0 + TW - 0.2); wire.box(x, x + 0.02, y0, y0 + FH, 0, 0.02, [0.07, 0.07, 0.07]); }
+ }
+ popXf();
+ };
+ face(1); face(-1);
+ const depth = TZF + TZB, np = 5, pw = depth / np;
+ for (const [ang, x, us] of [[-Math.PI / 2, T.x0, -TZB], [Math.PI / 2, T.x1, -TZF]]) {
+ pushXf(frameM(x, 0, ang)); makeStains(us, us + depth, topY, 3);
+ for (let f = 0; f < T.floors; f++) for (let i = 0; i < np; i++) { panel(us + i * pw, Y0 + f * FH, pw, FH, null, panelCol(tint)); if (f >= T.floors - 2) weatherBlank(us + i * pw + 0.03, us + (i + 1) * pw - 0.03, Y0 + f * FH, f === T.floors - 1, false); }
+ // roof-access ladder from the lower section roof
+ { const S2 = sections[x === T.x0 ? T.i : T.i + 1], lu = us + depth * rr(0.3, 0.7);
+ metal.box(lu - 0.22, lu - 0.18, S2.roofY + 0.1, topY + 0.9, 0.12, 0.16, RUSTY); metal.box(lu + 0.18, lu + 0.22, S2.roofY + 0.1, topY + 0.9, 0.12, 0.16, RUSTY);
+ for (let y = S2.roofY + 0.4; y < topY + 0.8; y += 0.3) metal.box(lu - 0.18, lu + 0.18, y, y + 0.025, 0.125, 0.155, RUSTY);
+ addDecal(lu - 0.3, lu + 0.3, topY - 0.2, S2.roofY + 0.2, 0.007, 0, 0.8, D_RUST); }
+ popXf();
+ }
+ // tower roof
+ tar.box(T.x0, T.x1, topY, topY + 0.1, -TZB, TZF, WHITE);
+ conc.box(T.x0 - 0.06, T.x1 + 0.06, topY, topY + 0.35, TZF - 0.2, TZF + 0.06, panelCol(tint)); conc.box(T.x0 - 0.06, T.x1 + 0.06, topY, topY + 0.35, -TZB - 0.06, -TZB + 0.2, panelCol(tint));
+ conc.box(T.x0 - 0.06, T.x0 + 0.2, topY, topY + 0.35, -TZB + 0.2, TZF - 0.2, panelCol(tint)); conc.box(T.x1 - 0.2, T.x1 + 0.06, topY, topY + 0.35, -TZB + 0.2, TZF - 0.2, panelCol(tint));
+ // drain pipes at the tower/section corners (front)
+ for (const px of [T.x0 - 0.12, T.x1 + 0.12]) {
+ const S = px < T.x0 ? sections[T.i] : sections[T.i + 1];
+ metal.cyl(px, Y0 + 0.1, S.zf + 0.12, px, S.roofY + 0.2, S.zf + 0.12, 0.07, 7, mul(RUSTY, rr(0.7, 1.1)));
+ for (let y = Y0 + 2; y < S.roofY; y += 3) metal.box(px - 0.1, px + 0.1, y, y + 0.05, S.zf, S.zf + 0.2, STEEL_D);
+ }
+ }
+
+ // ------------------------------------------------------------------ base slab
+ {
+ const n = 22, x0 = -CFG.BODY_LEN / 2 - 0.5, L = CFG.BODY_LEN + 1.0, seg = L / n;
+ for (let i = 0; i < n; i++) {
+ const c = panelCol([0.8, 0.8, 0.82]);
+ conc.box(x0 + i * seg + 0.02, x0 + (i + 1) * seg - 0.02, 0.0, Y0 - 0.03, -8.45, 8.85, c, mul(c, 0.75));
+ }
+ metal.box(x0, x0 + L, -0.02, 0.1, 8.85, 8.89, RUSTY); metal.box(x0, x0 + L, -0.02, 0.1, -8.49, -8.45, RUSTY);
+ }
+
+ // ------------------------------------------------------------------ roofs
+ const masts = [];
+ function antenna(x, y, z, h, type, reg = true) {
+ const c = mul(STEEL, rr(0.7, 1.2));
+ metal.cyl(x, y, z, x, y + h, z, 0.035, 5, c);
+ const top = y + h;
+ if (type === 0) { // yagi
+ const a = rr(0, Math.PI), dx = Math.cos(a), dz = Math.sin(a), L = rr(1.4, 2.4), n = Math.floor(rr(5, 9));
+ metal.cyl(x - dx * L / 2, top - 0.1, z - dz * L / 2, x + dx * L / 2, top - 0.1, z + dz * L / 2, 0.022, 4, c);
+ for (let i = 0; i < n; i++) { const k = (i / (n - 1) - 0.5) * L, el = 0.45 - 0.2 * (i / n) + 0.1; metal.cyl(x + dx * k + dz * el, top - 0.1, z + dz * k - dx * el, x + dx * k - dz * el, top - 0.1, z + dz * k + dx * el, 0.016, 3, c); }
+ } else if (type === 1) { // dipole stack
+ const a = rr(0, Math.PI), dx = Math.cos(a), dz = Math.sin(a);
+ for (let i = 0; i < 3; i++) { const yy = top - 0.1 - i * 0.55, el = 0.7 - i * 0.12; metal.cyl(x - dx * el, yy, z - dz * el, x + dx * el, yy, z + dz * el, 0.02, 3, c); }
+ metal.cyl(x - dz * 0.5, top - 0.4, z + dx * 0.5, x + dz * 0.5, top - 0.4, z - dx * 0.5, 0.016, 3, c);
+ } else if (type === 2) { // loop frame
+ const a = rr(0, Math.PI), dx = Math.cos(a), dz = Math.sin(a), w = 0.45, hh = 0.7;
+ metal.cyl(x - dx * w, top, z - dz * w, x + dx * w, top, z + dz * w, 0.016, 3, c); metal.cyl(x - dx * w, top - hh, z - dz * w, x + dx * w, top - hh, z + dz * w, 0.016, 3, c);
+ metal.cyl(x - dx * w, top, z - dz * w, x - dx * w, top - hh, z - dz * w, 0.016, 3, c); metal.cyl(x + dx * w, top, z + dz * w, x + dx * w, top - hh, z + dz * w, 0.016, 3, c);
+ } else { // tall whip with guy wires
+ for (let i = 0; i < 3; i++) { const a = i * 2.1 + rr(0, 1); wire.cyl(x, y + h * 0.75, z, x + Math.cos(a) * h * 0.4, y, z + Math.sin(a) * h * 0.4, 0.012, 3, [0.12, 0.12, 0.12]); }
+ metal.cyl(x - 0.5, top - 0.6, z, x + 0.5, top - 0.6, z, 0.018, 3, c); metal.cyl(x, top - 1.1, z - 0.4, x, top - 1.1, z + 0.4, 0.018, 3, c);
+ }
+ if (reg && type !== 3 && h > 4.3) for (let i = 0; i < 3; i++) { const a = i * 2.1 + rr(0, 1); wire.cyl(x, y + h * 0.7, z, x + Math.cos(a) * h * 0.35, y, z + Math.sin(a) * h * 0.35, 0.011, 3, [0.12, 0.12, 0.12]); }
+ if (reg) masts.push([x, top - 0.15, z]);
+ }
+ function parapet(x0, x1, z0, z1, y, h, tint) {
+ const t = 0.24, n = Math.max(1, Math.round((x1 - x0) / BW));
+ for (let i = 0; i < n; i++) {
+ const a = x0 + (x1 - x0) * i / n + 0.015, b = x0 + (x1 - x0) * (i + 1) / n - 0.015;
+ conc.box(a, b, y, y + h, z1 - t, z1 + 0.03, panelCol(tint)); conc.box(a, b, y, y + h, z0 - 0.03, z0 + t, panelCol(tint));
+ }
+ conc.box(x0 - 0.03, x0 + t, y, y + h, z0 + t, z1 - t, panelCol(tint)); conc.box(x1 - t, x1 + 0.03, y, y + h, z0 + t, z1 - t, panelCol(tint));
+ const fl = mul(lin(0x70757a), 0.7);
+ metal.box(x0 - 0.05, x1 + 0.05, y + h, y + h + 0.03, z1 - t - 0.02, z1 + 0.06, fl); metal.box(x0 - 0.05, x1 + 0.05, y + h, y + h + 0.03, z0 - 0.06, z0 + t + 0.02, fl);
+ }
+ for (const S of sections) {
+ const y = S.roofY, z0 = -S.zb, z1 = S.zf;
+ tar.box(S.x0, S.x1, y - 0.05, y + 0.12, z0 + 0.1, z1 - 0.1, WHITE);
+ parapet(S.x0, S.x1, z0, z1, y, 0.75, S.tint);
+ const ry = y + 0.12, L = S.x1 - S.x0;
+ // vent blocks
+ const nv = Math.floor(rr(2, 5));
+ for (let i = 0; i < nv; i++) {
+ const big = i === 0 && chance(0.7);
+ const vx = S.x0 + (i + rr(0.25, 0.75)) * L / nv, vz = rr(-3, 3), w = big ? rr(2.6, 3.6) : rr(0.9, 1.5), d = big ? rr(2.4, 3.4) : rr(0.8, 1.3), h = big ? rr(2.3, 3.1) : rr(0.9, 1.7), c = panelCol(S.tint, 0.9);
+ conc.box(vx - w / 2, vx + w / 2, ry, ry + h, vz - d / 2, vz + d / 2, c, mul(c, 0.7));
+ metal.box(vx - w / 2 - 0.1, vx + w / 2 + 0.1, ry + h, ry + h + 0.06, vz - d / 2 - 0.1, vz + d / 2 + 0.1, mul(RUSTY, rr(0.6, 1)));
+ paint.box(vx - w / 2 + 0.15, vx + w / 2 - 0.15, ry + h - 0.4, ry + h - 0.1, vz + d / 2, vz + d / 2 + 0.01, [0.03, 0.03, 0.035]);
+ if (chance(0.6)) antenna(vx + rr(-0.3, 0.3), ry + h, vz + rr(-0.3, 0.3), rr(2.5, 5), Math.floor(R() * 4));
+ }
+ // vent pipes
+ for (let i = 0; i < Math.floor(rr(3, 7)); i++) {
+ const px = rr(S.x0 + 1, S.x1 - 1), pz = rr(z0 + 1, z1 - 1), h = rr(0.6, 2.0), r = rr(0.08, 0.16), c = mul(chance(0.5) ? RUSTY : STEEL, rr(0.7, 1.1));
+ metal.cyl(px, ry, pz, px, ry + h, pz, r, 7, c); metal.cyl(px, ry + h, pz, px, ry + h + 0.18, pz, r * 1.9, 7, c, true, r * 0.4);
+ }
+ // antennas along the parapets
+ for (let i = 0; i < Math.floor(rr(7, 13)); i++) antenna(rr(S.x0 + 0.6, S.x1 - 0.6), ry, chance(0.5) ? z1 - rr(0.5, 1.6) : z0 + rr(0.5, 1.6), rr(2.2, 6.5), Math.floor(R() * 4));
+ // dishes
+ for (let i = 0; i < Math.floor(rr(1, 4)); i++) { const dx = rr(S.x0 + 1, S.x1 - 1), front = chance(0.6); metal.cyl(dx, ry, front ? z1 - 0.5 : z0 + 0.5, dx, ry + 1.3, front ? z1 - 0.5 : z0 + 0.5, 0.03, 4, STEEL); dish(dx, ry + 1.3, front ? z1 - 0.45 : z0 + 0.45, rr(0.35, 0.6), front ? rr(-0.8, 0.8) : Math.PI + rr(-0.8, 0.8), rr(0.3, 0.55)); }
+ // hatch, junk, water tank
+ { const hx = rr(S.x0 + 2, S.x1 - 2), hz = rr(-2, 2); conc.box(hx - 0.5, hx + 0.5, ry, ry + 0.45, hz - 0.5, hz + 0.5, panelCol(S.tint, 0.8)); metal.box(hx - 0.55, hx + 0.55, ry + 0.45, ry + 0.5, hz - 0.55, hz + 0.55, RUSTY); }
+ for (let i = 0; i < Math.floor(rr(2, 6)); i++) { const jx = rr(S.x0 + 1, S.x1 - 1), jz = rr(z0 + 1, z1 - 1), c = mul(pick(CLUTTER), rr(0.4, 0.8)); paint.box(jx, jx + rr(0.4, 1.4), ry, ry + rr(0.15, 0.7), jz, jz + rr(0.4, 1.0), c); }
+ if (S.floors >= 7 || chance(0.3)) {
+ const tx = rr(S.x0 + 3, S.x1 - 3), tz = rr(-2.5, 2.5), c = mul(RUSTY, rr(0.7, 1));
+ metal.cyl(tx - 1.4, ry + 1.5, tz, tx + 1.4, ry + 1.5, tz, 0.85, 14, c, true);
+ for (const sx of [-0.9, 0.9]) { metal.box(tx + sx - 0.06, tx + sx + 0.06, ry, ry + 1.0, tz - 0.7, tz - 0.58, STEEL_D); metal.box(tx + sx - 0.06, tx + sx + 0.06, ry, ry + 1.0, tz + 0.58, tz + 0.7, STEEL_D); }
+ metal.cyl(tx + 0.4, ry + 2.3, tz, tx + 0.4, ry + 2.7, tz, 0.12, 6, STEEL);
+ }
+ // roofing felt strips, patches, puddles
+ for (let x = S.x0 + 0.12; x < S.x1 - 0.3;) {
+ const wd = Math.min(rr(0.9, 1.1), S.x1 - 0.12 - x), k = rr(0.74, 1.22), yy = ry + 0.02;
+ tar.quad([x + 0.012, yy, z1 - 0.26], [x + wd - 0.012, yy, z1 - 0.26], [x + wd - 0.012, yy, z0 + 0.26], [x + 0.012, yy, z0 + 0.26], [0, 1, 0], [k, k, k * 1.03]); x += wd;
+ }
+ for (let i = 0; i < 7; i++) { const px = rr(S.x0 + 0.5, S.x1 - 3), pz = rr(z0 + 0.5, z1 - 3), pw = rr(0.8, 2.6), pd = rr(0.8, 2.4), k = chance(0.5) ? rr(1.25, 1.7) : rr(0.5, 0.75), yy = ry + 0.035;
+ tar.quad([px, yy, pz + pd], [px + pw, yy, pz + pd], [px + pw, yy, pz], [px, yy, pz], [0, 1, 0], [k, k, k]); }
+ for (let i = 0; i < 3 + Math.floor(R() * 4); i++) {
+ const px = rr(S.x0 + 1.5, S.x1 - 1.5), pz = rr(z0 + 1.2, z1 - 1.2), pr = rr(0.5, 1.7), n = 11, ph = rr(0, 6), el = rr(0.5, 1), yy = ry + 0.05;
+ const base = puddle.count; puddle.v(px, yy, pz, 0, 1, 0, WHITE);
+ for (let k = 0; k < n; k++) { const a = k / n * Math.PI * 2, r = pr * (0.7 + 0.3 * Math.sin(a * 3 + ph) + 0.12 * Math.sin(a * 5 + ph * 2)); puddle.v(px + Math.cos(a) * r, yy, pz + Math.sin(a) * r * el, 0, 1, 0, WHITE); }
+ for (let k = 0; k < n; k++) puddle.idx.push(base, base + 1 + (k + 1) % n, base + 1 + k);
+ }
+ // lift machine room / rooftop hut: lit window, door with a lamp, ladder, mast
+ for (let hI = 0; hI < (S.bays >= 5 ? 2 : 1); hI++) {
+ const hw2 = rr(2.4, 3.6), hd = rr(2.2, 3.0), hh = rr(2.3, 3.0), c = panelCol(S.tint, 0.95);
+ const hx = S.x0 + (hI + rr(0.15, 0.6)) * L / (S.bays >= 5 ? 2 : 1) * 0.8, back = chance(0.6), hz = back ? rr(z0 + 0.5, z0 + 1.6) : rr(z1 - hd - 1.6, z1 - hd - 0.5);
+ sbox(conc, hx, hx + hw2, ry, ry + hh, hz, hz + hd, c, mul(c, 0.72), 2, 2, 2);
+ tar.box(hx - 0.15, hx + hw2 + 0.15, ry + hh, ry + hh + 0.1, hz - 0.15, hz + hd + 0.15, WHITE);
+ metal.box(hx - 0.17, hx + hw2 + 0.17, ry + hh - 0.03, ry + hh + 0.08, hz - 0.17, hz + hd + 0.17, mul(RUSTY, 0.8));
+ pushXf(back ? frameM(0, hz, Math.PI) : frameM(0, hz + hd, 0));
+ const U = (x) => (back ? -x : x), sg = back ? -1 : 1;
+ const wu = U(hx + hw2 * 0.64), wy = ry + 1.5, lit = chance(0.8), tn = [1.0, 0.44, 0.15];
+ addWindow(wu, wy, 0.015, 0.8, 0.6, rr(1, 900), lit ? rr(0.7, 1.1) : 0, 0, 2, tn);
+ const fc = mul(pick(FRAME_COLS), 0.8);
+ paint.box(wu - 0.45, wu + 0.45, wy - 0.35, wy - 0.3, 0, 0.05, fc); paint.box(wu - 0.45, wu + 0.45, wy + 0.3, wy + 0.35, 0, 0.05, fc); paint.box(wu - 0.45, wu - 0.4, wy - 0.3, wy + 0.3, 0, 0.05, fc); paint.box(wu + 0.4, wu + 0.45, wy - 0.3, wy + 0.3, 0, 0.05, fc); paint.box(wu - 0.02, wu + 0.02, wy - 0.3, wy + 0.3, 0, 0.04, fc);
+ if (lit) addLight(wu, wy, 0.4, tn, 1.0);
+ const du = U(hx + hw2 * 0.22); paint.box(du - 0.42, du + 0.42, ry, ry + 1.95, 0, 0.04, mul(pick(SHEET_COLS), 0.7));
+ emis.box(du - 0.06, du + 0.06, ry + 2.1, ry + 2.18, 0.05, 0.17, LAMPC); metal.box(du - 0.09, du + 0.09, ry + 2.18, ry + 2.22, 0, 0.2, STEEL_D); addLight(du, ry + 2.0, 0.35, tn, 1.3);
+ addDecal(U(hx + 0.05), U(hx + hw2 - 0.05), ry + hh, ry + hh - rr(0.8, 2.0), 0.006, 1, 0.75, D_WATER);
+ addDecal(du - 0.45 * sg, du + 0.45 * sg, ry, ry + rr(0.3, 0.8), 0.006, 1, 0.7, D_MOSS);
+ popXf();
+ for (const lz of [hz + 0.5, hz + 0.95]) metal.box(hx - 0.12, hx - 0.08, ry, ry + hh + 0.9, lz - 0.02, lz + 0.02, RUSTY);
+ for (let y2 = ry + 0.3; y2 < ry + hh + 0.8; y2 += 0.3) metal.box(hx - 0.115, hx - 0.085, y2, y2 + 0.025, hz + 0.5, hz + 0.95, RUSTY);
+ if (chance(0.75)) antenna(hx + hw2 * rr(0.3, 0.7), ry + hh + 0.1, hz + hd * 0.5, rr(3, 6.5), Math.floor(R() * 4));
+ if (chance(0.6)) { const dx2 = hx + hw2 - 0.3, dz2 = back ? hz + 0.3 : hz + hd - 0.3; metal.cyl(dx2, ry + hh + 0.1, dz2, dx2, ry + hh + 1.0, dz2, 0.03, 4, STEEL); dish(dx2, ry + hh + 1.0, dz2, rr(0.4, 0.65), back ? Math.PI + rr(-0.8, 0.8) : rr(-0.8, 0.8), rr(0.3, 0.5)); }
+ }
+ // chimney stacks / capped vent shafts near the edges (silhouette)
+ for (let i = 0; i < 3 + Math.floor(R() * 3); i++) {
+ const vx = rr(S.x0 + 1, S.x1 - 2), vz = chance(0.5) ? rr(z0 + 0.6, z0 + 2.2) : rr(z1 - 2.8, z1 - 1.2), w = rr(0.5, 1.0), d = rr(0.5, 0.8), h = rr(1.3, 2.4), c = panelCol(S.tint, 0.85);
+ conc.box(vx, vx + w, ry, ry + h, vz, vz + d, c, mul(c, 0.7));
+ for (const [ox, oz] of [[0.04, 0.04], [w - 0.1, 0.04], [0.04, d - 0.1], [w - 0.1, d - 0.1]]) metal.box(vx + ox, vx + ox + 0.06, ry + h, ry + h + 0.22, vz + oz, vz + oz + 0.06, STEEL_D);
+ metal.box(vx - 0.1, vx + w + 0.1, ry + h + 0.22, ry + h + 0.27, vz - 0.1, vz + d + 0.1, mul(RUSTY, rr(0.6, 1)));
+ }
+ // pipe railing on the parapet
+ for (const zz of [z1 - 0.1, z0 + 0.1]) if (chance(0.55)) {
+ const ra = rr(S.x0 + 0.3, S.x0 + L * 0.4), rb = rr(S.x0 + L * 0.6, S.x1 - 0.3), yy = y + 0.78, rc = mul(RUSTY, rr(0.7, 1.1));
+ for (let x = ra; x <= rb + 0.01; x += (rb - ra) / Math.round((rb - ra) / 1.5)) metal.box(x - 0.018, x + 0.018, yy, yy + 0.55, zz - 0.018, zz + 0.018, rc);
+ metal.box(ra, rb, yy + 0.53, yy + 0.565, zz - 0.018, zz + 0.018, rc); metal.box(ra, rb, yy + 0.26, yy + 0.285, zz - 0.012, zz + 0.012, rc);
+ }
+ // cable tray + loose cables
+ { const tz = rr(-2, 2), ta = S.x0 + rr(0.5, 2), tb = S.x1 - rr(0.5, 2), tc = mul(RUSTY, 0.8);
+ metal.box(ta, tb, ry + 0.25, ry + 0.29, tz - 0.15, tz + 0.15, tc); metal.box(ta, tb, ry + 0.29, ry + 0.36, tz - 0.15, tz - 0.13, tc); metal.box(ta, tb, ry + 0.29, ry + 0.36, tz + 0.13, tz + 0.15, tc);
+ for (let x = ta + 0.3; x < tb; x += 2.2) metal.box(x - 0.03, x + 0.03, ry, ry + 0.25, tz - 0.12, tz + 0.12, STEEL_D);
+ for (let k = 0; k < 3; k++) wire.box(ta, tb, ry + 0.29, ry + 0.33, tz - 0.1 + k * 0.07, tz - 0.06 + k * 0.07, [0.05, 0.05, 0.055]);
+ for (let k = 0; k < 4; k++) { const cx = rr(ta, tb); catenary(wire, [cx, ry + 0.32, tz], [cx + rr(-3, 3), ry + 0.03, chance(0.5) ? z1 - 0.4 : z0 + 0.4], -0.05, 0.02, [0.05, 0.05, 0.055], 5); } }
+ // scruffy roof vegetation
+ for (let i = 0; i < 5; i++) if (chance(0.6)) bush(rr(S.x0 + 0.6, S.x1 - 0.6), ry, chance(0.5) ? z1 - 0.45 : z0 + 0.45, rr(0.15, 0.4), 3);
+ }
+ // tower-top masts with beacons
+ towers.forEach((T, i) => {
+ const topY = Y0 + T.floors * FH + 0.1, x = (T.x0 + T.x1) / 2;
+ const h = i % 2 === 0 ? rr(5.5, 8) : rr(2.5, 4);
+ antenna(x + rr(-0.5, 0.5), topY, rr(-2, 4), h, 3);
+ if (i % 2 === 0) beacons.push(masts[masts.length - 1].slice());
+ antenna(x + rr(-0.8, 0.8), topY, rr(-6, -3), rr(2.5, 4.5), Math.floor(R() * 3));
+ conc.box(x - 0.6, x + 0.6, topY, topY + 0.9, 5.2, 6.4, panelCol([0.9, 0.9, 0.92])); metal.box(x - 0.7, x + 0.7, topY + 0.9, topY + 0.95, 5.1, 6.5, RUSTY);
+ if (chance(0.7)) dish(x + 0.9, topY + 1.0, TZF - 0.5, 0.55, rr(-0.6, 0.6), 0.45);
+ });
+ // lattice radio mast on the tallest tower
+ {
+ const T = towers[0], x = (T.x0 + T.x1) / 2 + 0.2, z = -1.5, y = Y0 + T.floors * FH + 0.1, Hm = 11.5, b0 = 0.75, b1 = 0.16, c = mul(RUSTY, 0.9);
+ const corner = (k, t) => { const s = b0 + (b1 - b0) * t; return [x + (k & 1 ? s : -s), y + Hm * t, z + (k & 2 ? s : -s)]; };
+ const order = [0, 1, 3, 2];
+ for (let k = 0; k < 4; k++) { const a = corner(k, 0), b = corner(k, 1); metal.cyl(a[0], a[1], a[2], b[0], b[1], b[2], 0.045, 4, c); }
+ const nseg = 9;
+ for (let i = 0; i < nseg; i++) for (let k = 0; k < 4; k++) {
+ const k2 = order[(order.indexOf(k) + 1) % 4];
+ const a = corner(k, i / nseg), b = corner(k2, (i + 1) / nseg), h = corner(k2, i / nseg);
+ metal.cyl(a[0], a[1], a[2], b[0], b[1], b[2], 0.022, 3, c); metal.cyl(a[0], a[1], a[2], h[0], h[1], h[2], 0.022, 3, c);
+ }
+ metal.cyl(x, y + Hm, z, x, y + Hm + 2.2, z, 0.03, 4, c);
+ beacons.push([x, y + Hm + 2.0, z]); beacons.push([x + 0.5, y + Hm * 0.5, z + 0.5]);
+ dish(x - 0.5, y + Hm * 0.62, z + 0.45, 0.5, -0.7, 0.1); dish(x + 0.4, y + Hm * 0.78, z + 0.3, 0.38, 0.9, 0.1);
+ masts.push([x, y + Hm + 2.0, z]);
+ }
+ // wires strung between masts
+ {
+ const ms = masts.slice().sort((a, b) => a[0] - b[0]);
+ for (let i = 0; i < ms.length - 1; i++) {
+ const a = ms[i], b = ms[i + 1 + (chance(0.25) && i < ms.length - 2 ? 1 : 0)];
+ const d = Math.hypot(b[0] - a[0], b[2] - a[2]); if (d > 16 || d < 1.5) continue;
+ if (chance(0.72)) catenary(wire, a, b, 0.03 * d + rr(0.1, 0.5), 0.016, [0.07, 0.07, 0.07], 10);
+ }
+ }
+
+ // ------------------------------------------------------------------ baked warm light spill
+ const CS = 4.4, RMAX = 4.4, R2 = RMAX * RMAX;
+ const grid = new Map();
+ for (const L of lights) { const k = Math.floor(L.x / CS) + ',' + Math.floor(L.y / CS); if (!grid.has(k)) grid.set(k, []); grid.get(k).push(L); }
+ function computeGlow(b, translucent, gain = 1) {
+ const n = b.count, g = new Float32Array(n * 3), P = b.pos, N = b.nor;
+ for (let i = 0; i < n; i++) {
+ const x = P[3 * i], y = P[3 * i + 1], z = P[3 * i + 2], nx = N[3 * i], ny = N[3 * i + 1], nz = N[3 * i + 2];
+ const cx = Math.floor(x / CS), cy = Math.floor(y / CS);
+ let r = 0, gg = 0, bb = 0;
+ for (let dx = -1; dx <= 1; dx++) for (let dy = -1; dy <= 1; dy++) {
+ const list = grid.get((cx + dx) + ',' + (cy + dy)); if (!list) continue;
+ for (let j = 0; j < list.length; j++) {
+ const L = list[j], lx = L.x - x, ly = L.y - y, lz = L.z - z, d2 = lx * lx + ly * ly + lz * lz;
+ if (d2 > R2) continue;
+ const d = Math.sqrt(d2) + 1e-4; let ndl = (nx * lx + ny * ly + nz * lz) / d;
+ ndl = translucent ? 0.35 + 0.65 * Math.abs(ndl) : Math.max(0, ndl * 0.88 + 0.12);
+ const cut = 1 - d2 / R2, w = L.I * ndl * cut * cut / (1 + d2 / 1.0);
+ r += L.r * w; gg += L.g * w; bb += L.b * w;
+ }
+ }
+ g[3 * i] = r * gain; g[3 * i + 1] = gg * gain; g[3 * i + 2] = bb * gain;
+ }
+ return g;
+ }
+
+ // ------------------------------------------------------------------ materials
+ const uT = { value: 0 };
+ // extra prefab-concrete detail on top of the shared weathering: exposed aggregate speckle + fine pitting (mesh-local)
+ const CONC_F = /* glsl */`
+ {
+ vec3 q_ = vWp * 46.0; vec3 qi_ = floor(q_);
+ float hs_ = fract(sin(dot(qi_, vec3(127.1, 311.7, 74.7))) * 43758.5453);
+ float fw_ = length(fwidth(vWp)) * 46.0;
+ float sp_ = mix(0.5, hs_, clamp(1.4 - fw_, 0.0, 1.0));
+ diffuseColor.rgb *= 1.0 + 0.22 * smoothstep(0.86, 0.98, sp_) - 0.20 * smoothstep(0.16, 0.04, sp_);
+ vec3 q2_ = vWp * 9.0; vec3 q2i_ = floor(q2_);
+ float h2_ = fract(sin(dot(q2i_, vec3(269.5, 183.3, 246.1))) * 43758.5453);
+ diffuseColor.rgb *= 0.965 + 0.07 * mix(0.5, h2_, clamp(1.4 - fw_ * 0.2, 0.0, 1.0));
+ }
+ `;
+ function addGlow(mat, sway = false, extraF = '') {
+ const prev = mat.onBeforeCompile, prevKey = mat.customProgramCacheKey ? mat.customProgramCacheKey.bind(mat) : null;
+ const keyBase = prevKey ? prevKey() : '';
+ mat.onBeforeCompile = (sh, r) => {
+ if (prev) prev(sh, r);
+ sh.uniforms.uT = uT;
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nattribute vec3 glow; varying vec3 vGlow;\n' + (sway ? 'attribute vec3 aSway; uniform float uT;\n' : ''))
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvGlow = glow;\n' + (sway ? `{
+ float pin = aSway.x, ph = aSway.y;
+ float gust = 0.55 + 0.45 * sin(uT * 0.41 + ph * 0.31);
+ float s = sin(uT * 1.25 + ph) * 0.15 + sin(uT * 2.7 + ph * 1.9 + position.y * 1.3) * 0.045;
+ float ruf = sin(uT * 3.6 + ph * 3.1 + (position.x + position.z) * 5.0 + position.y * 2.2) * 0.03;
+ transformed += objectNormal * ((pin * pin * s * gust + pin * ruf) * aSway.z);
+ transformed.y += pin * pin * abs(s) * 0.06 * aSway.z;
+ }` : ''));
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vGlow;')
+ .replace('#include <emissivemap_fragment>', '#include <emissivemap_fragment>\ntotalEmissiveRadiance += vGlow * diffuseColor.rgb;');
+ if (extraF) sh.fragmentShader = sh.fragmentShader.replace('#include <roughnessmap_fragment>', extraF + '\n#include <roughnessmap_fragment>');
+ };
+ mat.customProgramCacheKey = () => 'bldglow2' + (sway ? 'S' : '') + (extraF ? 'X' : '') + keyBase.length;
+ return mat;
+ }
+ const meshes = [];
+ function addMesh(b, mat, { glow = true, translucent = false, cast = true, receive = true, gain = 1 } = {}) {
+ if (!b.count) return null;
+ const m = new THREE.Mesh(b.geometry(glow ? computeGlow(b, translucent, gain) : null), mat);
+ m.castShadow = cast; m.receiveShadow = receive; m.matrixAutoUpdate = false;
+ group.add(m); meshes.push(m);
+ return m;
+ }
+ const mConc = Mats.concrete({ color: 0x9a968e, w: { streak: 0.36, dirt: 0.42, moss: 0.2, grain: 0.9, wet: 0.2 } }); mConc.vertexColors = true; addGlow(mConc, false, CONC_F);
+ const mCore = Mats.concreteDark({ color: 0x17181a, w: { streak: 0.3, moss: 0.2 } });
+ const mPaint = Mats.paint({ color: 0xffffff, w: { chip: 0.3, rust: 0.34, streak: 0.8, dirt: 0.7 } }); mPaint.vertexColors = true; addGlow(mPaint);
+ const mMetal = Mats.steel({ color: 0xffffff, w: { rust: 0.5 } }); mMetal.vertexColors = true; mMetal.metalness = 0.6; addGlow(mMetal);
+ const mTar = Mats.concreteDark({ color: 0x2b2d30, w: { wet: 0.75, moss: 0.5, streak: 0, dirt: 0.9 } }); mTar.roughness = 0.8; mTar.vertexColors = true;
+ const mCloth = addGlow(new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: 0.92, side: THREE.DoubleSide }));
+ const mLaundry = addGlow(new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: 0.9, side: THREE.DoubleSide }), true);
+ const mPlant = addGlow(new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: 0.85 }));
+ const mWire = new THREE.MeshStandardMaterial({ color: 0xffffff, vertexColors: true, roughness: 0.6 });
+
+ addMesh(conc, mConc, { gain: 3.6 });
+ addMesh(core, mCore, { glow: false });
+ addMesh(paint, mPaint, { gain: 2.6 });
+ addMesh(metal, mMetal, { gain: 2.6 });
+ addMesh(tar, mTar, { glow: false });
+ addMesh(cloth, mCloth, { translucent: true, gain: 3.0, cast: false });
+ addMesh(laundry, mLaundry, { translucent: true, gain: 0.9 });
+ addMesh(plant, mPlant, { gain: 1.4, cast: false });
+ addMesh(wire, mWire, { glow: false, cast: false, receive: false });
+ addMesh(emis, new THREE.MeshBasicMaterial({ color: 0xffffff, vertexColors: true }), { glow: false, cast: false, receive: false });
+ addMesh(puddle, new THREE.MeshStandardMaterial({ color: 0x07090b, roughness: 0.03, metalness: 0.0, envMapIntensity: 1.6 }), { glow: false, cast: false, receive: true });
+
+ // weathering decals (multiply blend; fog is applied later from depth, so this simply darkens / tints the surface)
+ if (decal.count) {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(decal.pos), 3));
+ g.setAttribute('aUV', new THREE.BufferAttribute(new Float32Array(decal.uv), 4));
+ g.setAttribute('aPar', new THREE.BufferAttribute(new Float32Array(decal.par), 4));
+ g.setAttribute('aCol', new THREE.BufferAttribute(new Float32Array(decal.col), 3));
+ g.setIndex(new THREE.BufferAttribute(new Uint32Array(decal.idx), 1));
+ g.computeBoundingSphere();
+ const mDecal = new THREE.ShaderMaterial({
+ transparent: true, depthWrite: false, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4,
+ blending: THREE.CustomBlending, blendEquation: THREE.AddEquation, blendSrc: THREE.ZeroFactor, blendDst: THREE.SrcColorFactor,
+ blendSrcAlpha: THREE.ZeroFactor, blendDstAlpha: THREE.OneFactor,
+ vertexShader: /* glsl */`
+ attribute vec4 aUV; attribute vec4 aPar; attribute vec3 aCol;
+ varying vec4 vUV; varying vec4 vPar; varying vec3 vCol;
+ void main(){ vUV = aUV; vPar = aPar; vCol = aCol; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`,
+ fragmentShader: /* glsl */`
+ precision highp float;
+ varying vec4 vUV; varying vec4 vPar; varying vec3 vCol;
+ float h2(vec2 p){ p = fract(p * vec2(0.1031, 0.1030)); p += dot(p, p.yx + 33.33); return fract((p.x + p.y) * p.y); }
+ float vn(vec2 x){ vec2 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(h2(i), h2(i + vec2(1, 0)), f.x), mix(h2(i + vec2(0, 1)), h2(i + vec2(1, 1)), f.x), f.y); }
+ void main(){
+ float type = vPar.x, seed = vPar.y, k = vPar.z;
+ vec2 uv = vUV.xy; vec2 m = uv * vUV.zw;
+ float ex = smoothstep(0.0, 0.07, uv.x) * smoothstep(1.0, 0.93, uv.x);
+ float mask = 0.0;
+ if (type < 0.5) { // fine drip streaks
+ float len = 0.12 + 0.88 * pow(vn(vec2(m.x * 8.0 + seed * 13.0, seed)), 1.7);
+ float fine = 0.5 + 0.5 * vn(vec2(m.x * 42.0 + seed, m.y * 1.1 + seed));
+ mask = smoothstep(len, len * 0.2, uv.y) * fine * ex * (0.55 + 0.45 * vn(vec2(m.x * 2.2 + seed * 3.0, m.y * 0.6)));
+ } else if (type < 1.5) { // broad soak / rising damp with a ragged tide line
+ float len = 0.22 + 0.78 * vn(vec2(m.x * 0.8 + seed * 13.0, seed));
+ len *= 0.72 + 0.28 * vn(vec2(m.x * 5.5 + seed, seed * 2.0));
+ float body = smoothstep(len, len * 0.3, uv.y);
+ float tide = smoothstep(len * 1.02, len * 0.9, uv.y) * smoothstep(len * 0.72, len * 0.9, uv.y);
+ mask = (body * (0.6 + 0.4 * vn(m * vec2(11.0, 1.6) + seed)) + 0.35 * tide) * ex;
+ } else if (type < 2.5) { // hairline crack
+ float cx = 0.5 + (vn(vec2(m.y * 2.1 + seed * 7.0, seed)) - 0.5) * 0.7 + (vn(vec2(m.y * 13.0 + seed, 3.0)) - 0.5) * 0.10;
+ float d = abs(uv.x - cx) * vUV.z, aa = fwidth(d);
+ float wd = 0.003 + 0.004 * vn(vec2(m.y * 5.0, seed));
+ mask = (1.0 - smoothstep(wd, wd + 0.004 + aa, d)) * clamp(wd * 3.0 / (aa + 1e-4), 0.0, 1.0) * smoothstep(0.0, 0.08, uv.y) * smoothstep(1.0, 0.8, uv.y);
+ mask += 0.25 * (1.0 - smoothstep(0.0, 0.05, d)) * smoothstep(1.0, 0.6, uv.y) * vn(m * vec2(30.0, 3.0));
+ } else { // trowelled repair patch
+ vec2 q = abs(uv - 0.5) * 2.0;
+ float e = max(q.x, q.y) + (vn(m * 7.0 + seed) - 0.5) * 0.22;
+ mask = (1.0 - smoothstep(0.76, 0.84, e)) * (0.75 + 0.25 * vn(m * vec2(26.0, 5.0) + seed));
+ }
+ gl_FragColor = vec4(mix(vec3(1.0), vCol, clamp(mask * k, 0.0, 1.0)), 1.0);
+ }`,
+ });
+ const dm = new THREE.Mesh(g, mDecal); dm.renderOrder = 2; dm.matrixAutoUpdate = false; dm.frustumCulled = false; group.add(dm);
+ }
+
+ // loggia glazing: dirty reflective glass (premultiplied alpha)
+ const SKY_U = { uZenith: { value: LOOK.zenith }, uHorizon: { value: LOOK.horizon } };
+ const mGlass = new THREE.ShaderMaterial({
+ uniforms: { ...SKY_U }, transparent: true, depthWrite: false, side: THREE.DoubleSide,
+ blending: THREE.CustomBlending, blendSrc: THREE.OneFactor, blendDst: THREE.OneMinusSrcAlphaFactor,
+ vertexShader: /* glsl */`
+ varying vec3 vWP; varying vec3 vWN; varying vec3 vL; varying float vSeed;
+ attribute vec3 color;
+ void main(){ vec4 wp = modelMatrix * vec4(position, 1.0); vWP = wp.xyz; vWN = normalize(mat3(modelMatrix) * normal); vL = position; vSeed = color.r;
+ gl_Position = projectionMatrix * viewMatrix * wp; }`,
+ fragmentShader: /* glsl */`
+ precision highp float;
+ varying vec3 vWP; varying vec3 vWN; varying vec3 vL; varying float vSeed;
+ uniform vec3 uZenith, uHorizon;
+ float h3(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.yzx + 33.33); return fract((p.x + p.y) * p.z); }
+ float vn(vec3 x){ vec3 i = floor(x), f = fract(x); f = f*f*(3.0-2.0*f);
+ return mix(mix(mix(h3(i), h3(i+vec3(1,0,0)), f.x), mix(h3(i+vec3(0,1,0)), h3(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(h3(i+vec3(0,0,1)), h3(i+vec3(1,0,1)), f.x), mix(h3(i+vec3(0,1,1)), h3(i+vec3(1,1,1)), f.x), f.y), f.z); }
+ void main(){
+ vec3 V = normalize(vWP - cameraPosition); vec3 N = normalize(vWN); if (dot(N, V) > 0.0) N = -N;
+ vec3 Rf = reflect(V, N);
+ vec3 sky = mix(uHorizon, uZenith, 1.0 - exp(-max(Rf.y, 0.0) * 3.2));
+ sky = mix(sky, vec3(0.008, 0.014, 0.018), smoothstep(0.02, -0.3, Rf.y));
+ float F = 0.05 + 0.95 * pow(1.0 - max(dot(-V, N), 0.0), 5.0);
+ float dirt = 0.10 + 0.30 * vn(vL * vec3(2.3, 0.6, 2.3) + vSeed * 7.0) + 0.15 * vn(vL * 9.0);
+ vec3 c = sky * F * 1.5 + vec3(0.022, 0.03, 0.042) * dirt;
+ gl_FragColor = vec4(c, clamp(F * 0.75 + dirt * 0.8, 0.0, 0.95));
+ }`,
+ });
+ if (glass.count) { const gm = new THREE.Mesh(glass.geometry(null), mGlass); gm.renderOrder = 5; gm.matrixAutoUpdate = false; group.add(gm); }
+
+ // ------------------------------------------------------------------ interior-mapped windows
+ const winMat = new THREE.ShaderMaterial({
+ uniforms: { ...SKY_U, uTime: uT, uGain: { value: 2.2 } },
+ vertexShader: /* glsl */`
+ attribute vec4 aA; attribute vec3 aTint;
+ varying vec2 vP; varying vec3 vDir; varying vec2 vSize; varying vec4 vA; varying vec3 vTint; varying vec3 vWN; varying vec3 vWV;
+ void main(){
+ mat4 mm = modelMatrix * instanceMatrix;
+ vec3 cx = mm[0].xyz, cy = mm[1].xyz;
+ float sx = length(cx), sy = length(cy);
+ vec3 ex = cx / sx, ey = cy / sy, ez = normalize(cross(ex, ey));
+ vec4 wp = mm * vec4(position, 1.0);
+ vec3 V = wp.xyz - cameraPosition;
+ vDir = vec3(dot(V, ex), dot(V, ey), dot(V, ez));
+ vP = position.xy * vec2(sx, sy); vSize = vec2(sx, sy);
+ vA = aA; vTint = aTint; vWN = ez; vWV = V;
+ gl_Position = projectionMatrix * viewMatrix * wp;
+ }`,
+ fragmentShader: /* glsl */`
+ precision highp float;
+ varying vec2 vP; varying vec3 vDir; varying vec2 vSize; varying vec4 vA; varying vec3 vTint; varying vec3 vWN; varying vec3 vWV;
+ uniform vec3 uZenith, uHorizon; uniform float uTime, uGain;
+ float h1(float s, float k){ return fract(sin(s * 127.1 + k * 311.7) * 43758.5453); }
+ void main(){
+ float seed = vA.x, lit = vA.y, curtain = vA.z, kind = vA.w;
+ vec3 d = normalize(vDir); d.z = min(d.z, -0.03); d = normalize(d);
+ vec2 hs = vSize * 0.5;
+ float tall = step(1.9, vSize.y);
+ float xc = (h1(seed, 1.0) - 0.5) * 1.6;
+ float hw = hs.x + abs(xc) + 0.25 + h1(seed, 2.0) * 0.9;
+ float top = hs.y + 0.42, bot = -hs.y - mix(0.92, 0.1, tall);
+ float D = 2.7 + h1(seed, 3.0) * 2.2;
+ if (kind > 1.5 && kind < 2.5) { D = 2.2; xc = 0.0; hw = 1.35; top = hs.y + 0.9; bot = -hs.y - 1.4; }
+ vec3 o = vec3(vP, 0.0);
+ float tx = abs(d.x) < 1e-4 ? 1e5 : ((d.x > 0.0 ? xc + hw : xc - hw) - o.x) / d.x;
+ float ty = abs(d.y) < 1e-4 ? 1e5 : ((d.y > 0.0 ? top : bot) - o.y) / d.y;
+ float tz = -D / d.z;
+ float t = min(tx, min(ty, tz));
+ vec3 P = o + d * t;
+ vec3 n; vec3 alb; vec3 extra = vec3(0.0);
+ float wsel = h1(seed, 5.0);
+ vec3 wallCol = wsel < 0.3 ? vec3(0.78, 0.70, 0.55) : wsel < 0.55 ? vec3(0.66, 0.70, 0.58) : wsel < 0.8 ? vec3(0.80, 0.70, 0.56) : vec3(0.66, 0.68, 0.66);
+ float flat_ = (kind < 0.5 || kind > 2.5) ? 1.0 : 0.0;
+ if (t == tz) {
+ n = vec3(0.0, 0.0, 1.0); alb = wallCol * (0.92 + 0.08 * sin(P.x * 30.0));
+ float bx = P.x - (xc - hw), by = P.y - bot;
+ float w0 = h1(seed, 11.0) * (2.0 * hw - 1.4);
+ if (flat_ > 0.5) {
+ // wall carpet
+ float c0 = h1(seed, 12.0) * (2.0 * hw - 1.7);
+ if (h1(seed, 13.0) < 0.42 && bx > c0 && bx < c0 + 1.7 && by > 0.95 && by < 2.25)
+ { vec2 cp = vec2(bx - c0 - 0.85, by - 1.6); float dm = abs(fract(cp.x * 2.6) - 0.5) + abs(fract(cp.y * 2.6) - 0.5);
+ float bd = step(0.74, abs(cp.x)) + step(0.56, abs(cp.y));
+ alb = mix(vec3(0.30, 0.085, 0.06), vec3(0.42, 0.24, 0.12), smoothstep(0.30, 0.42, dm)); alb = mix(alb, vec3(0.16, 0.06, 0.045), min(bd, 1.0)); }
+ // framed picture / clock
+ float p0 = h1(seed, 33.0) * (2.0 * hw - 0.6);
+ if (h1(seed, 34.0) < 0.5 && bx > p0 && bx < p0 + 0.5 && by > 1.45 && by < 1.85)
+ alb = (abs(bx - p0 - 0.25) > 0.21 || abs(by - 1.65) > 0.16) ? vec3(0.12, 0.07, 0.04) : vec3(0.5, 0.55, 0.5) * (0.6 + 0.4 * h1(floor(bx * 9.0), floor(by * 9.0) + seed));
+ // bookshelf / wall unit with rows of spines
+ float s0 = h1(seed, 31.0) * (2.0 * hw - 1.3);
+ if (h1(seed, 32.0) < 0.55 && bx > s0 && bx < s0 + 1.3 && by > 0.05 && by < 1.75) {
+ float row = floor(by / 0.42), fy = fract(by / 0.42);
+ float bk = floor(bx * 24.0 + row * 7.0);
+ vec3 bc = vec3(0.16) + 0.42 * vec3(h1(bk, seed), h1(bk, seed + 1.0) * 0.7, h1(bk, seed + 2.0) * 0.5);
+ bc *= step(h1(bk, seed + 5.0) * 0.25 + 0.12, 1.0 - fy);
+ alb = (fy > 0.86 || row < 0.5) ? vec3(0.20, 0.115, 0.06) : bc;
+ if (abs(bx - s0 - 0.65) > 0.62) alb = vec3(0.17, 0.095, 0.05);
+ }
+ // wardrobe
+ if (bx > w0 && bx < w0 + 1.3 && by < 2.0) alb = vec3(0.19, 0.105, 0.055) * (0.75 + 0.25 * step(0.02, abs(bx - w0 - 0.65))) * (0.9 + 0.1 * step(0.06, abs(by - 1.0)));
+ // TV on a stand
+ float tv0 = h1(seed, 35.0) * (2.0 * hw - 0.8);
+ if ((h1(seed, 36.0) < 0.3 || kind > 2.5) && bx > tv0 && bx < tv0 + 0.8 && by < 1.05) {
+ alb = vec3(0.07, 0.05, 0.04);
+ if (by > 0.52 && by < 0.98 && abs(bx - tv0 - 0.4) < 0.33) { alb = vec3(0.02);
+ float f = floor(uTime * 6.0); extra = mix(vec3(0.22, 0.42, 1.0), vec3(0.65, 0.78, 1.0), h1(seed + 3.0, f)) * (0.5 + 0.5 * h1(seed, f)) * (0.7 + 0.3 * sin(by * 160.0)); }
+ }
+ } else if (by < 1.5) alb = vec3(0.22, 0.36, 0.30);
+ } else if (t == tx) {
+ n = vec3(-sign(d.x), 0.0, 0.0); alb = wallCol * 0.92;
+ if (kind > 1.5 && kind < 2.5 && (P.y - bot) < 1.5) alb = vec3(0.22, 0.36, 0.30);
+ else if (flat_ > 0.5) { // door / cupboard on a side wall
+ float dz = -P.z - D * (0.25 + 0.4 * h1(seed, 37.0));
+ if (h1(seed, 38.0) < 0.6 && dz > 0.0 && dz < 0.85 && (P.y - bot) < 2.02) alb = vec3(0.34, 0.25, 0.16) * (0.8 + 0.2 * step(0.05, abs(dz - 0.42)));
+ }
+ } else if (d.y > 0.0) { n = vec3(0.0, -1.0, 0.0); alb = vec3(0.82, 0.80, 0.74); }
+ else { n = vec3(0.0, 1.0, 0.0); alb = vec3(0.30, 0.18, 0.10);
+ // rug on the floor
+ if (flat_ > 0.5 && h1(seed, 39.0) < 0.5 && abs(P.x - xc) < hw * 0.6 && -P.z > D * 0.25 && -P.z < D * 0.85) alb = mix(vec3(0.32, 0.10, 0.07), vec3(0.36, 0.26, 0.14), step(0.5, fract(P.x * 3.0)) * step(0.5, fract(P.z * 3.0))); }
+ vec3 lamp = vec3(xc + (h1(seed, 4.0) - 0.5) * 0.8, top - 0.34, -D * 0.5);
+ vec3 Lv = lamp - P; float l2 = dot(Lv, Lv);
+ float ndl = max(dot(n, Lv * inversesqrt(l2)), 0.0);
+ float lsel = h1(seed, 17.0);
+ float E = (0.13 + 1.0 * ndl) / (0.30 + 0.42 * l2);
+ // table / floor lamp in a corner
+ float tl = step(h1(seed, 41.0), 0.4) * flat_;
+ vec3 lamp2 = vec3(xc + (h1(seed, 42.0) < 0.5 ? -1.0 : 1.0) * (hw - 0.45), bot + 1.05 + 0.5 * h1(seed, 43.0), -D * (0.55 + 0.35 * h1(seed, 44.0)));
+ vec3 Lv2 = lamp2 - P; float l22 = dot(Lv2, Lv2);
+ float E2 = tl * (0.1 + 0.9 * max(dot(n, Lv2 * inversesqrt(l22)), 0.0)) / (0.25 + 1.6 * l22);
+ // a room lit only by its lamp / TV
+ float dimRoom = step(h1(seed, 45.0), 0.22) * max(tl, step(2.5, kind));
+ E = E * (1.0 - 0.85 * dimRoom) + E2 * 0.9;
+ vec3 room = alb * E;
+ // visible ceiling lamp: bare bulb / fabric shade / three-arm chandelier
+ vec3 oc = o - lamp; float bq = dot(oc, d); float dd = dot(oc, oc) - bq * bq;
+ float vis = step(0.0, -bq) * (1.0 - 0.9 * dimRoom);
+ if (lsel < 0.38) room += vec3(1.0, 0.92, 0.75) * exp(-dd / 0.02) * vis * 2.6;
+ else if (lsel < 0.72) { vec3 pc_ = oc - d * bq; float sh = exp(-(pc_.x * pc_.x + pc_.z * pc_.z + pc_.y * pc_.y * 2.6) / 0.05);
+ room += (vec3(1.0, 0.60, 0.26) * sh * 1.25 + vec3(1.0, 0.9, 0.7) * exp(-dd / 0.006) * 1.2) * vis; }
+ else for (int i = 0; i < 3; i++) { vec3 o3 = oc - vec3((float(i) - 1.0) * 0.24, (i == 1 ? 0.07 : 0.0), 0.0); float b3 = dot(o3, d); room += vec3(1.0, 0.9, 0.72) * exp(-(dot(o3, o3) - b3 * b3) / 0.008) * vis * 2.0; }
+ { vec3 o2 = o - lamp2; float b2 = dot(o2, d); vec3 p2 = o2 - d * b2;
+ room += tl * step(0.0, -b2) * vec3(1.0, 0.66, 0.30) * exp(-(p2.x * p2.x + p2.z * p2.z + p2.y * p2.y * 1.6) / 0.03) * 1.5; }
+ float occ = 1.0;
+ if (kind < 0.5) {
+ // standing figure
+ if (h1(seed, 21.0) < 0.09) {
+ vec3 q = o + d * (1.3 / -d.z); float sx = xc + (h1(seed, 22.0) - 0.5) * 1.0;
+ vec2 qb = vec2(q.x - sx, q.y - (bot + 1.02));
+ float body = 1.0 - smoothstep(0.92, 1.05, length(qb / vec2(0.25, 0.50)));
+ float neck = (1.0 - smoothstep(0.045, 0.065, abs(qb.x))) * step(0.3, qb.y) * step(qb.y, 0.56);
+ float head = 1.0 - smoothstep(0.10, 0.125, length(vec2(qb.x, (qb.y - 0.64) * 0.85)));
+ occ *= 1.0 - 0.82 * max(body, max(neck, head));
+ } else if (h1(seed, 21.0) < 0.14) { // someone at the window: head and shoulders
+ vec3 q = o + d * (0.45 / -d.z); vec2 qb = vec2(q.x - (h1(seed, 22.0) - 0.5) * hs.x, q.y + hs.y - 0.42);
+ float sh = (1.0 - smoothstep(0.9, 1.05, length(vec2(qb.x / 0.27, (qb.y + 0.25) / 0.36)))) * step(qb.y, 0.12);
+ float head = 1.0 - smoothstep(0.105, 0.125, length(vec2(qb.x, (qb.y - 0.2) * 0.88)));
+ occ *= 1.0 - 0.85 * max(sh, head);
+ }
+ // plants on the sill
+ if (h1(seed, 23.0) < 0.45) {
+ vec3 q = o + d * (0.3 / -d.z);
+ for (int i = 0; i < 3; i++) {
+ float fi = float(i);
+ vec2 c = vec2((h1(seed, 24.0 + fi) - 0.5) * vSize.x * 0.8, -hs.y + 0.12 + 0.16 * h1(seed, 27.0 + fi));
+ float r = 0.14 + 0.12 * h1(seed, 30.0 + fi);
+ float a = atan(q.y - c.y, q.x - c.x);
+ float leaf = 1.0 - smoothstep(0.85, 1.0, length(q.xy - c) / (r * (0.8 + 0.2 * sin(a * 5.0 + seed + fi))));
+ float pot = step(abs(q.x - c.x), 0.07) * step(q.y, c.y) ;
+ occ *= 1.0 - 0.8 * max(leaf, pot);
+ }
+ }
+ }
+ room *= occ; extra *= occ;
+ // sheer tulle just behind the glass, heavier side curtains a little deeper (they parallax against each other)
+ vec3 qt = o + d * (0.07 / -d.z);
+ vec3 qc = o + d * (0.20 / -d.z);
+ float cx = qc.x / hs.x + 0.035 * sin(qc.y * 5.0 + seed) * (0.4 + 0.6 * smoothstep(hs.y, -hs.y, qc.y));
+ float covL = curtain * (0.1 + 0.8 * h1(seed, 7.0)), covR = curtain * (0.1 + 0.8 * h1(seed, 8.0));
+ float covered = max(step(cx, -1.0 + covL), step(1.0 - covR, cx));
+ float tulle = step(h1(seed, 9.0), 0.62) * step(0.01, curtain);
+ if (h1(seed, 14.0) < 0.3) tulle *= step(qt.x / hs.x, -0.3 + 1.1 * h1(seed, 15.0));
+ float tfold = 0.5 + 0.5 * sin(qt.x * 52.0 + 2.5 * sin(qt.y * 1.7 + seed));
+ float lace = step(qt.y, -hs.y + 0.32) * (0.5 + 0.5 * sin(qt.x * 110.0) * sin(qt.y * 110.0));
+ float tOp = tulle * clamp(0.44 + 0.12 * tfold + 0.25 * lace, 0.0, 0.92);
+ float folds = 0.76 + 0.24 * sin(qc.x * (20.0 + 26.0 * h1(seed, 18.0)) + 1.8 * sin(qc.y * 2.3 + seed)) * (0.8 + 0.2 * sin(qc.x * 97.0));
+ float fsel = h1(seed, 10.0);
+ vec3 fcol = fsel < 0.35 ? vec3(0.90, 0.84, 0.72) : fsel < 0.55 ? vec3(0.90, 0.70, 0.46) : fsel < 0.70 ? vec3(0.88, 0.76, 0.54) : fsel < 0.84 ? vec3(0.72, 0.50, 0.36) : fsel < 0.93 ? vec3(0.60, 0.66, 0.54) : vec3(0.50, 0.44, 0.40);
+ float lvl = 0.75 + 0.5 * h1(seed, 16.0);
+ vec3 curtRad = fcol * folds * (0.50 + 0.3 * smoothstep(-hs.y, hs.y, qc.y)) * lvl * (1.0 - 0.6 * dimRoom);
+ vec3 tulleRad = vec3(0.95, 0.90, 0.80) * (0.40 + 0.09 * tfold) * lvl * (1.0 - 0.6 * dimRoom);
+ vec3 colLit = room;
+ colLit = mix(colLit, tulleRad, tOp);
+ colLit = mix(colLit, curtRad, covered);
+ vec3 tint = vTint;
+ if (kind > 2.5) { // TV flicker
+ float f = floor(uTime * 7.0); float fl = 0.55 + 0.45 * h1(seed, f) ;
+ tint = mix(vec3(0.25, 0.45, 1.0), vec3(0.7, 0.8, 1.0), h1(seed + 3.0, f)) * fl;
+ }
+ colLit *= tint * lit * uGain;
+ colLit += extra * (1.0 - covered) * (1.0 - 0.6 * tOp) * 1.6 * step(0.01, lit);
+ float tulle_ = tOp;
+ // unlit: dim sky-lit interior, curtains barely visible
+ vec3 colDark = alb * vec3(0.006, 0.009, 0.016);
+ colDark = mix(colDark, vec3(0.022, 0.030, 0.048) * folds * dot(fcol, vec3(0.4)), max(covered, tulle * 0.6));
+ vec3 col = mix(colDark, colLit, step(0.01, lit));
+ // glass
+ vec3 V = normalize(vWV); vec3 N = normalize(vWN);
+ vec3 Rf = reflect(V, N);
+ vec3 sky = mix(uHorizon, uZenith, 1.0 - exp(-max(Rf.y, 0.0) * 3.2));
+ sky = mix(sky, vec3(0.008, 0.014, 0.018), smoothstep(0.02, -0.3, Rf.y));
+ float F = 0.045 + 0.955 * pow(1.0 - max(dot(-V, N), 0.0), 5.0);
+ float ed = max(abs(vP.x) / hs.x, abs(vP.y) / hs.y);
+ float dirt = 0.05 + 0.25 * smoothstep(0.55, 1.0, ed) * (0.5 + 0.5 * h1(seed, 40.0));
+ col = col * (1.0 - F) * (1.0 - dirt * 0.7) + sky * F * 1.5 + vec3(0.02, 0.028, 0.04) * dirt;
+ gl_FragColor = vec4(col, 1.0);
+ }`,
+ });
+ {
+ const n = winM.length;
+ const geo = new THREE.PlaneGeometry(1, 1);
+ geo.setAttribute('aA', new THREE.InstancedBufferAttribute(new Float32Array(winA), 4));
+ geo.setAttribute('aTint', new THREE.InstancedBufferAttribute(new Float32Array(winT), 3));
+ const im = new THREE.InstancedMesh(geo, winMat, n);
+ for (let i = 0; i < n; i++) im.setMatrixAt(i, winM[i]);
+ im.instanceMatrix.needsUpdate = true;
+ im.frustumCulled = false; im.matrixAutoUpdate = false;
+ group.add(im);
+ }
+
+ // beacons
+ const beaconMat = new THREE.MeshBasicMaterial({ color: new THREE.Color(3.2, 0.14, 0.08) });
+ if (beacons.length) {
+ const bm = new THREE.InstancedMesh(new THREE.SphereGeometry(0.13, 10, 8), beaconMat, beacons.length);
+ beacons.forEach((p, i) => bm.setMatrixAt(i, _m1.makeTranslation(p[0], p[1] + 0.25, p[2])));
+ bm.frustumCulled = false; group.add(bm);
+ }
+
+ let _tris = 0; group.traverse((o) => { if (o.geometry) _tris += (o.geometry.index ? o.geometry.index.count : o.geometry.attributes.position.count) / 3 * (o.isInstancedMesh ? o.count : 1); });
+ if (ctx.Q && ctx.Q.get('bldstats')) console.error('[building] tris=' + Math.round(_tris) + ' meshes=' + group.children.length + ' windows=' + winM.length + ' lights=' + lights.length + ' decals=' + decal.count / 4 + ' buildMs=' + Math.round(performance.now() - _t0));
+ return {
+ group,
+ stats: { windows: winM.length, lights: lights.length },
+ update(t) {
+ uT.value = t;
+ const pulse = 0.25 + 0.75 * Math.pow(Math.max(0, Math.sin(t * 2.2)), 6.0);
+ beaconMat.color.setRGB(3.2 * pulse, 0.14 * pulse, 0.08 * pulse);
+ },
+ };
+}
diff --git a/src/mods/chassis.js b/src/mods/chassis.js
new file mode 100644
index 0000000..7fc97f3
--- /dev/null
+++ b/src/mods/chassis.js
@@ -0,0 +1,1503 @@
+// CHASSIS: the mechanical belly between the apartment block and the legs.
+// Walker-local frame: x along the block (±45), z across (±8.5), chassis band y ∈ [-4.5, 0] (hangs to ≈ -7).
+// Everything is merged per material bucket (vertex colours carry tint / fake AO), so the whole module is
+// ~20 draw calls. Warm work lamps light the machinery through a cheap per-fragment "fake lamp" term
+// (up to 64 lamp points, no shadows) injected into every chassis material, plus ≤ 6 real PointLights.
+import * as BGU from 'three/addons/utils/BufferGeometryUtils.js';
+
+export async function create(ctx) {
+ const { THREE, walker, CFG, Mats, rng, Q } = ctx;
+ const T0 = performance.now();
+ const R = rng(0xC4A551);
+ const rnd = (a = 0, b = 1) => a + (b - a) * R();
+ const pick = (arr) => arr[Math.floor(R() * arr.length) % arr.length];
+ const V3 = (x, y, z) => new THREE.Vector3(x, y, z);
+ const SS = THREE.MathUtils.smoothstep;
+ const root = new THREE.Group(); root.name = 'chassis';
+ walker.add(root);
+
+ const LEGX = CFG.LEG_X, HY = CFG.HIP_Y, HZ = CFG.HIP_Z;
+ const HIPS = []; for (const hx of LEGX) for (const s of [1, -1]) HIPS.push(V3(hx, HY, s * HZ));
+ const hipHit = (p, r = 0) => HIPS.some((h) => h.distanceTo(p) < 3.25 + r);
+ const LINES = []; for (let i = 0; i <= 16; i++) LINES.push(-44 + 5.5 * i); // structural bay lines
+ const isHipLine = (x) => LEGX.some((hx) => Math.abs(hx - x) < 0.01);
+ const DRUMS = [{ x: 0, r: 4.0, fan: 2.3, big: true }, { x: -22, r: 2.7, fan: 1.5 }, { x: 22, r: 2.7, fan: 1.5 }];
+ // x-ranges of the edge band that are free (not in a hip bay)
+ const EDGE_SEGS = [[-44.6, -37.6], [-28.4, -15.6], [-6.4, 6.4], [15.6, 28.4], [37.6, 44.6]];
+ // x-ranges between the hip yokes (things at |z| > 4.9 stop at the cheek plates: hip recess)
+ const BAY_SEGS = [[-44, -36.7], [-29.3, -14.7], [-7.3, 7.3], [14.7, 29.3], [36.7, 44]];
+
+ // ------------------------------------------------------------------ fake lamp lighting
+ const LAMP_N = 48;
+ const lampU = {
+ uLampP: { value: Array.from({ length: LAMP_N }, () => new THREE.Vector4(0, -1e4, 0, 0.001)) },
+ uLampC: { value: Array.from({ length: LAMP_N }, () => new THREE.Vector3()) },
+ uLampD: { value: Array.from({ length: LAMP_N }, () => new THREE.Vector4(0, -1, 0, -2)) }, // spot dir + cos(outer); w<-1.5 = omni
+ uChsT: { value: 0 },
+ uChsFill: { value: new THREE.Vector3(0.40, 0.37, 0.27) },
+ uChsLampK: { value: 6.0 },
+ };
+ const DRIP_SRC = [];
+ const lamps = []; // {p: Vector3 (local), c: [r,g,b], r: radius, w: priority}
+ const addLight = (p, k = 1, r = 7, w = 1, col = [1.0, 0.46, 0.14], opt = {}) => { const L = { p: p.clone(), c: col.map((v) => v * k), r, w, ...opt }; lamps.push(L); return L; };
+
+ const LAMPV = /* glsl */`
+ {
+ vec4 cLp = vec4(transformed, 1.0); vec3 cLn = objectNormal;
+ #ifdef USE_INSTANCING
+ cLp = instanceMatrix * cLp; cLn = mat3(instanceMatrix) * cLn;
+ #endif
+ vChsP = (modelMatrix * cLp).xyz;
+ vChsN = normalize(mat3(modelMatrix) * cLn);
+ }`;
+ const SWAYV = /* glsl */`
+ transformed.x += aSway.x * sin(uChsT * aSway.z + aSway.y);
+ transformed.z += aSway.x * 0.7 * sin(uChsT * aSway.z * 0.73 + aSway.y * 1.9 + 1.3);
+ transformed.y += aSway.x * 0.12 * sin(uChsT * aSway.z * 1.31 + aSway.y);
+ `;
+ const LAMPF = /* glsl */`
+ {
+ vec3 cN = normalize(vChsN) * (gl_FrontFacing ? 1.0 : -1.0);
+ vec3 cAcc = vec3(0.0);
+ for (int i = 0; i < ${LAMP_N}; i++) {
+ vec4 lp = uLampP[i];
+ vec3 L = lp.xyz - vChsP;
+ float d2 = dot(L, L);
+ float rr = lp.w * lp.w;
+ if (d2 < rr) {
+ float f = 1.0 - d2 / rr; f *= f;
+ float inv = inversesqrt(d2 + 1e-4);
+ float nd = dot(cN, L) * inv;
+ vec4 ld = uLampD[i];
+ float sp = ld.w < -1.5 ? 1.0 : smoothstep(ld.w, ld.w + 0.32, -dot(L, ld.xyz) * inv);
+ cAcc += uLampC[i] * f * sp * (max(nd, 0.0) * 0.88 + 0.12) / (0.5 + d2 * 0.3);
+ }
+ }
+ cAcc *= uChsLampK;
+ // cool bounce from the fog / wet field below (the hemi light alone leaves the belly black)
+ vec3 cFill = uChsFill * (0.35 + 0.65 * max(-cN.y, 0.0));
+ reflectedLight.directDiffuse += (cAcc + cFill) * BRDF_Lambert(material.diffuseColor);
+ reflectedLight.directSpecular += cAcc * material.specularColor * 0.12;
+ }`;
+ // round 2: extra wet grime on top of the shared weathering (mesh-local, uses the shared detail texture):
+ // fine rust-brown run-off on vertical faces, moss + standing water on ledges, soot / oil / damp under faces.
+ const GRIME_DEF = { uGrRust: { value: new THREE.Vector4(0.62, 0.42, 0.3, 0.5) }, uGrMoss: { value: 0.5 }, uGrSoot: { value: 0.6 } };
+ const grime = (mat, r, g, b, a, moss, soot) => { mat.userData.grime = { uGrRust: { value: new THREE.Vector4(r, g, b, a) }, uGrMoss: { value: moss }, uGrSoot: { value: soot } }; return mat; };
+ const GRIMEF = /* glsl */`
+ {
+ vec3 gp = vWp; vec3 gn = normalize(vWn);
+ float gUp = gn.y, gVert = 1.0 - abs(gn.y);
+ vec2 gs = vec2((gp.x + gp.z) * 0.9, gp.y * 0.045);
+ float g1 = texture2D(uWDetail, gs).g;
+ float g2 = texture2D(uWDetail, gs * vec2(0.31, 0.55) + 0.21).r;
+ float gst = smoothstep(0.6, 0.86, g1 * 0.55 + g2 * 0.6) * gVert;
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * uGrRust.rgb, gst * uGrRust.a);
+ float g3 = texture2D(uWDetail, gp.xz * 0.13 + 0.4).a;
+ float g4 = texture2D(uWDetail, gp.xz * 0.047 + 0.13).b;
+ float gl = smoothstep(0.45, 0.9, gUp);
+ float gMoss = gl * smoothstep(0.42, 0.62, g3) * uGrMoss;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.045, 0.07, 0.028) * (0.5 + 1.0 * g1), gMoss);
+ float gPud = gl * smoothstep(0.52, 0.36, g3);
+ diffuseColor.rgb *= 1.0 - 0.5 * gPud;
+ float gd = smoothstep(0.4, 0.9, -gUp);
+ float gSoot = gd * uGrSoot * smoothstep(0.42, 0.7, g4 * 0.7 + g3 * 0.3);
+ diffuseColor.rgb *= 1.0 - 0.45 * gSoot;
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.8, 0.7, 0.55), gd * smoothstep(0.6, 0.8, g3) * uGrSoot);
+ wWetA = max(wWetA, max(gPud * 0.95, gd * smoothstep(0.5, 0.75, g4) * 0.55 + gst * 0.35));
+ }`;
+ function patch(mat, sway = false) {
+ const prev = mat.onBeforeCompile;
+ const prevKey = mat.customProgramCacheKey ? mat.customProgramCacheKey.bind(mat) : null;
+ const hadPrev = !!(mat.userData && mat.userData.weather);
+ mat.onBeforeCompile = (sh, r) => {
+ if (hadPrev && prev) prev(sh, r);
+ Object.assign(sh.uniforms, lampU);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vChsP; varying vec3 vChsN; uniform float uChsT;\n' + (sway ? 'attribute vec3 aSway;\n' : ''))
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\n' + (sway ? SWAYV : '') + LAMPV);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>\nvarying vec3 vChsP; varying vec3 vChsN;\nuniform vec4 uLampP[${LAMP_N}]; uniform vec3 uLampC[${LAMP_N}]; uniform vec4 uLampD[${LAMP_N}]; uniform vec3 uChsFill; uniform float uChsLampK;\n` + (hadPrev ? 'uniform vec4 uGrRust; uniform float uGrMoss, uGrSoot;\n' : ''))
+ .replace('#include <lights_fragment_end>', '#include <lights_fragment_end>\n' + LAMPF);
+ if (hadPrev) {
+ Object.assign(sh.uniforms, mat.userData.grime || GRIME_DEF);
+ sh.fragmentShader = sh.fragmentShader.replace('#include <roughnessmap_fragment>', GRIMEF + '\n#include <roughnessmap_fragment>');
+ }
+ };
+ mat.customProgramCacheKey = () => 'chs2' + (sway ? 's' : '') + (hadPrev && prevKey ? prevKey() : '');
+ return mat;
+ }
+
+ // ------------------------------------------------------------------ materials
+ const grateTex = (() => {
+ const c = document.createElement('canvas'); c.width = c.height = 64;
+ const g = c.getContext('2d');
+ g.fillStyle = '#000'; g.fillRect(0, 0, 64, 64); g.fillStyle = '#fff';
+ for (let i = 0; i < 64; i += 8) g.fillRect(i, 0, 4, 64);
+ for (let j = 0; j < 64; j += 16) g.fillRect(0, j, 64, 4);
+ const t = new THREE.CanvasTexture(c); t.wrapS = t.wrapT = THREE.RepeatWrapping; t.anisotropy = 4;
+ return t;
+ })();
+ const signTex = (() => {
+ const c = document.createElement('canvas'); c.width = 512; c.height = 512;
+ const g = c.getContext('2d');
+ // cell 0: long pale stencil warning plate (was hazard stripes: the look wants none)
+ g.fillStyle = '#b9b7ab'; g.fillRect(0, 0, 256, 128); g.fillStyle = '#23201c'; g.font = 'bold 30px Arial'; g.textAlign = 'center';
+ g.fillText('НЕ СТОЙ ПОД', 128, 52); g.fillText('ШАРНИРОМ', 128, 96); g.strokeStyle = '#23201c'; g.lineWidth = 4; g.strokeRect(8, 8, 240, 112);
+ // cell 1: red danger plate
+ g.fillStyle = '#9a1f17'; g.fillRect(256, 0, 256, 128); g.fillStyle = '#e8e2d0'; g.font = 'bold 54px Arial'; g.textAlign = 'center';
+ g.fillText('ОПАСНО', 384, 84); g.strokeStyle = '#e8e2d0'; g.lineWidth = 6; g.strokeRect(266, 10, 236, 108);
+ // cell 2: white stencil number plate
+ g.fillStyle = '#d8d6cc'; g.fillRect(0, 128, 256, 128); g.fillStyle = '#1b1b1b'; g.font = 'bold 72px Arial';
+ g.fillText('Ж-4', 128, 218);
+ // cell 3: yellow high-voltage
+ g.fillStyle = '#d0a92a'; g.fillRect(256, 128, 256, 128); g.fillStyle = '#121212';
+ g.beginPath(); g.moveTo(300, 236); g.lineTo(344, 148); g.lineTo(388, 236); g.closePath(); g.fill();
+ g.fillStyle = '#d0a92a'; g.beginPath(); g.moveTo(348, 166); g.lineTo(334, 200); g.lineTo(346, 200); g.lineTo(338, 226); g.lineTo(358, 190); g.lineTo(346, 190); g.closePath(); g.fill();
+ g.fillStyle = '#121212'; g.font = 'bold 30px Arial'; g.textAlign = 'left'; g.fillText('380 В', 402, 204);
+ // row 2: cell 4 stencil block id, cell 5 blue instruction plate
+ g.textAlign = 'center';
+ g.fillStyle = '#8f9189'; g.fillRect(0, 256, 256, 128); g.fillStyle = '#1a1a18'; g.font = 'bold 44px Arial';
+ g.fillText('БЛОК 7', 128, 318); g.font = 'bold 26px Arial'; g.fillText('СЕКЦИЯ Г-12', 128, 360);
+ g.fillStyle = '#27456b'; g.fillRect(256, 256, 256, 128); g.fillStyle = '#d9d6c8'; g.font = 'bold 30px Arial';
+ g.fillText('НЕ ВКЛЮЧАТЬ', 384, 312); g.fillText('РАБОТАЮТ ЛЮДИ', 384, 352);
+ // row 3: cell 6 gauge dials, cell 7 arrow + ВЫХОД
+ g.fillStyle = '#2a2b2a'; g.fillRect(0, 384, 256, 128);
+ for (const gx of [64, 192]) {
+ g.fillStyle = '#d6d2c2'; g.beginPath(); g.arc(gx, 448, 52, 0, 6.3); g.fill();
+ g.strokeStyle = '#141414'; g.lineWidth = 3;
+ for (let a = 0.75 * Math.PI; a <= 2.26 * Math.PI; a += 0.15 * Math.PI) { g.beginPath(); g.moveTo(gx + Math.cos(a) * 40, 448 + Math.sin(a) * 40); g.lineTo(gx + Math.cos(a) * 49, 448 + Math.sin(a) * 49); g.stroke(); }
+ g.strokeStyle = '#8a1a12'; g.lineWidth = 5; g.beginPath(); g.arc(gx, 448, 45, 1.9 * Math.PI, 2.25 * Math.PI); g.stroke();
+ g.strokeStyle = '#141414'; g.lineWidth = 4; const na = gx < 100 ? 1.35 * Math.PI : 1.8 * Math.PI;
+ g.beginPath(); g.moveTo(gx, 448); g.lineTo(gx + Math.cos(na) * 40, 448 + Math.sin(na) * 40); g.stroke();
+ g.fillStyle = '#141414'; g.beginPath(); g.arc(gx, 448, 6, 0, 6.3); g.fill();
+ }
+ g.fillStyle = '#2d5a3a'; g.fillRect(256, 384, 256, 128); g.fillStyle = '#dcd9cc'; g.font = 'bold 46px Arial';
+ g.fillText('ВЫХОД', 364, 464); g.beginPath(); g.moveTo(500, 448); g.lineTo(468, 424); g.lineTo(468, 472); g.closePath(); g.fill();
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
+ return t;
+ })();
+
+ const MAT = {
+ concrete: grime(Mats.concreteDark({ color: 0x7a7c7e, w: { offset: V3(13, 2, 7), moss: 0.42, streak: 1.0, dirt: 0.9, wet: 0.4, bump: 0.018 } }), 0.6, 0.47, 0.36, 0.55, 0.75, 0.5),
+ steel: grime(Mats.steel({ color: 0x43474c, w: { rust: 0.14, dirt: 0.85, streak: 0.8, offset: V3(3, 1, 9) } }), 0.62, 0.36, 0.24, 0.42, 0.3, 0.5),
+ rust: Mats.rust({ color: 0x3f2c20, w: { rust: 0.55, offset: V3(7, 3, 1) } }),
+ paint: grime(Mats.paintedMetal({ color: 0x9a9c96, w: { rust: 0.26, chip: 0.38, dirt: 0.9, moss: 0.12, offset: V3(5, 8, 2) } }), 0.6, 0.36, 0.24, 0.7, 0.45, 0.6),
+ steelS: Mats.steel({ color: 0x4a4e53, w: { rust: 0.12, offset: V3(1, 7, 3) } }),
+ rustS: Mats.rust({ color: 0x45301f, w: { rust: 0.5, offset: V3(9, 9, 4) } }),
+ paintS: Mats.paintedMetal({ color: 0x9fa19b, w: { rust: 0.22, chip: 0.3, offset: V3(2, 2, 8) } }),
+ chrome: Mats.chrome(),
+ rubber: Mats.rubber({ color: 0x111214 }),
+ sway: Mats.rubber({ color: 0x0f1012 }),
+ grate: Mats.steel({ color: 0x4a4d50, w: { rust: 0.3, offset: V3(4, 4, 4) } }),
+ signs: Mats.paint({ color: 0xffffff, w: { chip: 0.35, rust: 0.4, dirt: 0.75, streak: 0.8, offset: V3(6, 1, 6) } }),
+ glass: new THREE.MeshStandardMaterial({ color: 0x20262c, roughness: 0.12, metalness: 0.5 }),
+ emis: new THREE.MeshBasicMaterial({ vertexColors: true, toneMapped: false }),
+ emisF: new THREE.MeshBasicMaterial({ vertexColors: true, toneMapped: false }), // flickering practicals (colour driven by t)
+ };
+ // multiply-blended grime decals (rust runs, drip sets, oil / soot stains): one draw call, unlit, fog-correct (sits on the surface)
+ const decalTex = (() => {
+ const c = document.createElement('canvas'); c.width = c.height = 512;
+ const g = c.getContext('2d'); const D = rng(0xDECA1); const dr = (a, b) => a + (b - a) * D();
+ g.fillStyle = '#fff'; g.fillRect(0, 0, 512, 512);
+ const streak = (x, y0, w, len, rgb, a) => {
+ const gr = g.createLinearGradient(0, y0, 0, y0 + len);
+ gr.addColorStop(0, `rgba(${rgb},${a})`); gr.addColorStop(0.35, `rgba(${rgb},${a * 0.7})`); gr.addColorStop(1, `rgba(${rgb},0)`);
+ g.fillStyle = gr; g.beginPath(); g.moveTo(x - w / 2, y0); g.lineTo(x + w / 2, y0); g.lineTo(x + w * 0.22, y0 + len); g.lineTo(x - w * 0.22, y0 + len); g.closePath(); g.fill();
+ };
+ g.save(); g.beginPath(); g.rect(6, 0, 244, 250); g.clip(); g.filter = 'blur(2.5px)'; // cell 0: single rust run from a point source
+ for (let i = 0; i < 16; i++) streak(128 + dr(-34, 34) * dr(0.2, 1), 2, dr(6, 34), dr(90, 245), '96,50,24', dr(0.3, 0.7));
+ g.fillStyle = 'rgba(52,26,12,0.85)'; g.beginPath(); g.ellipse(128, 8, 30, 9, 0, 0, 6.3); g.fill();
+ g.restore();
+ g.save(); g.beginPath(); g.rect(262, 0, 244, 250); g.clip(); g.filter = 'blur(2px)'; // cell 1: wet drip set under a leak line
+ for (let i = 0; i < 26; i++) streak(dr(276, 492), 2, dr(5, 22), dr(50, 240), i % 3 ? '30,27,23' : '74,44,24', dr(0.35, 0.8));
+ g.fillStyle = 'rgba(28,25,21,0.7)'; g.fillRect(270, 0, 228, 7);
+ g.restore();
+ g.save(); g.beginPath(); g.rect(6, 262, 244, 244); g.clip(); g.filter = 'blur(5px)'; // cell 2: oil / soot stain
+ for (let i = 0; i < 40; i++) { const a = dr(0, 6.3), r = dr(0, 70) * dr(0.3, 1); g.fillStyle = `rgba(14,12,9,${dr(0.12, 0.4)})`; g.beginPath(); g.ellipse(128 + Math.cos(a) * r, 384 + Math.sin(a) * r, dr(10, 42), dr(10, 42), dr(0, 3), 0, 6.3); g.fill(); }
+ g.filter = 'blur(1.5px)';
+ for (let i = 0; i < 60; i++) { const a = dr(0, 6.3), r = dr(40, 105); g.fillStyle = `rgba(14,12,9,${dr(0.2, 0.6)})`; g.beginPath(); g.arc(128 + Math.cos(a) * r, 384 + Math.sin(a) * r, dr(1, 5), 0, 6.3); g.fill(); }
+ g.restore();
+ g.save(); g.beginPath(); g.rect(262, 262, 244, 244); g.clip(); g.filter = 'blur(3px)'; // cell 3: mottled rust bloom (around bolts, seams)
+ for (let i = 0; i < 70; i++) { const a = dr(0, 6.3), r = dr(0, 95) * dr(0.4, 1); g.fillStyle = `rgba(${i % 4 ? '88,44,20' : '40,22,12'},${dr(0.12, 0.42)})`; g.beginPath(); g.ellipse(384 + Math.cos(a) * r, 384 + Math.sin(a) * r, dr(4, 22), dr(4, 22), dr(0, 3), 0, 6.3); g.fill(); }
+ g.restore();
+ const t = new THREE.CanvasTexture(c); t.colorSpace = THREE.SRGBColorSpace; t.anisotropy = 4;
+ return t;
+ })();
+ const decalMat = new THREE.ShaderMaterial({
+ uniforms: { map: { value: decalTex } },
+ vertexShader: 'attribute vec3 color; varying vec2 vUv; varying float vK;\n#include <common>\n#include <logdepthbuf_pars_vertex>\nvoid main(){ vUv = uv; vK = color.r; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n#include <logdepthbuf_vertex>\n}',
+ fragmentShader: 'uniform sampler2D map; varying vec2 vUv; varying float vK;\n#include <common>\n#include <logdepthbuf_pars_fragment>\nvoid main(){\n#include <logdepthbuf_fragment>\n gl_FragColor = vec4(mix(vec3(1.0), texture2D(map, vUv).rgb, vK), 1.0); }',
+ blending: THREE.MultiplyBlending, transparent: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -4, toneMapped: false,
+ });
+ MAT.grate.alphaMap = grateTex; MAT.grate.alphaTest = 0.5; MAT.grate.side = THREE.DoubleSide;
+ MAT.signs.map = signTex;
+ for (const [k, m] of Object.entries(MAT)) if (k !== 'emis' && k !== 'emisF') { m.vertexColors = true; patch(m, k === 'sway'); }
+ MAT.decal = decalMat;
+
+ // ------------------------------------------------------------------ buckets & geometry helpers
+ const BK = {};
+ const bucket = (name, opt = {}) => (BK[name] = { name, geoms: [], ...opt });
+ bucket('concrete', { cast: true, recv: true });
+ bucket('steel', { cast: true, recv: true });
+ bucket('rust', { cast: true, recv: true });
+ bucket('paint', { cast: true, recv: true });
+ bucket('steelS', { recv: true }); bucket('rustS', { recv: true }); bucket('paintS', { recv: true });
+ bucket('chrome', {}); bucket('rubber', {}); bucket('sway', { sway: true });
+ bucket('grate', { uv: true, planar: true, recv: true }); bucket('signs', { uv: true });
+ bucket('glass', {}); bucket('emis', { noAO: true }); bucket('emisF', { noAO: true }); bucket('decal', { noAO: true, uv: true });
+
+ // fake ambient occlusion baked into vertex colours: deep inside the belly is darker
+ const ao = (x, y, z) => {
+ const depth = SS(-y, 0.6, 6.8);
+ const edge = SS(Math.abs(z), 5.8, 10.0);
+ const end = SS(Math.abs(x), 40.5, 46.0);
+ return 0.36 + 0.64 * Math.min(1, depth * 0.7 + edge * 0.65 + end * 0.6);
+ };
+ function push(bn, g, tint = [1, 1, 1], vary = 0.08) {
+ const b = BK[bn];
+ for (const k of Object.keys(g.attributes)) if (!(k === 'position' || k === 'normal' || (k === 'uv' && b.uv) || (k === 'aSway' && b.sway))) g.deleteAttribute(k);
+ if (!g.index) g = BGU.mergeVertices(g);
+ const pos = g.attributes.position, n = pos.count;
+ if (b.planar) {
+ const uv = new Float32Array(n * 2);
+ for (let i = 0; i < n; i++) { uv[i * 2] = pos.getX(i) / 0.25; uv[i * 2 + 1] = pos.getZ(i) / 0.25; }
+ g.setAttribute('uv', new THREE.BufferAttribute(uv, 2));
+ }
+ const col = new Float32Array(n * 3);
+ const v = b.name === 'decal' ? 1 : 1 + (R() * 2 - 1) * vary;
+ for (let i = 0; i < n; i++) {
+ const a = b.noAO ? 1 : ao(pos.getX(i), pos.getY(i), pos.getZ(i));
+ col[i * 3] = tint[0] * v * a; col[i * 3 + 1] = tint[1] * v * a; col[i * 3 + 2] = tint[2] * v * a;
+ }
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ if (b.sway && !g.attributes.aSway) g.setAttribute('aSway', new THREE.BufferAttribute(new Float32Array(n * 3), 3));
+ b.geoms.push(g);
+ return g;
+ }
+ const pushT = (bn, g, m, tint, vary) => push(bn, g.applyMatrix4(m), tint, vary);
+
+ const UBOX = new THREE.BoxGeometry(1, 1, 1);
+ const cylT = {}; const unitCyl = (seg) => (cylT[seg] ||= new THREE.CylinderGeometry(1, 1, 1, seg, 1));
+ const sphT = {}; const unitSph = (seg) => (sphT[seg] ||= new THREE.SphereGeometry(1, seg, Math.max(3, seg >> 1)));
+ const VUP = V3(0, 1, 0), VX = V3(1, 0, 0);
+ function segMatrix(p0, p1, sx, sz, roll = 0) {
+ const Y = V3().subVectors(p1, p0); const len = Y.length() || 1e-4; Y.divideScalar(len);
+ const ref = Math.abs(Y.y) > 0.95 ? VX : VUP;
+ const X = V3().crossVectors(ref, Y).normalize(); const Z = V3().crossVectors(X, Y);
+ if (roll) { X.applyAxisAngle(Y, roll); Z.applyAxisAngle(Y, roll); }
+ return new THREE.Matrix4().makeBasis(X.multiplyScalar(sx), Y.multiplyScalar(len), Z.multiplyScalar(sz))
+ .setPosition((p0.x + p1.x) / 2, (p0.y + p1.y) / 2, (p0.z + p1.z) / 2);
+ }
+ // ---- grime decals (own RNG so they never disturb the layout sequence)
+ const DR = rng(0xD17C5); const drnd = (a = 0, b = 1) => a + (b - a) * DR();
+ let decalN = 0;
+ // cell 0 rust run, 1 drip set, 2 oil / soot stain, 3 rust bloom; `up` = direction of the texture top (the source of the run)
+ function decal(cell, c, nrm, up, w, h, k = 1) {
+ const nn = nrm.clone().normalize(), u = up.clone().normalize(), r = V3().crossVectors(u, nn).normalize();
+ const o = c.clone().addScaledVector(nn, 0.012 + (decalN % 7) * 0.0015);
+ const P = [[-1, 1], [1, 1], [-1, -1], [1, -1]].map(([a, b]) => o.clone().addScaledVector(r, a * w / 2).addScaledVector(u, b * h / 2));
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P.flatMap((p) => [p.x, p.y, p.z]), 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute([0, 1, 2, 3].flatMap(() => [nn.x, nn.y, nn.z]), 3));
+ const cu = (cell % 2) * 0.5, cv = cell < 2 ? 0.5 : 0, e = 0.014;
+ g.setAttribute('uv', new THREE.Float32BufferAttribute([cu + e, cv + 0.5 - e, cu + 0.5 - e, cv + 0.5 - e, cu + e, cv + e, cu + 0.5 - e, cv + e], 2));
+ g.setIndex([0, 2, 1, 1, 2, 3]);
+ decalN++;
+ push('decal', g, [k, k, k], 0);
+ }
+ const AUTO = { concrete: [0.2, 0.7], steel: [0.14, 0.3], paint: [0.3, 0.5] }; // [runs per metre of wall, stains per 10 m² of underside]
+ const VDOWN = V3(0, -1, 0);
+ function grimeBox(bn, xa, xb, ya, yb, za, zb) {
+ const A = AUTO[bn]; if (!A) return;
+ const x0 = Math.min(xa, xb), x1 = Math.max(xa, xb), y0 = Math.min(ya, yb), y1 = Math.max(ya, yb), z0 = Math.min(za, zb), z1 = Math.max(za, zb);
+ const h = y1 - y0, sx = x1 - x0, sz = z1 - z0;
+ if (h > 0.45) for (const [len, nrm, at] of [
+ [sx, V3(0, 0, 1), (u) => V3(x0 + u, 0, z1)], [sx, V3(0, 0, -1), (u) => V3(x0 + u, 0, z0)],
+ [sz, V3(1, 0, 0), (u) => V3(x1, 0, z0 + u)], [sz, V3(-1, 0, 0), (u) => V3(x0, 0, z0 + u)]]) {
+ if (len < 0.9) continue;
+ let cnt = len * A[0]; cnt = Math.floor(cnt) + (DR() < cnt % 1 ? 1 : 0);
+ for (let i = 0; i < cnt; i++) {
+ const wide = DR() < 0.35 && len > 2.4;
+ const w = wide ? drnd(1.2, Math.min(3.4, len * 0.9)) : drnd(0.3, 0.85);
+ const hh = Math.min(h, wide ? drnd(0.7, 2.4) : drnd(0.8, 3.2));
+ const p = at(drnd(w / 2, len - w / 2)); p.y = y1 - hh / 2;
+ const bloom = !wide && DR() < 0.22;
+ decal(wide ? 1 : (bloom ? 3 : 0), p, nrm, VUP, bloom ? Math.min(w * 1.6, hh) : w, bloom ? Math.min(w * 1.6, hh) : hh, drnd(0.45, 0.95));
+ }
+ }
+ if (sx > 1.4 && sz > 1.4) {
+ let cnt = sx * sz / 10 * A[1]; cnt = Math.floor(cnt) + (DR() < cnt % 1 ? 1 : 0);
+ for (let i = 0; i < cnt; i++) {
+ const sw = drnd(1.0, Math.min(3.8, sx)), sd = drnd(1.0, Math.min(3.8, sz));
+ decal(DR() < 0.25 ? 3 : 2, V3(drnd(x0 + sw / 2, x1 - sw / 2), y0, drnd(z0 + sd / 2, z1 - sd / 2)), VDOWN, VX, sd, sw, drnd(0.45, 0.9));
+ }
+ }
+ }
+ const box = (bn, x0, x1, y0, y1, z0, z1, tint, vary) => {
+ const g = pushT(bn, UBOX.clone(),
+ new THREE.Matrix4().makeScale(Math.abs(x1 - x0), Math.abs(y1 - y0), Math.abs(z1 - z0)).setPosition((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2), tint, vary);
+ grimeBox(bn, x0, x1, y0, y1, z0, z1);
+ return g;
+ };
+ const boxC = (bn, cx, cy, cz, sx, sy, sz, tint, vary, ry = 0) => {
+ const m = new THREE.Matrix4().makeRotationY(ry).multiply(new THREE.Matrix4().makeScale(sx, sy, sz)).setPosition(cx, cy, cz);
+ return pushT(bn, UBOX.clone(), m, tint, vary);
+ };
+ const beam = (bn, p0, p1, w, h, tint, vary, roll) => pushT(bn, UBOX.clone(), segMatrix(p0, p1, w, h, roll), tint, vary);
+ const rod = (bn, p0, p1, r, seg = 8, tint, vary) => pushT(bn, unitCyl(seg).clone(), segMatrix(p0, p1, r, r), tint, vary);
+ const cylY = (bn, cx, cz, y0, y1, r, seg = 24, tint, vary) => rod(bn, V3(cx, y0, cz), V3(cx, y1, cz), r, seg, tint, vary);
+ const cylX = (bn, x0, x1, y, z, r, seg = 16, tint, vary) => rod(bn, V3(x0, y, z), V3(x1, y, z), r, seg, tint, vary);
+ const cylZ = (bn, z0, z1, x, y, r, seg = 16, tint, vary) => rod(bn, V3(x, y, z0), V3(x, y, z1), r, seg, tint, vary);
+ const sph = (bn, c, r, seg = 12, tint, sy = 1) => pushT(bn, unitSph(seg).clone(), new THREE.Matrix4().makeScale(r, r * sy, r).setPosition(c), tint);
+ // torus ring; axis: 'x' | 'y' | 'z'; stretch: thickness multiplier along the axis
+ function ring(bn, c, axis, Rr, r, tubSeg = 32, radSeg = 6, tint, stretch = 1) {
+ const g = new THREE.TorusGeometry(Rr, r, radSeg, tubSeg);
+ const m = new THREE.Matrix4();
+ if (axis === 'y') m.makeRotationX(Math.PI / 2); else if (axis === 'x') m.makeRotationY(Math.PI / 2);
+ m.multiply(new THREE.Matrix4().makeScale(1, 1, stretch));
+ m.setPosition(c);
+ return pushT(bn, g, m, tint);
+ }
+ // swept tube along points with parallel-transport frames; sw: optional per-point sway weight
+ function sweepGeo(pts, r, rs = 8, sw = null, phase = 0, freq = 1) {
+ const n = pts.length, pos = [], nor = [], idx = [], swa = [];
+ const tans = pts.map((p, i) => V3().subVectors(pts[Math.min(n - 1, i + 1)], pts[Math.max(0, i - 1)]).normalize());
+ let N = Math.abs(tans[0].y) < 0.9 ? V3(0, 1, 0) : V3(1, 0, 0);
+ N.sub(tans[0].clone().multiplyScalar(N.dot(tans[0]))).normalize();
+ const q = new THREE.Quaternion(), B = V3(), d = V3();
+ for (let i = 0; i < n; i++) {
+ if (i > 0) { q.setFromUnitVectors(tans[i - 1], tans[i]); N.applyQuaternion(q); N.sub(tans[i].clone().multiplyScalar(N.dot(tans[i]))).normalize(); }
+ B.crossVectors(tans[i], N);
+ const rr = typeof r === 'function' ? r(i / (n - 1)) : r;
+ for (let j = 0; j < rs; j++) {
+ const a = j / rs * Math.PI * 2;
+ d.copy(N).multiplyScalar(Math.cos(a)).addScaledVector(B, Math.sin(a));
+ pos.push(pts[i].x + d.x * rr, pts[i].y + d.y * rr, pts[i].z + d.z * rr);
+ nor.push(d.x, d.y, d.z);
+ if (sw) swa.push(sw[i], phase, freq);
+ }
+ }
+ for (let i = 0; i < n - 1; i++) for (let j = 0; j < rs; j++) {
+ const a = i * rs + j, b = i * rs + (j + 1) % rs, c = (i + 1) * rs + j, e = (i + 1) * rs + (j + 1) % rs;
+ idx.push(a, b, c, b, e, c);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(nor, 3));
+ if (sw) g.setAttribute('aSway', new THREE.Float32BufferAttribute(swa, 3));
+ g.setIndex(idx);
+ return g;
+ }
+ // polyline with rounded corners -> dense points only in the bends
+ function roundPath(pts, rad = 0.5, nArc = 6) {
+ const out = [pts[0].clone()];
+ for (let i = 1; i < pts.length - 1; i++) {
+ const p = pts[i], a = V3().subVectors(pts[i - 1], p), b = V3().subVectors(pts[i + 1], p);
+ const ra = Math.min(rad, a.length() * 0.45, b.length() * 0.45);
+ a.normalize(); b.normalize();
+ const s = p.clone().addScaledVector(a, ra), e = p.clone().addScaledVector(b, ra);
+ for (let k = 0; k <= nArc; k++) {
+ const t = k / nArc, u = 1 - t;
+ out.push(V3(u * u * s.x + 2 * u * t * p.x + t * t * e.x, u * u * s.y + 2 * u * t * p.y + t * t * e.y, u * u * s.z + 2 * u * t * p.z + t * t * e.z));
+ }
+ }
+ out.push(pts[pts.length - 1].clone());
+ return out;
+ }
+ function pipe(bn, pts, r, opt = {}) {
+ const rs = opt.rs ?? (r > 0.2 ? 14 : r > 0.09 ? 10 : 6);
+ const path = roundPath(pts, opt.bend ?? Math.max(r * 2.2, 0.25), opt.nArc ?? 6);
+ push(bn, sweepGeo(path, r, rs), opt.tint ?? [1, 1, 1], opt.vary ?? 0.12);
+ // flanges at the ends + along straight runs
+ if (opt.flanges !== false) {
+ const fl = opt.flangeBn ?? 'steelS';
+ const every = opt.every ?? 5.5;
+ for (let i = 0; i < pts.length - 1; i++) {
+ const a = pts[i], b = pts[i + 1], L = a.distanceTo(b);
+ const dir = V3().subVectors(b, a).normalize();
+ const cnt = Math.floor(L / every);
+ for (let k = 1; k <= cnt; k++) {
+ const c = a.clone().addScaledVector(dir, (k - 0.5) * (L / cnt) + rnd(-0.6, 0.6));
+ rod(fl, c.clone().addScaledVector(dir, -0.045), c.clone().addScaledVector(dir, 0.045), r * 1.5 + 0.03, rs + 2);
+ if (opt.valves && R() < opt.valves) valve(c.clone().addScaledVector(dir, 0.5), dir, r);
+ }
+ }
+ for (const [p, q2] of [[pts[0], pts[1]], [pts[pts.length - 1], pts[pts.length - 2]]]) {
+ if (opt.endFlange === false) break;
+ const dir = V3().subVectors(q2, p).normalize();
+ rod(fl, p.clone(), p.clone().addScaledVector(dir, 0.1), r * 1.55 + 0.03, rs + 2);
+ }
+ }
+ }
+ function valve(c, dir, r) {
+ rod('paintS', c.clone().addScaledVector(dir, -r * 1.3), c.clone().addScaledVector(dir, r * 1.3), r * 1.35, 10, pick(TINT.machine));
+ const up = Math.abs(dir.y) > 0.9 ? V3(1, 0, 0) : V3(0, -1, 0);
+ const top = c.clone().addScaledVector(up, r * 1.4 + 0.25);
+ rod('steelS', c, top, Math.max(0.035, r * 0.25), 6);
+ const m = new THREE.Matrix4().makeBasis(dir.clone().cross(up).normalize(), dir.clone(), up.clone()).setPosition(top);
+ pushT('rustS', new THREE.TorusGeometry(Math.max(0.14, r * 1.2), 0.025, 4, 14).applyMatrix4(new THREE.Matrix4().makeRotationX(Math.PI / 2)), m, TINT.redwheel);
+ }
+ const catenary = (a, b, sag, n = 14) => Array.from({ length: n + 1 }, (_, i) => {
+ const t = i / n; return V3(a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t - sag * 4 * t * (1 - t), a.z + (b.z - a.z) * t);
+ });
+ function hoseLoop(a, b, sag, r = 0.05, swayAmp = 0.08) {
+ const pts = catenary(a, b, sag, 14);
+ const w = pts.map((_, i) => Math.sin(Math.PI * i / 14) * swayAmp * (0.5 + sag));
+ push('sway', sweepGeo(pts, r, 6, w, rnd(0, 6.28), rnd(0.7, 1.4)), [1, 1, 1], 0.2);
+ }
+ function dangle(a, len, r = 0.03, swayAmp = 0.1, plug = true) {
+ const n = 10, pts = [], w = [];
+ const kink = V3(rnd(-0.15, 0.15), 0, rnd(-0.15, 0.15));
+ for (let i = 0; i <= n; i++) { const t = i / n; pts.push(V3(a.x + kink.x * t * t, a.y - len * t, a.z + kink.z * t * t)); w.push(Math.pow(t, 1.5) * swayAmp * len); }
+ const ph = rnd(0, 6.28), fr = rnd(0.8, 1.6) / Math.sqrt(Math.max(0.6, len));
+ push('sway', sweepGeo(pts, r, 5, w, ph, fr), [1, 1, 1], 0.2);
+ if (plug) {
+ const e = pts[n];
+ const g = unitCyl(6).clone().applyMatrix4(new THREE.Matrix4().makeScale(r * 2.4, 0.16, r * 2.4).setPosition(e.x, e.y - 0.06, e.z));
+ const sw = new Float32Array(g.attributes.position.count * 3);
+ for (let i = 0; i < sw.length; i += 3) { sw[i] = w[n]; sw[i + 1] = ph; sw[i + 2] = fr; }
+ g.setAttribute('aSway', new THREE.BufferAttribute(sw, 3));
+ push('sway', g, [1.6, 1.5, 1.3]);
+ }
+ }
+
+ const TINT = {
+ concrete: [[0.95, 0.95, 0.97], [0.86, 0.87, 0.88], [1.02, 1.0, 0.97], [0.8, 0.82, 0.83]],
+ steel: [1, 1, 1],
+ machine: [[0.62, 0.68, 0.6], [0.55, 0.6, 0.66], [0.82, 0.68, 0.44], [0.66, 0.4, 0.29], [0.78, 0.79, 0.76], [0.5, 0.56, 0.5]],
+ cabin: [[0.78, 0.8, 0.76], [0.66, 0.72, 0.66], [0.6, 0.66, 0.72], [0.82, 0.74, 0.58]],
+ rail: [[0.85, 0.72, 0.42], [0.7, 0.72, 0.7], [0.9, 0.9, 0.88]],
+ redwheel: [0.75, 0.2, 0.12],
+ };
+ const HOT = [2.4, 1.1, 0.32];
+ const lampCol = (k = 1) => HOT.map((v) => v * k);
+
+ // ---- lamp unit: bulkhead lamp with cage, light pointing along `dir` (default down)
+ let lampSeq = 0;
+ // round 2: the small bulkhead fittings are mostly dead glass (a few dim pilots); the visible pools come from
+ // the big practicals below (flood / cageLamp / tubeLamp), ~20 over the whole belly.
+ function lamp(p, dir = V3(0, -1, 0)) {
+ const sq = lampSeq++;
+ const q = new THREE.Quaternion().setFromUnitVectors(V3(0, -1, 0), dir.clone().normalize());
+ const m = new THREE.Matrix4().compose(p, q, V3(1.6, 1.6, 1.6));
+ const pilot = sq % 5 === 1;
+ pushT('steelS', unitCyl(10).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.17, 0.09, 0.17).setPosition(0, 0.05, 0)), m);
+ if (pilot) pushT('emis', unitSph(8).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.13, 0.17, 0.13).setPosition(0, -0.12, 0)), m, [1.9, 0.82, 0.23], 0);
+ else pushT('glass', unitSph(8).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.13, 0.17, 0.13).setPosition(0, -0.12, 0)), m, [1.3, 1.2, 1.0], 0.2);
+ pushT('steelS', new THREE.TorusGeometry(0.17, 0.014, 3, 12).applyMatrix4(new THREE.Matrix4().makeRotationX(Math.PI / 2).setPosition(0, -0.12, 0)), m);
+ for (let i = 0; i < 4; i++) {
+ const a = i * Math.PI / 2;
+ pushT('steelS', unitCyl(3).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.012, 0.3, 0.012).setPosition(Math.cos(a) * 0.17, -0.12, Math.sin(a) * 0.17)), m);
+ }
+ if (pilot) addLight(p.clone().addScaledVector(dir, 0.3), 0.75, 6.5, 0.8);
+ }
+ const REAL_PL = [];
+ // floodlight on a bracket: boxy head with fins, warm lens, spot pool along `dir`
+ function flood(p, dir, o = {}) {
+ dir = dir.clone().normalize();
+ if (o.from) { rod('steelS', o.from, p, 0.04, 5); boxC('steelS', o.from.x, o.from.y, o.from.z, 0.24, 0.24, 0.24); }
+ const a = p.clone().addScaledVector(dir, -0.2), b = p.clone().addScaledVector(dir, 0.2);
+ beam('paintS', a, b, 0.6, 0.44, [0.42, 0.44, 0.42], 0.05);
+ for (let i = 0; i < 3; i++) { const c = p.clone().addScaledVector(dir, -0.25 - i * 0.06); beam('steelS', c, c.clone().addScaledVector(dir, 0.025), 0.54, 0.38); }
+ beam('steelS', b, b.clone().addScaledVector(dir, 0.1), 0.66, 0.5); // hood frame
+ beam(o.flick ? 'emisF' : 'emis', b.clone().addScaledVector(dir, 0.1), b.clone().addScaledVector(dir, 0.115), 0.5, 0.34, lampCol(o.e ?? 0.85), 0);
+ const lp = p.clone().addScaledVector(dir, 0.5);
+ if (o.real) REAL_PL.push(lp.clone());
+ return addLight(lp, o.k ?? 2.6, o.r ?? 18, 5, o.col ?? [1.0, 0.5, 0.17], { dir, cone: o.cone ?? 0.3, solo: true, flick: !!o.flick });
+ }
+ // big caged well-glass lamp on a stem (omni pool)
+ function cageLamp(p, o = {}) {
+ const sc = o.s ?? 1;
+ if (o.from) rod('steelS', o.from, p.clone().add(V3(0, 0.1 * sc, 0)), 0.035, 5);
+ const m = new THREE.Matrix4().makeScale(sc, sc, sc).setPosition(p);
+ pushT('steelS', unitCyl(12).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.3, 0.16, 0.3).setPosition(0, 0.05, 0)), m);
+ pushT('steelS', unitCyl(12).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.5, 0.025, 0.5).setPosition(0, 0.0, 0)), m); // shade plate
+ pushT(o.flick ? 'emisF' : 'emis', unitSph(10).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.2, 0.27, 0.2).setPosition(0, -0.25, 0)), m, lampCol(o.e ?? 0.9), 0);
+ for (const yy of [-0.16, -0.36]) pushT('steelS', new THREE.TorusGeometry(0.25, 0.016, 3, 14).applyMatrix4(new THREE.Matrix4().makeRotationX(Math.PI / 2).setPosition(0, yy, 0)), m);
+ for (let i = 0; i < 6; i++) {
+ const a = i * Math.PI / 3;
+ pushT('steelS', unitCyl(3).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.014, 0.56, 0.014).setPosition(Math.cos(a) * 0.25, -0.26, Math.sin(a) * 0.25)), m);
+ }
+ const lp = p.clone().add(V3(0, -0.45 * sc, 0));
+ if (o.real) REAL_PL.push(lp.clone());
+ return addLight(lp, o.k ?? 1.7, o.r ?? 11, 5, o.col ?? [1.0, 0.47, 0.15], { solo: true, flick: !!o.flick });
+ }
+ // twin fluorescent tube fitting (cooler light, optional flicker)
+ function tubeLamp(p, ax, len = 1.5, o = {}) {
+ ax = ax.clone().normalize();
+ const a = p.clone().addScaledVector(ax, -len / 2), b = p.clone().addScaledVector(ax, len / 2);
+ const side = V3(-ax.z, 0, ax.x);
+ beam('paintS', a.clone().add(V3(0, 0.06, 0)), b.clone().add(V3(0, 0.06, 0)), 0.26, 0.08, [0.8, 0.82, 0.8]);
+ for (const e of [a, b]) rod('steelS', e.clone().add(V3(0, 0.06, 0)), e.clone().add(V3(0, 0.06 + (o.drop ?? 0.4), 0)), 0.018, 4);
+ for (const d of [-0.07, 0.07]) rod(o.flick ? 'emisF' : 'emis', a.clone().addScaledVector(side, d).addScaledVector(ax, 0.06), b.clone().addScaledVector(side, d).addScaledVector(ax, -0.06), 0.024, 6, o.ecol ?? [0.85, 1.2, 1.35], 0);
+ return addLight(p.clone().add(V3(0, -0.3, 0)), o.k ?? 1.25, o.r ?? 9, 5, o.col ?? [0.5, 0.78, 0.95], { solo: true, flick: !!o.flick });
+ }
+ function pendant(x, yTop, z, drop = 0.4, k = 1, lightK = 1, lightR = 7.5, prio = 1) {
+ rod('steelS', V3(x, yTop, z), V3(x, yTop - drop, z), 0.025, 4);
+ lamp(V3(x, yTop - drop - 0.05, z), V3(0, -1, 0), k, lightK, lightR, prio);
+ }
+
+ // ---- railings / catwalks / ladders / stairs
+ function railing(a, b, h = 1.05, tint) {
+ tint = tint ?? TINT.rail[0];
+ const L = a.distanceTo(b); const n = Math.max(1, Math.round(L / 1.5));
+ for (let i = 0; i <= n; i++) { const p = a.clone().lerp(b, i / n); boxC('rustS', p.x, p.y + h / 2, p.z, 0.05, h, 0.05, tint, 0.15); }
+ const up = V3(0, h, 0), mid = V3(0, h * 0.5, 0);
+ rod('rustS', a.clone().add(up), b.clone().add(up), 0.028, 6, tint, 0.1);
+ rod('rustS', a.clone().add(mid), b.clone().add(mid), 0.02, 5, tint, 0.1);
+ beam('rustS', a.clone().add(V3(0, 0.07, 0)), b.clone().add(V3(0, 0.07, 0)), 0.012, 0.14, tint, 0.1);
+ }
+ // straight catwalk from a to b (same y), width w; rails: [left, right]; hang: y to hang from (or null)
+ function catwalk(a, b, w = 1.1, rails = [true, true], hangY = null, hangEvery = 2.75) {
+ const dir = V3().subVectors(b, a); const L = dir.length(); dir.normalize();
+ const side = V3(-dir.z, 0, dir.x);
+ const ang = Math.atan2(dir.z, dir.x);
+ const c = a.clone().lerp(b, 0.5);
+ const fg = new THREE.PlaneGeometry(L, w).applyMatrix4(new THREE.Matrix4().makeRotationX(-Math.PI / 2))
+ .applyMatrix4(new THREE.Matrix4().makeRotationY(-ang)).applyMatrix4(new THREE.Matrix4().makeTranslation(c.x, c.y, c.z));
+ push('grate', fg, [1, 1, 1], 0.1);
+ for (const s of [-1, 1]) {
+ const o = side.clone().multiplyScalar(s * w / 2);
+ beam('steelS', a.clone().add(o).add(V3(0, -0.09, 0)), b.clone().add(o).add(V3(0, -0.09, 0)), 0.06, 0.2);
+ if (rails[s < 0 ? 0 : 1]) railing(a.clone().add(o), b.clone().add(o));
+ }
+ // cross members under the grating
+ const nX = Math.max(1, Math.round(L / 1.2));
+ for (let i = 0; i <= nX; i++) {
+ const p = a.clone().lerp(b, i / nX).add(V3(0, -0.14, 0));
+ beam('steelS', p.clone().addScaledVector(side, -w / 2), p.clone().addScaledVector(side, w / 2), 0.05, 0.08);
+ }
+ if (hangY !== null) {
+ const nH = Math.max(1, Math.round(L / hangEvery));
+ for (let i = 0; i <= nH; i++) {
+ const p = a.clone().lerp(b, i / nH);
+ for (const s of [-1, 1]) {
+ const q2 = p.clone().addScaledVector(side, s * (w / 2 + 0.03));
+ rod('steelS', q2.clone().add(V3(0, -0.1, 0)), V3(q2.x, hangY, q2.z), 0.022, 4);
+ }
+ }
+ }
+ }
+ function ladder(x, z, y0, y1, faceZ = true, cage = false) {
+ const o = faceZ ? V3(0.22, 0, 0) : V3(0, 0, 0.22);
+ rod('rustS', V3(x, y0, z).sub(o), V3(x, y1, z).sub(o), 0.025, 5, TINT.rail[0]);
+ rod('rustS', V3(x, y0, z).add(o), V3(x, y1, z).add(o), 0.025, 5, TINT.rail[0]);
+ for (let y = Math.min(y0, y1) + 0.15; y < Math.max(y0, y1); y += 0.3) rod('rustS', V3(x, y, z).sub(o), V3(x, y, z).add(o), 0.016, 4, TINT.rail[0]);
+ if (cage) for (let y = Math.min(y0, y1) + 0.6; y < Math.max(y0, y1) - 0.3; y += 0.75) {
+ ring('rustS', V3(x + (faceZ ? 0 : 0.35), y, z + (faceZ ? 0.35 : 0)), 'y', 0.38, 0.015, 12, 3, TINT.rail[0]);
+ }
+ }
+ function stairs(a, b, w = 0.8) { // from a (low) to b (high) – treads perpendicular to horizontal dir
+ const hor = V3(b.x - a.x, 0, b.z - a.z); const hl = hor.length(); hor.normalize();
+ const side = V3(-hor.z, 0, hor.x);
+ for (const s of [-1, 1]) {
+ const o = side.clone().multiplyScalar(s * w / 2);
+ beam('steelS', a.clone().add(o), b.clone().add(o), 0.05, 0.22, [1, 1, 1], 0.1, 0);
+ railing2(a.clone().add(o), b.clone().add(o));
+ }
+ const n = Math.max(2, Math.round((b.y - a.y) / 0.2));
+ for (let i = 1; i < n; i++) {
+ const p = a.clone().lerp(b, i / n);
+ boxC('steelS', p.x, p.y, p.z, Math.abs(hor.x) * 0.25 + Math.abs(side.x) * w, 0.04, Math.abs(hor.z) * 0.25 + Math.abs(side.z) * w);
+ }
+ void hl;
+ }
+ function railing2(a, b) { // sloped rail along a stair stringer
+ const up = V3(0, 0.95, 0);
+ rod('rustS', a.clone().add(up), b.clone().add(up), 0.025, 5, TINT.rail[0]);
+ rod('rustS', a, a.clone().add(up), 0.022, 4, TINT.rail[0]);
+ rod('rustS', b, b.clone().add(up), 0.022, 4, TINT.rail[0]);
+ rod('rustS', a.clone().lerp(b, 0.5), a.clone().lerp(b, 0.5).add(up), 0.022, 4, TINT.rail[0]);
+ }
+ function sign(cell, c, normal, w, h) {
+ const g = new THREE.PlaneGeometry(w, h);
+ const uv = g.attributes.uv; const cu = (cell % 2) * 0.5, cv = 0.75 - Math.floor(cell / 2) * 0.25;
+ for (let i = 0; i < uv.count; i++) uv.setXY(i, cu + uv.getX(i) * 0.5, cv + uv.getY(i) * 0.25);
+ const q = new THREE.Quaternion().setFromUnitVectors(V3(0, 0, 1), normal.clone().normalize());
+ pushT('signs', g, new THREE.Matrix4().compose(c.clone().addScaledVector(normal, 0.02), q, V3(1, 1, 1)), [0.8, 0.8, 0.8], 0.1);
+ }
+ function junction(c, faceN, s = 1) { // electrical box on a surface
+ const n = faceN.clone().normalize();
+ const w = 0.45 * s, h = 0.6 * s, d = 0.22 * s;
+ const ang = Math.atan2(n.x, n.z);
+ boxC('paintS', c.x + n.x * d / 2, c.y, c.z + n.z * d / 2, Math.abs(n.z) > 0.5 ? w : d, h, Math.abs(n.z) > 0.5 ? d : w, pick(TINT.cabin), 0.1);
+ void ang;
+ rod('steelS', V3(c.x + n.x * 0.12, c.y + h / 2, c.z + n.z * 0.12), V3(c.x + n.x * 0.12, c.y + h / 2 + rnd(0.4, 1.2), c.z + n.z * 0.12), 0.03, 5);
+ }
+
+ // ---- windowed cabin slung under the structure
+ // doorFace: 'px'|'nx'|'pz'|'nz'
+ function cabin(cx, cz, yTop, sx, sy, sz, opt = {}) {
+ const y0 = yTop - sy, tint = opt.tint ?? pick(TINT.cabin);
+ box('paint', cx - sx / 2, cx + sx / 2, y0, yTop - 0.12, cz - sz / 2, cz + sz / 2, tint, 0.05);
+ // roof slab with overhang, floor frame
+ box('steel', cx - sx / 2 - 0.15, cx + sx / 2 + 0.15, yTop - 0.12, yTop, cz - sz / 2 - 0.15, cz + sz / 2 + 0.15);
+ box('steel', cx - sx / 2 - 0.08, cx + sx / 2 + 0.08, y0 - 0.16, y0, cz - sz / 2 - 0.08, cz + sz / 2 + 0.08);
+ for (const fx of [-1, 1]) box('steelS', cx + fx * sx * 0.3 - 0.08, cx + fx * sx * 0.3 + 0.08, y0 - 0.34, y0 - 0.16, cz - sz / 2 - 0.25, cz + sz / 2 + 0.25);
+ // corrugation ribs on walls
+ for (let x = cx - sx / 2 + 0.2; x < cx + sx / 2 - 0.1; x += 0.32) for (const fz of [-1, 1]) box('paintS', x - 0.03, x + 0.03, y0 + 0.05, yTop - 0.15, cz + fz * sz / 2 - 0.02, cz + fz * (sz / 2 + 0.04), tint, 0.04);
+ // windows
+ const faces = opt.windows ?? ['pz', 'nz', 'px', 'nx'];
+ const winY0 = y0 + sy * 0.42, winY1 = yTop - 0.4;
+ let lit = 0;
+ for (const f of faces) {
+ const alongX = f === 'pz' || f === 'nz';
+ const len = alongX ? sx : sz, nW = Math.max(1, Math.floor((len - 0.6) / 1.05));
+ const sgn = f[0] === 'p' ? 1 : -1;
+ for (let i = 0; i < nW; i++) {
+ if (f === opt.door && i === 0) continue;
+ const u = -len / 2 + 0.3 + (i + 0.5) * ((len - 0.6) / nW);
+ const ww = Math.min(0.85, (len - 0.6) / nW - 0.18);
+ const on = R() < (opt.litP ?? 0.72);
+ const kk = on ? pick([0.8, 0.68, 0.58, 0.5, 0.4]) : 0;
+ const px = alongX ? cx + u : cx + sgn * (sx / 2 + 0.05);
+ const pz = alongX ? cz + sgn * (sz / 2 + 0.05) : cz + u;
+ const gx = alongX ? ww : 0.02, gz = alongX ? 0.02 : ww;
+ if (on) { box('emis', px - gx / 2, px + gx / 2, winY0, winY1, pz - gz / 2, pz + gz / 2, [2.4 * kk, 0.92 * kk, 0.22 * kk], 0); lit++; } else box('glass', px - gx / 2, px + gx / 2, winY0, winY1, pz - gz / 2, pz + gz / 2, [1, 1, 1], 0.3);
+ // frame + mullion
+ const fx2 = alongX ? ww + 0.12 : 0.06, fz2 = alongX ? 0.06 : ww + 0.12;
+ box('steelS', px - fx2 / 2, px + fx2 / 2, winY0 - 0.07, winY0, pz - fz2 / 2, pz + fz2 / 2);
+ box('steelS', px - fx2 / 2, px + fx2 / 2, winY1, winY1 + 0.06, pz - fz2 / 2, pz + fz2 / 2);
+ box('steelS', px - (alongX ? 0.025 : 0.035), px + (alongX ? 0.025 : 0.035), winY0, winY1, pz - (alongX ? 0.035 : 0.025), pz + (alongX ? 0.035 : 0.025));
+ if (on) addLight(V3(px + (alongX ? 0 : sgn * 0.8), (winY0 + winY1) / 2, pz + (alongX ? sgn * 0.8 : 0)), 0.55 * kk, 5.5, 0.6, [1.0, 0.45, 0.13]);
+ }
+ }
+ // door
+ if (opt.door) {
+ const f = opt.door, alongX = f === 'pz' || f === 'nz', sgn = f[0] === 'p' ? 1 : -1, len = alongX ? sx : sz;
+ const u = -len / 2 + 0.3 + 0.45;
+ const px = alongX ? cx + u : cx + sgn * (sx / 2 + 0.03), pz = alongX ? cz + sgn * (sz / 2 + 0.03) : cz + u;
+ box('steel', px - (alongX ? 0.42 : 0.04), px + (alongX ? 0.42 : 0.04), y0 + 0.02, y0 + 1.95, pz - (alongX ? 0.04 : 0.42), pz + (alongX ? 0.04 : 0.42), [0.7, 0.75, 0.7]);
+ lamp(V3(px + (alongX ? 0 : sgn * 0.2), y0 + 2.12, pz + (alongX ? sgn * 0.2 : 0)), V3(alongX ? 0 : sgn, -1.2, alongX ? sgn : 0).normalize(), 1.0, 0.9, 6.5, 1.3);
+ sign(2, V3(px + (alongX ? 0.75 : sgn * 0.03), y0 + 1.6, pz + (alongX ? sgn * 0.03 : 0.75)), V3(alongX ? 0 : sgn, 0, alongX ? sgn : 0), 0.42, 0.21);
+ }
+ // AC unit / vent box
+ if (opt.ac !== false) {
+ const f = R() < 0.5 ? 1 : -1;
+ box('paintS', cx + f * sx / 2, cx + f * (sx / 2 + 0.45), y0 + 0.4, y0 + 1.0, cz - 0.4, cz + 0.4, [0.75, 0.76, 0.73]);
+ ring('steelS', V3(cx + f * (sx / 2 + 0.46), y0 + 0.7, cz), 'x', 0.2, 0.02, 12, 3);
+ }
+ // hangers to structure above
+ if (opt.hangTo !== undefined) for (const ex of [-1, 1]) for (const ez of [-1, 1])
+ rod('steelS', V3(cx + ex * (sx / 2 + 0.05), yTop, cz + ez * (sz / 2 + 0.05)), V3(cx + ex * (sx / 2 + 0.05), opt.hangTo, cz + ez * (sz / 2 + 0.05)), 0.04, 5);
+ // underside clutter: drain + dangling cable
+ rod('steelS', V3(cx + sx * 0.3, y0 - 0.16, cz), V3(cx + sx * 0.3, y0 - 0.55, cz), 0.04, 6);
+ dangle(V3(cx - sx * 0.25, y0 - 0.2, cz + sz * 0.2), rnd(0.5, 1.6), 0.025);
+ return lit;
+ }
+
+ // =================================================================== 1. CONCRETE TRANSFER SLAB
+ {
+ const xs = [-45]; for (const hx of LEGX) xs.push(hx - 3.4, hx + 3.4); xs.push(45);
+ for (let i = 0; i < xs.length - 1; i++) {
+ if (i % 2 === 1) { // hip bay: ~1 m recess around the hip (thigh fork clearance at extreme yaw)
+ box('concrete', xs[i], xs[i + 1], -0.8, -0.25, -5.4, 5.4, TINT.concrete[0], 0.03);
+ box('concrete', xs[i], xs[i + 1], -0.25, 0, -6.4, 6.4, TINT.concrete[0], 0.03);
+ } else box('concrete', xs[i], xs[i + 1], -0.8, 0, -8.0, 8.0, TINT.concrete[0], 0.03);
+ }
+ // downstand beams on every bay line, with haunches
+ for (const L of LINES) {
+ const ze = isHipLine(L) ? 4.9 : 7.0;
+ const x0 = Math.max(-45, L - 0.45), x1 = Math.min(45, L + 0.45);
+ box('concrete', x0, x1, -2.2, -0.8, -ze, ze, pick(TINT.concrete), 0.05);
+ box('concrete', Math.max(-45, L - 0.9), Math.min(45, L + 0.9), -1.15, -0.8, -ze, ze, pick(TINT.concrete), 0.05);
+ }
+ // stepped coffers per bay
+ for (let i = 0; i < 16; i++) {
+ const x0 = LINES[i] + 0.45, x1 = LINES[i + 1] - 0.45;
+ const nearHip = isHipLine(LINES[i]) || isHipLine(LINES[i + 1]);
+ const ze = nearHip ? 4.9 : 6.6;
+ const kind = (i * 7 + 3) % 3;
+ const t = pick(TINT.concrete);
+ if (kind === 0) {
+ box('concrete', x0, x1, -1.6, -0.8, -ze, ze, t, 0.05);
+ box('concrete', x0 + 0.7, x1 - 0.7, -2.15, -1.6, -ze + 1.4, ze - 1.4, pick(TINT.concrete), 0.05);
+ } else if (kind === 1) {
+ box('concrete', x0, x1, -1.7, -0.8, 1.0, ze, t, 0.05);
+ box('concrete', x0, x1, -1.7, -0.8, -ze, -1.0, t, 0.05);
+ box('concrete', x0 + 0.5, x1 - 0.5, -2.1, -1.7, 3.0, ze - 0.5, pick(TINT.concrete), 0.05);
+ box('concrete', x0 + 0.5, x1 - 0.5, -2.1, -1.7, -ze + 0.5, -3.0, pick(TINT.concrete), 0.05);
+ } else {
+ box('concrete', x0, x1, -1.35, -0.8, -ze, ze, t, 0.05);
+ for (const s of [1, -1]) box('concrete', x0 + 0.3, x1 - 0.3, -2.05, -1.35, s > 0 ? 2.9 : -4.7, s > 0 ? 4.7 : -2.9, pick(TINT.concrete), 0.05);
+ }
+ }
+ // edge beams (interrupted at hip bays) with a lip
+ for (const [a, b] of EDGE_SEGS) for (const s of [1, -1]) {
+ const za = s > 0 ? 7.0 : -8.0, zb = s > 0 ? 8.0 : -7.0;
+ box('concrete', a, b, -2.0, -0.8, za, zb, pick(TINT.concrete), 0.04);
+ box('concrete', a, b, -2.3, -2.0, s > 0 ? 7.55 : -8.0, s > 0 ? 8.0 : -7.55, pick(TINT.concrete), 0.04);
+ }
+ // deep concrete piers on the hip lines (carry the hip transverse girders)
+ for (const hx of LEGX) {
+ box('concrete', hx - 1.6, hx + 1.6, -2.9, -0.8, -1.7, 1.7, pick(TINT.concrete), 0.04);
+ box('concrete', hx - 0.85, hx + 0.85, -3.5, -2.9, -1.2, 1.2, pick(TINT.concrete), 0.04);
+ box('concrete', hx - 2.4, hx + 2.4, -1.5, -0.8, -2.0, 2.0, pick(TINT.concrete), 0.04);
+ }
+ // end beams
+ for (const s of [1, -1]) box('concrete', s > 0 ? 44.0 : -45.0, s > 0 ? 45.0 : -44.0, -2.1, -0.8, -8.0, 8.0, TINT.concrete[1], 0.03);
+ }
+
+ // =================================================================== 2. STEEL SPACE FRAME
+ {
+ // outer trusses
+ for (const s of [1, -1]) {
+ const z = s * 5.6;
+ for (const [ta, tb] of BAY_SEGS) { // interrupted at the hip bays (recess)
+ box('steel', ta, tb, -2.05, -1.7, z - 0.22, z + 0.22);
+ box('steel', ta, tb, -4.42, -4.12, z - 0.3, z + 0.3);
+ box('steel', ta, tb, -4.12, -3.85, z - 0.05, z + 0.05);
+ }
+ for (let i = 0; i < LINES.length; i++) {
+ const L = LINES[i];
+ if (!isHipLine(L)) {
+ beam('steel', V3(L, -4.12, z), V3(L, -2.05, z), 0.32, 0.32);
+ for (const zz of [z - 0.24, z + 0.24]) boxC('steelS', L, -2.4, zz, 1.0, 0.6, 0.04);
+ for (const zz of [z - 0.33, z + 0.33]) boxC('steelS', L, -3.85, zz, 1.0, 0.55, 0.04);
+ }
+ if (i < LINES.length - 1) {
+ const L2 = LINES[i + 1];
+ const up = i % 2 === 0;
+ beam('rust', V3(isHipLine(L) ? L + 3.7 : L + 0.2, up ? -4.1 : -2.1, z), V3(isHipLine(L2) ? L2 - 3.7 : L2 - 0.2, up ? -2.1 : -4.1, z), 0.22, 0.2, [0.9, 0.9, 0.9], 0.1);
+ // bolt rows on chords (tiny)
+ }
+ }
+ }
+ // spine box girders (interrupted at the drums)
+ const spineSegs = [[-44, -25.3], [-18.7, -4.9], [4.9, 18.7], [25.3, 44]];
+ for (const s of [1, -1]) {
+ const z = s * 2.2;
+ for (const [a, b] of spineSegs) {
+ box('steel', a, b, -3.6, -1.7, z - 0.42, z + 0.42);
+ box('steel', a, b, -3.76, -3.6, z - 0.62, z + 0.62);
+ for (let x = a + 0.55; x < b - 0.3; x += 1.1) for (const f of [-1, 1]) box('steelS', x - 0.03, x + 0.03, -3.58, -1.75, z + f * 0.42, z + f * 0.58);
+ }
+ }
+ // cross beams on bay lines
+ for (const L of LINES) {
+ const hip = isHipLine(L);
+ const drum = DRUMS.find((d) => Math.abs(d.x - L) < 0.01);
+ const ze = hip ? 4.9 : 7.0;
+ const spans = drum ? [[drum.r + 0.85, ze], [-ze, -(drum.r + 0.85)]] : [[-ze, ze]];
+ for (const [za, zb] of spans) {
+ if (hip) {
+ box('steel', L - 0.55, L + 0.55, -4.1, -2.2, za, zb);
+ box('steel', L - 0.75, L + 0.75, -4.25, -4.1, za, zb);
+ for (let z = za + 0.6; z < zb - 0.2; z += 1.2) for (const f of [-1, 1]) box('steelS', L + f * 0.55, L + f * 0.62, -4.05, -2.25, z - 0.03, z + 0.03);
+ } else {
+ const xL = Math.max(-44.7, Math.min(44.7, L));
+ box('steel', xL - 0.3, xL + 0.3, -2.3, -2.2, za, zb);
+ box('steel', xL - 0.035, xL + 0.035, -3.7, -2.3, za, zb);
+ box('steel', xL - 0.3, xL + 0.3, -3.8, -3.7, za, zb);
+ for (let z = za + 0.7; z < zb - 0.2; z += 1.4) for (const f of [-1, 1]) box('steelS', xL + f * 0.035, xL + f * 0.27, -3.7, -2.3, z - 0.02, z + 0.02);
+ }
+ }
+ }
+ // ring girders around the drums
+ for (const d of DRUMS) {
+ const Rg = d.r + 0.85, n = 16;
+ for (let i = 0; i < n; i++) {
+ const a0 = i / n * Math.PI * 2, a1 = (i + 1) / n * Math.PI * 2;
+ beam('steel', V3(d.x + Math.cos(a0) * Rg, -2.6, Math.sin(a0) * Rg), V3(d.x + Math.cos(a1) * Rg, -2.6, Math.sin(a1) * Rg), 0.45, 0.8);
+ }
+ // radial struts from ring to spine ends
+ for (const s of [1, -1]) for (const f of [-1, 1]) beam('rust', V3(d.x + f * Rg * 0.7, -2.9, s * Rg * 0.72), V3(d.x + f * (Rg + 1.6), -3.2, s * 2.2), 0.3, 0.3);
+ }
+ // bottom X-bracing between trusses and spines
+ for (let i = 0; i < 16; i++) {
+ const x0 = LINES[i] + 0.3, x1 = LINES[i + 1] - 0.3;
+ const xm = (x0 + x1) / 2;
+ if (DRUMS.some((d) => Math.abs(d.x - xm) < d.r + 3.5)) continue;
+ for (const s of [1, -1]) {
+ const zo = isHipLine(LINES[i]) || isHipLine(LINES[i + 1]) ? 4.55 : 5.4;
+ rod('rustS', V3(x0, -4.15, s * zo), V3(x1, -3.55, s * 2.6), 0.07, 6);
+ rod('rustS', V3(x0, -3.55, s * 2.6), V3(x1, -4.15, s * zo), 0.07, 6);
+ boxC('steelS', xm, -3.85, s * 4.0, 0.5, 0.06, 0.5);
+ }
+ }
+ }
+
+ // =================================================================== 3. HIP MOUNTING BAYS (yokes)
+ {
+ for (const hx of LEGX) for (const s of [1, -1]) {
+ // cheek plates (extruded trapezoids), clear of the 3.2 m hip sphere
+ const sh = new THREE.Shape();
+ const P = [[5.0, -0.8], [10.0, -0.8], [11.3, -1.9], [11.3, -3.6], [10.3, -5.5], [7.6, -6.3], [5.0, -4.8]];
+ P.forEach(([u, v], i) => (i ? sh.lineTo(u * s, v) : sh.moveTo(u * s, v)));
+ sh.closePath();
+ const eg = new THREE.ExtrudeGeometry(sh, { depth: 0.7, bevelEnabled: true, bevelThickness: 0.04, bevelSize: 0.05, bevelSegments: 1, curveSegments: 1 });
+ for (const dx of [-1, 1]) {
+ const ox = dx > 0 ? hx + 4.1 : hx - 3.4;
+ const m = new THREE.Matrix4().makeBasis(V3(0, 0, 1), V3(0, 1, 0), V3(-1, 0, 0)).setPosition(ox, 0, 0);
+ pushT('paint', eg.clone(), m, [0.46, 0.47, 0.44], 0.06);
+ // boss + bolt circle on outer face
+ const xo = hx + dx * 4.1;
+ cylX('steel', xo, xo + dx * 0.75, HY, s * HZ, 1.75, 32);
+ cylX('steel', xo + dx * 0.75, xo + dx * 1.1, HY, s * HZ, 1.05, 24);
+ ring('steelS', V3(xo + dx * 0.76, HY, s * HZ), 'x', 1.42, 0.07, 28, 4);
+ for (let k = 0; k < 12; k++) {
+ const a = k / 12 * Math.PI * 2;
+ cylX('steelS', xo + dx * 0.75, xo + dx * 0.88, HY + Math.cos(a) * 1.42, s * HZ + Math.sin(a) * 1.42, 0.08, 6);
+ }
+ // stiffener ribs on outer face of the plate
+ for (const [zz, y0, y1] of [[6.2, -5.4, -0.9], [11.0, -3.7, -1.9]]) box('steel', Math.min(xo, xo + dx * 0.35), Math.max(xo, xo + dx * 0.35), y0, y1, s * zz - 0.12, s * zz + 0.12);
+ for (const [z0, z1, yy] of [[5.2, 10.0, -1.15], [5.4, 7.0, -4.3], [10.4, 11.2, -4.0]]) box('steel', Math.min(xo, xo + dx * 0.3), Math.max(xo, xo + dx * 0.3), yy - 0.1, yy + 0.1, Math.min(s * z0, s * z1), Math.max(s * z0, s * z1));
+ for (let zz = 5.4; zz < 10.0; zz += 0.45) cylX('steelS', xo, xo + dx * 0.1, -0.98, s * zz, 0.05, 6);
+ for (let yy = -1.5; yy > -4.4; yy -= 0.45) cylX('steelS', xo, xo + dx * 0.1, yy, s * 5.25, 0.05, 6);
+ // hazard stripe plate along the lower edge
+ sign(0, V3(xo + dx * 0.01, -5.65, s * 8.95), V3(dx, 0, 0), 2.6, 0.45);
+ if (dx > 0) sign(hx > 0 ? 3 : 1, V3(xo + dx * 0.01, -1.6, s * 7.0), V3(dx, 0, 0), 0.8, 0.4);
+ // work lamp on the cheek, pointing down/outward at the hip
+ lamp(V3(hx + dx * 4.35, -5.8, s * 10.3), V3(dx * 0.3, -1, s * 0.5).normalize(), 1.1, 1.0, 8, 1.6);
+ }
+ // back wall + ribs + manifold
+ // round 2: the bay wall sits 1 m further in (|z| 4.4..4.9) so the thigh fork never clips it at extreme yaw
+ box('steel', hx - 3.4, hx + 3.4, -5.2, -0.8, s > 0 ? 4.4 : -4.9, s > 0 ? 4.9 : -4.4);
+ for (const fx of [-2.4, -0.8, 0.8, 2.4]) box('steel', hx + fx - 0.09, hx + fx + 0.09, -5.0, -1.0, s > 0 ? 4.9 : -5.04, s > 0 ? 5.04 : -4.9);
+ box('steel', hx - 3.4, hx + 3.4, -5.38, -5.2, s > 0 ? 4.3 : -5.08, s > 0 ? 5.08 : -4.3);
+ box('paint', hx - 1.2, hx + 1.2, -4.5, -3.3, s > 0 ? 4.9 : -5.0, s > 0 ? 5.0 : -4.9, [0.66, 0.4, 0.29], 0.08);
+ for (let k = 0; k < 8; k++) { const a = k / 8 * Math.PI * 2; cylZ('steelS', s * 5.0, s * 5.06, hx + Math.cos(a) * 1.0, -3.9 + Math.sin(a) * 0.5, 0.045, 6); }
+ sign(4, V3(hx - 2.2, -1.7, s * 4.9), V3(0, 0, s), 1.3, 0.65);
+ for (const fx of [-1.9, -0.3, 1.4, 2.9]) decal(fx > 1 ? 1 : 0, V3(hx + fx, -2.3, s * 4.9), V3(0, 0, s), VUP, fx > 1 ? 1.5 : 0.6, 2.8, 0.85);
+ // big diagonal struts from cheek bottoms to the spine
+ for (const dx of [-1, 1]) beam('steel', V3(hx + dx * 3.75, -5.7, s * 7.2), V3(hx + dx * 3.2, -3.5, s * 2.7), 0.5, 0.55);
+ // hose bundles heading for the hip housing
+ for (let k = 0; k < 3; k++) {
+ const x = hx + (k - 1) * 0.5 + 2.2 * (k % 2 ? 1 : -1);
+ hoseLoop(V3(hx + (k - 1) * 0.6, -4.9, s * 5.0), V3(x, -5.5, s * (8.7 + k * 0.3)), 0.9 + k * 0.25, 0.07, 0.06);
+ }
+ dangle(V3(hx + 3.0, -5.3, s * 5.0), rnd(1.2, 2.6), 0.03);
+ }
+ }
+
+ // =================================================================== 4. MACHINERY
+ const fanList = []; // {x,y,z,r,spd,ph}
+ // ---- drums (reactor + secondary turbines)
+ for (const d of DRUMS) {
+ const Rr = d.r, yTop = -1.75, yBot = d.big ? -5.0 : -4.6, cx = d.x;
+ const tint = d.big ? [0.6, 0.64, 0.6] : [0.66, 0.6, 0.5];
+ cylY('steel', cx, 0, yTop - 0.4, yTop, Rr + 0.6, 48);
+ cylY('paint', cx, 0, yBot, yTop - 0.4, Rr, 48, tint, 0.03);
+ const nr = d.big ? 24 : 16;
+ for (let i = 0; i < nr; i++) {
+ const a = (i + 0.5) / nr * Math.PI * 2, c = Math.cos(a), sn = Math.sin(a);
+ beam('steel', V3(cx + c * (Rr + 0.24), yBot + 0.05, sn * (Rr + 0.24)), V3(cx + c * (Rr + 0.24), yTop - 0.42, sn * (Rr + 0.24)), 0.14, 0.5, [1, 1, 1], 0.08, -a);
+ }
+ for (const y of [yTop - 0.75, (yTop + yBot) / 2, yBot + 0.3]) ring('rustS', V3(cx, y, 0), 'y', Rr + 0.03, 0.09, 64, 5);
+ cylY('steel', cx, 0, yBot - 0.25, yBot, Rr + 0.2, 48);
+ // radial ribs under the bottom plate
+ for (let i = 0; i < nr / 2; i++) {
+ const a = i / (nr / 2) * Math.PI * 2, c = Math.cos(a), sn = Math.sin(a);
+ const r0 = d.fan + 0.95, r1 = Rr + 0.1;
+ beam('steel', V3(cx + c * r0, yBot - 0.38, sn * r0), V3(cx + c * r1, yBot - 0.38, sn * r1), 0.12, 0.26);
+ }
+ for (const rr of [Rr - 0.25, Rr * 0.78]) ring('steelS', V3(cx, yBot - 0.27, 0), 'y', rr, 0.05, 48, 4);
+ // second step + shroud + fan + grille
+ const r2 = d.fan + 0.9;
+ cylY('paint', cx, 0, yBot - 1.0, yBot - 0.25, r2, 40, d.big ? [0.42, 0.45, 0.43] : [0.5, 0.45, 0.38], 0.04);
+ ring('rustS', V3(cx, yBot - 0.45, 0), 'y', r2 + 0.02, 0.07, 48, 4);
+ for (let i = 0; i < 12; i++) {
+ const a = i / 12 * Math.PI * 2;
+ beam('steelS', V3(cx + Math.cos(a) * (r2 + 0.06), yBot - 0.95, Math.sin(a) * (r2 + 0.06)), V3(cx + Math.cos(a) * (r2 + 0.06), yBot - 0.3, Math.sin(a) * (r2 + 0.06)), 0.1, 0.14, [1, 1, 1], 0.05, -a);
+ }
+ for (const rr of [r2 - 0.25, d.fan + 0.45]) ring('steelS', V3(cx, yBot - 1.02, 0), 'y', rr, 0.045, 40, 4);
+ ring('steel', V3(cx, yBot - 1.35, 0), 'y', d.fan + 0.14, 0.17, 48, 8, [1, 1, 1], 2.4);
+ const gy = yBot - 1.72, fr = d.fan + 0.05;
+ for (let k = -4; k <= 4; k++) {
+ const off = k * fr / 4.6, half = Math.sqrt(Math.max(0, fr * fr - off * off));
+ if (half < 0.1) continue;
+ box('steelS', cx + off - 0.025, cx + off + 0.025, gy - 0.03, gy + 0.03, -half, half);
+ box('steelS', cx - half, cx + half, gy - 0.07, gy - 0.01, off - 0.025, off + 0.025);
+ }
+ ring('steelS', V3(cx, gy, 0), 'y', fr, 0.05, 40, 4);
+ cylY('steel', cx, 0, yBot - 1.9, yBot - 1.0, d.fan * 0.2, 16);
+ sph('steelS', V3(cx, yBot - 1.9, 0), d.fan * 0.2, 12, [1, 1, 1], 0.6);
+ fanList.push({ x: cx, y: yBot - 1.35, z: 0, r: d.fan * 0.97, spd: d.big ? 1.9 : 2.6, ph: rnd(0, 6) });
+ // warm-lit intake behind the fan + rim lamps
+ cylY('emis', cx, 0, yBot - 1.06, yBot - 1.02, d.fan - 0.05, 32, [0.2, 0.075, 0.02], 0);
+ addLight(V3(cx, yBot - 1.8, 0), 1.0, 6.5, 1.5);
+ const nRim = d.big ? 4 : 3;
+ for (let k = 0; k < nRim; k++) {
+ const a = (k + 0.5) / nRim * Math.PI * 2;
+ lamp(V3(cx + Math.cos(a) * (d.fan + 0.42), yBot - 1.62, Math.sin(a) * (d.fan + 0.42)), V3(Math.cos(a) * 0.3, -1, Math.sin(a) * 0.3).normalize(), 0.9, 0.5, 5, 0.9);
+ }
+ // nozzles / inspection hatches on the drum wall
+ for (let i = 0; i < (d.big ? 8 : 5); i++) {
+ const a = rnd(0, Math.PI * 2), y = rnd(yBot + 0.6, yTop - 1.0);
+ const c = Math.cos(a), sn = Math.sin(a);
+ if (R() < 0.5) {
+ const p0 = V3(cx + c * Rr, y, sn * Rr), p1 = V3(cx + c * (Rr + 0.55), y, sn * (Rr + 0.55));
+ rod('steelS', p0, p1, rnd(0.12, 0.22), 10);
+ rod('steelS', p1, p1.clone().add(V3(c * 0.08, 0, sn * 0.08)), 0.3, 12);
+ } else {
+ boxC('paintS', cx + c * (Rr + 0.05), y, sn * (Rr + 0.05), 0.75, 0.9, 0.75, tint, 0.05, -a);
+ }
+ }
+ if (d.big) for (let k = 0; k < 4; k++) {
+ const a = k / 4 * Math.PI * 2 + 0.4;
+ lamp(V3(cx + Math.cos(a) * (Rr + 0.62), yBot - 0.1, Math.sin(a) * (Rr + 0.62)), V3(Math.cos(a) * 0.4, -1, Math.sin(a) * 0.4).normalize(), 1.0, 1.1, 8, 1.4);
+ }
+ else for (const s of [1, -1]) lamp(V3(cx, yBot - 0.15, s * (Rr + 0.5)), V3(0, -1, s * 0.4).normalize(), 1.0, 1.0, 7.5, 1.2);
+ sign(1, V3(cx - Rr - 0.01, (yTop + yBot) / 2, 0), V3(-1, 0, 0), 0.9, 0.45);
+ }
+ // ---- ceiling lamps up in the concrete coffers (light the stepped slab like ref5)
+ for (let i = 0; i < 16; i++) {
+ const xm = (LINES[i] + LINES[i + 1]) / 2;
+ for (const z of i % 2 ? [-1.0] : [1.0]) pendant(xm + rnd(-1, 1), -1.75, z * rnd(0.6, 1.6), 0.25, 1.05, 1.1, 8.5, 1.15);
+ }
+ // ---- catwalk ring around the reactor
+ {
+ const Rc = 5.25, n = 20, y = -5.3;
+ for (let i = 0; i < n; i++) {
+ const a0 = i / n * Math.PI * 2, a1 = (i + 1) / n * Math.PI * 2;
+ const p0 = V3(Math.cos(a0) * Rc, y, Math.sin(a0) * Rc), p1 = V3(Math.cos(a1) * Rc, y, Math.sin(a1) * Rc);
+ const gap = Math.abs(Math.sin((a0 + a1) / 2)) > 0.62 && Math.abs(Math.cos((a0 + a1) / 2)) < 0.8;
+ catwalk(p0, p1, 1.0, [!gap, false], i % 2 ? null : -2.6, 10);
+ }
+ }
+ // ---- gearboxes + motors flanking the reactor
+ for (const f of [-1, 1]) {
+ const x0 = f * 5.3, x1 = f * 8.3;
+ const gt = [0.78, 0.64, 0.4];
+ box('paint', Math.min(x0, x1), Math.max(x0, x1), -4.6, -2.2, -1.5, 1.5, gt, 0.04);
+ box('steel', Math.min(x0, x1) - 0.1, Math.max(x0, x1) + 0.1, -2.35, -2.2, -1.65, 1.65);
+ box('steel', Math.min(x0, x1) - 0.1, Math.max(x0, x1) + 0.1, -3.5, -3.38, -1.6, 1.6);
+ for (let k = 0; k < 6; k++) { const x = f * (5.5 + k * 0.5); for (const s of [1, -1]) box('paintS', x - 0.04, x + 0.04, -4.5, -2.4, s * 1.5, s * 1.62, gt); }
+ cylX('chrome', f * 4.0, f * 5.3, -3.4, 0, 0.28, 16);
+ cylX('steel', f * 4.4, f * 4.65, -3.4, 0, 0.62, 20);
+ for (const z of [-0.8, 0.8]) {
+ const mt = [0.5, 0.58, 0.66];
+ cylX('paint', f * 8.3, f * 9.8, -3.5, z, 0.62, 24, mt, 0.04);
+ for (let k = 0; k < 7; k++) ring('paintS', V3(f * (8.45 + k * 0.2), -3.5, z), 'x', 0.63, 0.035, 20, 3, mt);
+ cylX('steel', f * 9.8, f * 10.05, -3.5, z, 0.45, 20);
+ box('paintS', f * 9.0 - 0.25, f * 9.0 + 0.25, -2.85, -2.6, z - 0.2, z + 0.2, [0.4, 0.42, 0.45]);
+ }
+ // oil cooler + piping up into the slab
+ pipe('rust', [V3(f * 6.0, -4.6, 1.0), V3(f * 6.0, -5.1, 1.0), V3(f * 3.6, -5.1, 1.0)], 0.1, { flanges: false });
+ pipe('steel', [V3(f * 7.6, -2.2, -1.1), V3(f * 7.6, -1.7, -1.1)], 0.2, {});
+ pipe('rust', [V3(f * 7.0, -4.6, -0.9), V3(f * 7.0, -4.95, -0.9), V3(f * 9.6, -4.95, -0.9), V3(f * 9.6, -4.95, -1.6), V3(f * 9.6, -2.2, -1.6)], 0.08, { flanges: false });
+ sign(3, V3(f * 8.31, -3.0, 0.9), V3(f, 0, 0), 0.5, 0.25);
+ lamp(V3(f * 9.6, -4.25, 0), V3(0, -1, 0), 0.95, 0.9, 7, 1.2);
+ }
+ // ---- tanks (horizontal capsules) above the service catwalks
+ for (const f of [-1, 1]) for (const s of [1, -1]) {
+ const xa = f * 11.9, xb = f * 15.7, z = s * 3.55, y = -2.35, r = 0.55;
+ const tt = pick([[0.78, 0.79, 0.76], [0.6, 0.66, 0.6], [0.82, 0.7, 0.48]]);
+ cylX('paint', xa, xb, y, z, r, 24, tt, 0.03);
+ sph('paint', V3(xa, y, z), r, 16, tt, 1); sph('paint', V3(xb, y, z), r, 16, tt, 1);
+ for (const x of [xa + f * 0.7, xb - f * 0.7]) {
+ ring('rustS', V3(x, y, z), 'x', r + 0.02, 0.06, 24, 4);
+ box('steelS', x - 0.08, x + 0.08, y + r * 0.5, -1.75, z - 0.06, z + 0.06);
+ }
+ pipe('steelS', [V3((xa + xb) / 2, y - r, z), V3((xa + xb) / 2, y - r - 0.2, z), V3((xa + xb) / 2 + f * 0.8, y - r - 0.2, s * 2.75)], 0.06, { flanges: false });
+ rod('steelS', V3(xa + f * 0.6, y - r, z), V3(xa + f * 0.6, y - r - 0.35, z), 0.05, 6);
+ if (s > 0) sign(2, V3((xa + xb) / 2, y, z + r + 0.01), V3(0, 0, 1), 0.6, 0.3);
+ }
+ // ---- central-lane cabins
+ for (const f of [-1, 1]) {
+ const cx = f * 14.3;
+ cabin(cx, 0, -1.75, 3.0, 2.55, 2.5, { door: 'pz', windows: ['pz', 'nz', 'px', 'nx'], ac: true, litP: 0.8 });
+ // door platform to the service catwalk + short stair
+ catwalk(V3(cx - 0.3, -4.3, 1.35), V3(cx - 0.3, -4.3, 2.75), 0.9, [true, true], null);
+ stairs(V3(cx - 0.3, -5.3, 3.75), V3(cx - 0.3, -4.3, 2.75), 0.8);
+ }
+ // ---- compressors (vertical finned) at ±29.5
+ for (const f of [-1, 1]) for (const z of [-0.9, 0.9]) {
+ const cx = f * 29.6, ct = [0.55, 0.6, 0.55];
+ cylY('paint', cx, z, -4.5, -2.2, 0.62, 24, ct, 0.04);
+ for (let y = -4.35; y < -2.4; y += 0.17) ring('paintS', V3(cx, y, z), 'y', 0.64, 0.035, 20, 3, ct);
+ cylY('steel', cx, z, -4.85, -4.5, 0.48, 20);
+ sph('steel', V3(cx, -4.85, z), 0.48, 14, [1, 1, 1], 0.5);
+ box('paint', cx - 0.45, cx + 0.45, -2.2, -1.72, z - 0.45, z + 0.45, [0.45, 0.47, 0.5]);
+ pipe('rust', [V3(cx, -3.0, z + Math.sign(z) * 0.6), V3(cx, -3.0, Math.sign(z) * 2.0), V3(cx - f * 1.5, -3.0, Math.sign(z) * 2.0)], 0.12, { flanges: false });
+ }
+ for (const f of [-1, 1]) lamp(V3(f * 29.6, -4.6, 0), V3(0, -1, 0), 1.0, 1.0, 7.5, 1.2);
+ // ---- electrical cabinets at ±35.8, vertical tanks + pumps at the ends
+ for (const f of [-1, 1]) {
+ const cx = f * 35.8;
+ for (let k = 0; k < 3; k++) {
+ const z0 = -1.6 + k * 1.07;
+ box('paint', cx - 0.55, cx + 0.55, -4.0, -2.2, z0 + 0.03, z0 + 1.04, pick(TINT.cabin), 0.05);
+ box('steelS', cx - f * 0.57, cx - f * 0.6, -3.85, -2.35, z0 + 0.1, z0 + 0.97);
+ if (k === 1) sign(3, V3(cx - f * 0.61, -2.75, z0 + 0.53), V3(-f, 0, 0), 0.4, 0.2);
+ for (let j = 0; j < 3; j++) rod('steelS', V3(cx + rnd(-0.3, 0.3), -2.2, z0 + 0.5 + rnd(-0.3, 0.3)), V3(cx + rnd(-0.3, 0.3), -1.75, z0 + 0.5), 0.04, 5);
+ }
+ pendant(cx - f * 1.0, -2.3, 0, 1.5, 1.0, 1.0, 7, 1.2);
+ // lit control cabin hanging under the block end + platform to the service walkways
+ cabin(f * 40.3, 0, -1.8, 3.6, 2.6, 3.0, { door: 'pz', windows: ['pz', 'nz', 'px', 'nx'], litP: 0.92, hangTo: -0.85 });
+ catwalk(V3(f * 39.6, -4.4, 1.6), V3(f * 39.6, -4.4, 2.9), 0.9, [true, true], null);
+ stairs(V3(f * 39.6, -5.3, 3.7), V3(f * 39.6, -4.4, 2.9), 0.8);
+ // pump skid
+ box('steel', f * 43.2 - 0.5, f * 43.2 + 0.5, -3.6, -3.45, -1.3, 1.3);
+ cylZ('paint', -0.9, 0.9, f * 43.2, -3.95, 0.4, 20, [0.5, 0.58, 0.66]);
+ for (const s of [-1, 1]) rod('steelS', V3(f * 43.2, -3.45, s * 1.1), V3(f * 43.2, -2.1, s * 1.1), 0.05, 6);
+ pipe('steel', [V3(f * 43.2, -3.95, 1.0), V3(f * 43.2, -3.95, 2.0), V3(f * 43.2, -3.3, 2.0)], 0.12, {});
+ }
+
+ // =================================================================== 5. SERVICES (pipes, trays, ducts)
+ {
+ // longitudinal pipe racks in the two service lanes
+ const racks = [[2.95, -3.05, 0.3], [3.55, -3.2, 0.18], [4.05, -3.0, 0.13], [4.45, -3.35, 0.22], [3.25, -3.62, 0.1], [4.7, -3.66, 0.08]];
+ for (const s of [1, -1]) for (const [zz, y, r] of racks) {
+ const z = s * zz;
+ // where would this pipe hit a drum? -> end it into the drum wall
+ const stops = [];
+ for (const d of DRUMS) { const Rr = d.r + 0.55; if (Math.abs(z) < Rr) stops.push([d.x - Math.sqrt(Rr * Rr - z * z), d.x + Math.sqrt(Rr * Rr - z * z)]); }
+ const tint = R() < 0.4 ? [0.85, 0.82, 0.78] : [1, 1, 1];
+ const bn = R() < 0.45 ? 'rust' : 'steel';
+ let x = -43.5;
+ const segs = [];
+ for (const [a, b] of stops.sort((p, q) => p[0] - q[0])) { segs.push([x, a]); x = b; }
+ segs.push([x, 43.5]);
+ for (const [a, b] of segs) {
+ if (b - a < 1.0) continue;
+ const pts = [];
+ if (a < -43) pts.push(V3(a + 0.6, -1.75, z), V3(a + 0.6, y, z)); else pts.push(V3(a, y, z));
+ if (b > 43) pts.push(V3(b - 0.6, y, z), V3(b - 0.6, -1.75, z)); else pts.push(V3(b, y, z));
+ pipe(bn, pts, r, { tint, valves: 0.12, every: 5.5 });
+ }
+ }
+ // cable trays
+ for (const s of [1, -1]) {
+ const z = s * 4.95, y = -4.0;
+ for (const [ta, tb] of BAY_SEGS) {
+ const a = Math.max(ta, -43.5), b = Math.min(tb, 43.5);
+ box('steelS', a, b, y - 0.02, y + 0.01, z - 0.27, z + 0.27);
+ for (const f of [-1, 1]) box('steelS', a, b, y, y + 0.12, z + f * 0.27 - 0.012, z + f * 0.27 + 0.012);
+ for (let k = 0; k < 7; k++) {
+ const zz = z - 0.21 + k * 0.07;
+ rod('rubber', V3(a, y + 0.05 + (k % 2) * 0.04, zz), V3(b, y + 0.05 + (k % 2) * 0.04, zz), 0.03 + (k % 3) * 0.008, 5, k % 4 === 1 ? [3.2, 2.9, 2.2] : k % 4 === 3 ? [2.2, 0.9, 0.6] : [1, 1, 1]);
+ }
+ }
+ for (const L of LINES) if (L > -44 && L < 44 && !isHipLine(L)) for (const f of [-1, 1]) rod('steelS', V3(L, -3.8, z + f * 0.28), V3(L, y, z + f * 0.28), 0.018, 4);
+ }
+ // high ducts between the spines and the trusses
+ for (const s of [1, -1]) for (const [a, b] of [[-43.5, -25.6], [-18.4, -16.2], [-11.4, -5.2], [5.2, 11.4], [16.2, 18.4], [25.6, 43.5]]) {
+ const z = s * 4.0;
+ box('paintS', a, b, -2.2, -1.75, z - 0.45, z + 0.45, [0.62, 0.64, 0.62], 0.05);
+ for (let x = a + 1.2; x < b - 0.5; x += 2.4) box('steelS', x - 0.05, x + 0.05, -2.24, -1.75, z - 0.5, z + 0.5);
+ }
+ // vertical risers from machinery to the slab + hose loops in the service lanes
+ for (let i = 0; i < 16; i++) {
+ const x0 = LINES[i];
+ for (const s of [1, -1]) {
+ if (R() < 0.75) {
+ const xa = x0 + rnd(0.8, 2.0), xb = xa + rnd(1.8, 3.2);
+ const za = s * rnd(2.8, 4.6), zb = s * rnd(2.8, 4.6);
+ if (!DRUMS.some((d) => Math.abs(d.x - (xa + xb) / 2) < d.r + 1.5)) hoseLoop(V3(xa, -3.75, za), V3(xb, -3.75, zb), rnd(0.35, 1.0), rnd(0.035, 0.07), 0.07);
+ }
+ if (R() < 0.5) {
+ const x = x0 + rnd(1.2, 4.3);
+ if (!DRUMS.some((d) => Math.abs(d.x - x) < d.r + 1)) dangle(V3(x, -3.8, s * rnd(2.8, 4.6)), rnd(0.6, 1.4), 0.025);
+ }
+ }
+ }
+ // junction boxes on truss posts (outer faces) with conduit
+ for (const L of LINES) for (const s of [1, -1]) if (R() < 0.7 && Math.abs(L) < 44 && !isHipLine(L)) junction(V3(L + 0.35, -3.1, s * 5.85), V3(0, 0, s), rnd(0.8, 1.2));
+ }
+
+ // =================================================================== 6. SERVICE CATWALKS + LAMPS (centre)
+ {
+ for (const s of [1, -1]) {
+ const z = s * 3.8, y = -5.3;
+ for (const [a, b] of [[-43.6, -4.4], [4.4, 43.6]]) catwalk(V3(a, y, z), V3(b, y, z), 1.1, s > 0 ? [true, true] : [true, true], -3.8, 5.5);
+ for (const L of LINES) {
+ if (Math.abs(L) < 4 || Math.abs(L) > 44) continue;
+ pendant(L, isHipLine(L) ? -4.25 : -3.8, z, 0.12, 1.0, 1.0, 7.5, 1.0);
+ }
+ // retractable access ladders hanging below the walkways + ladders up into hatches
+ for (const x of s > 0 ? [-38.2, 17.4] : [-17.6, 38.0]) ladder(x, z + s * 0.62, -5.3, -7.4, true, false);
+ for (const x of s > 0 ? [-25.5, 30.8] : [-31.2, 8.6]) { ladder(x, s * 3.82, -5.3, -2.1, true, true); box('steel', x - 0.5, x + 0.5, -2.2, -2.1, s * 3.82 - 0.5, s * 3.82 + 0.5); }
+ // cross-walks to the edge
+ }
+ // end catwalks across the block ends
+ for (const f of [-1, 1]) {
+ catwalk(V3(f * 44.9, -3.1, -7.4), V3(f * 44.9, -3.1, 7.4), 1.0, f > 0 ? [true, false] : [false, true], -2.1, 3.7);
+ for (const z of [-6, -2, 2, 6]) pendant(f * 45.1, -2.1, z, 0.1, 1.0, 0.9, 7, 1.0);
+ ladder(f * 45.0, -7.2, -3.1, -6.4, false, false);
+ // connecting stair down from end catwalk to the service catwalk level
+ stairs(V3(f * 43.0, -5.3, 3.8), V3(f * 44.6, -3.1, 3.8 + 0.0), 0.8);
+ }
+ }
+
+ // =================================================================== 7. EDGE SKIRT
+ const edgeCabins = [[-40.8, 1], [-24, 1], [-17.6, 1], [-1.5, 1], [20.2, 1], [26.0, 1], [41.0, 1], [-41.4, -1], [-25.6, -1], [-18.6, -1], [3.2, -1], [17.6, -1], [25.0, -1], [40.4, -1]];
+ {
+ const inCabin = (x, s, pad = 0) => edgeCabins.some(([cx, cs]) => cs === s && Math.abs(x - cx) < 1.6 + pad);
+ for (const s of [1, -1]) {
+ const zs = (z) => s * z;
+ for (const [a, b] of EDGE_SEGS) {
+ // fascia channel
+ box('steel', a, b, -2.5, -2.3, Math.min(zs(7.95), zs(8.2)), Math.max(zs(7.95), zs(8.2)));
+ box('steel', a, b, -2.5, -2.0, Math.min(zs(8.16), zs(8.22)), Math.max(zs(8.16), zs(8.22)));
+ // brackets every 2.75 m
+ for (let x = Math.ceil(a / 2.75) * 2.75; x <= b + 0.01; x += 2.75) {
+ beam('steel', V3(x, -0.95, zs(7.6)), V3(x, -0.95, zs(9.55)), 0.16, 0.3);
+ if (!inCabin(x, s, 0.2)) rod('rust', V3(x, -2.3, zs(7.95)), V3(x, -1.1, zs(9.4)), 0.06, 6);
+ if (!inCabin(x, s, 0.2)) rod('steelS', V3(x, -1.1, zs(9.38)), V3(x, -3.1, zs(9.38)), 0.025, 4);
+ boxC('steelS', x, -1.25, zs(7.62), 0.04, 0.6, 0.5);
+ }
+ // edge catwalk segments (cut around cabins)
+ const cuts = edgeCabins.filter(([cx, cs]) => cs === s && cx > a && cx < b).map(([cx]) => [cx - 1.7, cx + 1.7]).sort((p, q) => p[0] - q[0]);
+ let x = a + 0.1; const runs = [];
+ for (const [c0, c1] of cuts) { runs.push([x, c0]); x = c1; }
+ runs.push([x, b - 0.1]);
+ for (const [r0, r1] of runs) if (r1 - r0 > 0.8) catwalk(V3(r0, -3.1, zs(8.75)), V3(r1, -3.1, zs(8.75)), 1.1, s > 0 ? [false, true] : [true, false], null);
+ // wall-mounted pipes along fascia + under-floor pipes
+ pipe('rust', [V3(a + 0.3, -2.0, zs(8.36)), V3(a + 0.3, -2.75, zs(8.36)), V3(b - 0.3, -2.75, zs(8.36)), V3(b - 0.3, -2.0, zs(8.36))], 0.11, { valves: 0.25 });
+ pipe('steel', [V3(a + 0.6, -2.3, zs(8.3)), V3(a + 0.6, -2.42, zs(8.3)), V3(b - 0.6, -2.42, zs(8.3))], 0.07, { flanges: false });
+ pipe('steel', [V3(a + 0.5, -2.5, zs(8.6)), V3(a + 0.5, -3.42, zs(8.6)), V3(b - 0.5, -3.42, zs(8.6)), V3(b - 0.5, -2.5, zs(8.6))], 0.17, { every: 4.5 });
+ pipe('rust', [V3(a + 0.9, -3.35, zs(9.05)), V3(b - 0.9, -3.35, zs(9.05))], 0.1, { every: 3.5 });
+ // hanging cable loops under the walkways
+ for (let x2 = a + 1.0; x2 < b - 2.0; x2 += rnd(1.6, 3.2)) {
+ const len = rnd(1.4, 3.0);
+ if (x2 + len > b - 0.5) break;
+ hoseLoop(V3(x2, -3.3, zs(rnd(8.4, 9.2))), V3(x2 + len, -3.3, zs(rnd(8.4, 9.2))), rnd(0.25, 0.9), rnd(0.025, 0.05), 0.06);
+ }
+ // lamps under the bracket arms
+ for (let x2 = Math.ceil(a / 5.5) * 5.5 + 1.375; x2 < b; x2 += 5.5) {
+ if (inCabin(x2, s, 0.3)) continue;
+ pendant(x2, -1.1, zs(9.0), 0.15, 1.05, 1.0, 7.5, 1.1);
+ }
+ // drains with spouts (drips are animated)
+ for (let x2 = a + 2.0; x2 < b - 1; x2 += rnd(4.5, 7.5)) {
+ if (inCabin(x2, s, 0.3)) continue;
+ pipe('rustS', [V3(x2, -2.2, zs(8.2)), V3(x2, -2.2, zs(9.75)), V3(x2, -2.55, zs(9.75))], 0.06, { flanges: false, bend: 0.12 });
+ DRIP_SRC.push(V3(x2, -2.6, zs(9.75)));
+ }
+ // concrete corbels on the edge beam, fascia work lamps, utility boxes, downpipes
+ for (let x2 = Math.ceil(a / 2.75) * 2.75 + 1.375; x2 < b - 0.2; x2 += 2.75) {
+ box('concrete', x2 - 0.2, x2 + 0.2, -1.95, -0.8, Math.min(zs(7.9), zs(8.3)), Math.max(zs(7.9), zs(8.3)), pick(TINT.concrete), 0.05);
+ if (inCabin(x2, s, 0.1)) continue;
+ const r2 = R();
+ if (r2 < 0.45) lamp(V3(x2 + 0.6, -1.75, zs(8.36)), V3(0, -0.7, s).normalize(), 1.0, 0.9, 6.5, 1.05);
+ else if (r2 < 0.75) junction(V3(x2 + 0.7, -1.55, zs(8.0)), V3(0, 0, s), rnd(0.8, 1.3));
+ else pipe('rustS', [V3(x2 + 0.5, -0.8, zs(8.45)), V3(x2 + 0.5, -2.9, zs(8.45)), V3(x2 + 0.5, -2.9, zs(9.1))], 0.07, { flanges: false });
+ }
+ // dangling cables off the walkway edge
+ for (let k = 0; k < 3; k++) { const x2 = rnd(a + 0.5, b - 0.5); if (!inCabin(x2, s, 0.2)) dangle(V3(x2, -3.25, zs(9.3)), rnd(0.8, 2.8), rnd(0.02, 0.035)); }
+ }
+ }
+ // edge cabins + small balconies
+ for (const [cx, s] of edgeCabins) {
+ const z = s * 9.2;
+ cabin(cx, z, -1.12, 3.2, 2.25, 2.1, { door: Math.abs(cx) > 40 ? (cx > 0 ? 'nx' : 'px') : (cx < 0 ? 'px' : 'nx'), windows: [s > 0 ? 'pz' : 'nz', 'px', 'nx'], litP: 0.93 });
+ ladder(cx + (cx < 0 ? -0.9 : 0.9), s * 10.45, -3.4, -5.2 - rnd(0, 1.2), true, false);
+ }
+ for (const [x, s] of [[-12.0, 1], [8.8, -1], [-35.0, -1], [35.5, 1]].filter(([x]) => !LEGX.some((hx) => Math.abs(hx - x) < 4.6))) {
+ catwalk(V3(x - 1.2, -3.1, s * 9.9), V3(x + 1.2, -3.1, s * 9.9), 1.0, [true, true], -1.0, 2.4);
+ }
+ // ends: fascia, pipes, brackets
+ for (const f of [-1, 1]) {
+ box('steel', f * 44.9 - 0.12, f * 44.9 + 0.12, -2.5, -2.1, -8.0, 8.0);
+ pipe('rust', [V3(f * 45.15, -1.9, -7.2), V3(f * 45.15, -2.35, -7.2), V3(f * 45.15, -2.35, 7.2), V3(f * 45.15, -1.9, 7.2)], 0.12, {});
+ for (let z = -6.0; z <= 6.01; z += 4) dangle(V3(f * 45.35, -3.25, z + rnd(-1, 1)), rnd(0.8, 2.2), 0.03);
+ }
+ }
+
+ // =================================================================== 8. ROUND 2: PRACTICALS, HANGING MODULES, FASCIA CLUTTER
+ {
+ const swayConst = (g, w, ph, fr) => {
+ const sw = new Float32Array(g.attributes.position.count * 3);
+ for (let i = 0; i < sw.length; i += 3) { sw[i] = w; sw[i + 1] = ph; sw[i + 2] = fr; }
+ g.setAttribute('aSway', new THREE.BufferAttribute(sw, 3));
+ return g;
+ };
+ // hanging chain with a hook (beaded tube, sways as one pendulum)
+ function chain(a, len, hook = true) {
+ const nL = Math.max(8, Math.round(len / 0.11)), pts = [], w = [];
+ for (let i = 0; i <= nL; i++) { const t = i / nL; pts.push(V3(a.x, a.y - len * t, a.z)); w.push(Math.pow(t, 1.3) * 0.05 * len); }
+ const ph = rnd(0, 6.28), fr = rnd(0.9, 1.3) / Math.sqrt(Math.max(0.8, len));
+ push('sway', sweepGeo(pts, (t) => 0.022 + 0.022 * (Math.round(t * nL) % 2), 5, w, ph, fr), [2.6, 2.2, 1.8], 0.2);
+ if (hook) {
+ const e = pts[nL];
+ push('sway', swayConst(new THREE.TorusGeometry(0.13, 0.035, 5, 10, Math.PI * 1.4).applyMatrix4(new THREE.Matrix4().makeRotationZ(-2.2).setPosition(e.x, e.y - 0.17, e.z)), w[nL], ph, fr), [2.4, 1.6, 1.1]);
+ push('sway', swayConst(unitCyl(6).clone().applyMatrix4(new THREE.Matrix4().makeScale(0.07, 0.14, 0.07).setPosition(e.x, e.y - 0.02, e.z)), w[nL], ph, fr), [2.2, 2.0, 1.6]);
+ }
+ }
+ // bundle of dangling cables / hoses of different lengths from one clamp
+ function bundle(a, cnt, len, r = 0.03) {
+ boxC('steelS', a.x, a.y + 0.05, a.z, 0.3, 0.1, 0.3);
+ for (let i = 0; i < cnt; i++) dangle(V3(a.x + rnd(-0.12, 0.12), a.y, a.z + rnd(-0.12, 0.12)), len * rnd(0.45, 1.0), r * rnd(0.6, 1.3), 0.07, i % 2 === 0);
+ }
+ const gauge = (c, nrm, sz = 0.36) => { sign(6, c, nrm, sz * 2, sz); };
+
+ // ---------------- practicals: ~20 big lamps for the whole belly, everything else stays dark
+ // hip-bay work floods (6 of the 8 bays; they also carry the 6 real PointLights that spill onto the legs)
+ for (const [hx, s, dx] of [[-33, 1, 1], [-11, 1, -1], [11, 1, 1], [33, 1, -1], [-11, -1, 1], [11, -1, -1]]) {
+ const p = V3(hx + dx * 3.02, -0.72, s * 5.78); // tucked into the top corner of the bay, 4.9 m from the hip
+ flood(p, V3(hx - p.x, -3.4 - p.y, s * 9.6 - p.z), { from: V3(hx + dx * 3.4, -0.72, s * 5.78), k: 2.3, r: 14, cone: 0.25, real: true });
+ sign(0, V3(hx + dx * 3.39, -2.2, s * 7.6), V3(-dx, 0, 0), 1.3, 0.65);
+ }
+ // fascia floods washing down the edge between cabins (partly hidden behind the bracket arms / pipes)
+ for (const [x, s] of [[-20.8, 1], [23.1, 1], [-22.1, -1], [21.3, -1]]) {
+ flood(V3(x, -1.25, s * 9.25), V3(0.15, -1, -s * 0.28), { from: V3(x, -0.95, s * 8.3), k: 2.0, r: 13, cone: 0.2 });
+ }
+ // cool fluorescent tubes by the mid-block cabins (one stutters)
+ tubeLamp(V3(1.9, -1.45, 8.95), V3(1, 0, 0), 1.5, { flick: true, drop: 0.45 });
+ tubeLamp(V3(-0.6, -1.45, -8.95), V3(1, 0, 0), 1.5, { drop: 0.45 });
+ tubeLamp(V3(-41.6, -2.45, 3.4), V3(1, 0, 0), 1.5, { drop: 0.3, k: 1.0 });
+ // block ends
+ for (const f of [-1, 1]) cageLamp(V3(f * 45.15, -2.3, f * 2.2), { from: V3(f * 45.15, -2.1, f * 2.2), k: 1.5, r: 11, flick: f > 0 });
+ // under the reactor + secondary drums: caged lamps light the ribbed bottom plates and shrouds
+ for (const a of [0.9, 4.0]) cageLamp(V3(Math.cos(a) * 3.62, -5.42, Math.sin(a) * 3.62), { k: 1.8, r: 11, s: 1.1 });
+ for (const f of [-1, 1]) cageLamp(V3(f * 22 + 2.25, -4.85, f * 2.3), { from: V3(f * 22 + 2.25, -3.0, f * 2.3), k: 1.6, r: 10 });
+ // uplights from the service walkways: warm pools on the stepped concrete coffers (ref5)
+ for (const [x, s] of [[-27.4, 1], [16.6, -1], [37.9, 1], [-5.6, -1]]) {
+ flood(V3(x, -4.15, s * 3.25), V3(0.1, 1, -s * 0.55), { from: V3(x, -4.25, s * 3.8), k: 3.4, r: 15, cone: -0.05 });
+ }
+
+ // ---------------- concrete: stepped corbels under the transfer beams + secondary ribs in the coffers
+ for (const L of LINES) {
+ if (isHipLine(L) || Math.abs(L) > 43) continue;
+ for (const s of [1, -1]) {
+ box('concrete', L - 0.8, L + 0.8, -2.75, -2.2, Math.min(s * 5.98, s * 7.0), Math.max(s * 5.98, s * 7.0), pick(TINT.concrete), 0.05);
+ box('concrete', L - 0.58, L + 0.58, -3.2, -2.75, Math.min(s * 6.4, s * 7.0), Math.max(s * 6.4, s * 7.0), pick(TINT.concrete), 0.05);
+ box('concrete', L - 0.62, L + 0.62, -2.6, -2.2, Math.min(s * 0.35, s * 1.55), Math.max(s * 0.35, s * 1.55), pick(TINT.concrete), 0.05);
+ }
+ }
+ for (let i = 0; i < 16; i++) {
+ const x0 = LINES[i] + 0.45, x1 = LINES[i + 1] - 0.45, xm = (x0 + x1) / 2;
+ if (DRUMS.some((d) => Math.abs(d.x - xm) < d.r + 2.2)) continue;
+ box('concrete', xm - 0.22, xm + 0.22, -1.75, -0.8, -4.6, 4.6, pick(TINT.concrete), 0.05); // mid-bay rib
+ for (const s of [1, -1]) box('concrete', x0, x1, -1.95, -1.3, Math.min(s * 0.0, s * 0.28), Math.max(s * 0.0, s * 0.28), pick(TINT.concrete), 0.05);
+ }
+
+ // ---------------- transverse bridges between the two service catwalks (grated, hung)
+ for (const x of [-37.4, -26.6, -18.2, 18.2, 26.6, 37.4]) {
+ catwalk(V3(x, -5.3, -3.25), V3(x, -5.3, 3.25), 0.9, [true, true], -3.7, 2.17);
+ chain(V3(x + 0.6, -5.45, rnd(-2, 2)), rnd(1.4, 3.2));
+ }
+ // chains + hose bundles under the machinery (sway)
+ for (const [x, z, len] of [[-3.2, 4.6, 3.4], [3.6, -4.5, 2.6], [-8.9, 1.9, 2.2], [9.2, -1.9, 3.0], [-19.4, 3.1, 2.4], [24.9, -3.0, 2.0], [-30.6, 2.2, 2.8], [30.9, -2.3, 2.3], [-43.4, -2.4, 2.6], [43.5, 2.0, 2.2]]) {
+ if (R() < 0.5) chain(V3(x, -4.7, z), len); else bundle(V3(x, -4.7, z), 4, len, 0.035);
+ }
+ for (const f of [-1, 1]) for (const s of [1, -1]) bundle(V3(f * 6.6, -4.6, s * 1.9), 5, rnd(1.6, 2.8), 0.04);
+
+ // ---------------- outer cable trays on the truss faces, overflowing with cables
+ for (const s of [1, -1]) for (const [ta, tb] of BAY_SEGS) {
+ const z = s * 6.2, y = -3.42, a = Math.max(ta + 0.5, -43.6), b = Math.min(tb - 0.5, 43.6);
+ box('steelS', a, b, y - 0.02, y + 0.01, z - 0.24, z + 0.24);
+ for (const f of [-1, 1]) box('steelS', a, b, y, y + 0.1, z + f * 0.24 - 0.012, z + f * 0.24 + 0.012);
+ for (let x = a + 0.4; x < b; x += 1.8) { box('steelS', x - 0.03, x + 0.03, y - 0.06, y - 0.02, z - 0.3, z + 0.3); rod('steelS', V3(x, y - 0.04, s * 5.92), V3(x, y + 0.5, s * 5.92), 0.02, 4); }
+ for (let k = 0; k < 6; k++) rod('rubber', V3(a, y + 0.045 + (k % 2) * 0.035, z - 0.18 + k * 0.072), V3(b, y + 0.045 + (k % 2) * 0.035, z - 0.18 + k * 0.072), 0.028 + (k % 3) * 0.008, 5, k % 3 === 1 ? [3.0, 2.7, 2.1] : [1, 1, 1]);
+ for (let x = a + rnd(0.5, 2); x < b - 3; x += rnd(2.2, 4.5)) hoseLoop(V3(x, y - 0.03, z + s * 0.2), V3(x + rnd(1.4, 2.8), y - 0.03, z + s * 0.2), rnd(0.3, 0.9), rnd(0.025, 0.045), 0.05);
+ }
+
+ // ---------------- lower tier of hanging service modules under the edge walkways (ref1)
+ const pods = [[-21.0, 1, 0], [2.7, 1, 1], [23.2, 1, 2], [-41.6, 1, 1], [-22.0, -1, 2], [-2.2, -1, 0], [21.4, -1, 1], [42.0, -1, 0]];
+ for (const [cx, s, kind] of pods) {
+ const z = s * 9.35, yT = -3.78;
+ if (kind === 0) { // slung cabin with lit windows + balcony ledge + ladder up
+ cabin(cx, z, yT, 2.9, 1.95, 1.9, { windows: [s > 0 ? 'pz' : 'nz', 'px', 'nx'], litP: 1.1, hangTo: -3.15 });
+ catwalk(V3(cx - 1.45, yT - 1.95, s * 10.65), V3(cx + 1.45, yT - 1.95, s * 10.65), 0.7, s > 0 ? [false, true] : [true, false], null);
+ ladder(cx + 1.75, s * 10.5, yT - 1.95, -3.1, true, true);
+ sign(7, V3(cx - 0.9, yT - 0.32, s * (10.3 + 0.03)), V3(0, 0, s), 0.7, 0.35);
+ DRIP_SRC.push(V3(cx + 0.87, yT - 2.55, z));
+ } else if (kind === 1) { // tank rack: two vertical receivers with gauges on a hung grating
+ catwalk(V3(cx - 1.7, -5.75, z), V3(cx + 1.7, -5.75, z), 1.7, s > 0 ? [false, true] : [true, false], -3.2, 3.4);
+ for (const dx of [-0.75, 0.75]) {
+ const tt = pick([[0.78, 0.79, 0.76], [0.6, 0.66, 0.6], [0.82, 0.7, 0.48]]);
+ cylY('paint', cx + dx, z - s * 0.15, -5.55, -4.1, 0.52, 20, tt, 0.04);
+ sph('paint', V3(cx + dx, -4.1, z - s * 0.15), 0.52, 14, tt, 0.55); sph('paint', V3(cx + dx, -5.55, z - s * 0.15), 0.52, 14, tt, 0.45);
+ for (const yy of [-4.45, -5.2]) ring('rustS', V3(cx + dx, yy, z - s * 0.15), 'y', 0.53, 0.035, 20, 3);
+ pipe('rustS', [V3(cx + dx, -3.85, z - s * 0.15), V3(cx + dx, -3.3, z - s * 0.15)], 0.07, { flanges: false });
+ gauge(V3(cx + dx, -4.75, z + s * 0.38), V3(0, 0, s), 0.3);
+ decal(0, V3(cx + dx, -5.15, z + s * 0.385), V3(0, 0, s), VUP, 0.45, 0.8, 0.9);
+ }
+ pipe('steelS', [V3(cx - 0.75, -5.0, z - s * 0.15), V3(cx, -5.0, z - s * 0.15), V3(cx + 0.75, -5.0, z - s * 0.15)], 0.05, { flanges: false });
+ valve(V3(cx, -5.0, z - s * 0.15), V3(1, 0, 0), 0.06);
+ bundle(V3(cx + 1.3, -5.85, z), 4, rnd(1.6, 3.0), 0.03);
+ } else { // machinery crate with louvres, exhaust stub and soot
+ box('paint', cx - 1.3, cx + 1.3, -5.45, yT, z - 0.85, z + 0.85, pick(TINT.machine), 0.05);
+ box('steel', cx - 1.4, cx + 1.4, yT, yT + 0.1, z - 0.95, z + 0.95);
+ for (let yy = -5.2; yy < -4.3; yy += 0.14) box('steelS', cx - 0.95, cx + 0.15, yy, yy + 0.05, z + s * 0.85, z + s * 0.91);
+ for (const ex of [-1, 1]) for (const ez of [-1, 1]) rod('steelS', V3(cx + ex * 1.25, yT, z + ez * 0.8), V3(cx + ex * 1.25, -3.15, z + ez * 0.8), 0.04, 5);
+ pipe('rust', [V3(cx + 0.8, -5.45, z), V3(cx + 0.8, -6.1, z), V3(cx + 0.8, -6.1, z + s * 0.6)], 0.11, { flanges: false });
+ decal(2, V3(cx - 0.4, -4.3, z + s * 0.92), V3(0, 0, s), VUP, 1.9, 1.5, 0.9);
+ decal(2, V3(cx + 0.4, -5.45, z), VDOWN, VX, 1.7, 2.4, 0.95);
+ sign(5, V3(cx + 0.75, -4.2, z + s * 0.86), V3(0, 0, s), 0.7, 0.35);
+ DRIP_SRC.push(V3(cx + 0.8, -6.15, z + s * 0.62));
+ chain(V3(cx - 1.0, -5.5, z + s * 0.5), rnd(1.5, 2.6));
+ }
+ }
+
+ // ---------------- fascia silhouette: outriggers with strung cables, whip / yagi antennas, dishes, long cable bundles
+ for (const s of [1, -1]) for (const [a, b] of EDGE_SEGS) {
+ const tips = [];
+ for (let x = a + rnd(0.8, 1.6); x < b - 0.6; x += rnd(3.4, 5.2)) {
+ const kind = Math.floor(R() * 4), zt = s * rnd(10.7, 11.5), yt = rnd(-1.0, -0.45);
+ rod('steelS', V3(x, -0.95, s * 9.5), V3(x, yt, zt), 0.035, 5);
+ rod('steelS', V3(x, -2.3, s * 8.25), V3(x, yt - 0.25, s * (Math.abs(zt) - 0.5)), 0.022, 4);
+ tips.push(V3(x, yt, zt));
+ if (kind === 0) { // yagi
+ for (let k = 0; k < 5; k++) rod('steelS', V3(x - 0.45 + k * 0.05, yt + 0.05, zt - s * (0.15 + k * 0.28)), V3(x + 0.45 - k * 0.05, yt + 0.05, zt - s * (0.15 + k * 0.28)), 0.012, 4, [1.6, 1.6, 1.5]);
+ } else if (kind === 1) { // dish
+ pushT('paintS', new THREE.SphereGeometry(0.55, 14, 5, 0, Math.PI * 2, 0, 0.75), new THREE.Matrix4().makeRotationX(s * 2.0).setPosition(x, yt - 0.1, zt + s * 0.5), [0.8, 0.8, 0.77]);
+ } else if (kind === 2) { // drooping whips
+ for (const dx of [-0.25, 0.25]) dangle(V3(x + dx, yt, zt), rnd(1.6, 3.4), 0.014, 0.05, false);
+ } else lamp(V3(x, yt - 0.05, zt), V3(0, -1, 0));
+ if (R() < 0.7) bundle(V3(x + rnd(-0.8, 0.8), -3.3, s * rnd(9.25, 9.4)), 3 + Math.floor(R() * 3), rnd(2.2, 5.0), 0.03);
+ }
+ for (let i = 0; i < tips.length - 1; i++) hoseLoop(tips[i], tips[i + 1], rnd(0.5, 1.2), 0.016, 0.04);
+ // stencil block ids + plates on the concrete edge beam, rust runs from the fascia channel bolts
+ const xs2 = a + (b - a) * rnd(0.25, 0.75);
+ sign(4, V3(xs2, -1.38, s * 8.0), V3(0, 0, s), 1.9, 0.95);
+ for (let x = a + 0.7; x < b - 0.5; x += rnd(0.9, 2.1)) decal(DR() < 0.3 ? 1 : 0, V3(x, -2.75, s * 8.22), V3(0, 0, s), VUP, drnd(0.3, 0.8), 0.5, drnd(0.6, 0.95));
+ }
+ // end fascias: big block id + runs
+ for (const f of [-1, 1]) {
+ sign(4, V3(f * 45.0, -1.45, f * 3.4), V3(f, 0, 0), 2.4, 1.2);
+ bundle(V3(f * 45.3, -3.25, -f * 5.2), 5, rnd(2.5, 4.5), 0.035);
+ }
+ // gauges on the capsule tanks + drum hatches, rust runs down the drum walls and cheek plates
+ for (const f of [-1, 1]) for (const s of [1, -1]) gauge(V3(f * 13.8, -2.35, s * (3.55 + 0.56)), V3(0, 0, s), 0.26);
+ for (const d of DRUMS) {
+ const nr = d.big ? 24 : 16, yT = -2.2, yB = d.big ? -5.0 : -4.6;
+ for (let i = 0; i < nr; i++) {
+ if (DR() < 0.3) continue;
+ const a = i / nr * Math.PI * 2, c = Math.cos(a), sn = Math.sin(a), hh = drnd(1.0, yT - yB);
+ decal(DR() < 0.3 ? 3 : 0, V3(d.x + c * (d.r + 0.01), yT - hh / 2 - drnd(0, yT - yB - hh), sn * (d.r + 0.01)), V3(c, 0, sn), VUP, drnd(0.4, 0.75), hh, drnd(0.6, 1.0));
+ }
+ for (let k = 0; k < 5; k++) { const a = drnd(0, 6.28), r = drnd(d.fan + 1.2, d.r - 0.4); decal(2, V3(d.x + Math.cos(a) * r, yB - 0.26, Math.sin(a) * r), VDOWN, VX, drnd(1.2, 2.4), drnd(1.2, 2.4), 0.9); }
+ }
+ for (const hx of LEGX) for (const s of [1, -1]) for (const dx of [-1, 1]) {
+ const xo = hx + dx * 4.1;
+ for (let k = 0; k < 7; k++) decal(k % 3 === 2 ? 1 : 0, V3(xo, -1.05 - 0.9 - drnd(0, 0.5), s * drnd(5.5, 9.8)), V3(dx, 0, 0), VUP, k % 3 === 2 ? 1.6 : drnd(0.35, 0.7), 1.8, drnd(0.6, 0.95));
+ for (let k = 0; k < 3; k++) decal(3, V3(xo, drnd(-4.6, -1.6), s * drnd(5.6, 7.2)), V3(dx, 0, 0), VUP, 1.3, 1.3, 0.8);
+ }
+ }
+
+ // =================================================================== BUILD MESHES
+ const meshes = [];
+ for (const b of Object.values(BK)) {
+ if (!b.geoms.length) continue;
+ const g = BGU.mergeGeometries(b.geoms, false);
+ for (const gg of b.geoms) gg.dispose();
+ b.geoms.length = 0;
+ if (!g) throw new Error('chassis merge failed for bucket ' + b.name);
+ g.computeBoundingSphere(); g.computeBoundingBox();
+ const m = new THREE.Mesh(g, MAT[b.name]);
+ m.name = 'chassis_' + b.name;
+ m.castShadow = !!b.cast; m.receiveShadow = !!b.recv;
+ if (b.name === 'decal') m.renderOrder = -5;
+ m.matrixAutoUpdate = false; m.updateMatrix();
+ root.add(m); meshes.push(m);
+ }
+
+ // ---- rotating fans (instanced)
+ let fanMesh = null;
+ {
+ const parts = [];
+ const hub = new THREE.CylinderGeometry(0.22, 0.22, 0.3, 16); parts.push(hub);
+ for (let i = 0; i < 7; i++) {
+ const a = i / 7 * Math.PI * 2;
+ const bl = new THREE.BoxGeometry(0.76, 0.025, 0.24);
+ bl.applyMatrix4(new THREE.Matrix4().makeRotationX(0.42));
+ bl.applyMatrix4(new THREE.Matrix4().makeTranslation(0.58, 0, 0));
+ bl.applyMatrix4(new THREE.Matrix4().makeRotationY(a));
+ parts.push(bl);
+ }
+ for (const p of parts) { p.deleteAttribute('uv'); }
+ const fg = BGU.mergeGeometries(parts.map((p) => (p.index ? p : BGU.mergeVertices(p))), false);
+ const fm = patch(Mats.paintedMetal({ color: 0x5c605c, w: { rust: 0.6, chip: 0.4, offset: V3(3, 3, 3) } }));
+ fanMesh = new THREE.InstancedMesh(fg, fm, fanList.length);
+ fanMesh.name = 'chassis_fans';
+ fanMesh.frustumCulled = false;
+ root.add(fanMesh);
+ }
+
+ // ---- drips
+ const DROPS_PER = 2;
+ const dripSrc = DRIP_SRC.map((p) => ({ p, per: rnd(1.6, 3.2), ph: rnd(0, 1) }));
+ const dripMat = patch(new THREE.MeshStandardMaterial({ color: 0xaab8c6, roughness: 0.05, metalness: 0.0, emissive: new THREE.Color(0.03, 0.04, 0.06) }));
+ const dripMesh = new THREE.InstancedMesh(new THREE.SphereGeometry(1, 6, 4), dripMat, Math.max(1, dripSrc.length * DROPS_PER));
+ dripMesh.name = 'chassis_drips'; dripMesh.frustumCulled = false;
+ root.add(dripMesh);
+
+ // ---- real point lights (≤ 6)
+ const PL = REAL_PL.slice(0, 6).map((p) => [p.x, p.y, p.z]);
+ for (const [x, y, z] of PL) {
+ const l = new THREE.PointLight(new THREE.Color(1.0, 0.5, 0.18), 34, 22, 2);
+ l.position.set(x, y, z); l.castShadow = false;
+ root.add(l);
+ }
+
+ // ---- cluster lamps for the shader (nearby lamps merge, energy is kept)
+ lamps.sort((a, b) => b.w - a.w || a.p.x - b.p.x);
+ let clusters = [];
+ const solos = lamps.filter((L) => L.solo).map((L) => ({ ...L, e: 99, solo: true }));
+ for (const L of lamps) {
+ if (L.solo) continue;
+ const e = L.c[0] + L.c[1] + L.c[2];
+ const c = clusters.find((q) => q.p.distanceTo(L.p) < 2.6);
+ if (c) {
+ c.p.multiplyScalar(c.e).addScaledVector(L.p, e).divideScalar(c.e + e);
+ c.c = c.c.map((v, i) => v + L.c[i]); c.r = Math.max(c.r, L.r) + 0.4; c.e += e; c.w = Math.max(c.w, L.w);
+ } else clusters.push({ p: L.p.clone(), c: L.c.slice(), r: L.r, e, w: L.w });
+ }
+ clusters.sort((a, b) => b.e * b.w - a.e * a.w);
+ const chosen = solos.concat(clusters).slice(0, LAMP_N);
+ for (const c of chosen) if (!c.solo) { const k = Math.min(1, 2.2 / (c.c[0] || 1)); c.c = c.c.map((v) => v * k); }
+ const hash1 = (v) => { const q = Math.sin(v * 127.1 + 3.7) * 43758.5453; return q - Math.floor(q); };
+ const flickAt = (t) => { // pure function of t: steady seconds, then stuttering bursts
+ if (hash1(Math.floor(t * 0.8)) < 0.42) return 0.95 + 0.05 * Math.sin(t * 37.0);
+ const f = hash1(Math.floor(t * 19.0) + 31.7);
+ return f > 0.4 ? 1.0 : 0.12 + 0.5 * f;
+ };
+ const lampLocal = chosen.map((L) => L.p);
+ chosen.forEach((L, i) => { lampU.uLampC.value[i].set(L.c[0], L.c[1], L.c[2]); lampU.uLampP.value[i].w = L.r; });
+
+ const _hv = V3(), TB = performance.now();
+ if (Q && Q.has('chsstats')) {
+ let hipHits = 0, recessHits = 0; // vertices inside the 3.2 m hip spheres / inside the hip recess volume
+ for (const m of meshes) { const pa = m.geometry.attributes.position; for (let i = 0; i < pa.count; i++) {
+ _hv.fromBufferAttribute(pa, i);
+ if (HIPS.some((h) => h.distanceTo(_hv) < 3.2)) hipHits++;
+ if (LEGX.some((hx) => Math.abs(_hv.x - hx) < 3.3) && Math.abs(_hv.z) > 5.1 && _hv.y < -0.3) recessHits++;
+ } }
+ console.error(`[chassis stats] buildMs=${Math.round(TB - T0)} hipSphereVerts=${hipHits} recessVerts=${recessHits}`);
+ let tris = 0, calls = 0;
+ root.traverse((o) => { if (o.isMesh) { calls++; const n = o.geometry.index ? o.geometry.index.count / 3 : o.geometry.attributes.position.count / 3; tris += n * (o.isInstancedMesh ? o.count : 1); } });
+ console.error(`[chassis stats] meshes=${calls} tris=${Math.round(tris)} lamps=${lamps.length} practicals=${solos.length} shaderLamps=${chosen.length} pointLights=${PL.length} drips=${dripSrc.length} decals=${decalN}`);
+ }
+
+ // =================================================================== UPDATE (pure function of t)
+ const _m4 = new THREE.Matrix4(), _q = new THREE.Quaternion(), _p = V3(), _s = V3(), _v = V3(), YAX = V3(0, 1, 0);
+ return {
+ update(t) {
+ lampU.uChsT.value = t;
+ const mw = walker.matrixWorld;
+ const fl = flickAt(t);
+ MAT.emisF.color.setScalar(fl);
+ for (let i = 0; i < lampLocal.length; i++) {
+ const L = chosen[i];
+ _v.copy(lampLocal[i]).applyMatrix4(mw);
+ lampU.uLampP.value[i].x = _v.x; lampU.uLampP.value[i].y = _v.y; lampU.uLampP.value[i].z = _v.z;
+ if (L.dir) { _v.copy(L.dir).transformDirection(mw); lampU.uLampD.value[i].set(_v.x, _v.y, _v.z, L.cone); }
+ if (L.flick) lampU.uLampC.value[i].set(L.c[0] * fl, L.c[1] * fl, L.c[2] * fl);
+ }
+ fanList.forEach((f, i) => {
+ _q.setFromAxisAngle(YAX, t * f.spd + f.ph);
+ _m4.compose(_p.set(f.x, f.y, f.z), _q, _s.set(f.r, f.r, f.r));
+ fanMesh.setMatrixAt(i, _m4);
+ });
+ fanMesh.instanceMatrix.needsUpdate = true;
+ let k = 0;
+ for (const d of dripSrc) for (let j = 0; j < DROPS_PER; j++) {
+ const u = ((t / d.per + d.ph + j / DROPS_PER) % 1 + 1) % 1;
+ const tau = u * d.per;
+ const fall = 0.5 * 9.8 * tau * tau;
+ const vel = 9.8 * tau;
+ const y = d.p.y - fall;
+ if (y < -19) _m4.makeScale(0, 0, 0);
+ else {
+ const sy = 0.035 + Math.min(0.5, vel * 0.012);
+ _m4.compose(_p.set(d.p.x, y, d.p.z), _q.identity(), _s.set(0.022, sy, 0.022));
+ }
+ dripMesh.setMatrixAt(k++, _m4);
+ }
+ dripMesh.instanceMatrix.needsUpdate = true;
+ },
+ };
+}
diff --git a/src/mods/env.js b/src/mods/env.js
new file mode 100644
index 0000000..4825f3f
--- /dev/null
+++ b/src/mods/env.js
@@ -0,0 +1,1246 @@
+// Environment: wet dusk field. World-space ground shader (soil / matted grass / mud / ruts / puddles /
+// footprints), camera-following world-stable instanced vegetation, a single planar mirror pass for the
+// puddles, and sparse distant silhouettes (trees, shrubs, utility poles) swallowed by fog.
+//
+// Puddle placement rule (world space, shared by JS + GLSL, see puddlesNear()):
+// cells of PUD_CELL m; cell (i,j) has a puddle if u0 < PUD_P (u* = pcg hash floats of the cell);
+// centre = ((i + .15 + .7 u1), (j + .15 + .7 u2)) * PUD_CELL; semi-axes a = 1.4 + 3.4 u3, b = a(.45 + .4 u4);
+// rotation u5*PI; plus the HERO puddles listed below (world coordinates).
+// Round 2: rule unchanged; only HERO[3] (f_puddle) moved/enlarged to (132.6, 36.8, a 6.0, b 4.3, rot 0.985).
+// Field-road ruts (water-filled, world-stable): z = 35 + 2.5 sin(.021x) + 1.2 sin(.067x+1) and z = -35 + ... (see rutMask).
+import * as BGU from 'three/addons/utils/BufferGeometryUtils.js';
+import { SKY_GLSL } from '../look.js';
+
+const PUD_CELL = 22, PUD_P = 0.30;
+// hero puddles [x, z, a, b, rot]: world space. #0 sits in front of the `ref6` camera at t≈2 s.
+const HERO = [
+ [66.6, 38.0, 9.5, 3.6, 0.574],
+ [-40.0, 30.5, 4.0, 2.2, 0.3],
+ [-6.0, 44.0, 5.0, 2.4, -0.4],
+ [132.6, 36.8, 6.0, 4.3, 0.985], // f_puddle hero: long axis along the lens axis, near rim ~2 m from the camera
+];
+const NPRINT = 48, NPRINT_NEAR = 16, PRINTS_PER_LEG = 6;
+
+// ---------------------------------------------------------------- hashing (JS mirror of GLSL)
+function pcg(v) {
+ const s = (Math.imul(v >>> 0, 747796405) + 2891336453) >>> 0;
+ const w = Math.imul(((s >>> ((s >>> 28) + 4)) ^ s) >>> 0, 277803737) >>> 0;
+ return ((w >>> 22) ^ w) >>> 0;
+}
+const u2f = (h) => (h >>> 8) / 16777216;
+const cellHash = (i, j) => pcg(((i + 32768) >>> 0) + pcg((j + 32768) >>> 0) >>> 0);
+
+export function puddlesNear(cx, cz, R, out = []) {
+ out.length = 0;
+ const i0 = Math.floor((cx - R) / PUD_CELL), i1 = Math.floor((cx + R) / PUD_CELL);
+ const j0 = Math.floor((cz - R) / PUD_CELL), j1 = Math.floor((cz + R) / PUD_CELL);
+ for (let i = i0; i <= i1; i++) for (let j = j0; j <= j1; j++) {
+ let h = cellHash(i, j);
+ if (u2f(h) >= PUD_P) continue;
+ h = pcg(h); const u1 = u2f(h); h = pcg(h); const u2 = u2f(h); h = pcg(h); const u3 = u2f(h);
+ const a = 1.4 + 3.4 * u3;
+ out.push({ x: (i + 0.15 + 0.7 * u1) * PUD_CELL, z: (j + 0.15 + 0.7 * u2) * PUD_CELL, r: a * 1.5 });
+ }
+ for (const p of HERO) out.push({ x: p[0], z: p[1], r: p[2] * 1.5 });
+ return out;
+}
+
+// ---------------------------------------------------------------- shared GLSL
+const COMMON = /* glsl */`
+float sq(float x){ return x * x; }
+uint pcg(uint v){ uint s = v * 747796405u + 2891336453u; uint w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u; return (w >> 22u) ^ w; }
+uint cellHash(ivec2 c){ return pcg(uint(c.x + 32768) + pcg(uint(c.y + 32768))); }
+float u2f(uint h){ return float(h >> 8u) * (1.0 / 16777216.0); }
+float hash12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+vec3 noised(vec2 x){
+ vec2 i = floor(x), f = fract(x);
+ vec2 u = f * f * (3.0 - 2.0 * f), du = 6.0 * f * (1.0 - f);
+ float a = hash12(i), b = hash12(i + vec2(1.0, 0.0)), c = hash12(i + vec2(0.0, 1.0)), d = hash12(i + vec2(1.0, 1.0));
+ return vec3(a + (b - a) * u.x + (c - a) * u.y + (a - b - c + d) * u.x * u.y,
+ du * (vec2(b - a, c - a) + (a - b - c + d) * u.yx));
+}
+float vnoise(vec2 x){ return noised(x).x; }
+float fbm(vec2 p){ float s = 0.0, a = 0.5; for (int i = 0; i < 4; i++){ s += a * vnoise(p); p = mat2(1.6, 1.2, -1.2, 1.6) * p + 3.1; a *= 0.5; } return s / 0.9375; }
+float fbm2(vec2 p){ return (vnoise(p) * 0.6 + vnoise(p * 2.03 + 5.2) * 0.4); }
+
+uniform vec4 uHero[4]; // x z a b
+uniform float uHeroRot[4];
+float ellipseD(vec2 p, vec2 c, float a, float b, float r){
+ vec2 q = p - c; float cs = cos(r), sn = sin(r);
+ vec2 l = vec2(cs * q.x + sn * q.y, -sn * q.x + cs * q.y);
+ return length(l / vec2(a, b));
+}
+// normalized puddle distance: < 1 water, ~1..1.5 muddy rim
+float puddleField(vec2 p){
+ float d = 9.0;
+ vec2 cf = floor(p / ${PUD_CELL.toFixed(1)});
+ for (int k = 0; k < 9; k++){
+ vec2 c = cf + vec2(float(k - (k / 3) * 3) - 1.0, float(k / 3) - 1.0);
+ uint h = cellHash(ivec2(c));
+ float u0 = u2f(h);
+ h = pcg(h); float u1 = u2f(h); h = pcg(h); float u2 = u2f(h); h = pcg(h); float u3 = u2f(h);
+ h = pcg(h); float u4 = u2f(h); h = pcg(h); float u5 = u2f(h);
+ float a = 1.4 + 3.4 * u3;
+ vec2 ctr = (c + vec2(0.15) + 0.7 * vec2(u1, u2)) * ${PUD_CELL.toFixed(1)};
+ d = min(d, u0 < ${PUD_P} ? ellipseD(p, ctr, a, a * (0.45 + 0.4 * u4), u5 * 3.14159) : 9.0);
+ }
+ for (int k = 0; k < 4; k++) d = min(d, ellipseD(p, uHero[k].xy, uHero[k].z, uHero[k].w, uHeroRot[k]));
+ return d + ((fbm2(p * 0.32) - 0.5) * 0.55 + (vnoise(p * 1.9) - 0.5) * 0.16) * step(d, 2.2);
+}
+// tyre ruts: field road = two wobbly parallel tracks, one each side of the walker's path (world-stable)
+float rutMask(vec2 p){
+ float zc = p.y > 0.0 ? 35.0 + 2.5 * sin(p.x * 0.021) + 1.2 * sin(p.x * 0.067 + 1.0)
+ : -35.0 + 2.5 * sin(p.x * 0.017 + 1.3) + 1.0 * sin(p.x * 0.061);
+ float dz = abs(p.y - zc);
+ if (dz > 1.6) return 0.0;
+ float r = smoothstep(0.36, 0.12, abs(dz - 0.85));
+ return r * smoothstep(0.2, 0.5, vnoise(p * vec2(0.05, 0.3) + 4.0));
+}
+// tussocks: x = strength 0..1 (peak at the clump centre), yz = outward direction * strength
+vec3 tussock(vec2 p){
+ const float C = 0.9;
+ vec2 c = floor(p / C);
+ uint h = cellHash(ivec2(c) + 911);
+ float u0 = u2f(h); h = pcg(h); float u1 = u2f(h); h = pcg(h); float u2 = u2f(h); h = pcg(h); float u3 = u2f(h);
+ if (u0 > 0.62) return vec3(0.0);
+ vec2 q = p - (c + 0.3 + 0.4 * vec2(u1, u2)) * C;
+ float l = length(q);
+ float k = smoothstep(1.0, 0.2, l / (C * (0.24 + 0.2 * u3)));
+ return vec3(k * (0.45 + 0.55 * u3), q / max(l, 1e-3) * k);
+}
+float mudMask(vec2 p){
+ return smoothstep(0.66, 0.76, fbm2(p * 0.09 + 17.0) + (vnoise(p * 0.7) - 0.5) * 0.18);
+}
+`;
+
+// fake reflection of the lit facade (analytic glowing rectangle) for wet ground / dew glints
+const FACADE = /* glsl */`
+uniform vec3 uWalker; uniform float uFacZ;
+// soft sky occlusion under the walker's belly (the block hides a big part of the sky dome)
+float skyOcc(vec3 P){
+ vec2 d = abs(P.xz - uWalker.xz);
+ float o = smoothstep(60.0, 34.0, d.x) * smoothstep(24.0, 3.0, d.y);
+ return 1.0 - 0.55 * o * o;
+}
+vec3 facadeGlow(vec3 P, vec3 R, float blur){
+ float zf = uWalker.z + uFacZ * 7.5;
+ float s = (zf - P.z) / (abs(R.z) < 1e-4 ? 1e-4 : R.z);
+ if (s <= 0.0 || R.y <= 0.0) return vec3(0.0);
+ vec3 H = P + R * s;
+ float bl = 0.6 + blur * s;
+ float lx = H.x - uWalker.x, ly = H.y - uWalker.y;
+ float mx = smoothstep(-44.0 - bl, -44.0 + bl, lx) * smoothstep(44.0 + bl, 44.0 - bl, lx);
+ float my = smoothstep(-0.5 - bl, 1.0 + bl, ly) * smoothstep(19.0 + bl, 17.0 - bl, ly);
+ float belly = smoothstep(-4.5 - bl, -3.5 + bl, ly) * smoothstep(0.5 + bl, -0.5 - bl, ly) * 0.5;
+ // floors: brighter bands at window height, blurred out with roughness
+ float rows = mix(0.55 + 0.45 * sin(ly * 2.094 - 1.2), 0.55, smoothstep(0.5, 3.0, bl));
+ float cols = mix(0.5 + 0.5 * step(0.45, fract(lx * 0.22 + floor(ly / 3.0) * 0.37)), 0.5, smoothstep(0.3, 2.0, bl));
+ return vec3(0.42, 0.17, 0.045) * (mx * (my * rows * cols * 1.4 + belly)) * exp(-s * 0.004);
+}
+`;
+
+export async function create(ctx) {
+ const { THREE, scene, gait, LOOK, rng } = ctx;
+ const { GAIT, SPEED, NLEGS } = gait;
+ const renderer = ctx.renderer;
+ const DBG = ctx.Q ? ctx.Q.get("envdbg") : null;
+ const T0 = performance.now();
+
+ const uTime = { value: 0 };
+ const uCam = { value: new THREE.Vector3() };
+ const uWalker = { value: new THREE.Vector3(0, CFG_RIDE(ctx), 0) };
+ const uFacZ = { value: 1 };
+ const heroV = HERO.map((h) => new THREE.Vector4(h[0], h[1], h[2], h[3]));
+ const uHero = { value: heroV }, uHeroRot = { value: HERO.map((h) => h[4]) };
+ const prints = Array.from({ length: NPRINT }, () => new THREE.Vector4(0, 0, 1e5, 0));
+ const printsNear = Array.from({ length: NPRINT_NEAR }, () => new THREE.Vector4(0, 0, 1e5, 0));
+ const uPrintN = { value: printsNear };
+ const legU = Array.from({ length: NLEGS }, () => new THREE.Vector4(0, 0, 1e5, 1));
+ const uLeg = { value: legU }, uCyc = { value: new THREE.Vector2(SPEED * GAIT.T, GAIT.T) };
+ const skyU = {
+ uZenith: { value: LOOK.zenith }, uHorizon: { value: LOOK.horizon },
+ uSkyGlowDir: { value: LOOK.skyGlowDir }, uSkyGlow: { value: LOOK.skyGlow },
+ };
+
+ // ================================================================ GROUND
+ // mirror RT: the mirror camera's frustum is stretched downwards (= towards higher reflected elevations, see
+ // the mirror pass) so steep reflection rays still find the facade; a little taller than the screen aspect.
+ const mirrorW = Math.min(960, Math.round(renderer.domElement.width * 0.75)) || 960;
+ const aspect = (renderer.domElement.width / renderer.domElement.height) || 16 / 9;
+ const mirrorRT = new THREE.WebGLRenderTarget(mirrorW, Math.round(mirrorW / aspect * 1.25), {
+ type: THREE.HalfFloatType, samples: 0, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter,
+ });
+ const gU = {
+ uTime, uWalker, uFacZ, uHero, uHeroRot, uLeg, uCyc, ...skyU,
+ tMirror: { value: mirrorRT.texture }, uMirrorMat: { value: new THREE.Matrix4() }, uMirrorOn: { value: 0 },
+ uFogCol: { value: LOOK.fogColor }, uFogD: { value: LOOK.fogDensity }, uMist: { value: LOOK.mistDensity },
+ };
+ const groundMat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.8, metalness: 0, envMapIntensity: 0.5 });
+ groundMat.onBeforeCompile = (sh) => {
+ Object.assign(sh.uniforms, gU);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWP;')
+ .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvWP = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+varying vec3 vWP;
+uniform float uTime, uMirrorOn, uFogD, uMist;
+uniform vec3 uFogCol;
+uniform sampler2D tMirror; uniform mat4 uMirrorMat;
+uniform vec4 uLeg[${NLEGS}]; // last plant of every leg: x, z, age (s), side
+uniform vec2 uCyc; // metres / seconds between two prints of the same leg
+${SKY_GLSL}
+${COMMON}
+${FACADE}
+float gRough = 0.8, gWater = 0.0, gWet = 0.0, gDepth = 1.0, gBits = 0.0, gJit = 0.5;
+vec3 gN = vec3(0.0, 1.0, 0.0);
+vec2 gWaterGrad = vec2(0.0);
+// footprint height profile (m). Foot = round pad r 2.75 with radial tread + 4 claws (outward, +-63deg
+// forward/back, inward); squeezed-up mud rim around the pad, ridges beside and mounds ahead of every claw.
+// side flips z so "outward" is canonical +y.
+float printH(vec2 q, float side){
+ q.y *= side;
+ float r = length(q);
+ float ang = atan(q.y, q.x);
+ float h = -0.17 * smoothstep(2.95, 2.5, r) * (1.0 - 0.2 * cos(ang * 12.0) * smoothstep(0.7, 2.0, r));
+ h += 0.10 * exp(-sq((r - 3.15) / 0.34)) * (0.7 + 0.3 * cos(ang * 7.0 + 1.0));
+ for (int k = 0; k < 4; k++){
+ vec2 dir = k == 0 ? vec2(0.0, 1.0) : k == 1 ? vec2(0.891, 0.454) : k == 2 ? vec2(-0.891, 0.454) : vec2(0.0, -1.0);
+ float L = k == 3 ? 4.6 : 5.25;
+ float al = dot(q, dir), pe = abs(dot(q, vec2(-dir.y, dir.x)));
+ float along = smoothstep(2.4, 3.0, al) * smoothstep(L + 0.15, L - 0.6, al);
+ float g = smoothstep(0.75, 0.15, pe) * along;
+ h -= g * (0.11 + 0.2 * smoothstep(3.0, L, al));
+ h += 0.055 * exp(-sq((pe - 0.98) / 0.2)) * along;
+ h += 0.09 * exp(-sq((al - L - 0.4) / 0.32)) * smoothstep(1.0, 0.0, pe);
+ }
+ return h;
+}
+`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+{
+ vec2 p = vWP.xz;
+ float dCam = length(cameraPosition - vWP);
+ float m1 = fbm(p * 0.035);
+ vec3 n1 = noised(p * 0.9), n2 = noised(p * 2.7 + 5.0), n3 = noised(p * 8.3 + 11.0), n4 = noised(p * 23.0 + 3.0);
+ float clump = n1.x * 0.45 + n2.x * 0.3 + n3.x * 0.15 + n4.x * 0.1;
+ float mud = mudMask(p);
+ float rut = rutMask(p);
+ float pd = puddleField(p);
+ float water = smoothstep(1.0, 0.86, pd);
+ float rim = smoothstep(1.26, 0.99, pd);
+ // footprints
+ float ph = 0.0, phs = 0.0, pmask = 0.0, pfresh = 0.0, pwater = 0.0;
+ float pd1 = 1e9, pd2 = 1e9; vec4 pr1 = vec4(0.0, 0.0, 1e5, 1.0), pr2 = pr1;
+ for (int i = 0; i < ${NLEGS}; i++){ // each leg's trail is periodic: only its print nearest to this pixel matters
+ vec4 lg = uLeg[i];
+ float kp = clamp(floor((lg.x - p.x) / uCyc.x + 0.5), 0.0, ${(PRINTS_PER_LEG - 1).toFixed(1)});
+ vec4 pr = vec4(lg.x - kp * uCyc.x, lg.y, lg.z + kp * uCyc.y, lg.w);
+ vec2 q = p - pr.xy; float dq = dot(q, q);
+ if (dq < pd1) { pd2 = pd1; pr2 = pr1; pd1 = dq; pr1 = pr; } else if (dq < pd2) { pd2 = dq; pr2 = pr; }
+ }
+ for (int i = 0; i < 2; i++){
+ vec4 pr = i == 0 ? pr1 : pr2;
+ vec2 q = p - pr.xy;
+ float inr = step(dot(q, q), 46.0);
+ float h0 = 0.0;
+ if (inr > 0.5) h0 = printH(q, pr.w);
+ ph = min(ph, h0); phs += h0;
+ float e = length(q) / 2.9;
+ float m = max(smoothstep(1.3, 1.0, e + (n2.x - 0.5) * 0.3), smoothstep(-0.02, -0.08, h0));
+ pmask = max(pmask, m);
+ // churned mud spatter and clods thrown around the print
+ float spl = smoothstep(2.2, 1.1, e + (n3.x - 0.5) * 0.8) * step(0.42, n4.x + n2.x * 0.4);
+ pmask = max(pmask, spl * 0.85);
+ pfresh = max(pfresh, m * exp(-pr.z * 0.02));
+ // ground water seeps into the pad and the claw trenches within a few seconds
+ float seep = 0.07 * exp(-pr.z * 0.2);
+ pwater = max(pwater, inr * smoothstep(-0.115 - seep, -0.165 - seep, h0 + (n2.x - 0.5) * 0.09 + (n1.x - 0.5) * 0.05));
+ }
+ // slope of the print relief from screen-space derivatives (one height evaluation per print)
+ vec2 dpx = dFdx(p), dpy = dFdy(p); float dhx = dFdx(phs), dhy = dFdy(phs);
+ float pdet = dpx.x * dpy.y - dpx.y * dpy.x;
+ vec2 pgrad = abs(pdet) > 1e-10 ? clamp(vec2(dhx * dpy.y - dhy * dpx.y, dhy * dpx.x - dhx * dpy.x) / pdet, -1.5, 1.5) : vec2(0.0);
+ mud = max(max(mud, rut * 0.9), max(rim * 0.85, pmask));
+ // standing water: puddles, flooded prints, water in the ruts, small pools in churned mud
+ float rutW = rut * smoothstep(0.40, 0.58, vnoise(p * vec2(0.13, 0.45) + 9.0));
+ float pool = smoothstep(0.68, 0.75, n2.x * 0.65 + n1.x * 0.35) * smoothstep(0.7, 0.98, mud);
+ float shallow = max(pwater, max(rutW, pool)) * 0.92;
+ gDepth = max(smoothstep(1.0, 0.6, pd) * water, 0.35 * shallow);
+ water = max(water, shallow);
+ // albedo
+ vec3 grassC = mix(vec3(0.018, 0.030, 0.012), vec3(0.034, 0.038, 0.014), smoothstep(0.35, 0.75, m1));
+ grassC = mix(grassC, vec3(0.050, 0.044, 0.028), smoothstep(0.6, 0.85, n2.x * 0.6 + n4.x * 0.5) * 0.55);
+ float macro = fbm(p * 0.012 + 40.0);
+ grassC = mix(grassC, vec3(0.040, 0.036, 0.020), smoothstep(0.55, 0.8, macro) * 0.6); // dry straw meadow patches
+ grassC *= mix(0.7, 1.15, smoothstep(0.2, 0.7, fbm2(p * 0.05 + 3.0)));
+ // fine anisotropic streaks so the far field reads as grass, not paint
+ grassC *= 0.8 + 0.4 * vnoise(p * vec2(6.0, 1.3) + n2.x);
+ grassC *= (0.55 + 0.75 * clump) * 0.75;
+ vec3 mudC = mix(vec3(0.018, 0.014, 0.011), vec3(0.030, 0.024, 0.018), n3.x);
+ mudC = mix(mudC, vec3(0.012, 0.010, 0.008), pfresh * 0.6);
+ // crushed straw pressed into the print floor, dead thatch at the puddle rims
+ float straw = smoothstep(0.58, 0.72, vnoise(p * vec2(11.0, 2.4) + n2.x * 2.0)) * 0.5 + smoothstep(0.6, 0.75, vnoise(p.yx * vec2(9.0, 2.0) + 7.0)) * 0.5;
+ mudC = mix(mudC, vec3(0.055, 0.046, 0.026), straw * max(pmask * 0.55, rim * (1.0 - water) * 0.35));
+ vec3 alb = mix(grassC, mudC, mud);
+ float hollow = smoothstep(0.42, 0.28, m1 + (n1.x - 0.5) * 0.2);
+ gWet = clamp(max(hollow * 0.6, mud * 0.85), 0.0, 1.0);
+ alb *= 1.0 - 0.4 * gWet;
+ alb *= 1.0 - 0.45 * smoothstep(-0.02, -0.14, ph); // depth of the print reads darker
+ alb *= vec3(2.0, 1.55, 0.68) * skyOcc(vWP); // look-dev: olive, clearly green under the blue dusk light
+ gRough = mix(mix(0.95, 0.75, n3.x), 0.28 + 0.2 * n2.x, gWet);
+ vec2 grad = (n1.yz * 0.9 * 0.05 + n2.yz * 2.7 * 0.03 + n3.yz * 8.3 * 0.01) * (1.0 - 0.6 * mud)
+ + (n3.yz * 8.3 * 0.006 + n4.yz * 23.0 * 0.0015) * mud + (n3.yz * 8.3 * 0.014 + n4.yz * 23.0 * 0.005) * pfresh + pgrad * 0.9;
+ // pebbles and small stones pressed into bare soil (two sizes, one cell lookup each, near field only)
+ float nearK = smoothstep(34.0, 16.0, dCam);
+ if (nearK > 0.0){
+ float pk = 0.0; vec2 pg = vec2(0.0); float pc = 0.0;
+ for (int s = 0; s < 2; s++){
+ vec2 pp = p * (s == 0 ? 2.7 : 8.5) + float(s) * 17.0;
+ vec2 c = floor(pp), f = fract(pp);
+ float h1 = hash12(c + 17.3), h2 = hash12(c + 4.4);
+ vec2 q = f - (0.32 + 0.36 * vec2(hash12(c + 1.7), hash12(c + 9.2)));
+ q.x *= 0.75 + 0.6 * h1;
+ float d = length(q) / (0.10 + 0.20 * h2);
+ float dens = (s == 0 ? 0.07 : 0.12) + (s == 0 ? 0.33 : 0.5) * mud;
+ float k = step(hash12(c + 31.7), dens) * smoothstep(1.0, 0.8, d);
+ if (k > pk){ pk = k; pg = q * smoothstep(0.15, 1.0, d) * (s == 0 ? 2.2 : 4.0); pc = h1; }
+ }
+ pk *= nearK * (1.0 - 0.8 * water);
+ alb = mix(alb, mix(vec3(0.040, 0.040, 0.038), vec3(0.10, 0.097, 0.088), pc) * (0.6 + 0.4 * n4.x) * skyOcc(vWP), pk);
+ gRough = mix(gRough, 0.34, pk);
+ grad -= pg * pk * 3.0;
+ }
+ // muddy bottom showing through the shallow edge, dark deep water
+ alb = mix(alb, mix(vec3(0.060, 0.047, 0.030), vec3(0.010, 0.010, 0.009), gDepth), water);
+ diffuseColor.rgb = alb;
+ gN = normalize(vec3(-grad.x, 1.0, -grad.y));
+ gWater = water;
+ // water ripples: wind cat's-paws + rain rings; calmer (sharper mirror) towards the far rim
+ vec2 rp = p * 2.2;
+ vec3 r1 = noised(rp + uTime * vec2(0.35, 0.12)), r2 = noised(rp * 2.3 - uTime * vec2(0.2, 0.41));
+ float gust = 0.35 + 1.3 * smoothstep(0.35, 0.75, vnoise(p * 0.22 + uTime * vec2(0.28, 0.09)));
+ vec2 wg = (r1.yz * 0.5 + r2.yz * 1.6) * 0.006 * gust;
+ vec2 rc = floor(p * 1.6);
+ for (int j = 0; j < 4; j++){
+ vec2 cc = rc + vec2(float(j & 1), float(j >> 1));
+ float hh = hash12(cc * 1.37 + 0.5);
+ float ph2 = fract(uTime * 0.45 + hh * 7.0);
+ vec2 ctr = (cc + vec2(hash12(cc + 3.1), hash12(cc + 7.7))) / 1.6;
+ vec2 dq = p - ctr; float dd = length(dq);
+ float rr = ph2 * 0.34;
+ float ring = sin((dd - rr) * 70.0) * exp(-sq((dd - rr) * 18.0)) * (1.0 - ph2) * step(0.5, hh);
+ wg += dq / max(dd, 1e-3) * ring * 0.06;
+ }
+ gWaterGrad = wg * mix(1.0, 0.4, smoothstep(5.0, 30.0, dCam));
+ gJit = fract(52.9829189 * fract(dot(gl_FragCoord.xy, vec2(0.06711056, 0.00583715))) + uTime * 37.0);
+ // floating grass bits and seeds, gathered near the banks
+ vec2 bp = p * 6.5 + n2.x * 0.6;
+ vec2 bc = floor(bp), bf = fract(bp) - 0.5;
+ float ba = hash12(bc + 2.3) * 6.2832;
+ vec2 bq = vec2(cos(ba) * bf.x + sin(ba) * bf.y, -sin(ba) * bf.x + cos(ba) * bf.y);
+ gBits = smoothstep(0.05, 0.02, abs(bq.y)) * smoothstep(0.40, 0.30, abs(bq.x))
+ * step(hash12(bc + 7.1), 0.06 + 0.3 * smoothstep(0.55, 0.98, pd)) * smoothstep(40.0, 15.0, dCam);
+}`)
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(gRough, 1.0, gWater);')
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\nnormal = normalize((viewMatrix * vec4(gN, 0.0)).xyz);')
+ .replace('#include <opaque_fragment>', `
+{
+ vec3 V = normalize(cameraPosition - vWP);
+ // warm smear of the facade + cold sky sheen on wet ground
+ vec3 Nw = normalize(mix(gN, vec3(0.0, 1.0, 0.0), 0.5));
+ vec3 Rg = reflect(-V, Nw);
+ float Fg = 0.04 + 0.96 * pow(1.0 - max(dot(Nw, V), 0.0), 5.0);
+ outgoingLight += facadeGlow(vWP, Rg, 0.02 + gRough * 0.25) * Fg * gWet * (1.0 - gWater) * 0.8;
+ outgoingLight += skyColor(normalize(vec3(Rg.x, max(Rg.y, 0.03), Rg.z))) * Fg * gWet * (1.0 - gWater) * 0.12 * skyOcc(vWP);
+ if (gWater > 0.001){
+ vec3 Nr = normalize(vec3(-gWaterGrad.x, 1.0, -gWaterGrad.y));
+ vec3 R = reflect(-V, Nr);
+ R.y = max(R.y, 0.012);
+ float F = mix(mix(0.16, 0.34, gDepth), 1.0, pow(1.0 - max(dot(Nr, V), 0.0), 5.0));
+ vec3 fd = normalize(vec3(R.x, R.y * 0.35 + 0.03, R.z));
+ vec3 fogc = mix(uFogCol, skyColor(fd), 0.55);
+ vec3 sky = skyColor(normalize(vec3(R.x, max(R.y, 0.02), R.z)));
+ vec3 refl = sky, streak = vec3(0.0);
+ float hitA = 0.0;
+ if (uMirrorOn > 0.5){
+ // planar mirror: project the point the reflected ray would hit into the mirror camera
+ float zf = uWalker.z + uFacZ * 7.5;
+ float sD = (zf - vWP.z) / (abs(R.z) < 1e-3 ? 1e-3 : R.z);
+ sD = sD > 0.0 ? clamp(sD, 8.0, 160.0) : 60.0;
+ vec3 P0 = vec3(vWP.x, 0.0, vWP.z);
+ vec4 pc = uMirrorMat * vec4(P0 + R * sD, 1.0);
+ vec2 uv = pc.xy / pc.w;
+ vec4 m = textureLod(tMirror, clamp(uv, 0.002, 0.998), 0.0);
+ float inb = step(0.0, uv.x) * step(uv.x, 1.0) * step(0.0, uv.y) * step(uv.y, 1.0) * step(0.0, pc.w);
+ hitA = clamp(m.a, 0.0, 1.0) * inb;
+ refl = mix(sky, m.rgb, hitA);
+ // ripple glitter: bright lights (windows, lamps) smear into long vertical streaks towards the viewer
+ vec3 R1 = normalize(R + vec3(0.0, 0.46, 0.0));
+ vec4 pc1 = uMirrorMat * vec4(P0 + R1 * sD, 1.0);
+ vec2 uv1 = pc1.xy / pc1.w;
+ for (int k = 0; k < 8; k++){
+ float fk = (float(k) + 0.25 + 0.5 * gJit) / 8.0;
+ vec2 uvk = mix(uv, uv1, fk) + vec2(sin(vWP.x * 5.0 + vWP.z * 3.0 + fk * 23.0 + uTime * 1.3) * 0.0035 * fk, 0.0);
+ vec4 mk = textureLod(tMirror, clamp(uvk, 0.002, 0.998), 0.0);
+ streak += mk.rgb * smoothstep(0.3, 1.0, max(mk.r, mk.g)) * clamp(mk.a, 0.0, 1.0) * (1.0 - 0.8 * fk);
+ }
+ streak = mix(streak, dot(streak, vec3(0.45, 0.45, 0.1)) * vec3(1.0, 0.60, 0.26), 0.6) * 0.24 * step(0.0, pc1.w); // keep the smear amber, never red
+ } else {
+ refl += facadeGlow(vWP, R, 0.004) * 2.2;
+ hitA = 0.5;
+ }
+ // reflected path is not fogged by post: approximate extinction along it
+ float D = length(uWalker - vWP);
+ float extW = uFogD * D * 0.8 + uMist * min(D, 4.0 / max(R.y, 0.06)) * 0.5;
+ float ext = mix(6.0, extW, hitA);
+ refl = mix(refl, fogc, 1.0 - exp(-ext)) + streak * exp(-extW);
+ vec3 waterCol = outgoingLight * mix(0.85, 0.3, gDepth) * (1.0 - F) + refl * F;
+ waterCol = mix(waterCol, vec3(0.036, 0.034, 0.022) * skyOcc(vWP), gBits);
+ outgoingLight = mix(outgoingLight, waterCol, gWater);
+ }
+}
+#include <opaque_fragment>`);
+ };
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(3000, 3000, 1, 1).rotateX(-Math.PI / 2), groundMat);
+ ground.receiveShadow = true;
+ ground.frustumCulled = false;
+ ground.name = 'env-ground';
+ scene.add(ground);
+
+ // ================================================================ VEGETATION
+ // Generic camera-wrapped instanced plant shader (patched MeshStandardMaterial so it gets the scene's
+ // lighting, shadows and env reflections). Geometry is a plant model of nominal height 1 (y = 0..1).
+ // attribute aPart = part id + 0.3 * side (side = -1/+1 on the two edges of a strip, used for dew beads,
+ // wet edge highlights and feathered seed heads). Part ids: 0 leaf/blade, 1 seed head (feathered),
+ // 2 cattail head, 3 dead stalk, 4 broad leaf, 5 rusty seed spike (feathered), 6 stone.
+ // Placement modes: 0 grass (tussocks, meadow height patches), 1 puddle-rim lovers (reeds),
+ // 2 patchy weeds (own patch noise), 3 rigid stones / mud clods (no bending, like bare ground).
+ const vegMeshes = [];
+ let vegTris = 0;
+ function makeVeg(name, geo, count, o) {
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = geo.index;
+ ig.setAttribute('position', geo.getAttribute('position'));
+ ig.setAttribute('normal', geo.getAttribute('normal'));
+ ig.setAttribute('aPart', geo.getAttribute('aPart'));
+ if (geo.getAttribute('uv')) ig.setAttribute('uv', geo.getAttribute('uv'));
+ vegTris += count * (geo.index ? geo.index.count : geo.getAttribute('position').count) / 3;
+ const off = new Float32Array(count * 2);
+ const r = rng(o.seed);
+ // stratified (jittered grid) so density is even
+ const n = Math.ceil(Math.sqrt(count));
+ for (let i = 0; i < count; i++) {
+ const gx = i % n, gy = Math.floor(i / n);
+ off[i * 2] = ((gx + r()) / n) * o.S;
+ off[i * 2 + 1] = ((gy + r()) / n) * o.S;
+ }
+ ig.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 2));
+ ig.instanceCount = count;
+ const U = {
+ uTime, uCam, uWalker, uFacZ, uHero, uHeroRot, uPrintN, ...skyU,
+ uNear: { value: o.near || 0 }, uAO: { value: o.ao ?? 0.7 }, uS: { value: o.S }, uCtr: { value: new THREE.Vector2() }, uFade: { value: new THREE.Vector2(o.fade0, o.fade1) },
+ uH: { value: new THREE.Vector2(o.h0, o.h1) }, uW: { value: new THREE.Vector2(o.w0, o.w1) },
+ uLean: { value: o.lean }, uWind: { value: o.wind }, uMode: { value: o.mode || 0 },
+ uNUp: { value: o.nup ?? 0.55 }, uDens: { value: o.dens ?? 1 }, uDry: { value: o.dry ?? 0.08 },
+ uAbs: { value: o.abs || 0 }, uTus: { value: o.tus || 0 }, uPatch: { value: o.patch || 0 }, uTallDens: { value: o.tallDens || 0 }, uJit: { value: o.S / Math.sqrt(count) * 0.9 },
+ };
+ const mat = new THREE.MeshStandardMaterial({ color: 0xffffff, roughness: 0.45, metalness: 0, side: THREE.DoubleSide, envMapIntensity: 0.3 });
+ if (o.map) { mat.map = o.map; mat.alphaToCoverage = true; }
+ mat.onBeforeCompile = (sh) => {
+ Object.assign(sh.uniforms, U);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', `#include <common>
+attribute vec2 aOff; attribute float aPart;
+uniform vec3 uCam; uniform vec2 uCtr; uniform float uAO, uNear, uTime, uS, uLean, uWind, uMode, uNUp, uDens, uDry, uAbs, uTus, uPatch, uTallDens, uJit;
+uniform vec2 uFade, uH, uW;
+uniform vec4 uPrintN[${NPRINT_NEAR}];
+varying vec3 vGCol; varying vec3 vGDry; varying float vV; varying vec3 vWP; varying float vSeed; varying float vPart; varying float vSide; varying vec2 vDim;
+${COMMON}
+vec3 gPos;
+`)
+ .replace('#include <beginnormal_vertex>', `
+vec3 objectNormal;
+{
+ float part = floor(aPart + 0.5);
+ float side = (aPart - part) / 0.3;
+ vec2 camxz = uCam.xz;
+ vec2 rel = mod(aOff - uCtr + 0.5 * uS, uS) - 0.5 * uS;
+ vec2 root = uCtr + rel;
+ float edgeF = 1.0 - smoothstep(0.36 * uS, 0.49 * uS, max(abs(rel.x), abs(rel.y)));
+ ivec2 tile = ivec2(floor((root - aOff) / uS + 0.5));
+ uint h = pcg(uint(gl_InstanceID) * 7919u + cellHash(tile));
+ float r1 = u2f(h); h = pcg(h); float r2 = u2f(h); h = pcg(h); float r3 = u2f(h); h = pcg(h); float r4 = u2f(h);
+ h = pcg(h); float r5 = u2f(h); h = pcg(h); float r6 = u2f(h); h = pcg(h); float r7 = u2f(h); h = pcg(h); float r8 = u2f(h);
+ root += (vec2(r1, r2) - 0.5) * uJit;
+ float dist = length(root - camxz);
+ float fade = (1.0 - smoothstep(uFade.x, uFade.y, dist)) * edgeF * smoothstep(uNear, uNear * 1.8, dist);
+ // where it grows
+ float pd = puddleField(root);
+ float mudm = mudMask(root), rutm = rutMask(root);
+ float g; vec3 tk = vec3(0.0); float tallP = 0.5;
+ if (uMode < 0.5) {
+ g = smoothstep(0.95, 1.16, pd);
+ g *= 1.0 - 0.75 * mudm;
+ g *= 1.0 - 0.9 * rutm;
+ // big-scale density variation (meadow patches), tall-grass patches, tussocks
+ g *= 0.55 + 0.45 * smoothstep(0.25, 0.6, fbm2(root * 0.06 + 2.0));
+ tallP = smoothstep(0.3, 0.7, fbm2(root * 0.035 + 5.0));
+ g *= mix(1.0, 0.2 + 0.8 * tallP, uTallDens);
+ if (uTus > 0.0) tk = tussock(root);
+ } else if (uMode < 1.5) {
+ // reeds: love puddle borders (also standing in the shallows), sparse elsewhere
+ float edge = exp(-sq((pd - 1.04) / 0.16));
+ g = max(edge, 0.08 * smoothstep(0.55, 0.8, fbm2(root * 0.05 + 9.0))) * step(0.86, pd) * (1.0 - 0.9 * rutm);
+ } else if (uMode < 2.5) {
+ // weeds: patchy colonies
+ g = smoothstep(0.98, 1.2, pd) * (1.0 - 0.8 * mudm) * (1.0 - rutm);
+ g *= 0.10 + 0.90 * smoothstep(0.42, 0.68, fbm2(root * 0.045 + uPatch));
+ } else {
+ // stones and clods: mostly where the soil is bare
+ g = (0.22 + 0.78 * max(mudm, max(rutm, smoothstep(1.3, 1.02, pd)))) * step(0.97, pd);
+ }
+ // footprints: press blades flat outward
+ float press = 0.0; vec2 pdir = vec2(0.0);
+ for (int i = 0; i < ${NPRINT_NEAR}; i++){
+ vec2 q = root - uPrintN[i].xy;
+ float e = length(q) / 2.9;
+ float k = smoothstep(1.3, 0.95, e);
+ if (k > press) { press = k; pdir = q / max(length(q), 1e-3); }
+ g *= 1.0 - 0.9 * smoothstep(1.0, 0.75, e);
+ }
+ float alive = step(r3, g * uDens);
+ float clumpN = vnoise(root * 1.7 + 11.0) * 0.6 + vnoise(root * 0.45) * 0.4;
+ float H;
+ if (uMode > 2.5) H = mix(uH.x, uH.y, r4 * r4 * r4) * fade * alive;
+ else {
+ H = mix(uH.x, uH.y, r4 * r4) * fade * alive * (0.55 + 0.45 * g) * (0.45 + 1.0 * clumpN);
+ if (uMode < 0.5) H *= mix(0.7, 1.4, tallP) * (1.0 + uTus * (2.0 * tk.x - 0.3));
+ H *= 1.0 - 0.7 * press;
+ if (uAbs > 0.5) H = min(H, uH.y * 1.7); // no metre-long blades whipping across the lens
+ }
+ float wsc = mix(uW.x, uW.y, r6) * (0.4 + 0.6 * fade);
+ float xs = uAbs > 0.5 ? wsc : wsc * H;
+ float yaw = r5 * 6.28318;
+ vec2 dir = vec2(cos(yaw), sin(yaw));
+ // local model -> rotated
+ vec3 lp = position;
+ vec3 ln = normal;
+ vec2 rn = vec2(dir.x * ln.z + dir.y * ln.x, dir.y * ln.z - dir.x * ln.x);
+ float v;
+ if (uMode > 2.5) {
+ vec3 q = lp * H; q.y *= 0.5 + 0.45 * r6;
+ vec2 rxz = vec2(dir.x * q.z + dir.y * q.x, dir.y * q.z - dir.x * q.x);
+ gPos = vec3(root.x + rxz.x, q.y + H * (0.10 - 0.25 * r7), root.y + rxz.y);
+ objectNormal = normalize(vec3(rn.x, ln.y * 1.5, rn.y));
+ v = clamp(lp.y + 0.5, 0.0, 1.0);
+ } else {
+ vec2 lxz = lp.xz * xs;
+ vec2 rxz = vec2(dir.x * lxz.y + dir.y * lxz.x, dir.y * lxz.y - dir.x * lxz.x);
+ v = clamp(lp.y, 0.0, 1.2);
+ // wind (pure function of time) + lean
+ float wph = uTime * 1.25 + dot(root, vec2(0.23, 0.11));
+ float gust = 0.5 + 0.5 * sin(uTime * 0.37 + root.x * 0.045 + root.y * 0.02);
+ vec2 wind = vec2(0.85, 0.35) * (0.08 + 0.22 * gust) * (0.7 + 0.3 * sin(wph))
+ + vec2(sin(wph * 2.3 + r1 * 6.0), cos(wph * 1.9 + r2 * 5.0)) * 0.035;
+ vec2 bend = dir * uLean * (0.15 + 1.3 * r7 * r7) + wind * uWind + pdir * press * 1.6 + tk.yz * uTus * 0.55;
+ float bl = dot(bend, bend);
+ vec2 off = bend * v * v * H;
+ float y = lp.y * H * (1.0 - 0.3 * min(bl, 2.0) * v);
+ gPos = vec3(root.x + rxz.x + off.x, y, root.y + rxz.y + off.y);
+ objectNormal = normalize(mix(normalize(vec3(rn.x, 0.0, rn.y) + 1e-5), vec3(0.0, 1.0, 0.0), uNUp));
+ }
+ if (H < 0.003) gPos = vec3(root.x, -50.0, root.y); // collapse dead blades (degenerate tris gave NaN normals)
+ vWP = gPos; vV = v; vSeed = r8; vPart = part; vSide = side; vDim = vec2(uAbs > 0.5 ? xs : xs * (part > 3.5 ? 0.14 : 0.02), H);
+ // colour: dark green -> olive, some blue-green, rare straw; dead / dry parts khaki and brown
+ vec3 cA = vec3(0.026, 0.050, 0.012), cB = vec3(0.050, 0.055, 0.014), cC = vec3(0.020, 0.044, 0.020), cD = vec3(0.11, 0.088, 0.045);
+ vec3 tintG = vec3(1.75, 1.32, 0.58); // look-dev: olive green under the blue dusk light
+ vec3 tintD = vec3(1.12, 1.04, 0.86);
+ vec3 col; vec3 tint = tintD;
+ if (part < 0.5) {
+ col = mix(cA, cB, r7);
+ col = mix(col, cC, smoothstep(0.6, 1.0, r2) * 0.8);
+ float dry = step(r1, uDry + 0.25 * tk.x * uTus);
+ vec3 cDry = vec3(0.098, 0.088, 0.060) / tintG * tintD; // pale khaki straw (never orange)
+ col = mix(col, cDry, dry * smoothstep(0.15, 0.9, v) * 0.9);
+ col = mix(col, cDry, smoothstep(0.65, 1.0, v) * 0.3);
+ tint = tintG;
+ } else if (part < 1.5) col = mix(vec3(0.090, 0.082, 0.060), vec3(0.050, 0.045, 0.034), r4);
+ else if (part < 2.5) col = vec3(0.035, 0.022, 0.012);
+ else if (part < 3.5) col = mix(vec3(0.070, 0.062, 0.045), vec3(0.030, 0.026, 0.020), r4);
+ else if (part < 4.5) {
+ col = mix(vec3(0.020, 0.046, 0.016), vec3(0.036, 0.050, 0.014), r7);
+ col = mix(col, vec3(0.060, 0.036, 0.020), step(0.78, r2) * 0.55);
+ tint = tintG;
+ } else if (part < 5.5) col = mix(vec3(0.070, 0.038, 0.024), vec3(0.042, 0.026, 0.018), r4);
+ else {
+ col = mix(vec3(0.045, 0.045, 0.043), vec3(0.10, 0.096, 0.088), r7);
+ col = mix(col, vec3(0.026, 0.021, 0.016), step(0.6, r2));
+ tint = vec3(1.0);
+ }
+ float shade = mix(uAO, 1.0, smoothstep(0.0, 0.5, v)) * (0.75 + 0.5 * r6) * mix(0.85, 1.0, press);
+ vGCol = col * shade * tint;
+ vGDry = vec3(0.098, 0.088, 0.060) * tintD * shade;
+}`)
+ .replace('#include <begin_vertex>', 'vec3 transformed = gPos;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+varying vec3 vGCol; varying vec3 vGDry; varying float vV; varying vec3 vWP; varying float vSeed; varying float vPart; varying float vSide; varying vec2 vDim;
+${SKY_GLSL}
+${FACADE}
+float hashF(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+#ifdef USE_MAP
+ diffuseColor.rgb = mix(vGCol, vGDry, sampledDiffuseColor.g) * (0.35 + 0.9 * sampledDiffuseColor.r);
+ diffuseColor.a = clamp((sampledDiffuseColor.a - 0.45) / max(fwidth(sampledDiffuseColor.a), 1e-4) + 0.5, 0.0, 1.0);
+ if (diffuseColor.a < 0.02) discard;
+#else
+ diffuseColor.rgb = vGCol;
+ // feathered seed heads: ragged edges
+ if ((vPart > 0.5 && vPart < 1.5) || (vPart > 4.5 && vPart < 5.5)){
+ if (hashF(vec2(floor(vV * 90.0) + vSeed * 31.0, floor(vSide * 2.0 + 2.0))) < abs(vSide) * 1.1 - 0.15) discard;
+ }
+#endif
+ diffuseColor.rgb *= skyOcc(vWP);`)
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = vPart > 5.5 ? 0.36 : mix(0.9, 0.5, vV);')
+ .replace('#include <normal_fragment_begin>', `#include <normal_fragment_begin>
+if (vPart < 5.5) { // two-sided blades: flip only the horizontal part so back faces still face the sky
+ vec3 nw = normalize((vec4(normalize(vNormal), 0.0) * viewMatrix).xyz);
+ if (!gl_FrontFacing) nw.xz = -nw.xz;
+ normal = normalize((viewMatrix * vec4(nw, 0.0)).xyz);
+}`)
+ .replace('#include <opaque_fragment>', `
+float vPx = length(vec2(dFdx(vV), dFdy(vV)));
+if (vPart < 5.5) {
+ vec3 V = normalize(cameraPosition - vWP);
+ vec3 Nw = normalize((vec4(normal, 0.0) * viewMatrix).xyz);
+ float dist = length(cameraPosition - vWP);
+ // translucency / sky rim: blades lit through from the dusk sky
+ float rim = pow(1.0 - abs(dot(Nw, V)), 2.0);
+ vec3 skyL = skyColor(normalize(vec3(-V.x, 0.25, -V.z)));
+ outgoingLight += vGCol * mix(skyL, vec3(dot(skyL, vec3(0.33))), 0.88) * (1.6 * vV * vV + 1.0 * rim * vV + 0.5) * 2.0;
+ vec3 R = reflect(-V, Nw);
+ outgoingLight += facadeGlow(vWP, R, 0.03) * 0.25 * rim * vV;
+ float nearF = smoothstep(11.0, 3.0, dist) * smoothstep(0.55, 1.1, dist);
+ if (nearF > 0.0 && (vPart < 0.5 || vPart > 3.5)) {
+ vec3 skyR = skyColor(normalize(vec3(R.x, abs(R.y) + 0.15, R.z)));
+ vec3 cold = mix(skyR, vec3(dot(skyR, vec3(0.4))), 0.45);
+ // wet film on the blade edges
+ float edge = smoothstep(0.5, 1.0, abs(vSide)) * smoothstep(0.05, 0.4, vV);
+ outgoingLight += (cold * 0.55 + facadeGlow(vWP, R, 0.02) * 1.2) * edge * nearF;
+ // dew beads: tiny lens-like drops sitting along the blade, each catches the bright sky and the warm windows
+ float wid = max(vDim.x * pow(max(1.0 - vV, 0.02), 0.6), 0.004);
+ float nb = max(vDim.y / 0.016, 1.0);
+ float cell = floor(vV * nb);
+ float hb = hashF(vec2(cell + vSeed * 91.7, vSeed * 13.1 + cell * 0.37));
+ float cv = (fract(vV * nb) - 0.5) * 0.016;
+ float cs = (vSide - (hashF(vec2(cell * 1.7, vSeed * 57.0)) - 0.5) * 1.3) * wid * 0.5;
+ float px = max(vPx * vDim.y, 1e-5);
+ float rad = 0.0020 + 0.0022 * fract(hb * 17.0);
+ float re = max(rad, px * 0.8);
+ float bead = smoothstep(re, re * 0.45, length(vec2(cv, cs))) * step(0.66, hb) * (rad / re) * smoothstep(0.12, 0.3, vV);
+ if (bead > 0.0) {
+ vec2 bo = vec2(cs, cv) / re;
+ vec3 Nb = normalize(Nw + vec3(bo.x * V.z, bo.y * 0.9, -bo.x * V.x) * 0.8);
+ vec3 Rb = reflect(-V, Nb);
+ vec3 glint = facadeGlow(vWP, Rb, 0.002) * 7.0 + cold * 4.5 + vec3(0.03, 0.04, 0.06);
+ outgoingLight += glint * bead * nearF * (0.45 + 0.55 * fract(hb * 5.0));
+ }
+ }
+}
+#include <opaque_fragment>`);
+ };
+ const mesh = new THREE.Mesh(ig, mat);
+ mesh.frustumCulled = false;
+ mesh.receiveShadow = true;
+ mesh.castShadow = false;
+ mesh.name = 'env-' + name;
+ if (DBG !== "noveg" && DBG !== "no" + name) scene.add(mesh);
+ vegMeshes.push(mesh);
+ mesh.userData.ahead = o.ahead || 0;
+ mesh.userData.uCtr = U.uCtr;
+ mesh.userData.inMirror = !!o.mirror;
+ return mesh;
+ }
+
+ function finalize(pos, nrm, part, idx) {
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ g.setAttribute('normal', new THREE.Float32BufferAttribute(nrm, 3));
+ g.setAttribute('aPart', new THREE.Float32BufferAttribute(part, 1));
+ g.setIndex(idx);
+ return g;
+ }
+ // a tapered strip rising from base, curving outward along yaw (out = curve * v^2 * height).
+ // New-style plants are modelled in units of plant height (xz too); taper may be a width profile function.
+ function addStrip(P, N, A, I, nseg, base, height, width, curve, yaw, part, taper = 0.6, startY = 0) {
+ const s0 = P.length / 3;
+ const cs = Math.cos(yaw), sn = Math.sin(yaw);
+ for (let s = 0; s <= nseg; s++) {
+ const v = s / nseg;
+ const w = s === nseg ? 0 : width * (typeof taper === 'function' ? taper(v) : Math.pow(1 - v, taper));
+ const out = curve * v * v * height;
+ const cx = base[0] + cs * out, cz = base[2] + sn * out;
+ const y = base[1] + startY + v * height;
+ // side vector perpendicular to the curve direction
+ const sx = -sn, sz = cs;
+ P.push(cx - sx * w * 0.5, y, cz - sz * w * 0.5, cx + sx * w * 0.5, y, cz + sz * w * 0.5);
+ N.push(cs, 0, sn, cs, 0, sn);
+ A.push(part - 0.3, part + 0.3);
+ }
+ for (let s = 0; s < nseg; s++) {
+ const a = s0 + s * 2;
+ if (s === nseg - 1) I.push(a, a + 1, a + 3);
+ else I.push(a, a + 1, a + 3, a, a + 3, a + 2);
+ }
+ }
+ const leafW = (v) => 0.22 + 0.78 * Math.sin(Math.PI * Math.min(1, 0.08 + v * 1.0));
+ const plumeW = (v) => 0.25 + 0.75 * Math.sin(Math.PI * Math.min(1, 0.1 + v * 0.9));
+ // single blade: x = side, y = v, normal +z (the shader rotates it)
+ function bladeGeo(nseg) {
+ const P = [], N = [], A = [], I = [];
+ for (let s = 0; s < nseg; s++) {
+ const v = s / nseg, w = Math.pow(1 - v, 0.6);
+ P.push(-0.5 * w, v, 0, 0.5 * w, v, 0); N.push(0, 0, 1, 0, 0, 1); A.push(-0.3, 0.3);
+ }
+ P.push(0, 1, 0); N.push(0, 0, 1); A.push(0);
+ for (let s = 0; s < nseg - 1; s++) { const a = s * 2; I.push(a, a + 1, a + 3, a, a + 3, a + 2); }
+ const a = (nseg - 1) * 2; I.push(a, a + 1, nseg * 2);
+ return finalize(P, N, A, I);
+ }
+ // crossed alpha-tested card carrying ~60 drawn blades (mid ring: dense at a tiny triangle cost)
+ function cardGeo() {
+ const P = [], N = [], A = [], I = [], UV = [];
+ for (let k = 0; k < 2; k++) {
+ const yaw = k * Math.PI / 2, cs = Math.cos(yaw), sn = Math.sin(yaw), b = P.length / 3;
+ for (const [u, v] of [[0, 0], [1, 0], [1, 1], [0, 1]]) {
+ const x = (u - 0.5) * 2.0;
+ P.push(cs * x, v, sn * x); N.push(-sn, 0, cs); A.push(0); UV.push(u, v);
+ }
+ I.push(b, b + 1, b + 2, b, b + 2, b + 3);
+ }
+ const g = finalize(P, N, A, I);
+ g.setAttribute('uv', new THREE.Float32BufferAttribute(UV, 2));
+ return g;
+ }
+ // card texture: R = brightness, G = dryness (khaki tips, seed heads), A = coverage
+ function grassCardTex() {
+ const W = 1024, H = 512;
+ return ctx.TEX.canvasTexture(W, H, (c) => {
+ c.clearRect(0, 0, W, H);
+ const r = rng(31337);
+ for (let i = 0; i < 64; i++) {
+ const tall = i >= 52;
+ const x0 = 14 + r() * (W - 28), h = tall ? H * (0.72 + 0.26 * r()) : H * (0.2 + 0.5 * r() * r() + 0.02), lean = (r() - 0.5) * (tall ? 0.5 : 1.1) * h;
+ const w = tall ? 1.6 + r() * 1.2 : 3 + r() * 5.5, g = Math.round(105 + r() * 150);
+ const dry = Math.round((r() < 0.3 ? 200 : 60 + r() * 120));
+ const gr = c.createLinearGradient(0, H, 0, H - h);
+ gr.addColorStop(0, `rgb(${Math.round(g * 0.75)},0,0)`); gr.addColorStop(tall ? 0.3 : 0.55, `rgb(${g},${tall ? dry : 0},0)`); gr.addColorStop(1, `rgb(${g},${dry},0)`);
+ c.fillStyle = gr;
+ c.beginPath();
+ c.moveTo(x0 - w, H);
+ c.quadraticCurveTo(x0 - w * 0.6 + lean * 0.3, H - h * 0.55, x0 + lean, H - h);
+ c.quadraticCurveTo(x0 + w * 0.6 + lean * 0.3, H - h * 0.55, x0 + w, H);
+ c.closePath(); c.fill();
+ if (tall) { // drooping seed head
+ c.fillStyle = `rgb(${g},235,0)`;
+ const dx = lean >= 0 ? 1 : -1;
+ for (let k = 0; k < 16; k++) {
+ const u = k / 15, px = x0 + lean + dx * u * 26 + (r() - 0.5) * 6, py = H - h + u * u * 30 - 6 + (r() - 0.5) * 8;
+ c.beginPath(); c.ellipse(px, py, 2.2 + r() * 2.5, 4 + r() * 5, dx * 0.6, 0, 6.3); c.fill();
+ }
+ }
+ }
+ }, { repeat: false, srgb: false });
+ }
+ // tall seed grass (reed-grass): arching stalk, drooping feathery plume, long arching leaves
+ function tallGeo() {
+ const P = [], N = [], A = [], I = [];
+ const r = rng(5);
+ addStrip(P, N, A, I, 4, [0, 0, 0], 0.84, 0.008, 0.22, 0, 0, 0.25);
+ const tx = 0.22 * 0.84;
+ addStrip(P, N, A, I, 3, [tx - 0.01, 0.80, 0], 0.2, 0.05, 1.6, 0.25, 1, plumeW);
+ addStrip(P, N, A, I, 3, [0, 0, 0], 0.62, 0.022, 0.95, 2.2 + r(), 0, 0.7);
+ addStrip(P, N, A, I, 3, [0, 0, 0], 0.5, 0.02, 1.3, 4.3 + r(), 0, 0.7);
+ addStrip(P, N, A, I, 2, [0.03, 0.34, 0], 0.36, 0.016, 1.5, 0.9, 0, 0.8);
+ return finalize(P, N, A, I);
+ }
+ // lone weed stalk for the far ring (seed head on a bare stem), fat enough to survive the distance
+ function stalkGeo() {
+ const P = [], N = [], A = [], I = [];
+ addStrip(P, N, A, I, 3, [0, 0, 0], 1.0, 0.022, 0.12, 0, 3, 0.3);
+ addStrip(P, N, A, I, 1, [0.1, 0.78, 0], 0.22, 0.07, 0.6, 0.4, 1, 0.2);
+ addStrip(P, N, A, I, 2, [0, 0, 0], 0.4, 0.07, 0.9, 2.5, 0, 0.7);
+ return finalize(P, N, A, I);
+ }
+ // reed / cattail cluster (likes puddle edges)
+ function reedGeo() {
+ const P = [], N = [], A = [], I = [];
+ const r = rng(9);
+ for (let k = 0; k < 2; k++) {
+ const bx = (r() - 0.5) * 0.1, bz = (r() - 0.5) * 0.1, hh = 0.7 + r() * 0.3, yaw = r() * 6.28, cv = 0.06 + r() * 0.12;
+ addStrip(P, N, A, I, 4, [bx, 0, bz], hh, 0.008, cv, yaw, 0, 0.2);
+ if (k < 1) addStrip(P, N, A, I, 2, [bx + Math.cos(yaw) * cv * hh * 0.55, hh * 0.74, bz + Math.sin(yaw) * cv * hh * 0.55], 0.13, 0.024, 0.0, yaw + 1.57, 2, (v) => 0.9 - 0.3 * v);
+ addStrip(P, N, A, I, 3, [bx, 0, bz], hh * 0.85, 0.02, 0.55 + r() * 0.4, yaw + 2.0 + r(), 0, 0.8);
+ }
+ return finalize(P, N, A, I);
+ }
+ // dock / burdock: rosette of broad leaves and a rusty seed spike
+ function dockGeo() {
+ const P = [], N = [], A = [], I = [];
+ const r = rng(21);
+ for (let k = 0; k < 5; k++) {
+ const yaw = k * 1.2566 + r() * 0.5;
+ addStrip(P, N, A, I, 3, [Math.cos(yaw) * 0.02, 0, Math.sin(yaw) * 0.02], 0.26 + r() * 0.16, 0.13 + r() * 0.05, 1.3 + r() * 0.9, yaw, 4, leafW);
+ }
+ addStrip(P, N, A, I, 3, [0, 0, 0], 0.7, 0.014, 0.08, 0.3, 3, 0.2);
+ addStrip(P, N, A, I, 3, [0.03, 0.55, 0], 0.45, 0.07, 0.15, 0.3, 5, plumeW);
+ addStrip(P, N, A, I, 3, [0.03, 0.55, 0], 0.42, 0.07, 0.1, 1.87, 5, plumeW);
+ addStrip(P, N, A, I, 2, [0.02, 0.4, 0], 0.3, 0.035, 1.2, 3.4, 5, plumeW);
+ return finalize(P, N, A, I);
+ }
+ // dry umbellifer skeleton (hogweed / angelica): ribbed stalk, umbrella of rays with seed tufts, a side branch
+ function umbelGeo() {
+ const P = [], N = [], A = [], I = [];
+ const r = rng(33);
+ addStrip(P, N, A, I, 3, [0, 0, 0], 0.86, 0.014, 0.06, 0, 3, 0.3);
+ const top = [0.045, 0.85, 0];
+ for (let k = 0; k < 7; k++) {
+ const yaw = k * 0.8976 + r() * 0.3, out = 0.10 + r() * 0.05, hh = 0.09 + r() * 0.05;
+ addStrip(P, N, A, I, 1, top, hh, 0.006, out / hh, yaw, 3, 0.2);
+ addStrip(P, N, A, I, 1, [top[0] + Math.cos(yaw) * out, top[1] + hh - 0.012, top[2] + Math.sin(yaw) * out], 0.035, 0.05, 0.0, yaw + 1.57, 1, 0.5);
+ }
+ const by = 2.4, bo = 0.2, bh = 0.26;
+ addStrip(P, N, A, I, 2, [0, 0.46, 0], bh, 0.008, bo / bh, by, 3, 0.2);
+ const bt = [Math.cos(by) * bo, 0.46 + bh, Math.sin(by) * bo];
+ for (let k = 0; k < 4; k++) {
+ const yaw = k * 1.57 + 0.4, out = 0.06, hh = 0.06;
+ addStrip(P, N, A, I, 1, bt, hh, 0.005, out / hh, yaw, 3, 0.2);
+ addStrip(P, N, A, I, 1, [bt[0] + Math.cos(yaw) * out, bt[1] + hh - 0.01, bt[2] + Math.sin(yaw) * out], 0.028, 0.04, 0.0, yaw + 1.57, 1, 0.5);
+ }
+ addStrip(P, N, A, I, 2, [0, 0.0, 0], 0.22, 0.07, 1.6, 4.4, 3, leafW);
+ addStrip(P, N, A, I, 2, [0, 0.0, 0], 0.18, 0.06, 1.9, 1.1, 3, leafW);
+ return finalize(P, N, A, I);
+ }
+ // irregular flat-shaded stone
+ function stoneGeo() {
+ const g = new THREE.IcosahedronGeometry(0.5, 0);
+ const p = g.getAttribute('position');
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ const k = 1 + 0.28 * Math.sin(x * 9.1 + y * 5.3 + 1.0) * Math.cos(z * 7.7 - y * 3.9);
+ p.setXYZ(i, x * k * 1.15, y * k * 0.8, z * k);
+ }
+ g.deleteAttribute('uv');
+ g.computeVertexNormals();
+ g.setAttribute('aPart', new THREE.Float32BufferAttribute(new Float32Array(p.count).fill(6), 1));
+ return g;
+ }
+
+ // near: dense blades in tussocks. mid: blade cards out to ~50 m. Then the wild layers: tall seed grass,
+ // dock, dry umbels, far stalks, reeds at the puddle rims, stones and clods on bare soil.
+ makeVeg('grassNear', bladeGeo(4), 36000, { seed: 1, S: 13, ahead: 4.2, near: 0.65, fade0: 5.2, fade1: 8.0, h0: 0.11, h1: 0.52, w0: 0.011, w1: 0.03, lean: 0.55, wind: 1.0, abs: 1, tus: 1 });
+ makeVeg('grassMid', cardGeo(), 30000, { seed: 2, S: 72, ahead: 28, fade0: 40, fade1: 52, near: 3.0, h0: 0.28, h1: 0.8, w0: 0.24, w1: 0.4, lean: 0.25, wind: 0.6, nup: 0.85, ao: 0.75, map: grassCardTex(), abs: 1, tus: 0.4 });
+ makeVeg('grassTall', tallGeo(), 5200, { seed: 3, S: 44, ahead: 16, fade0: 22, fade1: 30, near: 1.7, h0: 0.6, h1: 2.1, w0: 0.8, w1: 1.25, lean: 0.3, wind: 1.6, dens: 1.0, dry: 0.5, tallDens: 1 });
+ makeVeg('weeds', dockGeo(), 1300, { seed: 6, S: 46, ahead: 17, fade0: 22, fade1: 30, near: 1.5, h0: 0.45, h1: 1.15, w0: 0.8, w1: 1.3, lean: 0.12, wind: 0.6, mode: 2, patch: 9.0, dry: 0.15, ao: 0.6 });
+ makeVeg('umbels', umbelGeo(), 1500, { seed: 7, S: 84, ahead: 34, fade0: 48, fade1: 64, near: 1.8, h0: 1.1, h1: 3.0, w0: 0.8, w1: 1.2, lean: 0.12, wind: 0.8, mode: 2, patch: 23.0, nup: 0.5, mirror: true });
+ makeVeg('stalksFar', stalkGeo(), 5000, { seed: 5, S: 120, ahead: 52, fade0: 75, fade1: 100, near: 14, h0: 0.7, h1: 1.8, w0: 0.9, w1: 1.3, lean: 0.15, wind: 1.2, dens: 0.8, dry: 0.6, nup: 0.6 });
+ makeVeg('reeds', reedGeo(), 2600, { seed: 4, S: 50, ahead: 18, near: 1.4, fade0: 19, fade1: 25, h0: 0.9, h1: 1.9, w0: 0.8, w1: 1.2, lean: 0.1, wind: 1.0, mode: 1, dry: 0.3, mirror: true });
+ makeVeg('stones', stoneGeo(), 1600, { seed: 8, S: 30, ahead: 10, near: 0.6, fade0: 13, fade1: 17, h0: 0.03, h1: 0.26, w0: 1, w1: 1, lean: 0, wind: 0, mode: 3, nup: 0, ao: 0.55 });
+
+ // ================================================================ DISTANT SILHOUETTES (one merged static mesh)
+ let farTris = 0, propTris = 0;
+ {
+ const r = rng(4242);
+ const parts = [];
+ const colorize = (g, c) => {
+ const n = g.getAttribute('position').count, col = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) { col[i * 3] = c[0]; col[i * 3 + 1] = c[1]; col[i * 3 + 2] = c[2]; }
+ g.setAttribute('color', new THREE.BufferAttribute(col, 3));
+ if (g.index) { const ng = g.toNonIndexed(); g.dispose(); return ng; }
+ return g;
+ };
+ // n-sided tube along a polyline (posts, twigs, rebar)
+ const tube = (pts, r0, r1, sides) => {
+ const P = [], I = [], n = pts.length;
+ for (let i = 0; i < n; i++) {
+ const a = pts[Math.max(0, i - 1)], b = pts[Math.min(n - 1, i + 1)];
+ let dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
+ const l = Math.hypot(dx, dy, dz) || 1; dx /= l; dy /= l; dz /= l;
+ const rx = Math.abs(dy) > 0.9 ? 1 : 0, ry = Math.abs(dy) > 0.9 ? 0 : 1;
+ let ux = dy * 0 - dz * ry, uy = dz * rx - dx * 0, uz = dx * ry - dy * rx;
+ const ul = Math.hypot(ux, uy, uz) || 1; ux /= ul; uy /= ul; uz /= ul;
+ const vx = dy * uz - dz * uy, vy = dz * ux - dx * uz, vz = dx * uy - dy * ux;
+ const rad = r0 + (r1 - r0) * (n > 1 ? i / (n - 1) : 0);
+ for (let s = 0; s < sides; s++) {
+ const an = s / sides * 6.2832, cs = Math.cos(an) * rad, sn = Math.sin(an) * rad;
+ P.push(pts[i][0] + ux * cs + vx * sn, pts[i][1] + uy * cs + vy * sn, pts[i][2] + uz * cs + vz * sn);
+ }
+ }
+ for (let i = 0; i < n - 1; i++) for (let s = 0; s < sides; s++) {
+ const a = i * sides + s, b = i * sides + (s + 1) % sides, c = a + sides, d = b + sides;
+ I.push(a, b, d, a, d, c);
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ g.setIndex(I); g.computeVertexNormals();
+ return g;
+ };
+ const blob = (rad, det, sy = 0.85) => {
+ const g = new THREE.IcosahedronGeometry(rad, det);
+ const p = g.getAttribute('position');
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ const k = 1 + 0.25 * Math.sin(x * 2.1 + y * 1.3) * Math.cos(z * 1.7 - y * 0.9) + (r() - 0.5) * 0.15;
+ p.setXYZ(i, x * k, y * k * sy, z * k);
+ }
+ g.computeVertexNormals();
+ return g;
+ };
+ const place = (g, x, y, z, ry = 0) => { g.rotateY(ry); g.translate(x, y, z); parts.push(g); };
+ const treeAt = (x, z) => {
+ const poplar = r() < 0.35;
+ const h = poplar ? 14 + r() * 9 : 8 + r() * 9, c = 0.6 + r() * 0.4;
+ const trunk = new THREE.CylinderGeometry(0.1, 0.3, h * 0.75, 5, 1, true);
+ place(colorize(trunk, [0.018 * c, 0.018 * c, 0.017 * c]), x, h * 0.375, z);
+ const nb = 3 + Math.floor(r() * 3);
+ for (let k = 0; k < nb; k++) {
+ const u = k / (nb - 1);
+ const rad = h * (poplar ? 0.1 + 0.05 * (1 - Math.abs(u - 0.4)) : 0.14 + r() * 0.1) * (1 - 0.35 * u);
+ const spread = poplar ? 0.08 : 0.3;
+ place(colorize(blob(rad, 1, poplar ? 2.2 : 1.25), [0.014 * c, 0.02 * c, 0.017 * c]),
+ x + (r() - 0.5) * h * spread, h * (0.42 + 0.48 * u), z + (r() - 0.5) * h * spread, r() * 6);
+ }
+ };
+ const shrubAt = (x, z) => {
+ const s = 1.2 + r() * 2.5, c = 0.6 + r() * 0.4;
+ place(colorize(blob(s, 1), [0.016 * c, 0.024 * c, 0.02 * c]), x, s * 0.4, z, r() * 6);
+ };
+ const inBand = () => {
+ const side = r() < 0.72 ? -1 : 1;
+ const z = side < 0 ? -(70 + Math.pow(r(), 1.3) * 260) : 235 + r() * 170;
+ return [-450 + r() * 1150, z];
+ };
+ // lone trees + small clusters
+ for (let k = 0; k < 26; k++) {
+ const [x, z] = inBand();
+ treeAt(x, z);
+ if (r() < 0.45) for (let m = 0; m < 2 + r() * 3; m++) treeAt(x + (r() - 0.5) * 30, z + (r() - 0.5) * 18);
+ }
+ for (let k = 0; k < 80; k++) { const [x, z] = inBand(); shrubAt(x, z); }
+ // utility pole line with sagging wires (z = -150)
+ const poleZ = -150, span = 55, poles = [];
+ for (let x = -450; x <= 720; x += span) {
+ const px = x + (r() - 0.5) * 6, pz = poleZ + (r() - 0.5) * 3, ph = 10.5 + r() * 1.0;
+ poles.push([px, pz, ph]);
+ const pole = new THREE.CylinderGeometry(0.13, 0.2, ph, 5, 1, true);
+ place(colorize(pole, [0.018, 0.016, 0.014]), px, ph / 2, pz);
+ const arm = new THREE.BoxGeometry(0.15, 0.15, 2.4);
+ place(colorize(arm, [0.018, 0.016, 0.014]), px, ph - 0.6, pz);
+ }
+ for (let k = 0; k + 1 < poles.length; k++) {
+ const [ax, az, ah] = poles[k], [bx, bz, bh] = poles[k + 1];
+ for (const wz of [-1.0, 0, 1.0]) {
+ const P = [], seg = 10;
+ for (let s = 0; s <= seg; s++) {
+ const u = s / seg, sag = 1.4 * 4 * u * (1 - u);
+ const x = ax + (bx - ax) * u, z = az + (bz - az) * u + wz, y = ah - 0.6 + (bh - ah) * u - sag + 0.1;
+ P.push(x, y + 0.03, z, x, y - 0.03, z);
+ }
+ const I = [];
+ for (let s = 0; s < seg; s++) { const a = s * 2; I.push(a, a + 1, a + 3, a, a + 3, a + 2); }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ g.setIndex(I); g.computeVertexNormals();
+ parts.push(colorize(g, [0.01, 0.01, 0.01]));
+ }
+ }
+ // ---- fences: rotten posts with two sagging wires; long runs far out + a broken fragment by the road
+ const fenceRun = (x0, z0, x1, z1, step, gapP, col) => {
+ const len = Math.hypot(x1 - x0, z1 - z0), nn = Math.floor(len / step);
+ let prev = null;
+ for (let k = 0; k <= nn; k++) {
+ const u = k / nn;
+ if (r() < gapP) { prev = null; continue; }
+ const px = x0 + (x1 - x0) * u + (r() - 0.5) * 0.3, pz = z0 + (z1 - z0) * u + (r() - 0.5) * 0.3;
+ const ph = 1.15 + r() * 0.35, lx = (r() - 0.5) * 0.45, lz = (r() - 0.5) * 0.45;
+ const top = [px + lx * ph, ph, pz + lz * ph];
+ parts.push(colorize(tube([[px, -0.1, pz], top], 0.055, 0.045, 5), [col[0] * (0.7 + 0.5 * r()), col[1] * (0.7 + 0.5 * r()), col[2] * (0.7 + 0.5 * r())]));
+ if (prev && r() > 0.12) for (const wy of [0.92, 0.55]) {
+ const a = [prev[0] + (prev[3] - prev[0]) * wy, prev[4] * wy, prev[2] + (prev[5] - prev[2]) * wy];
+ const b = [px + lx * ph * wy, ph * wy, pz + lz * ph * wy];
+ const sag = 0.08 + r() * 0.3, P = [], seg = 4;
+ for (let s = 0; s <= seg; s++) {
+ const t = s / seg, y = a[1] + (b[1] - a[1]) * t - sag * 4 * t * (1 - t);
+ const x = a[0] + (b[0] - a[0]) * t, z = a[2] + (b[2] - a[2]) * t;
+ P.push(x, Math.max(y, 0.03) + 0.012, z, x, Math.max(y, 0.03) - 0.012, z);
+ }
+ const I = [];
+ for (let s = 0; s < seg; s++) { const q = s * 2; I.push(q, q + 1, q + 3, q, q + 3, q + 2); }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ g.setIndex(I); g.computeVertexNormals();
+ parts.push(colorize(g, [0.012, 0.011, 0.010]));
+ }
+ prev = [px, 0, pz, top[0], ph, top[2]];
+ }
+ };
+ fenceRun(-260, -64, 520, -58, 3.3, 0.07, [0.03, 0.027, 0.022]);
+ fenceRun(-240, 82, 480, 76, 3.3, 0.10, [0.03, 0.027, 0.022]);
+ fenceRun(119.5, 45.5, 123.3, 38.5, 2.6, 0.0, [0.04, 0.034, 0.027]);
+ fenceRun(-30, 47, -21.5, 38, 2.8, 0.15, [0.04, 0.034, 0.027]);
+ // ---- twiggy willow shrubs and saplings scattered beside the walker's corridor (never on the foot lines)
+ const bushAt = (x, z, s) => {
+ const nt = 16 + Math.floor(r() * 10), c = 0.8 + r() * 0.5;
+ for (let k = 0; k < nt; k++) {
+ const yaw = r() * 6.283, lean = 0.08 + r() * r() * 0.5, hh = s * (0.5 + 0.5 * r());
+ const bx = x + Math.cos(yaw) * 0.22 * s * r(), bz = z + Math.sin(yaw) * 0.22 * s * r();
+ const cx = Math.cos(yaw), cz = Math.sin(yaw);
+ const mid = [bx + cx * lean * hh * 0.3, hh * 0.5, bz + cz * lean * hh * 0.3];
+ const tip = [bx + cx * lean * hh, hh, bz + cz * lean * hh];
+ const tc = [0.040 * c, 0.036 * c, 0.031 * c];
+ parts.push(colorize(tube([[bx, -0.05, bz], mid, tip], 0.010 + 0.006 * s, 0.003, 3), tc));
+ // side twiglets + a few small leaf sprays
+ for (let m = 0; m < 2; m++) {
+ const t = 0.25 + 0.6 * r(), ya = yaw + (r() - 0.5) * 2.6, L = hh * (0.2 + 0.25 * r());
+ const o = [mid[0] + (tip[0] - mid[0]) * t, mid[1] + (tip[1] - mid[1]) * t, mid[2] + (tip[2] - mid[2]) * t];
+ const e = [o[0] + Math.cos(ya) * L * 0.6, o[1] + L * 0.8, o[2] + Math.sin(ya) * L * 0.6];
+ parts.push(colorize(tube([o, e], 0.006 + 0.002 * s, 0.002, 3), tc));
+ // a few last narrow leaves hanging off the twig end
+ const lw = 0.025 + 0.02 * r(), ll = 0.10 + 0.08 * r(), la = r() * 6.283;
+ const q = new THREE.BufferGeometry();
+ q.setAttribute('position', new THREE.Float32BufferAttribute([e[0] - Math.cos(la) * lw, e[1], e[2] - Math.sin(la) * lw, e[0] + Math.cos(la) * lw, e[1], e[2] + Math.sin(la) * lw,
+ e[0] + Math.sin(la) * ll * 0.5, e[1] - ll, e[2] - Math.cos(la) * ll * 0.5], 3));
+ q.computeVertexNormals();
+ parts.push(colorize(q, [0.034 * c, 0.046 * c, 0.022 * c]));
+ }
+ }
+ };
+ const safeZ = (z) => Math.abs(z) > 31 && Math.abs(Math.abs(z) - 35) > 4.5;
+ for (let k = 0; k < 46; k++) {
+ const x = -130 + r() * 480, z = (r() < 0.5 ? -1 : 1) * (31 + r() * 85), s = 0.9 + r() * r() * 2.6;
+ if (!safeZ(z) || Math.hypot(x - 150, z - 50) < 9 || Math.hypot(x - 134, z - 40) < 12 || Math.hypot(x - 86, z - 34) < 6) continue;
+ bushAt(x, z, s);
+ if (r() < 0.4) bushAt(x + (r() - 0.5) * 4, z + (r() - 0.5) * 4, s * 0.6);
+ }
+ bushAt(113, 43.5, 2.0); bushAt(100.5, 31.5, 1.3); bushAt(-12, 41, 2.6); bushAt(-14.5, 42.5, 1.5); bushAt(60, 52, 1.8);
+ bushAt(-33, 44.5, 2.2); bushAt(96, 44, 2.6); bushAt(138, 33.5, 1.4);
+ const merged = BGU.mergeGeometries(parts.map((g) => { if (!g.getAttribute('normal')) g.computeVertexNormals(); g.deleteAttribute('uv'); return g; }), false);
+ parts.forEach((g) => g.dispose());
+ const mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 1, metalness: 0, side: THREE.DoubleSide });
+ const far = new THREE.Mesh(merged, mat);
+ far.name = 'env-far';
+ far.frustumCulled = false;
+ scene.add(far);
+ farTris = merged.getAttribute('position').count / 3;
+ // ---- debris with real parallax near the film cameras (all outside the foot lines |z| < 30)
+ {
+ const props = [];
+ const put = (g, c, x, y, z, ry = 0, rx = 0, rz = 0) => { g.rotateZ(rz); g.rotateX(rx); g.rotateY(ry); g.translate(x, y, z); props.push(colorize(g, c)); };
+ const WOOD = [0.050, 0.041, 0.031], CONC = [0.115, 0.115, 0.11], RUST = [0.085, 0.040, 0.020], RUBBER = [0.013, 0.013, 0.014];
+ const plank = (x, z, ry, len = 2.4, tilt = 0.0, y = 0.03) => put(new THREE.BoxGeometry(len, 0.045, 0.17, 3, 1, 1), [WOOD[0] * (0.7 + 0.6 * r()), WOOD[1] * (0.7 + 0.6 * r()), WOOD[2] * (0.7 + 0.6 * r())], x, y, z, ry, 0.05 * (r() - 0.5), tilt);
+ const chunk = (x, z, sx, sy, sz, ry, tilt, rebar = 2) => {
+ const g = new THREE.BoxGeometry(sx, sy, sz, 3, 2, 3);
+ const p = g.getAttribute('position');
+ for (let i = 0; i < p.count; i++) { // knock the corners off
+ const px = p.getX(i), py = p.getY(i), pz = p.getZ(i);
+ const k = 1 - 0.3 * Math.abs(Math.sin(px * 5.1 + pz * 3.3 + py * 4.7 + sx * 9));
+ p.setXYZ(i, px * k, py * (0.85 + 0.3 * Math.abs(Math.sin(px * 3 + pz * 2.1))), pz * k);
+ }
+ g.computeVertexNormals();
+ put(g, [CONC[0] * (0.75 + 0.4 * r()), CONC[1] * (0.75 + 0.4 * r()), CONC[2] * (0.75 + 0.4 * r())], x, sy * 0.28, z, ry, tilt, tilt * 0.6);
+ for (let k = 0; k < rebar; k++) {
+ const a = ry + (r() - 0.5) * 1.2, bx = x + Math.cos(a) * sx * 0.45, bz = z - Math.sin(a) * sx * 0.45, L = 0.4 + r() * 0.6;
+ props.push(colorize(tube([[bx, sy * 0.35, bz], [bx + Math.cos(a) * L * 0.5, sy * 0.5 + L * 0.35, bz - Math.sin(a) * L * 0.5], [bx + Math.cos(a + 0.6) * L, sy * 0.4 + L * 0.3, bz - Math.sin(a + 0.6) * L]], 0.012, 0.012, 3), RUST));
+ }
+ };
+ const tyre = (x, z, tilt, ry, sink = 0.05) => put(new THREE.TorusGeometry(0.40, 0.155, 7, 16), RUBBER, x, 0.155 - sink, z, ry, Math.PI / 2 + tilt, 0);
+ const sign = (x, z, ry, lean) => {
+ const top = [x + Math.sin(lean) * 2.1, 2.1 * Math.cos(lean), z];
+ props.push(colorize(tube([[x, -0.2, z], [x + Math.sin(lean) * 0.8, 0.95, z], top], 0.03, 0.028, 5), [0.07, 0.065, 0.06]));
+ put(new THREE.BoxGeometry(0.62, 0.62, 0.012), [0.20, 0.19, 0.17], top[0], top[1] - 0.25, top[2] + 0.04, ry, 0.12, lean * 0.8 + 0.5);
+ put(new THREE.BoxGeometry(0.5, 0.16, 0.014), [0.035, 0.05, 0.085], top[0] - 0.05, top[1] - 0.72, top[2] + 0.045, ry, 0.1, lean * 0.8 - 0.15);
+ };
+ const pipe = (x, z, ry, rad = 0.62, len = 1.3) => {
+ put(new THREE.CylinderGeometry(rad, rad, len, 14, 1, true), CONC, x, rad * 0.72, z, ry, 0, Math.PI / 2);
+ put(new THREE.CylinderGeometry(rad * 0.76, rad * 0.76, len, 14, 1, true), [0.03, 0.03, 0.03], x, rad * 0.72, z, ry, 0, Math.PI / 2);
+ for (const s of [-1, 1]) { const g = new THREE.RingGeometry(rad * 0.76, rad, 14); g.rotateY(Math.PI / 2); g.translate(s * len / 2, 0, 0); put(g, [CONC[0] * 0.8, CONC[1] * 0.8, CONC[2] * 0.8], x, rad * 0.72, z, ry); }
+ };
+ // f_puddle / f_open cluster around the hero puddle (132.6, 36.8)
+ tyre(125.1, 39.4, 0.18, 0.4, 0.07);
+ plank(130.6, 41.2, 0.9, 2.6, 0.04); plank(131.3, 40.6, 0.35, 1.7, -0.05, 0.05); plank(127.4, 31.6, 2.3, 2.2);
+ chunk(134.9, 30.6, 1.3, 0.55, 0.8, 0.5, 0.22, 3); chunk(136.4, 31.5, 0.5, 0.3, 0.4, 1.9, 0.3, 1);
+ sign(134.8, 50.6, 0.5, 0.33);
+ chunk(141.5, 39.5, 0.7, 0.35, 0.5, 1.1, 0.25, 1);
+ // f_foot foreground
+ chunk(80.9, 32.4, 0.9, 0.42, 0.6, 0.8, 0.28, 2); plank(84.2, 30.6, 1.9, 2.0, 0.06); tyre(78.2, 34.6, 0.5, 1.2, 0.02);
+ // f_hero / ref2 mid-ground
+ pipe(-24.6, 39.6, 0.7); chunk(-27.5, 41.5, 1.1, 0.5, 0.7, 2.2, 0.2, 2); plank(-40.5, 51.2, 0.4, 2.8, 0.03);
+ tyre(-58.5, 49.5, 0.1, 2.0); chunk(-62.0, 46.5, 0.8, 0.4, 0.55, 0.3, 0.3, 2);
+ // ref6 / ref1 / scattered along the road and the far side
+ plank(71.5, 41.5, 1.2, 2.2); tyre(61.5, 43.5, 0.3, 0.7, 0.06); chunk(64.0, 45.5, 0.9, 0.4, 0.6, 1.4, 0.25, 2);
+ chunk(-36.5, 33.5, 0.8, 0.4, 0.6, 0.6, 0.3, 2); plank(-44.0, 34.5, 2.6, 2.4);
+ for (let k = 0; k < 26; k++) {
+ const x = -120 + r() * 460, z = (r() < 0.5 ? -1 : 1) * (30.5 + r() * 26), t = r();
+ if (Math.hypot(x - 150, z - 50) < 6 || Math.hypot(x - 136, z - 43.8) < 5 || Math.hypot(x - 86, z - 34) < 3 || Math.hypot(x - 75.8, z - 44) < 5
+ || (z > 44 && x > -62 && x < -14) || (z < -29 && x > 20 && x < 40)) continue;
+ if (t < 0.4) chunk(x, z, 0.5 + r() * 0.9, 0.25 + r() * 0.3, 0.4 + r() * 0.5, r() * 6.3, 0.15 + r() * 0.25, r() < 0.5 ? 2 : 0);
+ else if (t < 0.75) plank(x, z, r() * 6.3, 1.4 + r() * 1.6, (r() - 0.5) * 0.1);
+ else if (t < 0.9) tyre(x, z, r() * 0.5, r() * 6.3, r() * 0.08);
+ else sign(x, z, r() * 6.3, 0.15 + r() * 0.4);
+ }
+ const pm = BGU.mergeGeometries(props.map((g) => { if (!g.getAttribute('normal')) g.computeVertexNormals(); g.deleteAttribute('uv'); return g; }), false);
+ props.forEach((g) => g.dispose());
+ const pmat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.6, metalness: 0, side: THREE.DoubleSide, envMapIntensity: 0.45 });
+ pmat.onBeforeCompile = (sh) => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', '#include <common>\nvarying vec3 vWP;')
+ .replace('#include <worldpos_vertex>', '#include <worldpos_vertex>\nvWP = (modelMatrix * vec4(transformed, 1.0)).xyz;');
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+varying vec3 vWP;
+float pH(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+float pN(vec3 x){ vec3 i = floor(x), f = fract(x); f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(mix(pH(i), pH(i + vec3(1, 0, 0)), f.x), mix(pH(i + vec3(0, 1, 0)), pH(i + vec3(1, 1, 0)), f.x), f.y),
+ mix(mix(pH(i + vec3(0, 0, 1)), pH(i + vec3(1, 0, 1)), f.x), mix(pH(i + vec3(0, 1, 1)), pH(i + vec3(1, 1, 1)), f.x), f.y), f.z); }
+float gPropN = 0.5;`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+{ // grime mottling, lichen and a mud skirt where the thing sits in the soil
+ gPropN = pN(vWP * 6.0) * 0.6 + pN(vWP * 21.0) * 0.4;
+ diffuseColor.rgb *= 0.5 + 1.0 * gPropN;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.030, 0.036, 0.016), smoothstep(0.66, 0.84, pN(vWP * 2.3 + 7.0)) * 0.22);
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.032, 0.025, 0.017), smoothstep(0.30, 0.02, vWP.y + (gPropN - 0.5) * 0.25) * 0.85);
+}`)
+ .replace('#include <roughnessmap_fragment>', '#include <roughnessmap_fragment>\nroughnessFactor = mix(0.38, 0.85, gPropN);');
+ };
+ const pmesh = new THREE.Mesh(pm, pmat);
+ pmesh.name = 'env-props';
+ pmesh.receiveShadow = true;
+ pmesh.frustumCulled = false;
+ scene.add(pmesh);
+ propTris = pm.getAttribute('position').count / 3;
+ }
+ }
+
+ // ================================================================ MIRROR PASS
+ const mCam = new THREE.PerspectiveCamera();
+ const _n = new THREE.Vector3(0, 1, 0), _rp = new THREE.Vector3(), _cp = new THREE.Vector3(), _rot = new THREE.Matrix4();
+ const _look = new THREE.Vector3(), _view = new THREE.Vector3(), _tgt = new THREE.Vector3(), _q = new THREE.Vector4();
+ const _plane = new THREE.Plane(), _clip = new THREE.Vector4();
+ const _clearC = new THREE.Color();
+ let noReflect = null;
+ let mirrorWanted = false;
+ ground.onBeforeRender = (rend, scn, camera) => {
+ gU.uMirrorOn.value = 0;
+ if (!mirrorWanted || camera.isOrthographicCamera || DBG === "nomirror") return;
+ _cp.setFromMatrixPosition(camera.matrixWorld);
+ if (_cp.y <= 0.02) return;
+ _rp.set(_cp.x, 0.0, _cp.z);
+ _view.subVectors(_rp, _cp).reflect(_n).negate().add(_rp);
+ _rot.extractRotation(camera.matrixWorld);
+ _look.set(0, 0, -1).applyMatrix4(_rot).add(_cp);
+ _tgt.subVectors(_rp, _look).reflect(_n).negate().add(_rp);
+ mCam.position.copy(_view);
+ mCam.up.set(0, 1, 0).applyMatrix4(_rot).reflect(_n);
+ mCam.lookAt(_tgt);
+ mCam.far = camera.far;
+ mCam.updateMatrixWorld();
+ // stretch the mirror frustum: keep the screen's x range, but map ndc y in [-K, Yt] (K > 1 = further
+ // below the frame = higher reflected elevation; Yt just above the mirrored horizon) onto the RT
+ const pm0 = mCam.projectionMatrix.copy(camera.projectionMatrix), e0 = pm0.elements;
+ const pitch = Math.asin(Math.max(-1, Math.min(1, -camera.matrixWorld.elements[9])));
+ const Tv = 1 / camera.projectionMatrix.elements[5];
+ const K = Math.min(4.0, Math.max(1.0, Math.tan(Math.min(pitch + 0.82, 1.45)) / Tv));
+ const Yt = Math.min(1.0, Math.max(-0.7, -Math.tan(pitch) / Tv + 0.3));
+ const sa = 2 / (Yt + K), sb = (K - Yt) / (Yt + K);
+ e0[5] *= sa; e0[9] = sa * e0[9] - sb;
+ const tm = gU.uMirrorMat.value;
+ tm.set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1);
+ tm.multiply(mCam.projectionMatrix).multiply(mCam.matrixWorldInverse);
+ // oblique near plane = water plane
+ _plane.setFromNormalAndCoplanarPoint(_n, _rp).applyMatrix4(mCam.matrixWorldInverse);
+ _clip.set(_plane.normal.x, _plane.normal.y, _plane.normal.z, _plane.constant);
+ const pm = mCam.projectionMatrix, e = pm.elements;
+ _q.x = (Math.sign(_clip.x) + e[8]) / e[0];
+ _q.y = (Math.sign(_clip.y) + e[9]) / e[5];
+ _q.z = -1.0;
+ _q.w = (1.0 + e[10]) / e[14];
+ _clip.multiplyScalar(2.0 / _clip.dot(_q));
+ e[2] = _clip.x; e[6] = _clip.y; e[10] = _clip.z + 1.0 - 0.003; e[14] = _clip.w;
+ mCam.projectionMatrixInverse.copy(pm).invert();
+
+ if (!noReflect) { noReflect = []; scn.traverse((o) => { if (o.userData && o.userData.noReflect) noReflect.push(o); }); }
+ const hidden = [ground, ...vegMeshes.filter((m) => !m.userData.inMirror), ...noReflect].filter((o) => o.visible);
+ hidden.forEach((o) => { o.visible = false; });
+ const prevRT = rend.getRenderTarget();
+ const prevAuto = rend.shadowMap.autoUpdate;
+ rend.getClearColor(_clearC); const prevA = rend.getClearAlpha();
+ rend.shadowMap.autoUpdate = false;
+ rend.setClearColor(0x000000, 0);
+ rend.setRenderTarget(mirrorRT);
+ rend.state.buffers.depth.setMask(true);
+ rend.clear();
+ rend.render(scn, mCam);
+ rend.setRenderTarget(prevRT);
+ rend.setClearColor(_clearC, prevA);
+ rend.shadowMap.autoUpdate = prevAuto;
+ hidden.forEach((o) => { o.visible = true; });
+ gU.uMirrorOn.value = 1;
+ };
+
+ if (DBG === 'stats') console.warn(`[env] tris: veg ${Math.round(vegTris)} far ${Math.round(farTris)} props ${Math.round(propTris)} total ${Math.round(vegTris + farTris + propTris + 2)}; build ${(performance.now() - T0).toFixed(0)} ms`);
+
+ // ================================================================ UPDATE
+ const fs = {};
+ const frustum = new THREE.Frustum(), _pm = new THREE.Matrix4(), _sph = new THREE.Sphere();
+ const pud = [];
+ const near = [];
+ const cyc = SPEED * GAIT.T;
+ return {
+ update(t, f) {
+ const cam = f.camera;
+ uTime.value = t;
+ uCam.value.copy(cam.position);
+ uWalker.value.set(f.pose.x, f.pose.y, f.pose.z);
+ uFacZ.value = cam.position.z >= f.pose.z ? 1 : -1;
+ const fx = -cam.matrixWorld.elements[8], fz = -cam.matrixWorld.elements[10], fl = Math.hypot(fx, fz) || 1;
+ for (const m of vegMeshes) m.userData.uCtr.value.set(cam.position.x + fx / fl * m.userData.ahead, cam.position.z + fz / fl * m.userData.ahead);
+ ground.position.set(Math.round(cam.position.x / 100) * 100, 0, Math.round(cam.position.z / 100) * 100);
+ // footprints: previous plants of every leg (closed form)
+ let n = 0;
+ near.length = 0;
+ for (let i = 0; i < NLEGS; i++) {
+ gait.footState(i, t, fs);
+ legU[i].set(fs.plantX, fs.z, fs.plantAge, fs.z > 0 ? 1 : -1);
+ for (let k = 0; k < PRINTS_PER_LEG; k++) {
+ const x = fs.plantX - k * cyc, age = fs.plantAge + k * GAIT.T;
+ // a foot only leaves its print once it has touched down (k=0 is always touched down)
+ prints[n++].set(x, fs.z, age, fs.z > 0 ? 1 : -1);
+ near.push(n - 1);
+ }
+ }
+ const cx = cam.position.x, cz = cam.position.z;
+ near.sort((a, b) => Math.hypot(prints[a].x - cx, prints[a].y - cz) - Math.hypot(prints[b].x - cx, prints[b].y - cz));
+ for (let k = 0; k < NPRINT_NEAR; k++) printsNear[k].copy(prints[near[k]]);
+ // mirror only when a puddle (or water-filled print) is actually in view
+ _pm.multiplyMatrices(cam.projectionMatrix, cam.matrixWorldInverse);
+ frustum.setFromProjectionMatrix(_pm);
+ mirrorWanted = false;
+ puddlesNear(cx, cz, 170, pud);
+ for (const p of pud) {
+ _sph.center.set(p.x, 0, p.z); _sph.radius = p.r;
+ if (Math.hypot(p.x - cx, p.z - cz) - p.r < 170 && frustum.intersectsSphere(_sph)) { mirrorWanted = true; break; }
+ }
+ if (!mirrorWanted) {
+ for (let k = 0; k < NPRINT; k++) {
+ const p = prints[k];
+ _sph.center.set(p.x, 0, p.y); _sph.radius = 5;
+ if (Math.hypot(p.x - cx, p.y - cz) < 60 && frustum.intersectsSphere(_sph)) { mirrorWanted = true; break; }
+ }
+ }
+ },
+ };
+}
+
+function CFG_RIDE(ctx) { return ctx.CFG.RIDE_H; }
diff --git a/src/mods/fx.js b/src/mods/fx.js
new file mode 100644
index 0000000..cf8a96c
--- /dev/null
+++ b/src/mods/fx.js
@@ -0,0 +1,472 @@
+// FX: stateless footfall effects + atmosphere. Every particle position is a closed-form function of
+// (per-instance seed, age), with ages / foot trajectories fed per frame as uniforms from gait.js.
+// - clods : lit low-poly mud lumps. kind 0 = ejected on touchdown, kind 1 = dropping off a lifted foot
+// - spray : tiny alpha-tested (opaque, depth-writing) mud/water droplets, same two kinds
+// - impactSheet: alpha-hashed (depth-writing) dirty spray sheet + fast low shock ring of mist on touchdown
+// - impactMist : soft blended mist rolling outward afterwards; wetter near puddles (puddlesNear from env.js)
+// - wisps : slow drifting low mist sprites, world-stable, very subtle
+// - drizzle : faint falling streaks around the camera catching light
+// - birds : a tiny far flock (opaque, fogged by post)
+import * as BGU from 'three/addons/utils/BufferGeometryUtils.js';
+import { puddlesNear } from './env.js'; // read-only: puddle placement rule
+
+export async function create(ctx) {
+ const { THREE, scene, gait, LOOK, rng } = ctx;
+ const { GAIT, NLEGS } = gait;
+ const T = GAIT.T, SWING = (1 - GAIT.duty) * T;
+ const NS = 8, DS = 0.2; // foot trajectory samples after lift-off
+
+ const uTime = { value: 0 };
+ const uPlant = { value: Array.from({ length: NLEGS }, () => new THREE.Vector4(0, 0, 99, 0)) };
+ const uLiftAge = { value: new Array(NLEGS).fill(99) };
+ const uFoot = { value: Array.from({ length: NLEGS * NS }, () => new THREE.Vector3()) };
+ const uCam = { value: new THREE.Vector3() };
+ const uWet = { value: new Array(NLEGS).fill(0.25) }; // how watery the ground is where each foot last planted
+ const uJit = { value: new THREE.Vector2() };
+ const uCtr = { value: new THREE.Vector2() };
+ const uFog = { value: LOOK.fogColor };
+ const amb = LOOK.hemiSky.clone().multiplyScalar(LOOK.hemiIntensity * 0.55);
+ const uAmb = { value: amb };
+
+ const DYN = /* glsl */`
+uniform vec4 uPlant[${NLEGS}]; // plant x, z, age since touchdown
+uniform float uLiftAge[${NLEGS}]; // seconds since last lift-off
+uniform vec3 uFoot[${NLEGS * NS}]; // sole centre at liftoff + k*${DS}
+uniform float uTime; uniform vec3 uCam; uniform float uWet[${NLEGS}];
+const float G = 9.81;
+vec3 footAt(int leg, float td, out vec3 vel){
+ float f = clamp(td / ${DS.toFixed(2)}, 0.0, ${(NS - 1.001).toFixed(3)});
+ int k = int(floor(f));
+ vec3 a = uFoot[leg * ${NS} + k], b = uFoot[leg * ${NS} + k + 1];
+ vel = (b - a) / ${DS.toFixed(2)};
+ return mix(a, b, fract(f));
+}
+// r: 4 uniform randoms. Returns world position; scale (0 = hidden); vel; age since emission
+vec3 particle(int leg, float kind, vec4 r, float speedMul, out float scale, out vec3 vel, out float age){
+ scale = 1.0;
+ vec3 p0, v0;
+ if (kind < 0.5) {
+ // touchdown burst from the rim of the sole
+ vec4 pl = uPlant[leg];
+ age = pl.z - r.w * 0.06;
+ float ang = r.x * 6.28318;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ float rad = 2.9 + 0.6 * r.y;
+ // a third of the debris squirts out at the claw tips
+ if (r.w > 0.66) { float kk = floor(r.x * 4.0); vec2 cd = kk < 1.0 ? vec2(0.0, 1.0) : kk < 2.0 ? vec2(0.891, 0.454) : kk < 3.0 ? vec2(-0.891, 0.454) : vec2(0.0, -1.0);
+ cd.y *= sign(pl.y); dir = normalize(cd + (vec2(r.y, r.z) - 0.5) * 0.6); rad = 5.0 + 0.4 * r.y; }
+ p0 = vec3(pl.x + dir.x * rad, 0.1 + 0.3 * r.z, pl.y + dir.y * rad);
+ float wk = 1.0 + 0.35 * uWet[leg];
+ float up = mix(1.6, 10.5, r.z * r.z * r.z) * speedMul * wk;
+ float out_ = mix(2.5, 10.5, r.y) * speedMul * wk;
+ v0 = vec3(dir.x * out_, up, dir.y * out_);
+ } else {
+ // dirt / clods dropping off a lifted foot
+ float td = 1.3 * r.w * r.w;
+ vec3 fv;
+ vec3 fp = footAt(leg, td, fv);
+ age = uLiftAge[leg] - td;
+ float ang = r.x * 6.28318, rad = 3.2 * sqrt(r.y);
+ p0 = fp + vec3(cos(ang) * rad * 1.1, -0.05 - 0.2 * r.z, sin(ang) * rad * 0.85);
+ v0 = fv * 0.55 + vec3(cos(ang), -0.5, sin(ang)) * (0.4 + 0.8 * r.z) * speedMul;
+ }
+ if (age < 0.0) { scale = 0.0; vel = vec3(0.0); return p0; }
+ // air drag on horizontal motion
+ float k = 1.2;
+ float e = (1.0 - exp(-k * age)) / k;
+ float tl = (v0.y + sqrt(max(v0.y * v0.y + 2.0 * G * p0.y, 0.0))) / G; // landing time
+ float ta = min(age, tl);
+ float ea = (1.0 - exp(-k * ta)) / k;
+ vec3 p = vec3(p0.x + v0.x * ea, p0.y + v0.y * ta - 0.5 * G * ta * ta, p0.z + v0.z * ea);
+ vel = vec3(v0.x * exp(-k * ta), v0.y - G * ta, v0.z * exp(-k * ta));
+ if (age > tl) { p.y = -0.02; vel = vec3(0.0); scale *= 1.0 - smoothstep(0.3, 2.2, age - tl); }
+ scale *= 1.0 - smoothstep(3.6, 4.2, age);
+ scale *= smoothstep(1.6, 3.6, distance(p, uCam)); // keep debris out of the lens
+ return p;
+}
+mat3 rotAxis(vec3 a, float ang){
+ float s = sin(ang), c = cos(ang), oc = 1.0 - c;
+ return mat3(oc*a.x*a.x + c, oc*a.x*a.y + a.z*s, oc*a.z*a.x - a.y*s,
+ oc*a.x*a.y - a.z*s, oc*a.y*a.y + c, oc*a.y*a.z + a.x*s,
+ oc*a.z*a.x + a.y*s, oc*a.y*a.z - a.x*s, oc*a.z*a.z + c);
+}
+`;
+
+ // per-instance seeds: leg, kind, 4 randoms
+ function seedGeo(base, nPerLegKind) {
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = base.index;
+ for (const k in base.attributes) ig.setAttribute(k, base.attributes[k]);
+ const counts = nPerLegKind; // [kind0, kind1]
+ const n = NLEGS * (counts[0] + counts[1]);
+ const leg = new Float32Array(n), kind = new Float32Array(n), rnd = new Float32Array(n * 4);
+ const r = rng(base.uuid.length * 31 + counts[0] * 7 + counts[1]);
+ let j = 0;
+ for (let l = 0; l < NLEGS; l++) for (let kd = 0; kd < 2; kd++) for (let c = 0; c < counts[kd]; c++) {
+ leg[j] = l; kind[j] = kd;
+ for (let q = 0; q < 4; q++) rnd[j * 4 + q] = r();
+ j++;
+ }
+ ig.setAttribute('aLeg', new THREE.InstancedBufferAttribute(leg, 1));
+ ig.setAttribute('aKind', new THREE.InstancedBufferAttribute(kind, 1));
+ ig.setAttribute('aRnd', new THREE.InstancedBufferAttribute(rnd, 4));
+ ig.instanceCount = n;
+ return ig;
+ }
+ const commonU = { uTime, uPlant, uLiftAge, uFoot, uCam, uWet };
+ const meshes = [];
+ const addMesh = (m, name) => { m.frustumCulled = false; m.name = 'fx-' + name; scene.add(m); meshes.push(m); return m; };
+
+ // ---------------------------------------------------------------- clods (lit)
+ {
+ let base = new THREE.IcosahedronGeometry(1, 0);
+ base.deleteAttribute('uv'); base.deleteAttribute('normal');
+ base = BGU.mergeVertices(base);
+ const p = base.getAttribute('position'), r = rng(12);
+ for (let i = 0; i < p.count; i++) p.setXYZ(i, p.getX(i) * (0.7 + 0.6 * r()), p.getY(i) * (0.35 + 0.4 * r()), p.getZ(i) * (0.7 + 0.6 * r()));
+ base.computeVertexNormals();
+ const geo = seedGeo(base, [190, 60]);
+ const mat = new THREE.MeshStandardMaterial({ color: 0x6a5a48, roughness: 0.42, metalness: 0 });
+ mat.onBeforeCompile = (sh) => {
+ Object.assign(sh.uniforms, commonU);
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', `#include <common>
+attribute float aLeg, aKind; attribute vec4 aRnd;
+${DYN}
+vec3 cPos; mat3 cRot; float cScale; varying vec3 vTint;`)
+ .replace('#include <beginnormal_vertex>', `
+{
+ float sc; vec3 vel; float age;
+ // mostly crumbs, a few fist-to-head sized lumps; the heavy ones are the slow, low ones
+ float big = aKind < 0.5 ? pow((1.0 - aRnd.y) * (1.0 - aRnd.z * aRnd.z), 2.5) : pow(aRnd.z * aRnd.x, 2.0);
+ cPos = particle(int(aLeg), aKind, aRnd, 1.05 - 0.3 * big, sc, vel, age);
+ float size = mix(0.018, 0.13, big) * (0.7 + 0.6 * fract(aRnd.w * 13.7));
+ // wet earth, clay, and torn sod carrying grass
+ float tq = fract(aRnd.x * 29.3);
+ vTint = tq < 0.55 ? mix(vec3(0.55, 0.47, 0.40), vec3(0.95, 0.82, 0.68), fract(aRnd.y * 17.0)) : tq < 0.8 ? vec3(1.1, 1.0, 0.9) : vec3(0.55, 0.78, 0.36);
+ cScale = size * sc;
+ vec3 ax = normalize(vec3(aRnd.y - 0.5, aRnd.z - 0.5, aRnd.x - 0.5) + 1e-3);
+ cRot = rotAxis(ax, age * (3.0 + 6.0 * aRnd.w) * step(0.0, vel.y * vel.y - 1e-4) + aRnd.x * 6.0);
+}
+vec3 objectNormal = cRot * normal;`)
+ .replace('#include <begin_vertex>', `vec3 transformed = cPos + cRot * position * cScale;
+if (cScale < 1e-4) transformed = vec3(0.0, -60.0, 0.0);`);
+ sh.fragmentShader = sh.fragmentShader
+ .replace('#include <common>', `#include <common>
+varying vec3 vTint;`)
+ .replace('#include <color_fragment>', `#include <color_fragment>
+diffuseColor.rgb *= vTint;`);
+ };
+ const m = addMesh(new THREE.Mesh(geo, mat), 'clods');
+ m.castShadow = false; m.receiveShadow = true;
+ }
+
+ // ---------------------------------------------------------------- spray (opaque alpha-tested droplets / mud flecks)
+ {
+ const base = new THREE.PlaneGeometry(1, 1);
+ base.deleteAttribute('normal');
+ const geo = seedGeo(base, [900, 260]);
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { ...commonU, uAmb, uFog, uJit },
+ vertexShader: `
+attribute float aLeg, aKind; attribute vec4 aRnd;
+${DYN}
+varying vec2 vUv; varying float vWet; varying float vKeep;
+void main(){
+ float sc; vec3 vel; float age;
+ int leg = int(aLeg);
+ vec3 p = particle(leg, aKind, aRnd, 1.3, sc, vel, age);
+ float size = mix(0.012, 0.055, aRnd.z * aRnd.z) * sc;
+ vec4 mv = viewMatrix * vec4(p, 1.0);
+ // never thinner than ~1 px (thin out by hashing instead), motion streak along view-space velocity
+ float pxs = -mv.z * 0.0011;
+ float s2 = max(size, pxs);
+ vKeep = size * size / (s2 * s2);
+ vec3 vv = (viewMatrix * vec4(vel, 0.0)).xyz;
+ vec2 sv = vv.xy; float sl = length(sv);
+ vec2 ax = sl > 1e-3 ? sv / sl : vec2(0.0, 1.0);
+ vec2 corner = position.xy;
+ vec2 off = ax * corner.y * (s2 + sl * 0.016) + vec2(-ax.y, ax.x) * corner.x * s2;
+ mv.xy += off;
+ // water share grows with how wet the ground is where the foot landed (kind 1 = run-off from the lifted foot)
+ float wet = aKind < 0.5 ? uWet[leg] : 0.75;
+ vUv = position.xy + 0.5; vWet = step(1.0 - wet, fract(aRnd.x * 7.31));
+ gl_Position = projectionMatrix * mv;
+ if (size < 1e-4) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+uniform vec3 uAmb, uFog; uniform vec2 uJit;
+varying vec2 vUv; varying float vWet; varying float vKeep;
+float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+void main(){
+ vec2 q = vUv - 0.5;
+ if (dot(q, q) > 0.25) discard;
+ if (vKeep < 0.999 && h12(gl_FragCoord.xy + uJit) > vKeep) discard;
+ vec3 mud = vec3(0.060, 0.050, 0.040) * uAmb;
+ // water drops: neutral grey, lit by the sky (no blue cast)
+ vec3 drop = vec3(dot(uFog, vec3(0.3, 0.5, 0.2))) * 1.25 + vec3(0.02, 0.012, 0.004);
+ gl_FragColor = vec4(mix(mud, drop, vWet), 1.0);
+}`,
+ });
+ const m = addMesh(new THREE.Mesh(geo, mat), 'spray');
+ m.userData.noReflect = true;
+ }
+
+ // ---------------------------------------------------------------- impact: spray sheet + shock ring (hashed) and rolling mist (blended)
+ // The post fog replaces pixels without depth by sky, so blended sprites only show over geometry (that made
+ // wet metal look "painted"). The fast, dense parts are therefore alpha-HASHED and write depth: they are
+ // visible against the sky too, get fogged by distance, and the per-pixel hash reads as droplets.
+ {
+ const base = new THREE.PlaneGeometry(1, 1);
+ const mk = (PER, seed, hashed) => {
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = base.index; ig.setAttribute('position', base.getAttribute('position'));
+ const n = NLEGS * PER, leg = new Float32Array(n), rnd = new Float32Array(n * 4), r = rng(seed);
+ for (let i = 0; i < n; i++) { leg[i] = Math.floor(i / PER); for (let q = 0; q < 4; q++) rnd[i * 4 + q] = r(); }
+ ig.setAttribute('aLeg', new THREE.InstancedBufferAttribute(leg, 1));
+ ig.setAttribute('aRnd', new THREE.InstancedBufferAttribute(rnd, 4));
+ ig.instanceCount = n;
+ const mat = new THREE.ShaderMaterial({
+ defines: hashed ? { HASHED: 1 } : {},
+ uniforms: { uTime, uPlant, uFog, uCam, uWet, uJit },
+ transparent: !hashed, depthWrite: hashed,
+ vertexShader: `
+uniform vec4 uPlant[${NLEGS}]; uniform float uWet[${NLEGS}]; uniform float uTime; uniform vec3 uCam;
+attribute float aLeg; attribute vec4 aRnd;
+varying vec2 vUv; varying float vA; varying float vY; varying vec4 vR; varying float vDark;
+void main(){
+ int leg = int(aLeg);
+ vec4 pl = uPlant[leg];
+ float a = pl.z, wet = uWet[leg];
+ float ang = aRnd.x * 6.28318;
+ vec2 dir = vec2(cos(ang), sin(ang));
+ vec3 c; float w, h;
+#ifdef HASHED
+ if (aRnd.w < 0.42) {
+ // fast, low shock ring of mist racing outward along the ground
+ float R = 3.6 + (13.0 + 7.0 * aRnd.y) * (1.0 - exp(-a * 2.4));
+ c = vec3(pl.x + dir.x * R * 1.08, 0.35 + 0.35 * aRnd.z + 0.25 * a, pl.y + dir.y * R * 0.92);
+ w = 2.6 + 3.2 * a; h = 0.75 + 0.7 * a;
+ vA = smoothstep(0.0, 0.07, a) * (1.0 - smoothstep(0.2, 1.1, a)) * (0.4 + 0.3 * aRnd.z);
+ vDark = 0.3;
+ } else {
+ // dirty spray sheet thrown up around the pad: rises fast, hangs, rains back down
+ float v0 = (2.6 + 5.0 * aRnd.z * aRnd.z) * (1.0 + 0.45 * wet);
+ float t1 = max(a - 0.05 * aRnd.y, 0.0);
+ float up = v0 * (1.0 - exp(-t1 * 2.6)) / 2.6 - 1.1 * t1 * t1 * 0.5;
+ float R = 3.3 + 0.7 * aRnd.y + (1.5 + 3.5 * aRnd.y) * (1.0 - exp(-t1 * 1.8));
+ c = vec3(pl.x + dir.x * R * 1.08, 0.3 + max(up, 0.0), pl.y + dir.y * R * 0.92);
+ w = 1.2 + 1.6 * t1 + 0.8 * aRnd.w; h = 0.9 + 1.2 * t1 + 0.7 * aRnd.z;
+ vA = smoothstep(0.0, 0.06, a) * (1.0 - smoothstep(0.3, 1.35, a)) * (0.5 + 0.35 * aRnd.y) * (1.0 + 0.4 * wet);
+ vDark = 0.8 * (1.0 - 0.5 * wet) * exp(-a * 0.9); // muddy at first, clearing to mist
+ }
+#else
+ // slow rolling mist left behind by the impact (blended, only reads over the ground and the legs)
+ float R = 4.0 + (6.0 + 6.0 * aRnd.y) * (1.0 - exp(-a * 0.9));
+ c = vec3(pl.x + dir.x * R * 1.08, 0.5 + 0.7 * aRnd.z + a * 0.22, pl.y + dir.y * R * 0.92);
+ w = (3.2 + 2.6 * aRnd.w) * (0.9 + a * 0.45); h = w * 0.42;
+ vA = smoothstep(0.1, 0.8, a) * (1.0 - smoothstep(1.6, 4.8, a)) * (0.45 + 0.55 * aRnd.z) * 0.5;
+ vDark = 0.0;
+#endif
+ vec3 toCam = uCam - c;
+ vA *= smoothstep(3.0, 8.0, length(toCam));
+ vA *= 1.0 - 0.6 * smoothstep(0.08, 0.3, toCam.y / length(toCam)); // never foam discs from above
+ vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), toCam));
+ vec3 p = c + right * position.x * w + vec3(0.0, 1.0, 0.0) * position.y * h;
+ vUv = position.xy + 0.5; vY = p.y; vR = aRnd;
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
+ if (vA < 1e-3) gl_Position = vec4(0.0, 0.0, -2.0, 1.0);
+}`,
+ fragmentShader: `
+uniform vec3 uFog; uniform vec2 uJit;
+varying vec2 vUv; varying float vA; varying float vY; varying vec4 vR; varying float vDark;
+float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+float vn(vec2 x){ vec2 i = floor(x), f = fract(x); f = f*f*(3.0-2.0*f);
+ return mix(mix(h12(i), h12(i + vec2(1,0)), f.x), mix(h12(i + vec2(0,1)), h12(i + vec2(1,1)), f.x), f.y); }
+void main(){
+ vec2 q = vUv - 0.5;
+ float d = length(q) * 2.0;
+ float n = vn(vUv * vec2(4.0, 1.6) + vR.xy * 20.0) * 0.6 + vn(vUv * vec2(9.0, 3.5) + vR.zw * 20.0) * 0.4;
+ float a = smoothstep(1.0, 0.15, d) * smoothstep(0.22, 0.72, n) * vA * smoothstep(0.0, 0.5, vY);
+ // neutral grey mist (a blue tint made wet metal behind it look painted blue), slightly muddy when fresh
+ float fl = dot(uFog, vec3(0.3, 0.5, 0.2));
+ vec3 col = mix(uFog, vec3(fl), 0.8) * 1.12 + vec3(0.012);
+ col = mix(col, vec3(0.062, 0.054, 0.046), vDark * (0.6 + 0.4 * n));
+#ifdef HASHED
+ // steep alpha: mostly solid sheets with a droplet fringe instead of sparse static
+ if (smoothstep(0.05, 0.5, a) * 0.72 <= h12(gl_FragCoord.xy + uJit)) discard;
+ gl_FragColor = vec4(col * (0.72 + 0.3 * n), 1.0);
+#else
+ gl_FragColor = vec4(col, a);
+#endif
+}`,
+ });
+ return new THREE.Mesh(ig, mat);
+ };
+ const sheet = addMesh(mk(70, 91, true), 'impactSheet'); sheet.userData.noReflect = true;
+ const roll = addMesh(mk(30, 92, false), 'impactMist'); roll.renderOrder = 2; roll.userData.noReflect = true;
+ }
+
+ // ---------------------------------------------------------------- drifting low mist wisps (world-stable drift)
+ const WS = 180;
+ {
+ const N = 46, base = new THREE.PlaneGeometry(1, 1);
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = base.index; ig.setAttribute('position', base.getAttribute('position'));
+ const off = new Float32Array(N * 4), r = rng(303);
+ for (let i = 0; i < N; i++) { off[i * 4] = r() * WS; off[i * 4 + 1] = r() * WS; off[i * 4 + 2] = r(); off[i * 4 + 3] = r(); }
+ ig.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 4));
+ ig.instanceCount = N;
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uFog, uCam, uCtr },
+ transparent: true, depthWrite: false,
+ vertexShader: `
+uniform float uTime; uniform vec3 uCam; uniform vec2 uCtr;
+attribute vec4 aOff;
+varying vec2 vUv; varying float vA; varying vec3 vWP; varying vec2 vR;
+void main(){
+ vec2 drift = vec2(0.55, 0.18) * uTime;
+ vec2 rel = mod(aOff.xy + drift - uCtr + ${WS / 2}.0, ${WS}.0) - ${WS / 2}.0;
+ vec2 xz = uCtr + rel;
+ float edge = 1.0 - smoothstep(${(WS * 0.36).toFixed(1)}, ${(WS * 0.49).toFixed(1)}, max(abs(rel.x), abs(rel.y)));
+ vec3 c = vec3(xz.x, 0.6 + 1.6 * aOff.z, xz.y);
+ vec3 toCam = uCam - c;
+ float dist = length(toCam);
+ float w = 9.0 + 12.0 * aOff.w, h = 2.0 + 2.5 * aOff.z;
+ vA = edge * smoothstep(5.0, 18.0, dist) * (0.4 + 0.6 * aOff.w);
+ vec3 right = normalize(cross(vec3(0.0, 1.0, 0.0), toCam));
+ vec3 p = c + right * position.x * w + vec3(0.0, position.y * h, 0.0);
+ vUv = position.xy + 0.5; vWP = p; vR = aOff.zw;
+ gl_Position = projectionMatrix * viewMatrix * vec4(p, 1.0);
+}`,
+ fragmentShader: `
+uniform vec3 uFog; uniform float uTime;
+varying vec2 vUv; varying float vA; varying vec3 vWP; varying vec2 vR;
+float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * 0.1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+float vn(vec2 x){ vec2 i = floor(x), f = fract(x); f = f*f*(3.0-2.0*f);
+ return mix(mix(h12(i), h12(i + vec2(1,0)), f.x), mix(h12(i + vec2(0,1)), h12(i + vec2(1,1)), f.x), f.y); }
+void main(){
+ vec2 q = (vUv - 0.5) * 2.0;
+ float env = smoothstep(1.0, 0.1, length(q * vec2(1.0, 1.15)));
+ vec2 np = vUv * vec2(4.0, 1.6) + vR * 40.0 + vec2(uTime * 0.03, 0.0);
+ float n = vn(np) * 0.55 + vn(np * 2.1 + 3.0) * 0.3 + vn(np * 4.3 + 9.0) * 0.15;
+ float a = env * smoothstep(0.35, 0.8, n) * vA * smoothstep(0.0, 0.8, vWP.y);
+ gl_FragColor = vec4(uFog * 1.6, a * 0.11);
+}`,
+ });
+ const m = addMesh(new THREE.Mesh(ig, mat), 'wisps');
+ m.renderOrder = 1; m.userData.noReflect = true;
+ }
+
+ // ---------------------------------------------------------------- drizzle streaks / motes around the camera
+ const DS2 = 26;
+ {
+ const N = 1400, base = new THREE.PlaneGeometry(1, 1);
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.index = base.index; ig.setAttribute('position', base.getAttribute('position'));
+ const off = new Float32Array(N * 4), r = rng(505);
+ for (let i = 0; i < N; i++) { off[i * 4] = r() * DS2; off[i * 4 + 1] = r() * 14; off[i * 4 + 2] = r() * DS2; off[i * 4 + 3] = r(); }
+ ig.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 4));
+ ig.instanceCount = N;
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime, uCam, uCtr },
+ transparent: true, depthWrite: false, blending: THREE.AdditiveBlending,
+ vertexShader: `
+uniform float uTime; uniform vec3 uCam; uniform vec2 uCtr;
+attribute vec4 aOff;
+varying float vA; varying vec2 vUv;
+void main(){
+ bool mote = aOff.w < 0.25;
+ vec3 vel = mote ? vec3(0.25, -0.12 + 0.1 * sin(uTime * 0.7 + aOff.w * 30.0), 0.1) : vec3(0.6, -3.2 - 1.5 * aOff.w, 0.25);
+ vec3 p = aOff.xyz + vel * uTime;
+ vec3 c = vec3(uCtr.x, uCam.y - 3.0, uCtr.y);
+ vec3 rel = mod(p - c + vec3(${DS2 / 2}.0, 7.0, ${DS2 / 2}.0), vec3(${DS2}.0, 14.0, ${DS2}.0)) - vec3(${DS2 / 2}.0, 7.0, ${DS2 / 2}.0);
+ vec3 wp = c + rel;
+ vec3 toCam = uCam - wp; float dist = length(toCam);
+ float edge = 1.0 - smoothstep(${(DS2 * 0.36).toFixed(1)}, ${(DS2 * 0.49).toFixed(1)}, max(abs(rel.x), abs(rel.z)));
+ edge *= 1.0 - smoothstep(5.0, 7.0, abs(rel.y));
+ vA = edge * smoothstep(1.0, 3.0, dist) * (1.0 - smoothstep(10.0, 13.0, dist)) * step(0.0, wp.y);
+ vec3 dir = normalize(vel);
+ vec3 side = normalize(cross(dir, toCam));
+ float len = mote ? 0.012 : 0.22, wid = mote ? 0.012 : 0.0045;
+ vec3 pp = wp + dir * position.y * len + side * position.x * wid;
+ vUv = position.xy + 0.5;
+ vA *= mote ? 1.6 : 1.0;
+ gl_Position = projectionMatrix * viewMatrix * vec4(pp, 1.0);
+}`,
+ fragmentShader: `
+varying float vA; varying vec2 vUv;
+void main(){
+ float a = (1.0 - abs(vUv.x - 0.5) * 2.0) * sin(vUv.y * 3.14159) * vA;
+ gl_FragColor = vec4(vec3(0.10, 0.12, 0.17) * a, 1.0);
+}`,
+ });
+ const m = addMesh(new THREE.Mesh(ig, mat), 'drizzle');
+ m.renderOrder = 3; m.userData.noReflect = true;
+ }
+
+ // ---------------------------------------------------------------- far birds
+ {
+ // body + two wings, the wing tips flap in the shader (position.z marks tip vertices)
+ const P = [0, 0, 0.35, 0, 0, -0.3, -1, 0, 0, 0, 0, 0.35, 0, 0, -0.3, 1, 0, 0];
+ const base = new THREE.BufferGeometry();
+ base.setAttribute('position', new THREE.Float32BufferAttribute(P, 3));
+ const N = 14, ig = new THREE.InstancedBufferGeometry();
+ ig.setAttribute('position', base.getAttribute('position'));
+ const off = new Float32Array(N * 4), r = rng(808);
+ for (let i = 0; i < N; i++) { off[i * 4] = (r() - 0.5) * 30; off[i * 4 + 1] = (r() - 0.5) * 8; off[i * 4 + 2] = (r() - 0.5) * 30; off[i * 4 + 3] = r(); }
+ ig.setAttribute('aOff', new THREE.InstancedBufferAttribute(off, 4));
+ ig.instanceCount = N;
+ const mat = new THREE.ShaderMaterial({
+ uniforms: { uTime }, side: THREE.DoubleSide,
+ vertexShader: `
+uniform float uTime; attribute vec4 aOff;
+void main(){
+ float w = uTime * 0.075;
+ vec3 ctr = vec3(160.0 + 150.0 * cos(w), 58.0, -260.0 + 90.0 * sin(w));
+ vec3 fwd = normalize(vec3(-sin(w), 0.0, cos(w) * 0.6));
+ vec3 rt = normalize(cross(fwd, vec3(0.0, 1.0, 0.0)));
+ float flap = sin(uTime * (8.0 + 3.0 * aOff.w) + aOff.w * 40.0);
+ vec3 lp = position * 0.55;
+ lp.y += abs(position.x) * flap * 0.45;
+ vec3 wp = ctr + aOff.xyz + aOff.xyz * 0.15 * sin(uTime * 0.3 + aOff.w * 9.0) + rt * lp.x + vec3(0.0, lp.y, 0.0) + fwd * lp.z;
+ gl_Position = projectionMatrix * viewMatrix * vec4(wp, 1.0);
+}`,
+ fragmentShader: `void main(){ gl_FragColor = vec4(0.012, 0.014, 0.02, 1.0); }`,
+ });
+ addMesh(new THREE.Mesh(ig, mat), 'birds');
+ }
+
+ // ---------------------------------------------------------------- update
+ const fs = {}, fs2 = {}, pud = [];
+ return {
+ update(t, f) {
+ const cam = f.camera;
+ uTime.value = t;
+ uCam.value.copy(cam.position);
+ const fx = -cam.matrixWorld.elements[8], fz = -cam.matrixWorld.elements[10], fl = Math.hypot(fx, fz) || 1;
+ uCtr.value.set(cam.position.x + fx / fl * 6, cam.position.z + fz / fl * 6);
+ uJit.value.set(((t * 61.7) % 1) * 113.0, ((t * 37.3) % 1) * 71.0);
+ for (let i = 0; i < NLEGS; i++) {
+ gait.footState(i, t, fs);
+ uPlant.value[i].set(fs.plantX, fs.z, fs.plantAge, 0);
+ // the whole field is wet; landing in or beside a puddle makes a real splash
+ let wet = 0.25;
+ puddlesNear(fs.plantX, fs.z, 16, pud);
+ for (const pd of pud) {
+ const a = pd.r / 1.5, d = Math.hypot(pd.x - fs.plantX, pd.z - fs.z);
+ const k = Math.min(1, Math.max(0, (d - a * 0.8) / (a * 0.5 + 8)));
+ wet = Math.max(wet, 1 - k * k * (3 - 2 * k));
+ }
+ uWet.value[i] = wet;
+ const ageL = fs.swing > 0 ? fs.liftAge : fs.plantAge + SWING;
+ uLiftAge.value[i] = ageL;
+ const tl = t - ageL;
+ for (let k = 0; k < NS; k++) {
+ gait.footState(i, tl + k * DS + 1e-4, fs2);
+ uFoot.value[i * NS + k].set(fs2.x, Math.max(0.05, fs2.y - ctx.CFG.ANKLE_H + 0.1), fs2.z);
+ }
+ }
+ },
+ };
+}
diff --git a/src/mods/legs.js b/src/mods/legs.js
new file mode 100644
index 0000000..1a6cf08
--- /dev/null
+++ b/src/mods/legs.js
@@ -0,0 +1,1381 @@
+// Colossal mechanical walking legs (8x). Fully stateless: update(t) is a pure function of t.
+//
+// Kinematic chain per leg (all solved in walker-local space):
+// hip base (bolted to chassis, static) -> yoke (yaws about the vertical kingpin at L.hip)
+// -> thigh (pitches on the yoke trunnion, offset E outward from the kingpin)
+// -> shin (knee hinge, same horizontal axis) -> ball ankle -> foot (stays flat on the ground) -> 4 hinged toes
+// The leg always lies in the vertical plane through the kingpin axis and the ankle, so every joint is a
+// physically plausible single-axis hinge. Hydraulic cylinders are re-aimed between fixed anchors each frame.
+//
+// Rendering: every rigid part is one InstancedMesh per material (8 instances = 8 legs), so the whole set is
+// ~50 draw calls. The shared weathering shader is patched to use the pre-instance local position (+ a
+// per-instance offset) so grime does not swim while the instances animate.
+import * as THREE from 'three';
+import * as BGU from 'three/addons/utils/BufferGeometryUtils.js';
+
+const PI = Math.PI;
+const E_TRUN = 2.2; // trunnion offset from the kingpin axis (m)
+
+// ----------------------------------------------------------------------------------------------
+// geometry toolkit
+// ----------------------------------------------------------------------------------------------
+function xf(px = 0, py = 0, pz = 0, rx = 0, ry = 0, rz = 0, sx = 1, sy = sx, sz = sx) {
+ return new THREE.Matrix4().compose(new THREE.Vector3(px, py, pz),
+ new THREE.Quaternion().setFromEuler(new THREE.Euler(rx, ry, rz)), new THREE.Vector3(sx, sy, sz));
+}
+const MIRX = new THREE.Matrix4().makeScale(-1, 1, 1);
+const MIRZ = new THREE.Matrix4().makeScale(1, 1, -1);
+const IDENT = new THREE.Matrix4();
+
+function flipWinding(g) {
+ for (const name of Object.keys(g.attributes)) {
+ const a = g.attributes[name], n = a.itemSize, arr = a.array;
+ for (let i = 0; i < a.count; i += 3) {
+ for (let k = 0; k < n; k++) { const t = arr[(i + 1) * n + k]; arr[(i + 1) * n + k] = arr[(i + 2) * n + k]; arr[(i + 2) * n + k] = t; }
+ }
+ }
+}
+
+let _tintSeed = 1;
+const _tintRnd = () => { _tintSeed = (Math.imul(_tintSeed, 1664525) + 1013904223) >>> 0; return _tintSeed / 4294967296; };
+class Part {
+ constructor() { this.bins = new Map(); }
+ // aFx attribute: x = 1 on bevel/edge faces (edge wear), y = per-primitive paint tint
+ add(geo, key, m, tint) {
+ const g = geo.index ? geo.toNonIndexed() : geo.clone();
+ for (const n of Object.keys(g.attributes)) if (n !== 'position' && n !== 'normal' && n !== 'uv' && n !== 'aFx') g.deleteAttribute(n);
+ if (!g.attributes.normal) g.computeVertexNormals();
+ if (!g.attributes.uv) g.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(g.attributes.position.count * 2), 2));
+ if (!g.attributes.aFx) g.setAttribute('aFx', new THREE.BufferAttribute(new Float32Array(g.attributes.position.count * 2), 2));
+ { const a = g.attributes.aFx.array, tv = tint ?? (0.86 + 0.24 * _tintRnd()); for (let i = 1; i < a.length; i += 2) a[i] = tv; }
+ if (m) { g.applyMatrix4(m); if (m.determinant() < 0) flipWinding(g); }
+ if (!this.bins.has(key)) this.bins.set(key, []);
+ this.bins.get(key).push(g);
+ return this;
+ }
+ // add + mirrored copy across the X=0 plane
+ mirX(geo, key, m, tint) { const tv = tint ?? (0.86 + 0.24 * _tintRnd()); this.add(geo, key, m, tv); this.add(geo, key, MIRX.clone().multiply(m || IDENT), tv); return this; }
+ build() {
+ const out = {};
+ for (const [k, list] of this.bins) { out[k] = BGU.mergeGeometries(list, false); list.forEach((g) => g.dispose()); }
+ return out;
+ }
+}
+
+function fromTris(P, flatUV = true) {
+ const pos = new Float32Array(P.length * 3);
+ for (let i = 0; i < P.length; i++) { pos[i * 3] = P[i][0]; pos[i * 3 + 1] = P[i][1]; pos[i * 3 + 2] = P[i][2]; }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(pos, 3));
+ g.computeVertexNormals();
+ g.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(P.length * 2), 2));
+ return g;
+}
+
+// chamfered box (flat shaded, 44 tris) — bevels catch the wet sky reflections
+function cbox(w, h, d, c = 0.05) {
+ c = Math.min(c, w * 0.45, h * 0.45, d * 0.45);
+ const hx = w / 2, hy = h / 2, hz = d / 2, P = [];
+ const v = (sx, sy, sz, ax) => ax === 0 ? [sx * hx, sy * (hy - c), sz * (hz - c)] : ax === 1 ? [sx * (hx - c), sy * hy, sz * (hz - c)] : [sx * (hx - c), sy * (hy - c), sz * hz];
+ const tri = (a, b, cc) => {
+ const ux = b[0] - a[0], uy = b[1] - a[1], uz = b[2] - a[2], vx = cc[0] - a[0], vy = cc[1] - a[1], vz = cc[2] - a[2];
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
+ if (nx * (a[0] + b[0] + cc[0]) + ny * (a[1] + b[1] + cc[1]) + nz * (a[2] + b[2] + cc[2]) < 0) P.push(a, cc, b); else P.push(a, b, cc);
+ };
+ const quad = (a, b, cc, dd) => { tri(a, b, cc); tri(a, cc, dd); };
+ for (const s of [1, -1]) {
+ quad(v(s, 1, 1, 0), v(s, 1, -1, 0), v(s, -1, -1, 0), v(s, -1, 1, 0));
+ quad(v(1, s, 1, 1), v(1, s, -1, 1), v(-1, s, -1, 1), v(-1, s, 1, 1));
+ quad(v(1, 1, s, 2), v(1, -1, s, 2), v(-1, -1, s, 2), v(-1, 1, s, 2));
+ }
+ for (const sa of [1, -1]) for (const sb of [1, -1]) {
+ quad(v(sa, sb, 1, 0), v(sa, sb, -1, 0), v(sa, sb, -1, 1), v(sa, sb, 1, 1));
+ quad(v(sa, 1, sb, 0), v(sa, -1, sb, 0), v(sa, -1, sb, 2), v(sa, 1, sb, 2));
+ quad(v(1, sa, sb, 1), v(-1, sa, sb, 1), v(-1, sa, sb, 2), v(1, sa, sb, 2));
+ }
+ for (const sx of [1, -1]) for (const sy of [1, -1]) for (const sz of [1, -1]) tri(v(sx, sy, sz, 0), v(sx, sy, sz, 1), v(sx, sy, sz, 2));
+ const g = fromTris(P);
+ const fx = new Float32Array(P.length * 2);
+ for (let i = 36; i < P.length; i++) fx[i * 2] = 1; // everything after the 6 main faces is bevel
+ g.setAttribute('aFx', new THREE.BufferAttribute(fx, 2));
+ return g;
+}
+
+// Lathe about +Y with HARD profile edges and smooth circumference. Profile [[r,y],...] must run
+// counter-clockwise in the (r,y) half-plane (bottom-centre -> out -> up -> back to the axis).
+function lathe(prof, segs = 32, { a0 = 0, a1 = PI * 2, flat = false } = {}) {
+ const pos = [], nor = [];
+ const push = (A, B, C, nA, nB, nC) => {
+ const ux = B[0] - A[0], uy = B[1] - A[1], uz = B[2] - A[2], vx = C[0] - A[0], vy = C[1] - A[1], vz = C[2] - A[2];
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;
+ if (nx * nx + ny * ny + nz * nz < 1e-14) return;
+ if (nx * (nA[0] + nB[0] + nC[0]) + ny * (nA[1] + nB[1] + nC[1]) + nz * (nA[2] + nB[2] + nC[2]) < 0) { pos.push(...A, ...C, ...B); nor.push(...nA, ...nC, ...nB); }
+ else { pos.push(...A, ...B, ...C); nor.push(...nA, ...nB, ...nC); }
+ };
+ for (let i = 0; i < prof.length - 1; i++) {
+ const r0 = prof[i][0], y0 = prof[i][1], r1 = prof[i + 1][0], y1 = prof[i + 1][1];
+ let nr = y1 - y0, ny = -(r1 - r0); const l = Math.hypot(nr, ny); if (l < 1e-9) continue; nr /= l; ny /= l;
+ for (let j = 0; j < segs; j++) {
+ const t0 = a0 + (a1 - a0) * j / segs, t1 = a0 + (a1 - a0) * (j + 1) / segs;
+ const c0 = Math.cos(t0), s0 = Math.sin(t0), c1 = Math.cos(t1), s1 = Math.sin(t1);
+ const A = [r0 * s0, y0, r0 * c0], B = [r1 * s0, y1, r1 * c0], C = [r1 * s1, y1, r1 * c1], D = [r0 * s1, y0, r0 * c1];
+ const nA = [nr * s0, ny, nr * c0], nD = [nr * s1, ny, nr * c1];
+ push(A, B, C, nA, nA, nD); push(A, C, D, nA, nD, nD);
+ }
+ }
+ const g = new THREE.BufferGeometry();
+ g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(pos), 3));
+ if (flat) g.computeVertexNormals(); else g.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(nor), 3));
+ g.setAttribute('uv', new THREE.BufferAttribute(new Float32Array(pos.length / 3 * 2), 2));
+ return g;
+}
+const latheX = (prof, segs, o) => lathe(prof, segs, o).rotateZ(-PI / 2); // profile "y" becomes local +x
+const cyl = (r, len, segs = 20) => lathe([[0, -len / 2], [r, -len / 2], [r, len / 2], [0, len / 2]], segs);
+const cylX = (r, len, segs = 20) => cyl(r, len, segs).rotateZ(-PI / 2);
+const cylZ = (r, len, segs = 20) => cyl(r, len, segs).rotateX(PI / 2);
+
+const _boltCache = new Map();
+function bolt(r = 0.07, h = 0.07) {
+ const k = r + '_' + h;
+ if (!_boltCache.has(k)) _boltCache.set(k, lathe([[r, 0], [r, h], [0, h * 1.15]], 6, { flat: true }));
+ return _boltCache.get(k);
+}
+// n bolts on a circle of radius R in the XZ plane of frame m (bolt axis = frame +Y)
+function boltRing(P, key, n, R, m, r = 0.07, h = 0.07, a0 = 0, a1 = PI * 2) {
+ const full = Math.abs(a1 - a0 - PI * 2) < 1e-6;
+ for (let i = 0; i < n; i++) {
+ const a = a0 + (a1 - a0) * (full ? i / n : i / Math.max(1, n - 1));
+ P.add(bolt(r, h), key, m.clone().multiply(xf(Math.sin(a) * R, 0, Math.cos(a) * R)));
+ }
+}
+// row of bolts from p0 to p1 (frame m, bolt axis = frame +Y)
+function boltRow(P, key, n, p0, p1, m, r = 0.06, h = 0.06) {
+ for (let i = 0; i < n; i++) {
+ const k = n === 1 ? 0.5 : i / (n - 1);
+ P.add(bolt(r, h), key, m.clone().multiply(xf(p0[0] + (p1[0] - p0[0]) * k, p0[1] + (p1[1] - p0[1]) * k, p0[2] + (p1[2] - p0[2]) * k)));
+ }
+}
+
+function tube(pts, r, radial = 6, tubular = 0) {
+ const curve = new THREE.CatmullRomCurve3(pts.map((p) => new THREE.Vector3(p[0], p[1], p[2])), false, 'catmullrom', 0.5);
+ return new THREE.TubeGeometry(curve, tubular || Math.max(4, (pts.length - 1) * 6), r, radial, false);
+}
+
+const poly = (pts) => { const s = new THREE.Shape(); s.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) s.lineTo(pts[i][0], pts[i][1]); s.closePath(); return s; };
+function sector(ri, ro, a0, a1) {
+ const s = new THREE.Shape();
+ s.absarc(0, 0, ro, a0, a1, false);
+ s.absarc(0, 0, ri, a1, a0, true);
+ s.closePath();
+ return s;
+}
+// extrude a shape to total thickness `depth` (bevels included, outline preserved); spans z in [0, depth]
+function extr(shape, depth, bevel = 0.05, curveSegments = 12) {
+ const b = Math.min(bevel, depth * 0.45);
+ const g = new THREE.ExtrudeGeometry(shape, { depth: depth - 2 * b, bevelEnabled: b > 0, bevelThickness: b, bevelSize: b, bevelOffset: -b, bevelSegments: 1, curveSegments });
+ g.translate(0, 0, b);
+ if (b > 0) {
+ const p = g.attributes.position, fx = new Float32Array(p.count * 2);
+ for (let i = 0; i < p.count; i += 3) {
+ const ax = p.getX(i), ay = p.getY(i), az = p.getZ(i);
+ const ux = p.getX(i + 1) - ax, uy = p.getY(i + 1) - ay, uz = p.getZ(i + 1) - az, vx = p.getX(i + 2) - ax, vy = p.getY(i + 2) - ay, vz = p.getZ(i + 2) - az;
+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx, l = Math.hypot(nx, ny, nz) || 1;
+ const k = Math.abs(nz) / l;
+ if (k > 0.15 && k < 0.97) { fx[i * 2] = fx[i * 2 + 2] = fx[i * 2 + 4] = 1; }
+ }
+ g.setAttribute('aFx', new THREE.BufferAttribute(fx, 2));
+ }
+ return g;
+}
+// shape drawn as (X = local z, Y = local y), extruded along local x from x0 to x1
+const extrYZ = (shape, x0, x1, bevel, cs) => extr(shape, x1 - x0, bevel, cs).rotateY(-PI / 2).translate(x1, 0, 0);
+// shape drawn as (X = local x, Y = local z), slab with top at yTop
+const extrXZ = (shape, yTop, thick, bevel, cs) => extr(shape, thick, bevel, cs).rotateX(PI / 2).translate(0, yTop, 0);
+// shape drawn as (X = local x, Y = local y), from z0 to z1
+const extrXY = (shape, z0, z1, bevel, cs) => extr(shape, z1 - z0, bevel, cs).translate(0, 0, z0);
+
+// hex nut / fitting about +Y, base at y = 0
+const hex = (r, h) => lathe([[0, 0], [r, 0], [r, h], [0, h]], 6, { flat: true });
+// pleated rubber gaiter about +Y
+function bellows(r0, r1, y0, y1, n, segs = 16) {
+ const prof = [];
+ for (let i = 0; i <= n * 2; i++) prof.push([i % 2 ? r1 : r0, y0 + (y1 - y0) * i / (n * 2)]);
+ return lathe(prof, segs);
+}
+// lumpy clod (caked mud), flat-ish bottom
+function lump(sx, sy, sz, seed, detail = 1) {
+ let g = new THREE.IcosahedronGeometry(1, detail);
+ g.deleteAttribute('normal'); g.deleteAttribute('uv');
+ g = BGU.mergeVertices(g, 1e-4);
+ const p = g.attributes.position, s = seed * 1.37;
+ for (let i = 0; i < p.count; i++) {
+ const x = p.getX(i), y = p.getY(i), z = p.getZ(i);
+ const k = 1 + 0.22 * Math.sin(x * 3.1 + s) * Math.sin(y * 2.7 + s * 1.3) + 0.2 * Math.sin(z * 3.7 + s * 0.7 + x * 2.1) + 0.1 * Math.sin((x + y + z) * 7.3 + s);
+ p.setXYZ(i, x * k * sx, Math.max(-0.3, y * k) * sy, z * k * sz);
+ }
+ g.computeVertexNormals();
+ return g;
+}
+
+const linspace = (a, b, n) => Array.from({ length: n }, (_, i) => (n === 1 ? (a + b) / 2 : a + (b - a) * i / (n - 1)));
+
+// ----------------------------------------------------------------------------------------------
+export async function create(ctx) {
+ const { walker, CFG, gait, Mats, weathered, TEX, rng } = ctx;
+ const tBuild0 = performance.now();
+ const g = new THREE.Group(); g.name = 'legs';
+ walker.add(g);
+ const N = gait.NLEGS, LT = CFG.THIGH, LS = CFG.SHIN;
+ const rnd = rng(4242);
+
+ // ---------------------------------------------------------------- materials
+ const MUD_F = /* glsl */`
+ {
+ float mn = texture2D(uWDetail, vWp.xz * 0.21).b * 0.6 + texture2D(uWDetail, vWp.xy * 0.83).r * 0.4;
+ float mud = (1.0 - smoothstep(uMud.x, uMud.y, vMudY + (mn - 0.5) * (uMud.y - uMud.x) * 1.1)) * uMud.z;
+ mud *= 0.6 + 0.4 * mn;
+ // flung splatter: reaches well above the caked band, thinning with height
+ float sn = texture2D(uWDetail, vWp.xy * 1.7 + vWp.zz * vec2(1.3, 0.9)).g * 0.6 + texture2D(uWDetail, vWp.zy * 0.47 + vWp.xx * 0.61).a * 0.5;
+ float sph = 1.0 - smoothstep(uMud.x, uMud.y + (uMud.y - uMud.x) * 0.9, vMudY);
+ float spl = smoothstep(0.86 - 0.30 * sph, 0.90 - 0.28 * sph, sn) * uMud.z * step(0.001, sph);
+ mud = max(mud, spl * 0.9);
+ // worn bright steel (claw tips / leading edges) stays clear of mud
+ float wn = texture2D(uWDetail, vWp.zy * 0.9 + vWp.x * 0.4).g;
+ float wb = texture2D(uWDetail, vWp.zy * 0.13 + vWp.x * 0.21).b;
+ float wear = clamp(smoothstep(uWear.x, uWear.y, vLp.z + (wn - 0.5) * 0.9) + vFx.x * smoothstep(0.3, 0.6, wn) * 0.9 + smoothstep(0.5, 0.75, wb + wn * 0.3) * 0.55, 0.0, 1.0) * uWear.z;
+ mud *= 1.0 - 0.8 * wear;
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.34, 0.335, 0.32) * (0.6 + 0.8 * wn), wear * 0.75);
+ roughnessFactor = mix(roughnessFactor, 0.3 + 0.25 * wn, wear);
+ metalnessFactor = mix(metalnessFactor, 0.95, wear);
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.050, 0.043, 0.032) * (0.55 + 0.9 * mn), mud);
+ roughnessFactor = mix(roughnessFactor, 0.30 + 0.6 * mn, mud);
+ metalnessFactor *= 1.0 - mud;
+ lpH += mud * mn * 0.012;
+ }`;
+ // plate-detail layer: panel seams, rivets, hatches, welds, stencil remnants, dents, rust drips, oily runoff.
+ // Dominant-axis projection of a tileable atlas in mesh-local space (free per frame, never swims).
+ const PLATE_F = /* glsl */`
+ {
+ vec3 an = abs(vWn);
+ float isX = step(max(an.y, an.z), an.x), isZ = (1.0 - isX) * step(an.y, an.z);
+ float sgx = vWn.x < 0.0 ? -1.0 : 1.0, sgz = vWn.z < 0.0 ? -1.0 : 1.0;
+ vec2 pX = mix(vec2(-vWp.z * sgx, vWp.y), vec2(vWp.y * sgx, vWp.z), uPlate.w);
+ vec2 puv = isX * pX + isZ * vec2(vWp.x * sgz, vWp.y) + (1.0 - isX - isZ) * vWp.xz;
+ vec4 pl = texture2D(uPlateTex, puv * ${(1 / 6.4).toFixed(6)});
+ float pk = uPlate.x * (1.0 - vFx.x);
+ float pn = texture2D(uWDetail, puv * 0.83).a;
+ diffuseColor.rgb *= mix(1.0, 0.36 + 1.42 * pl.r, pk);
+ float oil = pl.a * pk;
+ diffuseColor.rgb *= 1.0 - 0.6 * oil;
+ wWetA = max(wWetA, oil * 0.8);
+ float pr = smoothstep(0.22, 0.6, pl.b * (0.45 + 1.1 * pn)) * pk;
+ diffuseColor.rgb = mix(diffuseColor.rgb, mix(vec3(0.03, 0.017, 0.01), vec3(0.11, 0.057, 0.03), pn), pr);
+ wRustA = max(wRustA, pr * 0.85);
+ lpH += (pl.g - 0.5) * uPlate.y * pk;
+ float pit = smoothstep(0.40, 0.16, texture2D(uWDetail, puv * 2.1 + 0.3).r) * uPlate.z;
+ diffuseColor.rgb *= 1.0 - 0.5 * pit; lpH -= pit * 0.003;
+ }`;
+ // grease / oil thrown out of the hinge joints (axis = local X) and running down-gravity (uGrDir, in local YZ)
+ const GREASE_F = /* glsl */`
+ {
+ vec2 gp = vec2(-uGrDir.y, uGrDir.x);
+ float sd = (vWp.x - vLp.x) * 0.37;
+ vec2 d0 = vLp.yz - uGr0.xy; float al0 = dot(d0, uGrDir), ac0 = dot(d0, gp);
+ vec2 d1 = vLp.yz - uGr1.xy; float al1 = dot(d1, uGrDir), ac1 = dot(d1, gp);
+ float n0 = texture2D(uWDetail, vec2(ac0 * 0.9 + vLp.x * 0.33 + sd, al0 * 0.04)).b * 0.65 + texture2D(uWDetail, vec2(ac0 * 2.7 + vLp.x * 0.9, al0 * 0.11 + sd)).a * 0.45;
+ float n1 = texture2D(uWDetail, vec2(ac1 * 0.9 + vLp.x * 0.33 + sd + 0.5, al1 * 0.04)).b * 0.65 + texture2D(uWDetail, vec2(ac1 * 2.7 + vLp.x * 0.9, al1 * 0.11 + sd)).a * 0.45;
+ float m0 = smoothstep(uGr0.z * 1.15, uGr0.z * 0.4, abs(ac0)) * smoothstep(-uGr0.z * 0.6, uGr0.z * 0.5, al0) * (1.0 - smoothstep(uGr0.z, uGr0.z * 3.0, al0));
+ float m1 = smoothstep(uGr1.z * 1.15, uGr1.z * 0.4, abs(ac1)) * smoothstep(-uGr1.z * 0.6, uGr1.z * 0.5, al1) * (1.0 - smoothstep(uGr1.z, uGr1.z * 3.0, al1));
+ float gr = max(uGr0.w * m0 * smoothstep(0.50, 0.68, n0 + m0 * 0.22), uGr1.w * m1 * smoothstep(0.50, 0.68, n1 + m1 * 0.22));
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(0.016, 0.012, 0.008), gr * 0.9);
+ wWetA = max(wWetA, gr); wRustA *= 1.0 - gr;
+ // rust never orange: clamp to dark brown
+ diffuseColor.rgb = mix(diffuseColor.rgb, min(diffuseColor.rgb, vec3(0.115, 0.062, 0.036)), smoothstep(0.1, 0.6, wRustA));
+ }`;
+ // make a (weathered) material safe for animated InstancedMesh + optional mud gradient / decal atlas
+ const EDGE_F = /* glsl */`
+ {
+ float en = texture2D(uWDetail, vWp.xy * 0.71 + vWp.z * 0.37).g * 0.6 + texture2D(uWDetail, vWp.zx * 0.23 + vWp.y * 0.19).a * 0.6;
+ float edge = vFx.x * smoothstep(0.34, 0.62, en) * uEdge;
+ vec3 bare = mix(vec3(0.13, 0.135, 0.14), vec3(0.20, 0.095, 0.042), smoothstep(0.35, 0.75, texture2D(uWDetail, vWp.zy * 0.31 + vWp.x * 0.3).r));
+ diffuseColor.rgb = mix(diffuseColor.rgb, bare, edge * 0.9);
+ wRustA = max(wRustA, edge * 0.55);
+ if (uRust2.x > 0.0) {
+ vec2 ruv = vWp.xy * 0.85 + vWp.z * vec2(0.53, 0.47);
+ float rmask = texture2D(uWDetail, ruv * 0.11 + 0.3).b * 0.7 + texture2D(uWDetail, ruv * 0.37).a * 0.45;
+ #define LEG_FINE(q) (texture2D(uWDetail, q).g * 0.62 + texture2D(uWDetail, (q) * 2.3 + 0.17).a * 0.5)
+ float gate = 0.36 + 1.02 * rmask;
+ float r2 = smoothstep(0.735, 0.85, LEG_FINE(ruv) * gate) * uRust2.x;
+ float tr = max(smoothstep(0.70, 0.83, LEG_FINE(ruv + vec2(0.0, 0.22)) * gate) * 0.6, smoothstep(0.70, 0.83, LEG_FINE(ruv + vec2(0.0, 0.5)) * gate) * 0.32) * uRust2.y;
+ vec3 rc = mix(vec3(0.05, 0.026, 0.015), vec3(0.15, 0.078, 0.04), texture2D(uWDetail, ruv * 3.1).r);
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * vec3(0.78, 0.52, 0.33), tr * (1.0 - r2));
+ diffuseColor.rgb = mix(diffuseColor.rgb, rc, r2);
+ wRustA = max(wRustA, r2);
+ }
+ }`;
+ // plate: [strength, bump height (m), pitting, swap (1 = gravity runs along local -Z on the X faces)]
+ // wear: [z0, z1, strength] (mud variants only) ; grease: { a:[cy,cz,R,k], b:[cy,cz,R,k], dir:[gy,gz] }
+ function patch(mat, { mud = null, atlas = 0, edge = 0, rust2 = [0, 0], plate = [0, 0, 0, 0], wear = [0, 1, 0], grease = null } = {}) {
+ const prev = mat.onBeforeCompile;
+ const isW = !!mat.userData.weather;
+ mat.onBeforeCompile = (shader, r) => {
+ if (prev) prev(shader, r);
+ let vs = shader.vertexShader;
+ if (isW) {
+ const a = 'wP_ = instanceMatrix * wP_;', b = 'wN_ = mat3(instanceMatrix) * wN_;';
+ if (vs.includes(a)) vs = vs.replace(a, 'wP_.xyz += vec3(float(gl_InstanceID)) * vec3(17.3, 9.1, 13.7);').replace(b, '');
+ else console.warn('[legs] weathering instancing patch not applied (materials.js changed?)');
+ vs = vs.replace('#include <common>', '#include <common>\nattribute vec2 aFx; varying vec2 vFx; varying vec3 vLp;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvFx = aFx; vLp = position;');
+ const G = grease || { a: [0, 0, 1, 0], b: [0, 0, 1, 0], dir: [-1, 0] };
+ shader.uniforms.uEdge = { value: edge };
+ shader.uniforms.uRust2 = { value: new THREE.Vector2(rust2[0], rust2[1]) };
+ shader.uniforms.uPlateTex = { value: plateTex };
+ shader.uniforms.uPlate = { value: new THREE.Vector4(...plate) };
+ shader.uniforms.uGr0 = { value: new THREE.Vector4(...G.a) };
+ shader.uniforms.uGr1 = { value: new THREE.Vector4(...G.b) };
+ shader.uniforms.uGrDir = { value: new THREE.Vector2(...G.dir) };
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying vec2 vFx; varying vec3 vLp; uniform float uEdge; uniform vec2 uRust2; uniform sampler2D uPlateTex; uniform vec4 uPlate, uGr0, uGr1; uniform vec2 uGrDir; float lpH = 0.0;')
+ .replace('#include <color_fragment>', '#include <color_fragment>\ndiffuseColor.rgb *= vFx.y;')
+ .replace('#include <alphamap_fragment>', PLATE_F + EDGE_F + GREASE_F + '\n#include <alphamap_fragment>')
+ .replace('#include <normal_fragment_maps>', '#include <normal_fragment_maps>\n{ vec2 dHp = vec2(dFdx(lpH), dFdy(lpH)); normal = wPerturb(-vViewPosition, normal, dHp, faceDirection); }');
+ }
+ if (mud && isW) {
+ vs = vs.replace('#include <common>', '#include <common>\nvarying float vMudY;')
+ .replace('#include <begin_vertex>', '#include <begin_vertex>\nvMudY = position.y;');
+ shader.uniforms.uMud = { value: new THREE.Vector3(mud[0], mud[1], mud[2]) };
+ shader.uniforms.uWear = { value: new THREE.Vector3(...wear) };
+ shader.fragmentShader = shader.fragmentShader
+ .replace('#include <common>', '#include <common>\nvarying float vMudY; uniform vec3 uMud, uWear;')
+ .replace('#include <normal_fragment_begin>', MUD_F + '\n#include <normal_fragment_begin>');
+ }
+ if (atlas) vs = vs.replace('#include <uv_vertex>', `#include <uv_vertex>\n#ifdef USE_MAP\n vMapUv.x = (vMapUv.x + float(gl_InstanceID % ${atlas})) / ${atlas}.0;\n#endif`);
+ shader.vertexShader = vs;
+ };
+ mat.customProgramCacheKey = () => 'legs4' + (isW ? 'W' : 'N') + (mud ? 'M' : '') + (atlas ? 'A' + atlas : '');
+ return mat;
+ }
+
+ const tPlate0 = performance.now();
+ // ---- plate-detail atlas (tileable 6.4 m): R tone, G height, B rust, A oily runoff
+ const plateTex = (() => {
+ const S = 2048, px = S / 6.4, r = rng(977);
+ const mk = (fill) => { const cv = document.createElement('canvas'); cv.width = cv.height = S; const c = cv.getContext('2d', { willReadFrequently: true }); c.fillStyle = fill; c.fillRect(0, 0, S, S); return c; };
+ const cT = mk('#808080'), cH = mk('#808080'), cR = mk('#000'), cO = mk('#000');
+ const g8 = (v, a = 1) => `rgba(${v | 0},${v | 0},${v | 0},${a})`;
+ const R = (a, b) => a + (b - a) * r();
+ const dot = (c, x, y, rad, v, a = 1) => { c.fillStyle = g8(v, a); c.beginPath(); c.arc(x, y, rad, 0, 6.2832); c.fill(); };
+ const drip = (c, x, y, w, len, a) => {
+ const gr = c.createLinearGradient(0, y, 0, y + len); gr.addColorStop(0, g8(255, a)); gr.addColorStop(0.35, g8(255, a * 0.6)); gr.addColorStop(1, g8(255, 0)); c.fillStyle = gr;
+ for (const oy of [0, -S]) { c.setTransform(1, 0, 0, 1, 0, oy); c.beginPath(); c.moveTo(x - w / 2, y); c.lineTo(x + w / 2, y); c.lineTo(x + w * 0.2, y + len); c.lineTo(x - w * 0.2, y + len); c.closePath(); c.fill(); }
+ c.setTransform(1, 0, 0, 1, 0, 0);
+ };
+ const panels = [];
+ (function split(x, y, w, h, d) {
+ const mw = 2.3 * px, mh = 3.2 * px, minS = 0.8 * px, canW = w > 2 * minS, canH = h > 2 * minS;
+ if ((w > mw || h > mh || d < 2 || r() < 0.3) && (canW || canH)) {
+ const vert = canW && (!canH || w / mw > h / mh), k = R(0.36, 0.64);
+ if (vert) { const a = Math.round(w * k); split(x, y, a, h, d + 1); split(x + a, y, w - a, h, d + 1); }
+ else { const a = Math.round(h * k); split(x, y, w, a, d + 1); split(x, y + a, w, h - a, d + 1); }
+ } else panels.push({ x, y, w, h });
+ })(0, 0, S, S, 0);
+ for (const p of panels) {
+ p.tone = 128 + R(-26, 26); if (r() < 0.18) p.tone = r() < 0.5 ? R(162, 184) : R(76, 96); // replaced / repainted plates
+ p.lvl = 128 + R(-10, 10);
+ cT.fillStyle = g8(p.tone); cT.fillRect(p.x, p.y, p.w, p.h);
+ cH.fillStyle = g8(p.lvl); cH.fillRect(p.x, p.y, p.w, p.h);
+ }
+ const rivet = (x, y, rad) => {
+ if (r() < 0.035) { dot(cH, x, y, rad * 0.8, 40); dot(cT, x, y, rad * 0.8, 30); dot(cR, x, y, rad * 1.6, 255, 0.7); drip(cR, x, y, rad * 2, R(60, 260), 0.6); return; }
+ dot(cT, x + 1, y + 2, rad * 1.3, 45, 0.55);
+ dot(cT, x, y - 1, rad * 0.9, 165, 0.55);
+ const gr = cH.createRadialGradient(x, y, 0, x, y, rad * 1.15); gr.addColorStop(0, g8(255)); gr.addColorStop(0.6, g8(228)); gr.addColorStop(1, g8(140, 0));
+ cH.fillStyle = gr; cH.beginPath(); cH.arc(x, y, rad * 1.15, 0, 6.2832); cH.fill();
+ if (r() < 0.3) { dot(cR, x, y, rad * R(1.1, 1.6), 255, R(0.4, 0.9)); if (r() < 0.7) drip(cR, x + R(-2, 2), y, rad * R(1.0, 1.8), R(60, 420), R(0.3, 0.65)); }
+ };
+ const words = ['ОП-4', 'Ж-17', '№ 03', 'СМАЗКА', 'ТО-2', '12.87', 'ГИДРО', 'ДАВЛ. 210', 'ОТК', 'СЕКЦ. Б', 'НЕ ВСТАВАТЬ', '4Т', 'ЛЮК 7', 'МАСЛО'];
+ for (const p of panels) {
+ const { x, y, w, h } = p, kind = r();
+ cT.strokeStyle = g8(52, 0.22); cT.lineWidth = 34; cT.strokeRect(x + 0.5, y + 0.5, w, h); // grime gathered along the seam
+ cH.strokeStyle = g8(20); cH.lineWidth = 9; cH.strokeRect(x + 0.5, y + 0.5, w, h);
+ cT.strokeStyle = g8(22, 0.95); cT.lineWidth = 8; cT.strokeRect(x + 0.5, y + 0.5, w, h);
+ cT.fillStyle = g8(215, 0.4); cT.fillRect(x + 5, y + 5, w - 10, 3);
+ cT.fillStyle = g8(40, 0.4); cT.fillRect(x + 5, y + h - 9, w - 10, 4);
+ const ins = 0.11 * px, sp = R(0.24, 0.36) * px, rad = R(0.03, 0.04) * px;
+ if (kind < 0.72) {
+ const nx = Math.max(2, Math.round((w - 2 * ins) / sp)), ny = Math.max(2, Math.round((h - 2 * ins) / sp));
+ for (let i = 0; i <= nx; i++) { const xx = x + ins + (w - 2 * ins) * i / nx; rivet(xx, y + ins, rad); rivet(xx, y + h - ins, rad); }
+ if (kind < 0.5) for (let i = 1; i < ny; i++) { const yy = y + ins + (h - 2 * ins) * i / ny; rivet(x + ins, yy, rad); rivet(x + w - ins, yy, rad); }
+ } else {
+ const bead = (x0, y0, x1, y1) => { const n = Math.hypot(x1 - x0, y1 - y0) / 5; for (let i = 0; i <= n; i++) { const k = i / n, bx = x0 + (x1 - x0) * k + R(-1.2, 1.2), by = y0 + (y1 - y0) * k + R(-1.2, 1.2); dot(cH, bx, by, R(5.5, 8), 238, 0.9); dot(cT, bx, by, R(5, 7.5), R(60, 100), 0.75); if (r() < 0.12) dot(cR, bx, by, R(4, 9), 255, 0.6); } };
+ const o = 14; bead(x + o, y + o, x + w - o, y + o); bead(x + w - o, y + o, x + w - o, y + h - o); bead(x + w - o, y + h - o, x + o, y + h - o); bead(x + o, y + h - o, x + o, y + o);
+ }
+ // chipped edges
+ for (let i = 0, n = 4 + r() * 9; i < n; i++) {
+ const e = (r() * 4) | 0, k = r(), cx = e < 2 ? x + w * k : (e === 2 ? x : x + w), cy = e < 2 ? (e === 0 ? y : y + h) : y + h * k;
+ for (let j = 0, m = 2 + r() * 6; j < m; j++) dot(cR, cx + R(-22, 22), cy + R(-10, 10), R(3, 13), 255, R(0.5, 1));
+ }
+ const f = r();
+ if (f < 0.26 && w > 1.0 * px && h > 1.1 * px) {
+ // inspection hatch: hinges on the left, latch on the right, grime weeping from the bottom gap
+ const hw = R(0.5, 0.75) * px, hh = R(0.6, 0.95) * px, hx = x + 30 + R(0.2, 0.8) * (w - hw - 60), hy = y + 30 + R(0.2, 0.8) * (h - hh - 60);
+ cT.fillStyle = g8(p.tone + R(-18, 18)); cT.fillRect(hx, hy, hw, hh);
+ cH.fillStyle = g8(p.lvl + 24); cH.fillRect(hx, hy, hw, hh);
+ cH.strokeStyle = g8(25); cH.lineWidth = 7; cH.strokeRect(hx, hy, hw, hh);
+ cT.strokeStyle = g8(25, 0.95); cT.lineWidth = 6; cT.strokeRect(hx, hy, hw, hh);
+ for (const k of [0.22, 0.78]) {
+ cH.fillStyle = g8(252); cH.fillRect(hx - 9, hy + hh * k - 16, 18, 32); cT.fillStyle = g8(70, 0.8); cT.fillRect(hx - 9, hy + hh * k - 16, 18, 32);
+ drip(cR, hx, hy + hh * k + 14, 12, R(40, 160), 0.6);
+ }
+ cH.fillStyle = g8(252); cH.fillRect(hx + hw - 26, hy + hh * 0.5 - 22, 16, 44); cT.fillStyle = g8(60, 0.85); cT.fillRect(hx + hw - 26, hy + hh * 0.5 - 22, 16, 44);
+ for (const [a, b] of [[0.1, 0.08], [0.9, 0.08], [0.1, 0.92], [0.9, 0.92]]) rivet(hx + hw * a, hy + hh * b, 8);
+ for (let i = 0; i < 5; i++) drip(cO, hx + r() * hw, hy + hh, R(8, 26), R(80, 500), R(0.3, 0.7));
+ } else if (f < 0.52) {
+ // faded stencil remnant, mostly worn away
+ const fs2 = R(0.16, 0.36) * px, word = words[(r() * words.length) | 0];
+ cT.save(); cT.font = `700 ${fs2 | 0}px "Arial Narrow", Arial, sans-serif`; cT.textBaseline = 'middle';
+ const tw = Math.min(cT.measureText(word).width, w - 60), tx = x + 30 + r() * Math.max(1, w - 60 - tw), ty = y + h * R(0.25, 0.75);
+ cT.fillStyle = r() < 0.7 ? g8(215, R(0.35, 0.7)) : g8(45, R(0.4, 0.7));
+ cT.fillText(word, tx, ty, tw);
+ for (let i = 0; i < 26; i++) dot(cT, tx + r() * tw, ty + R(-0.6, 0.6) * fs2, R(4, fs2 * 0.3), p.tone, R(0.5, 1));
+ cT.restore();
+ } else if (f < 0.72) {
+ for (let i = 0, n = 1 + r() * 3; i < n; i++) {
+ const dx = x + R(0.15, 0.85) * w, dy = y + R(0.15, 0.85) * h, dr = R(0.08, 0.26) * px;
+ const gr = cH.createRadialGradient(dx, dy, 0, dx, dy, dr); gr.addColorStop(0, g8(40, 0.85)); gr.addColorStop(1, g8(40, 0));
+ cH.fillStyle = gr; cH.beginPath(); cH.arc(dx, dy, dr, 0, 6.2832); cH.fill();
+ for (let j = 0; j < 7; j++) dot(cR, dx + R(-0.4, 0.4) * dr, dy + R(-0.4, 0.4) * dr, R(2, 8), 255, R(0.5, 1));
+ dot(cT, dx, dy - dr * 0.2, dr * 0.7, 190, 0.12);
+ }
+ } else if (f < 0.88) {
+ const ang = R(-0.5, 0.5) + (r() < 0.3 ? 1.5 : 0), sx0 = x + R(0.2, 0.6) * w, sy0 = y + R(0.2, 0.8) * h, len = R(0.3, 0.9) * Math.min(w, h);
+ cT.save(); cT.beginPath(); cT.rect(x, y, w, h); cT.clip();
+ for (let i = 0; i < 10; i++) {
+ const o = R(-34, 34), l = len * R(0.4, 1), ax = sx0 - Math.sin(ang) * o, ay = sy0 + Math.cos(ang) * o;
+ cT.strokeStyle = g8(r() < 0.6 ? 212 : 46, R(0.35, 0.75)); cT.lineWidth = R(2, 6);
+ cT.beginPath(); cT.moveTo(ax, ay); cT.lineTo(ax + Math.cos(ang) * l, ay + Math.sin(ang) * l); cT.stroke();
+ }
+ cT.restore();
+ }
+ }
+ // weeping seams + long runoff streaks
+ for (const p of panels) for (let i = 0, n = 2 + r() * 7; i < n; i++) {
+ const xx = p.x + r() * p.w;
+ if (r() < 0.6) drip(cR, xx, p.y + p.h, R(5, 16), R(40, 380), R(0.25, 0.65)); else drip(cO, xx, p.y + p.h, R(8, 30), R(150, 900), R(0.2, 0.55));
+ }
+ for (let i = 0; i < 46; i++) drip(cO, r() * S, r() * S, R(10, 44), R(300, 1700), R(0.12, 0.34));
+ for (let i = 0; i < 260; i++) {
+ const sx = r() * S, sy = r() * S, a = r() < 0.5 ? R(-0.3, 0.3) : r() * 3.14, l = R(15, 220) * r() + 10;
+ cT.strokeStyle = g8(r() < 0.55 ? 215 : 40, R(0.15, 0.5)); cT.lineWidth = R(0.7, 2);
+ cT.beginPath(); cT.moveTo(sx, sy); cT.lineTo(sx + Math.cos(a) * l, sy + Math.sin(a) * l); cT.stroke();
+ }
+ const bl = cH;
+ const dT = cT.getImageData(0, 0, S, S).data, dH = bl.getImageData(0, 0, S, S).data, dR = cR.getImageData(0, 0, S, S).data, dO = cO.getImageData(0, 0, S, S).data;
+ const data = new Uint8Array(S * S * 4);
+ for (let y = 0; y < S; y++) {
+ const row = (S - 1 - y) * S;
+ for (let x = 0; x < S; x++) { const i = (y * S + x) * 4, o = (row + x) * 4; data[o] = dT[i]; data[o + 1] = dH[i]; data[o + 2] = dR[i]; data[o + 3] = dO[i]; }
+ }
+ const tex = new THREE.DataTexture(data, S, S, THREE.RGBAFormat, THREE.UnsignedByteType);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping; tex.magFilter = THREE.LinearFilter; tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.generateMipmaps = true; tex.anisotropy = 8; tex.colorSpace = THREE.NoColorSpace; tex.needsUpdate = true;
+ for (const c of [cT, cH, cR, cO]) c.canvas.width = c.canvas.height = 1;
+ return tex;
+ })();
+ const tPlate1 = performance.now();
+
+ const hazardTex = TEX.canvasTexture(256, 64, (c, w, h) => {
+ c.fillStyle = '#16140f'; c.fillRect(0, 0, w, h);
+ c.fillStyle = '#c29a1e';
+ for (let x = -h; x < w + h; x += 44) { c.beginPath(); c.moveTo(x, h); c.lineTo(x + 22, h); c.lineTo(x + 22 + h, 0); c.lineTo(x + h, 0); c.closePath(); c.fill(); }
+ });
+ const decalTex = TEX.canvasTexture(2048, 256, (c, w, h) => {
+ c.clearRect(0, 0, w, h);
+ c.fillStyle = 'rgb(214,208,190)'; c.strokeStyle = 'rgb(214,208,190)';
+ c.textAlign = 'center'; c.textBaseline = 'middle';
+ for (let i = 0; i < 8; i++) {
+ const cx = i * 256 + 128;
+ c.font = '900 150px Impact, "Arial Black", sans-serif';
+ c.fillText('0' + (i + 1), cx, 138);
+ c.font = '700 30px "Arial Narrow", Arial, sans-serif';
+ c.fillText('ОПОРА', cx, 36);
+ c.font = '700 22px "Arial Narrow", Arial, sans-serif';
+ c.fillText('НЕ СТОЯТЬ ПОД ОПОРОЙ', cx, 232);
+ c.lineWidth = 5; c.strokeRect(i * 256 + 18, 58, 220, 152);
+ // stencil bridges
+ c.clearRect(cx - 62, 60, 5, 150); c.clearRect(cx + 4, 60, 5, 150); c.clearRect(cx - 100, 136, 200, 4);
+ }
+ });
+ decalTex.anisotropy = 8;
+
+ const off = (i) => new THREE.Vector3(i * 31.7 + 3, i * 17.3 + 5, i * 23.9 + 7);
+ const matCache = new Map();
+ // variants: '' (default), 'thigh' (few streaks: it lies near horizontal), 'boot', 'foot', 'toe' (mud gradients)
+ const MUDS = { boot: [-19.5, -11.4, 0.72], foot: [-1.75, -0.4, 1.0], toe: [-0.95, -0.15, 0.8] };
+ // grease sources per part (hinge centres in local YZ, radius, strength) + local gravity direction
+ const GREASE = {
+ thigh: { a: [0, 0, 1.5, 0.8], b: [-LT, 0, 2.3, 1.0], dir: [0.56, -0.83] },
+ shin: { a: [0, 0, 2.1, 1.0], b: [-13.2, 0.3, 1.5, 0.7], dir: [-1, 0] },
+ foot: { a: [0, 0, 1.5, 0.8], b: [0, 0, 1, 0], dir: [-1, 0] },
+ };
+ GREASE.boot = GREASE.shin;
+ function M(key, variant = '') {
+ const id = key + '|' + variant;
+ if (matCache.has(id)) return matCache.get(id);
+ const lying = /thigh|cyl/.test(variant);
+ const st = lying ? 0.3 : 0.9;
+ const wet = variant === 'foot' || variant === 'toe' ? 0.85 : 0.6;
+ let m;
+ switch (key) {
+ case 'armorA': m = Mats.paintedMetal({ color: 0xb3a993, w: { chip: 0.26, rust: 0.17, streak: st, dirt: 0.8, wet, offset: off(1) } }); m.metalness = 0.1; m.roughness = 0.56; break;
+ case 'armorB': m = Mats.paintedMetal({ color: 0x8a887b, w: { chip: 0.28, rust: 0.18, streak: st, dirt: 0.7, wet, offset: off(2) } }); m.metalness = 0.12; m.roughness = 0.56; break;
+ case 'armorY': m = Mats.paintedMetal({ color: 0xb08f3c, w: { chip: 0.36, rust: 0.3, streak: st, dirt: 0.75, wet, offset: off(3) } }); m.metalness = 0.1; m.roughness = 0.58; break;
+ case 'steel': m = Mats.steel({ color: 0x3a3e44, w: { rust: 0.33, streak: st * 0.6, wet, offset: off(4) } }); break;
+ case 'joint': m = Mats.steel({ color: 0x23262b, w: { rust: 0.24, streak: st * 0.4, wet: 0.7, dirt: 0.5, offset: off(5) } }); m.roughness = 0.4; break;
+ case 'rust': m = Mats.rust({ w: { offset: off(6) } }); break;
+ case 'cyl': m = Mats.paintedMetal({ color: 0x5a5d58, w: { chip: 0.32, rust: 0.36, streak: 0.3, wet: 0.6, offset: off(7) } }); m.metalness = 0.2; break;
+ case 'chrome': m = Mats.chrome({ color: 0xf0e4d2, w: { rust: 0.05, dirt: 0.14, streak: 0.1, grain: 0.08, offset: off(8) } }); m.roughness = 0.12; m.envMapIntensity = 1.3; break;
+ case 'mud': m = weathered({ color: 0x3a3024, roughness: 0.8, metalness: 0 }, { tex: 0.9, grain: 0.9, dirt: 0.7, streak: 0.1, moss: 0.15, wet: 0.6, bump: 0.01, offset: off(12) }); break;
+ case 'claw': m = Mats.steel({ color: 0x8a867d, w: { rust: 0.36, grain: 0.7, dirt: 0.65, streak: 0.5, wet: 0.9, bump: 0.009, tex: 0.42, offset: off(9) } }); m.roughness = 0.42; m.metalness = 0.62; break;
+ case 'hazard': m = Mats.paintedMetal({ color: 0x86847a, w: { chip: 0.36, rust: 0.3, dirt: 0.75, streak: st, wet, offset: off(10) } }); m.metalness = 0.12; m.roughness = 0.56; break; // look-dev: no hazard stripes (refs have none)
+ case 'decal': m = weathered({ map: decalTex, alphaTest: 0.42, roughness: 0.62, metalness: 0.1, polygonOffset: true, polygonOffsetFactor: -3, polygonOffsetUnits: -3 }, { chip: 0.5, rust: 0.2, dirt: 0.6, streak: 0.5, moss: 0, offset: off(11) }); break;
+ case 'rubber': m = Mats.rubber(); break;
+ case 'dark': m = new THREE.MeshStandardMaterial({ color: 0x040506, roughness: 1, metalness: 0 }); break;
+ case 'lampA': m = new THREE.MeshBasicMaterial({ color: new THREE.Color(1.9, 0.62, 0.12), toneMapped: false }); break;
+ default: throw new Error('unknown material ' + key);
+ }
+ const low = variant === 'foot' || variant === 'toe';
+ if (m.userData.weather || key === 'decal') patch(m, { mud: key === 'mud' ? null : MUDS[variant] || null, atlas: key === 'decal' ? 8 : 0,
+ edge: (/armor|cyl|hazard/.test(key) ? 1 : /steel|claw/.test(key) ? 0.5 : 0) * (low ? 1.5 : 1),
+ rust2: /armor|hazard/.test(key) ? [0.45, variant === 'thigh' || low ? 0.25 : 1] : key === 'cyl' ? [0.7, 0] : [0, 0],
+ plate: /armor|hazard/.test(key) ? [1, 0.045, 0.15, lying ? 1 : 0] : key === 'steel' ? [0.7, 0.035, 0.3, lying ? 1 : 0] : key === 'rust' ? [0.6, 0.016, 0.6, 0]
+ : key === 'claw' ? [0, 0, 1, 0] : key === 'cyl' ? [0, 0, 0.25, 0] : [0, 0, 0, 0],
+ wear: key === 'claw' ? [1.7, 2.6, 1] : key === 'steel' && low ? [9, 10, 0.5] : [9, 10, 0],
+ grease: key === 'decal' || key === 'mud' || key === 'chrome' ? null : GREASE[variant] || null });
+ matCache.set(id, m);
+ return m;
+ }
+
+ // ---------------------------------------------------------------- part: hip base (static)
+ // frame: origin = kingpin point (L.hip), +Z outward, +Y up. Chassis side is around z = -0.7.
+ function buildHipBase() {
+ const P = new Part();
+ P.add(cbox(5.8, 5.0, 0.5, 0.08), 'steel', xf(0, 0, -0.78));
+ const fz = xf(0, 0, -0.53, PI / 2, 0, 0);
+ for (const y of [-2.25, 2.25]) boltRow(P, 'joint', 12, [-2.6, 0, -y], [2.6, 0, -y], fz, 0.085, 0.09);
+ for (const x of [-2.65, 2.65]) boltRow(P, 'joint', 7, [x, 0, -1.6], [x, 0, 1.6], fz, 0.085, 0.09);
+ const lug = new THREE.Shape();
+ lug.moveTo(-2.0, -0.8); lug.lineTo(-2.0, 0); lug.absarc(0, 0, 2.0, PI, 0, true); lug.lineTo(2.0, -0.8); lug.closePath();
+ P.add(extrXZ(lug, 2.25, 0.75, 0.07, 28), 'steel');
+ P.add(extrXZ(lug, -1.5, 0.75, 0.07, 28), 'steel');
+ // kingpin caps + bolt circles
+ const cap = lathe([[0, 0], [1.2, 0], [1.2, 0.2], [1.02, 0.29], [0.45, 0.29], [0.45, 0.33], [0, 0.33]], 28);
+ P.add(cap, 'joint', xf(0, 2.22, 0));
+ P.add(cap, 'joint', xf(0, -2.22, 0, PI, 0, 0));
+ boltRing(P, 'joint', 12, 0.86, xf(0, 2.5, 0), 0.07, 0.06);
+ boltRing(P, 'joint', 12, 0.86, xf(0, -2.5, 0, PI, 0, 0), 0.07, 0.06);
+ // slew bearing races between lugs and yoke
+ const race = lathe([[1.42, 0], [1.86, 0], [1.86, 0.12], [1.42, 0.12]], 36);
+ P.add(race, 'joint', xf(0, 1.38, 0)); P.add(race, 'joint', xf(0, -1.5, 0));
+ boltRing(P, 'joint', 20, 1.7, xf(0, 1.38, 0, PI, 0, 0), 0.06, 0.05);
+ // side posts + gussets tying the lugs to the flange
+ P.mirX(cbox(0.5, 4.5, 0.75, 0.06), 'steel', xf(2.3, 0, -0.42));
+
+ // grease lines
+ P.mirX(tube([[1.3, 2.26, -0.6], [1.35, 2.34, 0.2], [1.0, 2.34, 0.9], [0.5, 2.5, 0.75]], 0.035, 5), 'rubber');
+ // slew-ring gear teeth on the outward half of both races + pinion drive
+ for (const y of [1.44, -1.44]) for (let i = 0; i < 30; i++) {
+ const a = -1.75 + 3.5 * i / 29;
+ P.add(new THREE.BoxGeometry(0.11, 0.13, 0.12), 'joint', xf(Math.sin(a) * 1.9, y, Math.cos(a) * 1.9, 0, a, 0));
+ }
+ P.mirX(cyl(0.3, 0.5, 12), 'joint', xf(2.2, 1.44, 0.55));
+ P.mirX(cyl(0.34, 0.7, 12), 'steel', xf(2.2, 2.05, 0.55));
+ P.mirX(hex(0.16, 0.14), 'joint', xf(2.2, 2.4, 0.55));
+ // lubrication distributor + ID plate on the flange
+ P.add(cbox(0.7, 0.4, 0.3, 0.03), 'joint', xf(-2.3, 2.05, -0.3));
+ for (const x of [-2.5, -2.3, -2.1]) P.add(hex(0.05, 0.1), 'joint', xf(x, 2.25, -0.3));
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- part: yoke (yaws about kingpin)
+ const A_LIFT = [1.25, -2.52, 3.5]; // lift cylinder base pin on the yoke chin (yoke frame)
+ function buildYoke() {
+ const P = new Part();
+ P.add(lathe([[0, -1.38], [1.2, -1.38], [1.36, -1.24], [1.36, -0.52], [1.27, -0.44], [1.27, 0.44], [1.36, 0.52], [1.36, 1.24], [1.2, 1.38], [0, 1.38]], 36), 'joint');
+ P.add(cbox(2.2, 2.2, 2.3, 0.1), 'steel', xf(0, 0, 1.25));
+ P.add(latheX([[0, -1.17], [1.02, -1.17], [1.18, -1.02], [1.18, 1.02], [1.02, 1.17], [0, 1.17]], 32), 'joint', xf(0, 0, E_TRUN));
+ P.add(cbox(1.7, 0.5, 2.9, 0.08), 'steel', xf(0, 1.12, 1.5));
+ // chin: carries the lift-cylinder base pins, sweeps outside the lower lug
+ const chin = poly([[1.25, -0.9], [3.1, -1.12], [4.1, -2.3], [3.8, -3.1], [2.5, -2.8], [2.16, -1.42], [1.25, -1.42]]);
+ P.add(extrYZ(chin, -0.78, 0.78, 0.07), 'steel');
+ P.mirX(extrYZ(poly([[2.3, -1.5], [3.4, -1.5], [4.15, -2.35], [3.8, -3.15], [2.6, -2.85]]), 0.78, 0.92, 0.03), 'armorB');
+ P.add(cylX(0.24, 3.7, 16), 'joint', xf(0, A_LIFT[1], A_LIFT[2]));
+ P.mirX(cylX(0.36, 0.14, 14), 'joint', xf(1.82, A_LIFT[1], A_LIFT[2]));
+ boltRow(P, 'joint', 4, [-0.55, 0, 0], [0.55, 0, 0], xf(0, 1.37, 2.3), 0.07, 0.06);
+ boltRow(P, 'joint', 4, [-0.55, 0, 0], [0.55, 0, 0], xf(0, 1.37, 0.8), 0.07, 0.06);
+ // hose stubs
+ for (const x of [-0.5, 0, 0.5]) P.add(tube([[x, -1.3, 1.3], [x * 1.1, -1.75, 1.7], [x * 1.2, -1.9, 2.4], [x, -1.55, 2.9]], 0.07, 6), 'rubber');
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- part: thigh
+ // frame: origin = trunnion, bone runs to (0,-LT,0) = knee, +X hinge axis, +Z = top face.
+ const A_KNEE = [1.25, -3.05, 2.1]; // knee cylinder base clevis on thigh top
+ const B_LIFT = [1.25, -7.6, -1.62]; // lift cylinder rod eye under the thigh
+ function buildThigh() {
+ const P = new Part();
+ // hip fork cheeks
+ {
+ const s = new THREE.Shape(); const a0 = Math.atan2(-0.963, 1.15);
+ s.moveTo(1.15, -3.7); s.lineTo(1.15, -0.963); s.absarc(0, 0, 1.5, a0, PI - a0, false); s.lineTo(-1.15, -3.7); s.closePath();
+ P.mirX(extrYZ(s, 1.2, 1.75, 0.06, 30), 'steel');
+ const cap = lathe([[0, 0], [1.22, 0], [1.22, 0.16], [1.06, 0.23], [0.62, 0.23], [0.62, 0.36], [0.5, 0.42], [0, 0.42]], 28).rotateZ(-PI / 2);
+ P.mirX(cap, 'joint', xf(1.75, 0, 0));
+ const br = xf(1.98, 0, 0, 0, 0, -PI / 2);
+ boltRing(P, 'joint', 10, 0.86, br, 0.06, 0.06);
+ boltRing(P, 'joint', 10, 0.86, MIRX.clone().multiply(br), 0.06, 0.06);
+ }
+ // twin box girders
+ const GY0 = -1.85, GY1 = -9.3, GL = GY0 - GY1;
+ P.mirX(cbox(1.3, GL, 2.4, 0.08), 'steel', xf(1.4, (GY0 + GY1) / 2, 0));
+ // girder end caps at the knee side (rust accent)
+ P.mirX(cbox(1.36, 0.3, 2.46, 0.05), 'rust', xf(1.4, GY1 + 0.1, 0));
+ // knee fork cheeks (big discs)
+ {
+ const KR = 2.3;
+ const s = new THREE.Shape(); const top = Math.sqrt(KR * KR - 1.3 * 1.3), a0 = Math.atan2(top, -1.3);
+ s.moveTo(-1.3, -8.4); s.lineTo(-1.3, -LT + top); s.absarc(0, -LT, KR, a0, PI * 2 + (PI - a0), false); s.lineTo(1.3, -8.4); s.closePath();
+ P.mirX(extrYZ(s, 1.85, 2.5, 0.09, 56), 'armorB', undefined, 0.9);
+ // layered outer hubs
+ const hub = lathe([[0, 0], [1.98, 0], [1.98, 0.2], [1.85, 0.29], [1.36, 0.29], [1.36, 0.5], [1.26, 0.58], [0.68, 0.58], [0.68, 0.8], [0.56, 0.88], [0, 0.88]], 48).rotateZ(-PI / 2);
+ P.mirX(hub, 'armorA', xf(2.5, -LT, 0), 0.95);
+ P.mirX(cylX(0.5, 0.12, 20), 'joint', xf(3.4, -LT, 0));
+ const cover = lathe([[1.41, 0], [1.82, 0], [1.82, 0.07], [1.41, 0.07]], 40, { a0: 0.35, a1: 5.2 }).rotateZ(-PI / 2);
+ P.mirX(cover, 'armorB', xf(2.79, -LT, 0));
+ const cover2 = lathe([[0.71, 0], [1.22, 0], [1.22, 0.06], [0.71, 0.06]], 30, { a0: 2.2, a1: 6.0 }).rotateZ(-PI / 2);
+ P.mirX(cover2, 'armorB', xf(3.08, -LT, 0));
+ for (const mir of [IDENT, MIRX]) {
+ boltRing(P, 'joint', 22, 1.915, mir.clone().multiply(xf(2.7, -LT, 0, 0, 0, -PI / 2)), 0.07, 0.07);
+ boltRing(P, 'joint', 14, 1.61, mir.clone().multiply(xf(2.86, -LT, 0, 0, 0, -PI / 2)), 0.06, 0.05);
+ boltRing(P, 'joint', 10, 0.96, mir.clone().multiply(xf(3.14, -LT, 0, 0, 0, -PI / 2)), 0.07, 0.07);
+ boltRing(P, 'joint', 6, 0.36, mir.clone().multiply(xf(3.38, -LT, 0, 0, 0, -PI / 2)), 0.06, 0.06);
+ }
+ // rim armour band around the lower half of each disc
+ const band = extrYZ(sector(KR, KR + 0.17, PI * 1.02, PI * 1.98), 1.8, 2.55, 0.04, 30);
+ P.mirX(band, 'armorA', xf(0, -LT, 0));
+ // inspection port on the cheek bar
+ const ring = lathe([[0.36, 0], [0.56, 0], [0.56, 0.09], [0.36, 0.09]], 20).rotateZ(-PI / 2);
+ for (const y of [-8.95, -7.0 - 100]) if (y > -50) { P.mirX(ring, 'joint', xf(2.5, y, 0)); P.mirX(cylX(0.36, 0.04, 16), 'dark', xf(2.52, y, 0)); }
+ P.mirX(new THREE.BoxGeometry(0.05, 0.42, 2.3), 'armorB', xf(2.525, -9.75, 0), 0.8);
+ }
+ // cross members + X bracing between the girders
+ const cy = [-3.0, -4.9, -6.8, -8.7];
+ for (const y of cy) P.add(cbox(1.7, 0.55, 1.7, 0.05), 'steel', xf(0, y, -0.1));
+ for (let i = 0; i < cy.length - 1; i++) {
+ const s = i % 2 ? 1 : -1;
+ P.add(tube([[-0.72 * s, cy[i] - 0.2, 0.35], [0.72 * s, cy[i + 1] + 0.2, 0.35]], 0.1, 6, 1), 'rust');
+ P.add(tube([[0.72 * s, cy[i] - 0.2, -0.5], [-0.72 * s, cy[i + 1] + 0.2, -0.5]], 0.1, 6, 1), 'rust');
+ }
+ // spine pipes in the gap (top side)
+ for (const [x, r] of [[-0.42, 0.13], [-0.08, 0.09], [0.2, 0.09], [0.48, 0.14]]) {
+ P.add(tube([[x, -2.3, 0.5], [x, -3.0, 0.92], [x, -6.0, 0.95], [x, -8.6, 0.92], [x * 0.6, -9.6, 0.6], [x * 0.4, -10.4, 0.0]], r, 7), x > 0.3 ? 'armorY' : 'joint');
+ }
+ for (const y of [-3.9, -5.9, -7.9]) P.add(cbox(1.5, 0.16, 0.14, 0.03), 'joint', xf(0, y, 1.08));
+ // top armour plates (pale), ribs, bolts
+ const plates = [[-3.75, -6.35, 'armorA'], [-6.55, -9.15, 'armorA']];
+ plates.forEach(([y0, y1, key], pi) => {
+ const yc = (y0 + y1) / 2, len = y0 - y1;
+ P.add(cbox(4.3, len, 0.26, 0.08), key, xf(0, yc, 1.33));
+ P.add(cbox(0.55, len - 0.4, 0.14, 0.04), pi ? 'armorB' : key, xf(0, yc, 1.52));
+ P.mirX(cbox(0.2, len - 0.3, 0.12, 0.04), key, xf(1.98, yc, 1.5));
+ const fr = xf(0, 0, 1.46, PI / 2, 0, 0);
+ for (const x of [-2.05, 2.05]) boltRow(P, 'joint', 6, [x, 0, -(y0 - 0.2)], [x, 0, -(y1 + 0.2)], fr, 0.055, 0.05);
+ for (const y of [y0 - 0.14, y1 + 0.14]) boltRow(P, 'joint', 5, [-0.5, 0, -y], [0.5, 0, -y], fr, 0.05, 0.05);
+ });
+ // safety handrails along both top edges (human-scale cue), chipped yellow
+ for (const sx of [1, -1]) {
+ for (let y = -3.9; y > -9.2; y -= 1.3) P.add(cbox(0.06, 0.06, 1.1, 0.01), 'armorY', xf(sx * 2.08, y, 2.0));
+ for (const z of [2.05, 2.55]) P.add(cbox(0.06, 5.5, 0.06, 0.01), 'armorY', xf(sx * 2.08, -6.5, z));
+ }
+ // lifting eyes
+ P.mirX(new THREE.TorusGeometry(0.17, 0.045, 6, 12).rotateY(PI / 2), 'joint', xf(2.02, -3.95, 1.56));
+ P.mirX(new THREE.TorusGeometry(0.17, 0.045, 6, 12).rotateY(PI / 2), 'joint', xf(2.02, -8.95, 1.56));
+ // knee-cylinder base clevises on the top
+ for (const s of [1, -1]) {
+ P.add(cbox(1.0, 1.25, 0.75, 0.08), 'steel', xf(s * A_KNEE[0], A_KNEE[1] + 0.25, 1.55));
+ for (const dx of [-0.42, 0.42]) P.add(extrYZ(poly([[1.5, -3.75], [1.5, -2.5], [2.3, -2.62], [2.52, -3.05], [2.3, -3.45]]), s * A_KNEE[0] + dx - 0.07, s * A_KNEE[0] + dx + 0.07, 0.02), 'steel');
+ P.add(cylX(0.2, 1.15, 12), 'joint', xf(s * A_KNEE[0], A_KNEE[1], A_KNEE[2]));
+ }
+ // side armour on the outer girder faces
+ {
+ const s1 = poly([[-1.08, -2.45], [0.9, -2.45], [1.08, -2.75], [1.08, -5.95], [-1.08, -5.95]]);
+ P.mirX(extrYZ(s1, 2.05, 2.28, 0.06), 'armorA');
+ const s2 = poly([[-1.08, -6.2], [1.08, -6.2], [1.08, -8.2], [0.7, -8.45], [-1.08, -8.45]]);
+ P.mirX(extrYZ(s2, 2.05, 2.25, 0.06), 'armorB');
+ P.mirX(cbox(0.1, 3.1, 0.16, 0.03), 'armorA', xf(2.3, -4.3, -0.62));
+ P.mirX(cbox(0.1, 1.3, 1.0, 0.03), 'armorB', xf(2.31, -3.5, 0.3));
+ P.mirX(tube([[2.36, -3.0, 0.62], [2.5, -3.1, 0.62], [2.5, -3.9, 0.62], [2.36, -4.0, 0.62]], 0.03, 5), 'joint');
+ for (const mir of [IDENT, MIRX]) {
+ const fr = mir.clone().multiply(xf(2.28, 0, 0, 0, 0, -PI / 2)); // bolt axis -> +x
+ // frame: local y -> +x ; local x -> -y(thigh) ; local z -> z
+ boltRow(P, 'joint', 8, [2.6, 0, 0.95], [5.8, 0, 0.95], fr, 0.055, 0.05);
+ boltRow(P, 'joint', 8, [2.6, 0, -0.95], [5.8, 0, -0.95], fr, 0.055, 0.05);
+ boltRow(P, 'joint', 5, [6.35, 0, 0.92], [8.05, 0, 0.92], fr, 0.055, 0.05);
+ boltRow(P, 'joint', 5, [6.35, 0, -0.92], [8.3, 0, -0.92], fr, 0.055, 0.05);
+ }
+ // leg number stencil on both sides (kept readable: not mirrored)
+ P.add(new THREE.PlaneGeometry(1.7, 1.7), 'decal', xf(2.285, -7.3, 0, 0, PI / 2, 0).multiply(xf(0, 0, 0, 0, 0, PI / 2)));
+ P.add(new THREE.PlaneGeometry(1.7, 1.7), 'decal', xf(-2.285, -7.3, 0, 0, -PI / 2, 0).multiply(xf(0, 0, 0, 0, 0, -PI / 2)));
+ }
+ // ---- round 2: hydraulics on the girder sides (accumulators, valve block, clipped hard lines), cable drum, lamps
+ {
+ const bottle = lathe([[0, -0.85], [0.16, -0.85], [0.27, -0.7], [0.27, 0.7], [0.16, 0.85], [0.08, 0.9], [0.08, 1.0], [0, 1.0]], 14);
+ for (const z of [-0.3, 0.32]) {
+ P.mirX(bottle, 'armorY', xf(2.6, -5.0, z), z < 0 ? 0.55 : 0.7);
+ P.mirX(hex(0.1, 0.12), 'joint', xf(2.6, -4.0, z));
+ }
+ for (const y of [-4.55, -5.5]) { P.mirX(cbox(0.14, 0.1, 1.3, 0.02), 'joint', xf(2.84, y, 0.01)); P.mirX(cbox(0.6, 0.1, 0.1, 0.02), 'joint', xf(2.58, y, -0.64)); P.mirX(cbox(0.6, 0.1, 0.1, 0.02), 'joint', xf(2.58, y, 0.66)); }
+ // valve block with fittings, pilot lines to the bottles
+ P.mirX(cbox(0.36, 0.62, 0.9, 0.04), 'joint', xf(2.48, -6.25, 0.5));
+ for (const z of [0.22, 0.5, 0.78]) { P.mirX(hex(0.07, 0.12).rotateZ(-PI / 2), 'joint', xf(2.66, -6.1, z)); P.mirX(cyl(0.05, 0.12, 8), 'joint', xf(2.56, -5.9, z)); }
+ P.mirX(tube([[2.6, -5.95, 0.3], [2.62, -5.75, 0.31], [2.6, -5.86, -0.3]], 0.03, 5), 'joint');
+ // three hard lines along the lower edge of the girder side, clipped every metre, down to the knee hub
+ for (const [z, r] of [[-0.84, 0.045], [-0.72, 0.035], [-0.62, 0.035]]) {
+ P.mirX(tube([[2.5, -6.4, 0.2 + z * 0.3], [2.36, -6.7, z], [2.34, -8.6, z], [2.6, -9.3, z * 0.9], [2.6, -10.3, z * 1.25]], r, 5, 18), z < -0.8 ? 'armorY' : 'joint');
+ P.mirX(tube([[2.34, -2.2, z], [2.36, -3.4, z], [2.34, -4.3, z], [2.5, -4.5, z + 0.1]], r, 5, 10), 'joint');
+ }
+ for (const y of [-2.6, -3.5, -7.1, -7.9, -8.6]) { P.mirX(cbox(0.1, 0.09, 0.4, 0.015), 'joint', xf(2.36, y, -0.73)); P.mirX(bolt(0.03, 0.04), 'joint', xf(2.4, y, -0.56, 0, 0, -PI / 2)); }
+ // ID plate + grab handles + latches on the side armour
+ P.mirX(cbox(0.03, 0.34, 0.52, 0.008), 'armorY', xf(2.3, -2.95, -0.2), 1.1);
+ for (const y of [-6.5, -8.15]) for (const z of [-0.7, 0.7]) P.mirX(cbox(0.06, 0.2, 0.09, 0.015), 'joint', xf(2.27, y, z));
+ // cable drum between the knee rams
+ const drum = latheX([[0, -0.52], [0.72, -0.52], [0.72, -0.44], [0.46, -0.44], [0.5, -0.33], [0.46, -0.22], [0.5, -0.11], [0.46, 0], [0.5, 0.11], [0.46, 0.22], [0.5, 0.33], [0.46, 0.44], [0.72, 0.44], [0.72, 0.52], [0, 0.52]], 20);
+ P.add(drum, 'joint', xf(0, -7.85, 2.2));
+ P.mirX(extrYZ(poly([[1.5, -8.35], [1.5, -7.35], [2.25, -7.7], [2.25, -8.0]]), 0.56, 0.66, 0.02), 'steel');
+ P.mirX(cyl(0.09, 0.2, 8).rotateZ(PI / 2), 'joint', xf(0.72, -7.85, 2.2));
+ P.add(tube([[0.2, -7.4, 2.4], [0.24, -6.6, 1.75], [0.3, -5.6, 1.62], [0.32, -4.2, 1.6]], 0.045, 5, 12), 'rubber');
+ // amber marker lamps: knee cheek + hip end
+ for (const [y, z] of [[-9.4, 1.5], [-2.25, 0.9]]) { P.mirX(cbox(0.14, 0.2, 0.3, 0.02), 'joint', xf(2.54, y, z)); P.mirX(new THREE.BoxGeometry(0.04, 0.06, 0.1), 'lampA', xf(2.63, y, z)); }
+ // grease nipples around the knee hubs
+ for (const a of [0.6, 2.2, 3.9, 5.4]) P.mirX(hex(0.045, 0.1).rotateZ(-PI / 2), 'joint', xf(2.7, -LT + Math.cos(a) * 2.12, Math.sin(a) * 2.12));
+ }
+ // underside: flange ribs, lift-cylinder lugs, sagging hose bundle
+ for (let y = -2.6, i = 0; y > -9.2; y -= 0.95, i++) P.mirX(cbox(1.38, 0.15, 0.3, 0.03), i % 3 === 1 ? 'rust' : 'steel', xf(1.4, y, -1.3));
+ for (const s of [1, -1]) {
+ P.add(cbox(1.05, 1.3, 0.5, 0.07), 'steel', xf(s * B_LIFT[0], B_LIFT[1], -1.4));
+ for (const dx of [-0.4, 0.4]) P.add(extrYZ(poly([[-1.25, -6.8], [-1.25, -8.4], [-1.75, -8.05], [-1.98, -7.6], [-1.75, -7.15]]), s * B_LIFT[0] + dx - 0.07, s * B_LIFT[0] + dx + 0.07, 0.02), 'steel');
+ P.add(cylX(0.2, 1.1, 12), 'joint', xf(s * B_LIFT[0], B_LIFT[1], B_LIFT[2]));
+ }
+ const hx = [-0.52, -0.3, -0.1, 0.12, 0.34, 0.54];
+ hx.forEach((x, i) => {
+ const sag = 0.35 + rnd() * 0.5, r = 0.055 + rnd() * 0.05;
+ P.add(tube([[x, -2.2, -0.9], [x, -3.0, -1.2], [x + (rnd() - 0.5) * 0.15, -4.8, -1.25 - sag], [x, -6.8, -1.2], [x + (rnd() - 0.5) * 0.15, -8.2, -1.25 - sag * 0.8], [x * 0.7, -9.4, -1.0], [x * 0.5, -10.2, -0.3]], r, 6), 'rubber');
+ });
+ for (const y of [-3.0, -6.8]) P.add(cbox(1.5, 0.18, 0.2, 0.03), 'joint', xf(0, y, -1.22));
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- part: shin
+ // frame: origin = knee, bone to (0,-LS,0) = ankle ball, +X hinge, +Z = OUTER face (seen from outside).
+ const B_KNEE = [1.25, 2.9, 0.6]; // knee cylinder rod eye on the shin's lever tail
+ const A_ANK = [[1.32, -13.2, 2.28], [1.15, -13.2, -1.62]]; // ankle stabiliser bases (outer, inner)
+ function buildShin() {
+ const P = new Part();
+ // knee: centre drum, axle, lever plates (fork for the cylinder rods), kneecap
+ P.add(latheX([[0, -0.74], [1.55, -0.74], [1.7, -0.6], [1.7, 0.6], [1.55, 0.74], [0, 0.74]], 36), 'joint');
+ P.add(cylX(0.62, 3.72, 20), 'joint');
+ {
+ const tipA = Math.atan2(B_KNEE[1], B_KNEE[2]), tipR = Math.hypot(B_KNEE[1], B_KNEE[2]);
+ const disc = new THREE.Shape(); disc.absarc(0, 0, 1.95, 0, PI * 2, false);
+ // inner lever: disc + stadium to the pin
+ const st = new THREE.Shape(); const w = 0.62, ux = Math.cos(tipA), uy = Math.sin(tipA), vx = -uy, vy = ux;
+ st.moveTo(-vx * w, -vy * w); st.lineTo(B_KNEE[2] - vx * w, B_KNEE[1] - vy * w);
+ st.absarc(B_KNEE[2], B_KNEE[1], w, tipA - PI / 2, tipA + PI / 2, false); st.lineTo(vx * w, vy * w); st.closePath();
+ P.mirX(extrYZ(disc, 0.78, 0.98, 0.04, 40), 'steel');
+ P.mirX(extrYZ(st, 0.78, 0.98, 0.04, 16), 'steel');
+ // outer lever: disc + big sector that also carries the kneecap lames
+ const sec = new THREE.Shape(); const s0 = -0.42, s1 = tipA - 0.05;
+ sec.moveTo(0, 0); sec.absarc(0, 0, 2.62, s0, s1, false); sec.closePath();
+ P.mirX(extrYZ(disc, 1.52, 1.74, 0.04, 40), 'steel');
+ P.mirX(extrYZ(sec, 1.52, 1.74, 0.04, 30), 'steel');
+ P.mirX(extrYZ(st, 1.52, 1.74, 0.04, 16), 'steel');
+ P.add(cylX(0.21, 3.7, 14), 'joint', xf(0, B_KNEE[1], B_KNEE[2]));
+ P.mirX(cylX(0.38, 0.12, 14), 'joint', xf(1.8, B_KNEE[1], B_KNEE[2]));
+ // stiffener ribs on the sector
+ for (const a of [0.0, 0.45, 0.9]) P.mirX(cbox(0.1, 0.14, 0.8, 0.03), 'steel', xf(1.77, Math.sin(a) * 2.15, Math.cos(a) * 2.15, -a, 0, 0));
+ // kneecap: three overlapping lames (lobster tail)
+ const lames = [[-0.40, 0.26, 2.58, 2.77, 'armorA'], [0.18, 0.76, 2.67, 2.86, 'armorB'], [0.68, 1.16, 2.76, 2.95, 'armorA']];
+ for (const [a0, a1, ri, ro, key] of lames) {
+ P.add(extrYZ(sector(ri, ro, a0, a1), -1.79, 1.79, 0.05, 14), key);
+ for (const a of [a0 + 0.07, a1 - 0.07]) {
+ const fr = xf(0, Math.sin(a) * ro, Math.cos(a) * ro, PI / 2 - a, 0, 0);
+ boltRow(P, 'joint', 7, [-1.55, 0, 0], [1.55, 0, 0], fr, 0.06, 0.05);
+ }
+ for (const x of [-1.05, 1.05]) P.add(extrYZ(sector(ro - 0.01, ro + 0.05, a0 + 0.02, a1 - 0.02), x - 0.09, x + 0.09, 0.015, 10), 'joint');
+ const am = (a0 + a1) / 2;
+ P.add(cbox(0.3, 0.1, (a1 - a0) * ro * 0.8, 0.03), key, xf(0, Math.sin(am) * (ro + 0.03), Math.cos(am) * (ro + 0.03), -am + PI / 2, 0, 0).multiply(xf(0, 0, 0, PI / 2, 0, 0)));
+ }
+ }
+ // structural core
+ P.add(cbox(2.5, 15.7, 2.7, 0.08), 'steel', xf(0, -9.0, 0));
+ // ---- armour shell: one big tapered shield wrapping the outer face and both sides (three stacked
+ // sections with real seams), open at the back. Detail is layered on in surface-aligned frames.
+ {
+ const SH = { yT: -3.3, yB: -16.3, hx: 2.3, z0: -1.25, z1: 2.15, tx: 0.33, tz: 0.1 };
+ const zc = (SH.z0 + SH.z1) / 2, H = SH.yT - SH.yB;
+ const taperShell = (geo) => {
+ const p = geo.attributes.position;
+ for (let i = 0; i < p.count; i++) {
+ const k = Math.min(1, Math.max(0, (SH.yT - p.getY(i)) / H));
+ p.setX(i, p.getX(i) * (1 - SH.tx * k)); p.setZ(i, zc + (p.getZ(i) - zc) * (1 - SH.tz * k));
+ }
+ geo.computeVertexNormals(); return geo;
+ };
+ for (const [ya, yb, key, tint] of [[-3.3, -8.2, 'armorA', 1.0], [-8.33, -12.35, 'armorA', 0.92], [-12.48, -16.3, 'armorA', 1.04]]) {
+ P.add(taperShell(cbox(SH.hx * 2, ya - yb, SH.z1 - SH.z0, 0.14).translate(0, (ya + yb) / 2, zc)), key, undefined, tint);
+ }
+ const tiltX = Math.atan(SH.hx * SH.tx / H), tiltZ = Math.atan((SH.z1 - zc) * SH.tz / H);
+ // sloped visor from the shell top up toward the kneecap
+ P.add(cbox(4.0, 1.6, 0.26, 0.07), 'armorA', xf(0, -2.72, 1.72, -0.62, 0, 0));
+ P.mirX(extrYZ(poly([[-1.2, -3.3], [2.15, -3.3], [1.25, -2.05], [-1.2, -2.6]]), 1.76, 2.0, 0.05), 'armorA');
+
+ // ---- outer face frame: coordinates (x, -s, dz) with s = distance down the face, dz = out of the face
+ const FO = xf(0, SH.yT, SH.z1, tiltZ, 0, 0);
+ const O = (geo, key, m, tint) => P.add(geo, key, FO.clone().multiply(m || IDENT), tint);
+ const OB = (dz) => FO.clone().multiply(xf(0, 0, dz, PI / 2, 0, 0)); // bolt frame: [x, 0, s]
+ // upper section
+ O(extrXY(poly([[-1.8, -0.6], [1.8, -0.6], [1.98, -1.2], [1.8, -4.55], [-1.8, -4.55], [-1.98, -1.2]]), 0, 0.17, 0.06), 'armorA');
+ O(extrXY(poly([[-1.15, -1.2], [1.15, -1.2], [1.15, -2.9], [0.85, -3.3], [-0.85, -3.3], [-1.15, -2.9]]), 0.15, 0.31, 0.05), 'armorB');
+ O(tube([[-0.5, -2.0, 0.3], [-0.5, -2.0, 0.45], [0.5, -2.0, 0.45], [0.5, -2.0, 0.3]], 0.035, 5), 'joint');
+ for (let i = 0; i < 5; i++) O(cbox(1.9, 0.07, 0.13, 0.02), 'joint', xf(0, -3.72 - i * 0.16, 0.2, 0.5, 0, 0));
+ for (const x of [-1.56, 1.56]) O(cbox(0.2, 3.3, 0.14, 0.04), 'armorA', xf(x, -2.85, 0.24));
+ boltRow(P, 'joint', 7, [-1.6, 0, 0.85], [1.6, 0, 0.85], OB(0.17), 0.07, 0.06);
+ boltRow(P, 'joint', 8, [-1.6, 0, 4.32], [1.6, 0, 4.32], OB(0.17), 0.07, 0.06);
+ for (const x of [-2.1, 2.1]) boltRow(P, 'joint', 9, [x, 0, 0.5], [x * 0.895, 0, 4.6], OB(0), 0.075, 0.07);
+ boltRow(P, 'joint', 4, [-0.95, 0, 1.38], [0.95, 0, 1.38], OB(0.31), 0.05, 0.05);
+ boltRow(P, 'joint', 3, [-0.65, 0, 3.12], [0.65, 0, 3.12], OB(0.31), 0.05, 0.05);
+ // mid section
+ O(new THREE.BoxGeometry(3.5, 0.5, 0.05), 'armorB', xf(0, -5.62, 0.02), 0.85);
+ O(new THREE.PlaneGeometry(1.9, 1.9), 'decal', xf(0, -7.35, 0.012));
+ for (const x of [-1.5, 1.5]) O(cbox(0.18, 2.6, 0.12, 0.04), 'armorA', xf(x, -7.4, 0.05));
+ for (const x of [-1.62, 1.62]) O(new THREE.TorusGeometry(0.16, 0.045, 6, 12), 'joint', xf(x, -5.28, 0.04, PI / 2, 0, 0));
+ boltRow(P, 'joint', 8, [-1.72, 0, 5.22], [1.72, 0, 5.22], OB(0), 0.07, 0.06);
+ boltRow(P, 'joint', 7, [-1.55, 0, 8.85], [1.55, 0, 8.85], OB(0), 0.07, 0.06);
+ // boot section
+ O(extrXY(poly([[-0.95, -9.5], [0.95, -9.5], [0.95, -12.3], [0.72, -12.8], [-0.72, -12.8], [-0.95, -12.3]]), 0, 0.2, 0.07), 'armorB');
+ O(cbox(2.9, 0.24, 0.18, 0.04), 'armorB', xf(0, -9.42, 0.08));
+ O(cbox(2.5, 0.24, 0.18, 0.04), 'armorB', xf(0, -12.86, 0.08));
+ O(new THREE.BoxGeometry(1.7, 0.36, 0.04), 'armorA', xf(0, -11.0, 0.21), 0.8);
+ boltRow(P, 'joint', 4, [-0.75, 0, 9.75], [0.75, 0, 9.75], OB(0.2), 0.06, 0.06);
+ boltRow(P, 'joint', 4, [-0.72, 0, 12.2], [0.72, 0, 12.2], OB(0.2), 0.06, 0.06);
+ for (const x of [-1.5, 1.5]) boltRow(P, 'joint', 6, [x, 0, 9.75], [x * 0.94, 0, 12.6], OB(0), 0.07, 0.06);
+
+ // ---- round 2 (outer face): hinged hatches with latches, overlapping applique plates, clipped hard lines,
+ // ID plates, footsteps, marker lamps
+ for (const s of [1.55, 2.6]) { O(cbox(0.2, 0.3, 0.1, 0.02), 'joint', xf(-1.17, -s, 0.3)); O(cyl(0.035, 0.36, 6), 'joint', xf(-1.25, -s, 0.33)); }
+ O(cbox(0.1, 0.36, 0.08, 0.02), 'joint', xf(1.02, -2.4, 0.34)); O(cbox(0.22, 0.08, 0.06, 0.015), 'joint', xf(1.1, -2.4, 0.37));
+ // mid section: two overlapping applique plates (different tone, lifted edge = visible gap) + small hatch
+ O(extrXY(poly([[-1.36, -5.95], [-1.04, -5.95], [-1.04, -8.7], [-1.3, -8.7], [-1.42, -8.2]]), 0.03, 0.1, 0.03), 'armorB', xf(0, 0, 0, 0, 0.035, 0), 0.82);
+ O(extrXY(poly([[1.04, -6.1], [1.4, -6.1], [1.33, -8.75], [1.04, -8.75]]), 0.03, 0.1, 0.03), 'armorA', xf(0, 0, 0, 0, -0.03, 0), 1.12);
+ boltRow(P, 'joint', 6, [-1.2, 0, 6.1], [-1.2, 0, 8.55], OB(0.1), 0.045, 0.04);
+ boltRow(P, 'joint', 6, [1.2, 0, 6.25], [1.2, 0, 8.6], OB(0.1), 0.045, 0.04);
+ O(cbox(0.62, 0.46, 0.05, 0.015), 'armorB', xf(0.45, -8.62, 0.03), 0.9);
+ for (const x of [0.2, 0.7]) O(cbox(0.1, 0.08, 0.05, 0.01), 'joint', xf(x, -8.38, 0.06));
+ O(cbox(0.14, 0.06, 0.06, 0.01), 'joint', xf(0.45, -8.84, 0.06));
+ O(cbox(0.5, 0.3, 0.025, 0.006), 'armorY', xf(-0.5, -8.62, 0.015), 1.15); // ID plate
+ for (const x of [-0.71, -0.29]) for (const s of [8.51, 8.73]) P.add(bolt(0.018, 0.02), 'joint', OB(0.027).multiply(xf(x, 0, s)));
+ // two hard lines down the left margin, P-clips every metre, unions at the section seams
+ for (const [x, r] of [[-1.86, 0.04], [-1.76, 0.03]]) {
+ O(tube([[x - 0.1, -0.7, 0.2], [x, -1.3, 0.07], [x + 0.08, -4.6, 0.07], [x + 0.13, -7.0, 0.07], [x + 0.2, -9.0, 0.07], [x + 0.22, -9.35, -0.1]], r, 5, 36), x < -1.8 ? 'armorY' : 'joint');
+ O(hex(r * 1.8, 0.16), 'joint', xf(x + 0.085, -4.9, 0.07));
+ }
+ for (let s = 1.6; s < 9.1; s += 1.05) O(cbox(0.26, 0.07, 0.08, 0.012), 'joint', xf(-1.845 + 0.026 * s, -s, 0.06));
+ // footsteps / grab rungs up the right margin (human scale)
+ for (let s = 9.75; s < 12.7; s += 0.42) O(tube([[1.14, -s, 0.2], [1.14, -s, 0.33], [1.42, -s, 0.33], [1.42, -s, 0.2]].map(([a, b, c]) => [a - 0.0, b, c - 0.2]), 0.02, 4, 6), 'joint');
+ // marker lamps at the boot corners
+ for (const x of [-1.32, 1.32]) { O(cbox(0.2, 0.14, 0.1, 0.02), 'joint', xf(x, -12.98, 0.05)); O(new THREE.BoxGeometry(0.09, 0.05, 0.04), 'lampA', xf(x, -12.98, 0.11)); }
+ // drain scuppers under the louvres with weld-on lips
+ for (const x of [-0.6, 0, 0.6]) O(cbox(0.22, 0.05, 0.07, 0.01), 'joint', xf(x, -4.5, 0.2));
+
+ // ---- side frames: coordinates (dx out of the face, -s down the face, z)
+ for (const sx of [1, -1]) {
+ const F = (sx > 0 ? IDENT : MIRX).clone().multiply(xf(SH.hx, SH.yT, 0, 0, 0, -tiltX));
+ const S = (geo, key, m, tint) => P.add(geo, key, F.clone().multiply(m || IDENT), tint);
+ const SB = (dx) => F.clone().multiply(xf(dx, 0, 0, 0, 0, -PI / 2)); // bolt frame: [s, 0, z]
+ S(extrYZ(poly([[-0.9, -0.6], [1.75, -0.6], [1.95, -1.1], [1.95, -4.5], [-0.9, -4.5], [-1.05, -4.0], [-1.05, -1.1]]), 0, 0.15, 0.05), 'armorA');
+ S(cbox(0.1, 1.5, 1.15, 0.03), 'armorB', xf(0.2, -2.3, 0.45));
+ S(tube([[0.24, -1.9, 0.8], [0.38, -2.0, 0.8], [0.38, -2.6, 0.8], [0.24, -2.7, 0.8]], 0.03, 5), 'joint');
+ S(cbox(0.14, 3.6, 0.22, 0.03), 'armorA', xf(0.2, -2.6, -0.72));
+ S(cbox(0.14, 3.6, 0.22, 0.03), 'armorA', xf(0.2, -2.6, 1.72));
+ S(cbox(0.18, 0.22, 0.42, 0.03), 'joint', xf(0.08, -0.32, 1.35));
+ S(new THREE.BoxGeometry(0.06, 0.12, 0.26), 'lampA', xf(0.2, -0.32, 1.35));
+ boltRow(P, 'joint', 6, [0.8, 0, -0.75], [0.8, 0, 1.75], SB(0.15));
+ boltRow(P, 'joint', 6, [4.3, 0, -0.75], [4.3, 0, 1.75], SB(0.15));
+ boltRow(P, 'joint', 9, [0.4, 0, 2.02], [4.6, 0, 2.0], SB(0), 0.07, 0.06);
+ boltRow(P, 'joint', 9, [0.4, 0, -1.12], [4.6, 0, -1.1], SB(0), 0.07, 0.06);
+ // mid: external shock strut
+ S(lathe([[0, -7.7], [0.3, -7.7], [0.3, -7.5], [0.26, -7.45], [0.26, -5.5], [0.33, -5.45], [0.33, -5.15], [0, -5.15]], 16), 'cyl', xf(0.34, 0, -0.62));
+ S(lathe([[0.14, -8.9], [0.14, -7.65]], 14), 'chrome', xf(0.34, 0, -0.62));
+ for (const y of [-5.3, -8.85]) { S(cbox(0.6, 0.5, 0.55, 0.05), 'steel', xf(0.2, y, -0.62)); S(cylZ(0.1, 0.8, 8), 'joint', xf(0.34, y, -0.62)); }
+ boltRow(P, 'joint', 5, [5.2, 0, 0.1], [5.2, 0, 1.75], SB(0));
+ boltRow(P, 'joint', 5, [8.85, 0, 0.1], [8.85, 0, 1.75], SB(0));
+ // boot
+ S(extrYZ(poly([[-0.9, -9.5], [1.6, -9.5], [1.6, -12.7], [-0.9, -12.7]]), 0, 0.16, 0.05), 'armorA');
+ S(cbox(0.12, 0.25, 2.5, 0.03), 'armorA', xf(0.2, -10.0, 0.35));
+ S(cbox(0.12, 0.25, 2.5, 0.03), 'armorA', xf(0.2, -12.2, 0.35));
+ boltRow(P, 'joint', 6, [9.7, 0, -0.75], [9.7, 0, 1.45], SB(0.16), 0.07, 0.06);
+ boltRow(P, 'joint', 6, [12.5, 0, -0.75], [12.5, 0, 1.45], SB(0.16), 0.07, 0.06);
+ // heavy sagging hose loops hanging off the back corner
+ S(tube([[-0.25, -3.2, -1.3], [0.4, -4.0, -1.75], [0.95, -6.5, -1.95], [0.75, -8.8, -1.8], [-0.15, -9.8, -1.45]], 0.15, 8, 30), 'rubber');
+ S(tube([[-0.25, -1.9, -1.35], [0.75, -3.1, -2.05], [1.35, -7.0, -2.2], [1.0, -10.2, -1.95], [-0.15, -11.0, -1.5]], 0.11, 8, 30), 'rubber');
+ S(cbox(0.5, 0.5, 0.5, 0.05), 'joint', xf(-0.2, -2.6, -1.4));
+ S(cbox(0.5, 0.5, 0.5, 0.05), 'joint', xf(-0.2, -10.4, -1.42));
+ if (sx > 0) {
+ // access ladder
+ for (const z of [0.2, 0.92]) S(cbox(0.06, 7.9, 0.06, 0.01), 'joint', xf(0.34, -9.0, z));
+ for (let y = -5.2; y > -12.9; y -= 0.42) S(cylZ(0.03, 0.72, 6), 'joint', xf(0.34, y, 0.56));
+ for (const y of [-5.3, -7.6, -9.9, -12.5]) for (const z of [0.2, 0.92]) S(cbox(0.36, 0.06, 0.06, 0.01), 'joint', xf(0.17, y, z));
+ } else {
+ for (const z of [0.5, 0.75]) S(tube([[0.1, -0.2, z], [0.1, -4.6, z], [0.06, -5.0, z], [0.06, -9.3, z], [0.22, -9.7, z], [0.22, -12.6, z]], 0.05, 6), 'joint');
+ S(cbox(0.3, 0.8, 0.7, 0.03), 'armorB', xf(0.12, -6.6, 0.62));
+ S(cbox(0.28, 0.5, 0.5, 0.03), 'armorY', xf(0.26, -11.2, 0.62));
+ }
+ }
+ }
+ // ---- inner/back face (-Z): exposed structure, hoses, tanks
+ {
+ for (let y = -2.7, i = 0; y > -16.5; y -= 1.12, i++) P.add(cbox(2.74, 0.16, 0.42, 0.03), i % 4 === 2 ? 'rust' : 'steel', xf(0, y, -1.42));
+ P.mirX(cbox(0.22, 14.4, 0.34, 0.04), 'steel', xf(1.08, -9.4, -1.5));
+ const hz = [-0.82, -0.6, -0.36, -0.12, 0.14, 0.4, 0.66, 0.86];
+ hz.forEach((x, i) => {
+ const r = 0.05 + rnd() * 0.07, z = -1.72 - rnd() * 0.12, w = () => (rnd() - 0.5) * 0.16;
+ P.add(tube([[x * 0.7, -1.5, -1.0], [x, -2.6, z + 0.1], [x + w(), -5.2, z - 0.1 - rnd() * 0.2], [x + w(), -8.0, z], [x + w(), -11.0, z - rnd() * 0.25], [x + w(), -14.0, z], [x * 0.8, -15.9, z + 0.05], [x * 0.6, -16.6, -1.3]], r, 5, 28), i === 3 ? 'armorY' : 'rubber');
+ });
+ for (const y of [-3.9, -7.3, -10.6, -13.9]) P.add(cbox(2.1, 0.2, 0.16, 0.03), 'joint', xf(0, y, -1.86));
+ // accumulator bottles
+ const tank = lathe([[0, -1.25], [0.25, -1.25], [0.42, -1.05], [0.42, 1.05], [0.25, 1.25], [0.12, 1.3], [0.12, 1.42], [0, 1.42]], 18);
+ P.mirX(tank, 'armorY', xf(0.56, -5.6, -2.2));
+ P.mirX(cbox(0.95, 0.12, 0.5, 0.02), 'joint', xf(0.56, -4.9, -2.05));
+ P.mirX(cbox(0.95, 0.12, 0.5, 0.02), 'joint', xf(0.56, -6.3, -2.05));
+ P.add(cbox(1.5, 0.62, 0.5, 0.05), 'joint', xf(0, -12.2, -1.95));
+ for (const x of [-0.55, -0.2, 0.2, 0.55]) P.add(cyl(0.07, 0.3, 8), 'joint', xf(x, -11.8, -1.95));
+ P.add(cbox(1.1, 0.85, 0.36, 0.04), 'armorB', xf(0, -9.0, -2.0));
+ }
+ // ---- ankle: socket cup, octagonal boot skirt, stabiliser lugs
+ P.add(lathe([[1.3, -17.82], [1.56, -17.82], [1.78, -17.6], [1.78, -16.95], [1.5, -16.5], [0, -16.5]], 32), 'joint');
+ P.add(lathe([[2.02, -17.42], [2.3, -17.36], [1.86, -15.95], [1.6, -15.95]], 8, { flat: true, a0: PI / 8, a1: PI / 8 + PI * 2 }), 'armorA');
+ boltRing(P, 'joint', 16, 1.79, xf(0, -17.25, 0), 0.07, 0.06);
+ for (const [ax, ay, az] of A_ANK) {
+ const zs = Math.sign(az);
+ P.mirX(cbox(0.72, 0.9, 0.6, 0.06), 'steel', xf(ax, ay, az - zs * 0.3));
+ P.mirX(cylX(0.13, 0.9, 10), 'joint', xf(ax, ay, az));
+ }
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- part: foot + toes
+ // foot frame: origin = ankle ball centre, +Y up, +Z outward; ground plane at y = -ANKLE_H.
+ const TOE_ANG = [0, 1.16, -1.16, PI], TOE_SCALE = [1, 1, 1, 0.78];
+ const TOE_HINGE = [0, -0.95, 2.5];
+ const B_ANK = [[1.18, -0.78, 1.92], [1.25, -0.78, -1.85]];
+ function buildFoot() {
+ const P = new Part();
+ const GY = -CFG.ANKLE_H;
+ P.add(new THREE.SphereGeometry(1.2, 24, 14), 'joint');
+ // heavy pad (lathe) with a stepped rim
+ P.add(lathe([[0, GY], [2.35, GY], [2.75, GY + 0.3], [2.75, -1.25], [2.6, -1.1], [2.45, -1.1], [2.45, -0.92], [1.75, -0.86], [1.36, -0.58], [1.12, -0.46], [0, -0.46]], 44), 'steel');
+ // lower tier: 8 radial armour wedges
+ for (let i = 0; i < 8; i++) {
+ const a = i * PI / 4 + PI / 8;
+ P.add(extrXZ(sector(1.5, 2.56, -0.335, 0.335), -0.70, 0.22, 0.06, 8), i % 2 ? 'armorB' : 'armorA', xf(0, 0, 0, 0, a - PI / 2, 0));
+ const fr = xf(0, -0.70, 0, 0, a, 0);
+ P.add(bolt(0.07, 0.06), 'joint', fr.clone().multiply(xf(0.3, 0, 2.32)));
+ P.add(bolt(0.07, 0.06), 'joint', fr.clone().multiply(xf(-0.3, 0, 2.32)));
+ }
+ // upper tier: thick knuckle covers over each toe root
+ TOE_ANG.forEach((a, i) => {
+ const s = TOE_SCALE[i], fr = xf(0, 0, 0, 0, a, 0);
+ P.add(cbox(2.1 * s, 0.5, 1.5, 0.09), 'armorA', fr.clone().multiply(xf(0, -0.42, 2.05, 0.2, 0, 0)));
+ P.add(cbox(1.5 * s, 0.22, 1.0, 0.05), 'armorB', fr.clone().multiply(xf(0, -0.1, 1.9, 0.2, 0, 0)));
+ boltRow(P, 'joint', 4, [-0.9 * s, 0, 0.5], [0.9 * s, 0, 0.5], fr.clone().multiply(xf(0, -0.42, 2.05, 0.2, 0, 0)).multiply(xf(0, 0.25, 0)), 0.07, 0.06);
+ for (const x of [-0.98, 0.98]) P.add(cbox(0.3, 0.95, 1.1, 0.05), 'steel', fr.clone().multiply(xf(x * s, TOE_HINGE[1], TOE_HINGE[2] - 0.05)));
+ P.add(cylX(0.22, 2.35 * s, 12), 'joint', fr.clone().multiply(xf(0, TOE_HINGE[1], TOE_HINGE[2])));
+ });
+ P.add(lathe([[1.18, -0.6], [1.52, -0.72], [1.52, -0.5], [1.3, -0.38]], 32), 'joint');
+ boltRing(P, 'joint', 14, 1.4, xf(0, -0.44, 0, 0.5, 0, 0).multiply(xf(0, 0, 0, -0.5, 0, 0)), 0.06, 0.06);
+ // rim bolts
+ for (let i = 0; i < 32; i++) P.add(bolt(0.09, 0.08), 'joint', xf(0, 0, 0, 0, i / 32 * PI * 2, 0).multiply(xf(0, -1.5, 2.75, PI / 2, 0, 0)));
+ // ankle stabiliser lugs
+ for (const [bx, by, bz] of B_ANK) {
+ P.mirX(cbox(0.6, 0.5, 0.6, 0.05), 'steel', xf(bx, by - 0.14, bz));
+ P.mirX(cylX(0.12, 0.8, 10), 'joint', xf(bx, by, bz));
+ }
+ // sole cleats
+ for (let i = 0; i < 8; i++) P.add(cbox(0.4, 0.24, 1.5, 0.04), 'steel', xf(0, 0, 0, 0, i * PI / 4, 0).multiply(xf(0, GY - 0.02, 1.4)));
+ // ---- round 2: pleated ankle gaiter with clamp bands, guard hoops, heel spurs, scraper lips, caked mud
+ P.add(bellows(1.36, 1.64, -0.52, 0.46, 4, 28), 'rubber');
+ for (const y of [-0.5, 0.42]) P.add(lathe([[1.5, y - 0.05], [1.68, y - 0.05], [1.68, y + 0.05], [1.5, y + 0.05]], 28), 'joint');
+ for (let i = 0; i < 3; i++) P.add(cbox(0.16, 0.1, 0.12, 0.02), 'joint', xf(0, 0, 0, 0, 0.6 + i * 2.1, 0).multiply(xf(0, -0.5, 1.72)));
+ for (const sa of [1, -1]) {
+ // heel spurs between the side toes and the rear toe (fixed, worn)
+ const spur = extrYZ(poly([[2.2, -1.2], [2.9, -1.3], [3.45, GY + 0.02], [3.4, GY - 0.12], [2.2, GY + 0.05]]), -0.3, 0.3, 0.07);
+ P.add(spur, 'steel', xf(0, 0, 0, 0, sa * 2.2, 0));
+ // guard hoop / grab rail over the pad between the front and side toes
+ const pts = []; for (let i = 0; i <= 8; i++) { const a = sa * (0.34 + 0.5 * i / 8); pts.push([Math.sin(a) * 2.58, -0.92 + 0.42 * Math.sqrt(Math.sin(PI * i / 8)), Math.cos(a) * 2.58]); }
+ P.add(tube(pts, 0.035, 5, 16), 'joint');
+ // tie-down / towing lugs on the rim
+ for (const a of [0.58, 2.62]) { const m = xf(0, 0, 0, 0, sa * a, 0); P.add(cbox(0.5, 0.5, 0.2, 0.04), 'steel', m.clone().multiply(xf(0, -1.38, 2.8))); P.add(new THREE.TorusGeometry(0.16, 0.05, 5, 10), 'joint', m.clone().multiply(xf(0, -1.52, 2.93))); }
+ }
+ // scraper lips welded round the rim, bent and uneven
+ for (let i = 0; i < 12; i++) { const a = i / 12 * PI * 2 + 0.26; P.add(cbox(0.9, 0.12, 0.1, 0.02), 'steel', xf(0, 0, 0, 0, a, 0).multiply(xf(0, GY + 0.36, 2.79, 0.25 * Math.sin(i * 2.3), 0, 0.06 * Math.sin(i * 1.7)))); }
+ {
+ const mr = rng(771);
+ for (let i = 0; i < 18; i++) { // clods squeezed out round the pad
+ const a = mr() * PI * 2, rad = 2.7 + mr() * 0.45, sc = 0.13 + mr() * 0.22;
+ P.add(lump(sc * (1 + mr() * 0.9), sc * (0.5 + mr() * 0.4), sc * (1 + mr() * 0.9), i + 1, sc > 0.24 ? 2 : 1), 'mud', xf(Math.sin(a) * rad, GY + sc * 0.1, Math.cos(a) * rad, 0, mr() * 6, 0));
+ }
+ for (let i = 0; i < 9; i++) { // cakes sitting on the pad shoulder and wedges
+ const a = mr() * PI * 2, rad = 1.75 + mr() * 0.85, sc = 0.09 + mr() * 0.15;
+ P.add(lump(sc * (1 + mr()), sc * 0.5, sc * (1 + mr()), i + 31), 'mud', xf(Math.sin(a) * rad, (rad > 2.45 ? -1.12 : -0.74) + sc * 0.1, Math.cos(a) * rad, 0, mr() * 6, 0));
+ }
+ }
+ return P.build();
+ }
+ // toe frame: origin = knuckle hinge, +Z radially outward, hinge axis X; ground at y = gy
+ function buildToe() {
+ const P = new Part();
+ const gy = -(CFG.ANKLE_H + TOE_HINGE[1]);
+ const LZ = 2.75;
+ const taper = (geo, k) => {
+ const p = geo.attributes.position;
+ for (let i = 0; i < p.count; i++) { const z = Math.min(1, Math.max(0, p.getZ(i) / LZ)); p.setX(i, p.getX(i) * (1 + k * z * z)); }
+ geo.computeVertexNormals(); return geo;
+ };
+ // big curved blade: arched back, concave belly, chisel tip dug into the ground
+ const claw = poly([[-0.5, gy + 0.35], [-0.5, 0.25], [-0.2, 0.62], [0.5, 0.86], [1.3, 0.78], [2.05, 0.38], [2.55, -0.3], [LZ, gy - 0.12],
+ [2.3, gy - 0.12], [2.0, gy + 0.1], [1.45, gy + 0.2], [0.8, gy + 0.14], [0.25, gy + 0.0], [-0.2, gy]]);
+ P.add(taper(extrYZ(claw, -0.86, 0.86, 0.13), -0.42), 'claw');
+ // raised spine + cheek ribs on the blade
+ const spine = poly([[-0.1, 0.6], [0.5, 0.95], [1.32, 0.88], [2.1, 0.46], [2.5, -0.1], [2.36, -0.2], [1.98, 0.34], [1.28, 0.74], [0.5, 0.8], [-0.02, 0.52]]);
+ P.add(extrYZ(spine, -0.16, 0.16, 0.04), 'claw');
+ // armour cover over the root
+ const top = poly([[-0.42, 0.34], [-0.22, 0.72], [0.5, 0.98], [1.22, 0.92], [1.34, 0.8], [0.5, 0.86], [-0.14, 0.6], [-0.3, 0.3]]);
+ P.add(extrYZ(top, -0.7, 0.7, 0.04), 'armorA');
+ for (const x of [-0.55, 0.55]) for (const z of [0.2, 0.9]) P.add(bolt(0.07, 0.06), 'joint', xf(x, 0.86 + (z < 0.5 ? 0.02 : 0.1), z, 0.15, 0, 0));
+ // hardened tip cap
+ const tooth = poly([[2.18, -0.15], [2.6, -0.42], [LZ + 0.1, gy - 0.14], [2.2, gy - 0.14], [2.05, gy + 0.2]]);
+ P.add(taper(extrYZ(tooth, -0.9, 0.9, 0.05), -0.42), 'claw');
+ // knuckle barrel + end caps
+ P.add(cylX(0.5, 1.6, 18), 'joint');
+ P.mirX(cylX(0.32, 0.1, 12), 'joint', xf(0.85, 0, 0));
+ // little hydraulic toe actuator under the cover (static)
+ P.add(cyl(0.12, 0.9, 10), 'chrome', xf(0, 0.55, 0.55, PI / 2 - 0.3, 0, 0));
+ // ---- round 2: hard-facing weld ridges on the cheeks, wear-plate bolts, tooth retainer pin, caked mud
+ const hw = (z) => 0.86 * (1 - 0.42 * (z / LZ) * (z / LZ));
+ [[0.75, 0.84], [1.15, 0.8], [1.55, 0.64], [1.95, 0.43], [2.3, 0.05]].forEach(([z, top]) => {
+ const len = (top - gy) * 0.62, yc = (top + gy) / 2 + 0.05;
+ for (const sx of [1, -1]) P.add(cbox(0.07, len, 0.08, 0.02), 'claw', xf(sx * (hw(z) - 0.005), yc, z, 0.5, 0, 0));
+ });
+ for (const sx of [1, -1]) {
+ for (const [y, z] of [[0.3, 0.1], [0.42, 0.55], [0.36, 1.0], [-0.5, 0.1], [-0.55, 0.6]]) P.add(bolt(0.075, 0.07), 'joint', xf(sx * (hw(z) - 0.01), y, z, 0, 0, -sx * PI / 2));
+ P.add(cyl(0.11, 0.08, 10).rotateZ(PI / 2), 'joint', xf(sx * hw(2.42), -0.5, 2.42));
+ }
+ // ragged worn cutting edge segments along the tip
+ for (let i = 0; i < 4; i++) P.add(cbox(0.3, 0.2, 0.22, 0.04), 'claw', xf((i - 1.5) * 0.3, gy - 0.02, LZ - 0.06 + 0.05 * Math.sin(i * 2.1), 0.5 + 0.1 * Math.sin(i * 3.3), 0, 0));
+ P.add(lump(0.34, 0.2, 0.3, 5), 'mud', xf(0.62, gy + 0.03, 0.75, 0, 0.4, 0));
+ P.add(lump(0.3, 0.17, 0.36, 9), 'mud', xf(-0.6, gy + 0.03, 1.25, 0, 1.4, 0));
+ P.add(lump(0.22, 0.07, 0.28, 13), 'mud', xf(0.1, 0.9, 0.75, 0.1, 2.0, 0));
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- hydraulic cylinders
+ // body: clevis at origin, barrel along +Y. rod: eye at origin, rod along +Y (slides inside the barrel).
+ function buildCylBody(rb, rr, Lb) {
+ const P = new Part();
+ P.add(cylX(rb * 0.78, rb * 1.5, 14), 'cyl');
+ P.add(cbox(rb * 1.3, rb * 1.4, rb * 1.3, rb * 0.15), 'cyl', xf(0, rb * 1.0, 0));
+ P.add(lathe([[0, rb * 1.5], [rb * 1.08, rb * 1.5], [rb * 1.08, rb * 2.1], [rb, rb * 2.2], [rb, Lb - rb * 1.0], [rb * 1.14, Lb - rb * 0.9], [rb * 1.14, Lb - rb * 0.15], [rb, Lb], [rr * 1.3, Lb], [rr * 1.3, Lb + rb * 0.12], [0, Lb + rb * 0.12]], 22), 'cyl');
+ // mid clamp bands + hydraulic line
+ for (const k of [0.38, 0.7]) P.add(lathe([[rb, 0], [rb * 1.06, 0], [rb * 1.06, rb * 0.25], [rb, rb * 0.25]], 20), 'cyl', xf(0, Lb * k, 0));
+ P.add(cbox(rb * 0.7, rb * 0.6, rb * 0.5, 0.03), 'cyl', xf(0, rb * 2.8, rb * 1.05));
+ P.add(cbox(rb * 0.7, rb * 0.6, rb * 0.5, 0.03), 'cyl', xf(0, Lb - rb * 1.6, rb * 1.05));
+ P.add(tube([[0, rb * 2.8, rb * 1.25], [0, rb * 4, rb * 1.42], [0, Lb - rb * 2.8, rb * 1.42], [0, Lb - rb * 1.6, rb * 1.25]], rb * 0.13, 6), 'cyl');
+ // ---- round 2: hex gland nut with wiper seal, tie rods, line clips + unions, port elbows, grease nipples, data plate
+ P.add(hex(rb * 1.3, rb * 0.55), 'cyl', xf(0, Lb - rb * 0.78, 0), 0.72);
+ P.add(lathe([[rr * 1.05, Lb + rb * 0.1], [rr * 1.6, Lb + rb * 0.1], [rr * 1.45, Lb + rb * 0.34], [rr * 1.05, Lb + rb * 0.4]], 18), 'cyl', undefined, 0.35);
+ boltRing(P, 'cyl', 6, rb * 0.82, xf(0, Lb, 0), rb * 0.11, rb * 0.12);
+ for (let i = 0; i < 4; i++) { const a = PI / 4 + i * PI / 2; P.add(cyl(rb * 0.07, Lb - rb * 3.3, 5), 'cyl', xf(Math.sin(a) * rb * 1.09, (Lb + rb * 1.2) / 2, Math.cos(a) * rb * 1.09), 0.7); }
+ for (const k of [0.2, 0.54, 0.86]) P.add(lathe([[rb, 0], [rb * 1.12, 0], [rb * 1.12, rb * 0.16], [rb, rb * 0.16]], 12), 'cyl', xf(0, Lb * k, 0), 0.8);
+ for (const k of [0.3, 0.46, 0.62, 0.78]) P.add(cbox(rb * 0.5, rb * 0.16, rb * 0.36, 0.01), 'cyl', xf(0, Lb * k, rb * 1.36), 0.6);
+ P.add(hex(rb * 0.22, rb * 0.5), 'cyl', xf(0, Lb * 0.5, rb * 1.42), 0.6);
+ for (const y of [rb * 2.8, Lb - rb * 1.6]) { P.add(hex(rb * 0.2, rb * 0.3).rotateX(PI / 2), 'cyl', xf(0, y, rb * 1.28), 0.55); P.add(hex(rb * 0.16, rb * 0.5).rotateZ(-PI / 2), 'cyl', xf(rb * 0.3, y, rb * 1.1), 0.55); }
+ P.add(hex(rb * 0.09, rb * 0.22).rotateZ(-PI / 2), 'cyl', xf(rb * 0.74, 0, 0), 0.6);
+ P.add(cbox(rb * 0.7, rb * 0.5, 0.02, 0.005), 'cyl', xf(0, Lb * 0.3, -rb * 1.0), 1.25);
+ return P.build();
+ }
+ function buildCylRod(rr, Lr, boot = 0.5) {
+ const P = new Part();
+ P.add(cylX(rr * 1.6, rr * 3.0, 14), 'joint');
+ P.add(lathe([[0, rr * 1.2], [rr * 1.35, rr * 1.2], [rr * 1.35, rr * 3.0], [rr, rr * 3.4]], 16), 'joint');
+ P.add(lathe([[rr, rr * 3.2], [rr, Lr], [0, Lr]], 18), 'chrome');
+ // round 2: pleated dust boot on the eye end, clamp rings, lock nut, grease nipple on the eye
+ P.add(bellows(rr * 1.3, rr * 1.95, rr * 3.5, rr * 3.5 + boot, Math.max(3, Math.round(boot / (rr * 0.7))), 14), 'joint');
+ for (const y of [rr * 3.4, rr * 3.5 + boot]) P.add(lathe([[rr * 1.2, y - rr * 0.18], [rr * 1.75, y - rr * 0.18], [rr * 1.75, y + rr * 0.18], [rr * 1.2, y + rr * 0.18]], 14), 'joint');
+ P.add(hex(rr * 1.7, rr * 0.8), 'joint', xf(0, rr * 2.4, 0));
+ P.mirX(hex(rr * 0.9, rr * 0.4).rotateZ(-PI / 2), 'joint', xf(rr * 1.5, 0, 0));
+ return P.build();
+ }
+
+ // ---------------------------------------------------------------- kinematics
+ const fs = {}, hipA = [0, 0, 0], footA = [0, 0, 0], kneeA = [0, 0, 0], UP = [0, 1, 0], ONE = new THREE.Vector3(1, 1, 1);
+ const vF = new THREE.Vector3(), vKp = new THREE.Vector3(), vH = new THREE.Vector3(), vK = new THREE.Vector3();
+ const X = new THREE.Vector3(), Y = new THREE.Vector3(), Z = new THREE.Vector3();
+ const eF = new THREE.Euler(), qF = new THREE.Quaternion();
+ const K = { yoke: new THREE.Matrix4(), thigh: new THREE.Matrix4(), shin: new THREE.Matrix4(), foot: new THREE.Matrix4(), swing: 0, plantAge: 0 };
+ function solveLeg(L, t, invW, qInvW) {
+ gait.footState(L.i, t, fs);
+ vF.set(fs.x, fs.y, fs.z).applyMatrix4(invW);
+ vKp.set(L.hip[0], L.hip[1], L.hip[2]);
+ const ox = vF.x - vKp.x, oz = vF.z - vKp.z, ol = Math.hypot(ox, oz) || 1;
+ const th = Math.atan2(ox, oz);
+ vH.set(vKp.x + E_TRUN * ox / ol, vKp.y, vKp.z + E_TRUN * oz / ol);
+ hipA[0] = vH.x; hipA[1] = vH.y; hipA[2] = vH.z; footA[0] = vF.x; footA[1] = vF.y; footA[2] = vF.z;
+ gait.solveKnee(hipA, footA, UP, LT, LS, kneeA);
+ vK.set(kneeA[0], kneeA[1], kneeA[2]);
+ X.set(Math.cos(th), 0, -Math.sin(th));
+ K.yoke.makeRotationY(th).setPosition(vKp);
+ Y.copy(vH).sub(vK).normalize(); Z.crossVectors(X, Y); K.thigh.makeBasis(X, Y, Z).setPosition(vH);
+ Y.copy(vK).sub(vF).normalize(); Z.crossVectors(X, Y); K.shin.makeBasis(X, Y, Z).setPosition(vK);
+ // foot: flat in WORLD space (cancel walker roll/pitch), fixed outward yaw, pitches in swing
+ eF.set(0, L.side > 0 ? 0 : PI, -fs.pitch, 'ZYX');
+ qF.setFromEuler(eF).premultiply(qInvW);
+ K.foot.compose(vF, qF, ONE);
+ K.swing = fs.swing; K.plantAge = fs.plantAge;
+ return K;
+ }
+
+ // cylinder definitions: anchors given for the +x side; mirrored copies are generated
+ const CYL = [
+ { name: 'lift', a: ['yoke', A_LIFT], b: ['thigh', B_LIFT], rb: 0.43, rr: 0.25 },
+ { name: 'knee', a: ['thigh', A_KNEE], b: ['shin', B_KNEE], rb: 0.5, rr: 0.28 },
+ { name: 'ankO', a: ['shin', A_ANK[0]], b: ['foot', B_ANK[0]], rb: 0.23, rr: 0.125 },
+ { name: 'ankI', a: ['shin', A_ANK[1]], b: ['foot', B_ANK[1]], rb: 0.23, rr: 0.125 },
+ ];
+ for (const c of CYL) { c.pa = new THREE.Vector3(...c.a[1]); c.pb = new THREE.Vector3(...c.b[1]); c.min = 1e9; c.max = 0; }
+ const pA = new THREE.Vector3(), pB = new THREE.Vector3();
+ // sample one gait cycle to size barrels / rods so they never bottom out or pull apart
+ {
+ const pose = {}, W = new THREE.Matrix4(), inv = new THREE.Matrix4(), q = new THREE.Quaternion(), qi = new THREE.Quaternion(), e = new THREE.Euler(), p = new THREE.Vector3();
+ for (let n = 0; n < 240; n++) {
+ const t = n / 240 * gait.GAIT.T;
+ gait.bodyPose(t, pose);
+ e.set(pose.roll, pose.yaw, pose.pitch); q.setFromEuler(e); qi.copy(q).invert();
+ W.compose(p.set(pose.x, pose.y, pose.z), q, ONE); inv.copy(W).invert();
+ for (const L of gait.LEGS) {
+ solveLeg(L, t, inv, qi);
+ for (const c of CYL) for (const sx of [1, -1]) {
+ pA.copy(c.pa); pA.x *= sx; pA.applyMatrix4(K[c.a[0]]);
+ pB.copy(c.pb); pB.x *= sx; pB.applyMatrix4(K[c.b[0]]);
+ const d = pA.distanceTo(pB); c.min = Math.min(c.min, d); c.max = Math.max(c.max, d);
+ }
+ }
+ }
+ // ankle pairs share one geometry
+ const aMin = Math.min(CYL[2].min, CYL[3].min), aMax = Math.max(CYL[2].max, CYL[3].max);
+ CYL[2].min = CYL[3].min = aMin; CYL[2].max = CYL[3].max = aMax;
+ for (const c of CYL) {
+ c.Lr = c.min - 0.12;
+ c.Lb = Math.max(0.8 * c.min, c.max - c.Lr + 0.35);
+ }
+ }
+
+ // ---------------------------------------------------------------- instanced meshes
+ const allMeshes = [];
+ function instantiate(geos, count, variantOf, { shadow = true } = {}) {
+ const list = [];
+ for (const key of Object.keys(geos)) {
+ const geo = geos[key];
+ const im = new THREE.InstancedMesh(geo, M(key, variantOf(key)), count);
+ im.frustumCulled = false;
+ const small = key === 'decal' || key === 'lampA' || key === 'hazard' || key === 'dark' || key === 'mud';
+ im.castShadow = shadow && !small; im.receiveShadow = key !== 'lampA';
+ im.name = 'legs:' + key;
+ g.add(im); list.push(im); allMeshes.push(im);
+ }
+ return list;
+ }
+ const setAll = (list, i, m) => { for (let k = 0; k < list.length; k++) list[k].setMatrixAt(i, m); };
+
+ const hipBase = instantiate(buildHipBase(), N, () => '');
+ const yoke = instantiate(buildYoke(), N, () => '');
+ const thigh = instantiate(buildThigh(), N, () => 'thigh');
+ const shin = instantiate(buildShin(), N, (k) => (k === 'armorA' || k === 'armorB' || k === 'steel' || k === 'joint') ? 'boot' : 'shin');
+ const foot = instantiate(buildFoot(), N, () => 'foot');
+ const toe = instantiate(buildToe(), N * 4, () => 'toe');
+ const cylMeshes = [];
+ {
+ const done = new Map();
+ for (const c of CYL) {
+ const gk = c.name.startsWith('ank') ? 'ank' : c.name;
+ if (!done.has(gk)) {
+ const count = gk === 'ank' ? N * 4 : N * 2;
+ if (gk !== 'ank') GREASE['cyl' + gk] = { a: [c.Lb, 0, c.rb * 1.7, 0.95], b: [c.Lb * 0.5, 0, c.rb * 1.3, 0.5], dir: [-1, 0] };
+ const gap = c.min - c.Lb;
+ done.set(gk, { body: instantiate(buildCylBody(c.rb, c.rr, c.Lb), count, () => gk === 'ank' ? '' : 'cyl' + gk), rod: instantiate(buildCylRod(c.rr, c.Lr, Math.max(0.2, Math.min(gap * 0.5, c.rr * 4))), count, () => ''), n: 0 });
+ }
+ c.inst = done.get(gk);
+ c.base = c.inst.n; c.inst.n += N * 2;
+ }
+ for (const v of done.values()) cylMeshes.push(v);
+ }
+
+ // ---------------------------------------------------------------- dynamic hoses (cubic bezier, GPU-evaluated)
+ // [partA, posA, dirA, partB, posB, dirB, length, radius]; +x side only where mirrored = true
+ const HOSES = [];
+ for (const [x, r] of [[-0.48, 0.1], [-0.17, 0.13], [0.16, 0.09], [0.46, 0.12]])
+ HOSES.push(['thigh', [x, -9.35, -0.55], [0, -0.55, -0.85], 'shin', [x * 1.7, -3.7, -1.5], [0, 0.35, -1], 6.6 + Math.abs(x) * 0.8, r]);
+ for (const sx of [1, -1]) {
+ HOSES.push(['hip', [sx * 2.0, -0.3, -0.4], [sx * 0.55, -0.35, 1], 'thigh', [sx * 2.2, -3.1, -0.85], [sx * 0.45, 0.1, -1], 7.4, 0.12]);
+ HOSES.push(['shin', [sx * 0.78, -15.7, -1.6], [0, -0.45, -1], 'foot', [sx * 0.95, -0.66, -2.25], [0, 1, -0.35], 4.6, 0.1]);
+ }
+ const NH = HOSES.length;
+ const hose = (() => {
+ const SEG = 22, RAD = 7, pos = [], idx = [];
+ for (let i = 0; i <= SEG; i++) for (let j = 0; j < RAD; j++) { const a = j / RAD * PI * 2; pos.push(Math.cos(a), i / SEG, Math.sin(a)); }
+ for (let i = 0; i < SEG; i++) for (let j = 0; j < RAD; j++) {
+ const a = i * RAD + j, b = i * RAD + (j + 1) % RAD, c = a + RAD, d = b + RAD;
+ idx.push(a, c, b, b, c, d);
+ }
+ const ig = new THREE.InstancedBufferGeometry();
+ ig.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
+ ig.setAttribute('normal', new THREE.Float32BufferAttribute(pos, 3));
+ ig.setIndex(idx);
+ const n = N * NH, mk = (k) => { const a = new THREE.InstancedBufferAttribute(new Float32Array(n * k), k); a.setUsage(THREE.DynamicDrawUsage); return a; };
+ const at = { iC0: mk(3), iC1: mk(3), iC2: mk(3), iC3: mk(3), iX: mk(3), iR: mk(1) };
+ for (const k in at) ig.setAttribute(k, at[k]);
+ ig.instanceCount = n;
+ const mat = new THREE.MeshStandardMaterial({ color: 0x0b0c0d, roughness: 0.5, metalness: 0.0 });
+ mat.onBeforeCompile = (sh) => {
+ sh.vertexShader = sh.vertexShader
+ .replace('#include <common>', `#include <common>
+attribute vec3 iC0, iC1, iC2, iC3, iX; attribute float iR;
+vec3 hosePos, hoseNrm;
+void hoseEval(vec3 p) {
+ float t = p.y, u = 1.0 - t;
+ vec3 c = u*u*u*iC0 + 3.0*u*u*t*iC1 + 3.0*u*t*t*iC2 + t*t*t*iC3;
+ vec3 d = 3.0*u*u*(iC1 - iC0) + 6.0*u*t*(iC2 - iC1) + 3.0*t*t*(iC3 - iC2);
+ vec3 T = normalize(d);
+ vec3 Nn = normalize(cross(T, iX)); vec3 B = cross(T, Nn);
+ hoseNrm = Nn * p.x + B * p.z;
+ // corrugation rings near the fittings
+ float e = min(t, 1.0 - t);
+ hosePos = c + hoseNrm * iR * (1.0 + 0.35 * smoothstep(0.06, 0.0, e));
+}`)
+ .replace('#include <beginnormal_vertex>', 'hoseEval(position);\nvec3 objectNormal = hoseNrm;')
+ .replace('#include <begin_vertex>', 'vec3 transformed = hosePos;');
+ };
+ mat.customProgramCacheKey = () => 'legsHose';
+ const mesh = new THREE.Mesh(ig, mat);
+ mesh.frustumCulled = false; mesh.castShadow = false; mesh.receiveShadow = true; mesh.name = 'legs:hoses';
+ g.add(mesh);
+ return { at, mesh };
+ })();
+ const hipM = gait.LEGS.map((L) => new THREE.Matrix4().makeRotationY(L.side > 0 ? 0 : PI).setPosition(L.hip[0], L.hip[1], L.hip[2]));
+ const hA = new THREE.Vector3(), hB = new THREE.Vector3(), hDA = new THREE.Vector3(), hDB = new THREE.Vector3();
+ function updateHoses(i) {
+ const at = hose.at;
+ for (let h = 0; h < NH; h++) {
+ const H = HOSES[h], o = (i * NH + h) * 3;
+ const MA = H[0] === 'hip' ? hipM[i] : K[H[0]], MB = K[H[3]];
+ hA.set(H[1][0], H[1][1], H[1][2]).applyMatrix4(MA); hB.set(H[4][0], H[4][1], H[4][2]).applyMatrix4(MB);
+ hDA.set(H[2][0], H[2][1], H[2][2]).transformDirection(MA); hDB.set(H[5][0], H[5][1], H[5][2]).transformDirection(MB);
+ const d = hA.distanceTo(hB), L = H[6], k = L * 0.3, sag = Math.max(0, L - d) * 0.7 + 0.15;
+ at.iC0.array[o] = hA.x; at.iC0.array[o + 1] = hA.y; at.iC0.array[o + 2] = hA.z;
+ at.iC1.array[o] = hA.x + hDA.x * k; at.iC1.array[o + 1] = hA.y + hDA.y * k - sag; at.iC1.array[o + 2] = hA.z + hDA.z * k;
+ at.iC2.array[o] = hB.x + hDB.x * k; at.iC2.array[o + 1] = hB.y + hDB.y * k - sag; at.iC2.array[o + 2] = hB.z + hDB.z * k;
+ at.iC3.array[o] = hB.x; at.iC3.array[o + 1] = hB.y; at.iC3.array[o + 2] = hB.z;
+ // frame reference: the leg-plane normal (hoses stay near that plane), nudged for the side loops
+ const e = K.shin.elements;
+ at.iX.array[o] = e[0] + 0.01; at.iX.array[o + 1] = e[1] + (H[0] === 'hip' ? 0.8 : 0.02); at.iX.array[o + 2] = e[2];
+ at.iR.array[i * NH + h] = H[7];
+ }
+ }
+
+ // per-leg tint variation on painted armour (so the legs are not clones)
+ {
+ const col = new THREE.Color();
+ const tint = Array.from({ length: N }, () => [0.86 + rnd() * 0.2, (rnd() - 0.5) * 0.06]);
+ for (const im of allMeshes) {
+ if (!/armor|cyl/.test(im.name)) continue;
+ const per = im.count / N;
+ for (let i = 0; i < im.count; i++) {
+ const [b, w] = tint[Math.floor(i / per) % N];
+ col.setRGB(b * (1 + w), b, b * (1 - w)); im.setColorAt(i, col);
+ }
+ im.instanceColor.needsUpdate = true;
+ }
+ }
+
+ // static hip bases
+ {
+ const m = new THREE.Matrix4();
+ for (const L of gait.LEGS) { m.makeRotationY(L.side > 0 ? 0 : PI).setPosition(L.hip[0], L.hip[1], L.hip[2]); setAll(hipBase, L.i, m); }
+ for (const im of hipBase) im.instanceMatrix.needsUpdate = true;
+ }
+
+ // toe local matrices (relative to the foot)
+ const toeRest = TOE_ANG.map((a, i) => xf(0, 0, 0, 0, a, 0).multiply(xf(TOE_HINGE[0], TOE_HINGE[1], TOE_HINGE[2])));
+ const toeScale = TOE_SCALE.map((s) => new THREE.Matrix4().makeScale(s, s, s));
+ const mT = new THREE.Matrix4(), mR = new THREE.Matrix4(), mC = new THREE.Matrix4();
+ const invW = new THREE.Matrix4(), qInvW = new THREE.Quaternion();
+ const cX = new THREE.Vector3(), cY = new THREE.Vector3(), cZ = new THREE.Vector3(), aX = new THREE.Vector3();
+
+ function update(t) {
+ invW.copy(walker.matrixWorld).invert();
+ qInvW.copy(walker.quaternion).invert();
+ for (const L of gait.LEGS) {
+ const i = L.i;
+ solveLeg(L, t, invW, qInvW);
+ setAll(yoke, i, K.yoke); setAll(thigh, i, K.thigh); setAll(shin, i, K.shin); setAll(foot, i, K.foot);
+ // toes: droop while the foot is in the air, flat (and a touch splayed) when planted
+ const s = K.swing;
+ const droop = s > 0 ? 0.26 * Math.pow(Math.sin(PI * Math.min(1, s * 1.08)), 0.8) : 0;
+ const settle = s > 0 ? 0 : -0.035 * Math.exp(-K.plantAge * 5.0) * Math.cos(K.plantAge * 9.0);
+ for (let k = 0; k < 4; k++) {
+ mR.makeRotationX((droop + settle) * (k === 3 ? 0.7 : 1));
+ mT.multiplyMatrices(K.foot, toeRest[k]).multiply(mR).multiply(toeScale[k]);
+ setAll(toe, i * 4 + k, mT);
+ }
+ // hydraulic cylinders
+ for (const c of CYL) {
+ for (let si = 0; si < 2; si++) {
+ const sx = si ? -1 : 1;
+ pA.copy(c.pa); pA.x *= sx; pA.applyMatrix4(K[c.a[0]]);
+ pB.copy(c.pb); pB.x *= sx; pB.applyMatrix4(K[c.b[0]]);
+ cY.copy(pB).sub(pA).normalize();
+ aX.setFromMatrixColumn(K[c.a[0]], 0);
+ cX.copy(aX).addScaledVector(cY, -aX.dot(cY)).normalize();
+ cZ.crossVectors(cX, cY);
+ mC.makeBasis(cX, cY, cZ).setPosition(pA);
+ const idx = c.base + i * 2 + si;
+ setAll(c.inst.body, idx, mC);
+ cY.negate(); cZ.negate();
+ mC.makeBasis(cX, cY, cZ).setPosition(pB);
+ setAll(c.inst.rod, idx, mC);
+ }
+ }
+ updateHoses(i);
+ }
+ for (const k in hose.at) hose.at[k].needsUpdate = true;
+ for (const list of [yoke, thigh, shin, foot, toe]) for (const im of list) im.instanceMatrix.needsUpdate = true;
+ for (const c of cylMeshes) { for (const im of c.body) im.instanceMatrix.needsUpdate = true; for (const im of c.rod) im.instanceMatrix.needsUpdate = true; }
+ }
+
+ let tris = 0;
+ for (const im of allMeshes) tris += im.geometry.attributes.position.count / 3 * im.count;
+ if (ctx.Q && ctx.Q.get('legsdbg')) console.warn('[legs] per-mesh tris: ' + allMeshes.map((im) => im.name.slice(5) + ':' + Math.round(im.geometry.attributes.position.count / 3) + 'x' + im.count).join(' '));
+ (ctx.Q && ctx.Q.get('legsdbg') ? console.warn : console.info)(`[legs] ${allMeshes.length} instanced meshes, ${Math.round(tris)} tris, build ${Math.round(performance.now() - tBuild0)} ms (plate atlas ${Math.round(tPlate1 - tPlate0)} ms), cylinders: ` + CYL.map((c) => `${c.name} ${c.min.toFixed(2)}..${c.max.toFixed(2)}`).join(', '));
+ update(0);
+ return { update, group: g, stats: { meshes: allMeshes.length, tris } };
+}
diff --git a/src/post.js b/src/post.js
new file mode 100644
index 0000000..221dc27
--- /dev/null
+++ b/src/post.js
@@ -0,0 +1,430 @@
+// Post chain: scene (HDR, MSAA, depth) -> height fog + sky -> DOF -> bloom -> grade/grain.
+import * as THREE from 'three';
+import { LOOK, SKY_GLSL } from './look.js';
+
+const VERT = /* glsl */`
+varying vec2 vUv;
+void main() { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }
+`;
+
+const FOG_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv;
+uniform sampler2D tColor; uniform sampler2D tDepth; uniform sampler2D tAO; uniform float uAO;
+uniform mat4 uInvProj, uCamWorld;
+uniform vec3 uCamPos, uFogCol, uMistCol;
+uniform float uTime, uDensity, uMist, uMistH, uMistNoise, uFrame;
+uniform vec4 uGlowPos[10]; // xyz world, w radius falloff scale
+uniform vec3 uGlowCol[10];
+uniform int uGlowN;
+${SKY_GLSL}
+float hash13(vec3 p){ p = fract(p * 0.1031); p += dot(p, p.zyx + 31.32); return fract((p.x + p.y) * p.z); }
+float vnoise(vec3 x){
+ vec3 i = floor(x), f = fract(x); f = f*f*(3.0-2.0*f);
+ return mix(mix(mix(hash13(i), hash13(i+vec3(1,0,0)), f.x), mix(hash13(i+vec3(0,1,0)), hash13(i+vec3(1,1,0)), f.x), f.y),
+ mix(mix(hash13(i+vec3(0,0,1)), hash13(i+vec3(1,0,1)), f.x), mix(hash13(i+vec3(0,1,1)), hash13(i+vec3(1,1,1)), f.x), f.y), f.z);
+}
+float fbm(vec3 p){ float s = 0.0, a = 0.5; for(int i=0;i<4;i++){ s += a*vnoise(p); p = p*2.02 + 7.1; a *= 0.5; } return s; }
+float ign(vec2 p){ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
+void main(){
+ float d = texture2D(tDepth, vUv).r;
+ vec4 clip = vec4(vUv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0);
+ vec4 vp = uInvProj * clip; vp /= vp.w;
+ vec3 wp = (uCamWorld * vp).xyz;
+ vec3 rd = normalize(wp - uCamPos);
+ bool sky = d >= 0.99999;
+ float dist = sky ? 6000.0 : length(wp - uCamPos);
+ vec3 col = sky ? skyColor(rd) : texture2D(tColor, vUv).rgb;
+ if (!sky) {
+ // ambient obscurance (spare bright emitters)
+ float aov = texture2D(tAO, vUv).r;
+ float em = smoothstep(0.5, 1.6, max(col.r, max(col.g, col.b)));
+ col *= mix(1.0, mix(aov, 1.0, em), uAO);
+ }
+ if (sky) {
+ // overcast dusk: two drifting cloud layers, darker bellies higher up
+ vec2 sp = rd.xz / (abs(rd.y) + 0.22);
+ float c1 = fbm(vec3(sp * 0.9 + vec2(uTime * 0.003, 0.0), 0.3));
+ float c2 = fbm(vec3(sp * 2.7 - vec2(uTime * 0.006, uTime * 0.002), 1.7));
+ col *= 0.80 + 0.42 * (c1 * 0.65 + c2 * 0.35);
+ col = mix(col, col * vec3(0.76, 0.81, 0.90), smoothstep(0.52, 0.78, c1) * 0.55 * smoothstep(0.04, 0.45, rd.y));
+ }
+ // --- analytic fog: homogeneous + exponential ground layer ---
+ float od = uDensity * min(dist, 2500.0);
+ float k = rd.y / uMistH;
+ float base = uMist * exp(-max(uCamPos.y, 0.0) / uMistH);
+ float lay = abs(k) < 1e-4 ? base * dist : base * (1.0 - exp(-k * dist)) / k;
+ // keep the near field clear: ground mist only builds up beyond the first tens of metres
+ float nearClear = smoothstep(6.0, 75.0, dist);
+ // drifting fog banks: the layer is patchy over hundreds of metres
+ vec3 pe = uCamPos + rd * min(dist, 420.0);
+ float bank = fbm(vec3(pe.x * 0.011 - uTime * 0.012, 0.37, pe.z * 0.011 + uTime * 0.006));
+ lay = max(lay, 0.0) * nearClear * (0.5 + 1.1 * bank);
+ od += lay;
+ float odHomog = od - lay;
+ // --- wispy modulation, short raymarch through the mist layer ---
+ float marchEnd = min(dist, 220.0);
+ const int STEPS = 20;
+ float jit = ign(gl_FragCoord.xy + uFrame * 5.588);
+ float stepLen = marchEnd / float(STEPS);
+ float nod = 0.0;
+ for (int i = 0; i < STEPS; i++) {
+ float s = (float(i) + jit) * stepLen;
+ vec3 p = uCamPos + rd * s;
+ // tongues of mist reach higher in places
+ float tall = vnoise(vec3(p.x * 0.018 - uTime * 0.02, 1.3, p.z * 0.018));
+ float hd = exp(-max(p.y, 0.0) / (uMistH * (1.0 + 1.9 * tall * tall)));
+ if (hd < 0.02) continue;
+ float n = fbm(vec3(p.x * 0.035 - uTime * 0.045, p.y * 0.11 + uTime * 0.01, p.z * 0.035 + uTime * 0.02)) * 0.72
+ + vnoise(vec3(p.x * 0.13 - uTime * 0.09, p.y * 0.3, p.z * 0.13 + uTime * 0.05)) * 0.28;
+ nod += uMist * hd * (n - 0.47) * 2.4 * stepLen;
+ }
+ od = max(od + nod * uMistNoise * nearClear, 0.0);
+ float T = exp(-od);
+ // fog colour: what the sky looks like near the horizon in this direction, a bit brighter low down
+ vec3 fd = normalize(vec3(rd.x, max(rd.y, 0.0) * 0.35 + 0.03, rd.z));
+ vec3 fogc = mix(uFogCol, skyColor(fd), 0.55);
+ // where the ground mist dominates the optical depth, the fog turns paler and greyer
+ float mw = clamp((od - odHomog) / max(od, 1e-4), 0.0, 1.0);
+ fogc = mix(fogc, uMistCol, mw * 0.85);
+ col = col * T + fogc * (1.0 - T);
+ // --- warm volumetric halos around light clusters (analytic 1/r^2 line integral) ---
+ vec3 glow = vec3(0.0);
+ for (int i = 0; i < 10; i++) {
+ if (i >= uGlowN) break;
+ vec3 L = uGlowPos[i].xyz - uCamPos;
+ float b = dot(L, rd);
+ float h = sqrt(max(dot(L, L) - b * b, 0.0)) + uGlowPos[i].w;
+ float I = (atan((dist - b) / h) + atan(b / h)) / h;
+ float fade = exp(-uDensity * 1.5 * max(b, 0.0));
+ glow += uGlowCol[i] * I * fade;
+ }
+ col += glow * 0.07;
+ gl_FragColor = vec4(col, T);
+}
+`;
+
+// Scalable ambient obscurance from the depth buffer (McGuire SAO estimator)
+const AO_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv;
+uniform sampler2D tDepth; uniform mat4 uInvProj; uniform vec2 uRes; uniform float uRadius, uProjScale, uFrame;
+vec3 viewPos(vec2 uv){ float d = texture2D(tDepth, uv).r; vec4 c = vec4(uv * 2.0 - 1.0, d * 2.0 - 1.0, 1.0); vec4 v = uInvProj * c; return v.xyz / v.w; }
+float ign(vec2 p){ return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); }
+void main(){
+ float d = texture2D(tDepth, vUv).r;
+ if (d >= 0.99999) { gl_FragColor = vec4(1.0); return; }
+ vec2 px = 1.0 / uRes;
+ vec3 p = viewPos(vUv);
+ vec3 pr = viewPos(vUv + vec2(px.x, 0.0)), pl = viewPos(vUv - vec2(px.x, 0.0));
+ vec3 pu = viewPos(vUv + vec2(0.0, px.y)), pd = viewPos(vUv - vec2(0.0, px.y));
+ vec3 dx = abs(pr.z - p.z) < abs(p.z - pl.z) ? pr - p : p - pl;
+ vec3 dy = abs(pu.z - p.z) < abs(p.z - pd.z) ? pu - p : p - pd;
+ vec3 n = normalize(cross(dx, dy));
+ float ao = 0.0;
+ // two scales: wide (structures) and tight (creases)
+ for (int s = 0; s < 2; s++) {
+ float radius = s == 0 ? uRadius : uRadius * 0.28;
+ float rpx = min(radius * uProjScale / max(-p.z, 0.1), 140.0); // radius in pixels
+ if (rpx < 1.5) { continue; }
+ float r2 = radius * radius;
+ float rot = ign(gl_FragCoord.xy + uFrame * 3.71 + float(s) * 17.0) * 6.2831853;
+ float sum = 0.0;
+ const int N = 9;
+ for (int i = 0; i < N; i++) {
+ float a = (float(i) + 0.5) / float(N);
+ float ang = a * 6.2831853 * 2.6 + rot;
+ vec2 off = vec2(cos(ang), sin(ang)) * a * rpx * px;
+ vec3 v = viewPos(vUv + off) - p;
+ float vv = dot(v, v), vn = dot(v, n);
+ float f = max(r2 - vv, 0.0);
+ sum += f * f * f * max((vn - 0.012 * (-p.z) * 0.02 - 0.015) / (0.01 + vv), 0.0);
+ }
+ ao += (5.0 / (r2 * r2 * r2)) * sum / float(N) * (s == 0 ? 1.0 : 0.45);
+ }
+ gl_FragColor = vec4(vec3(clamp(1.0 - ao * 1.15, 0.0, 1.0)), 1.0);
+}
+`;
+const AOBLUR_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv; uniform sampler2D tAO; uniform sampler2D tDepth; uniform vec2 uRes; uniform float uNear, uFar;
+float lin(float d){ float z = d * 2.0 - 1.0; return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
+void main(){
+ float zc = lin(texture2D(tDepth, vUv).r);
+ float acc = 0.0, w = 0.0;
+ for (int y = -2; y <= 2; y++) for (int x = -2; x <= 2; x++) {
+ vec2 uv = vUv + vec2(float(x), float(y)) * 1.5 / uRes;
+ float z = lin(texture2D(tDepth, uv).r);
+ float ww = max(0.0, 1.0 - abs(z - zc) / (0.04 * zc + 0.05));
+ acc += texture2D(tAO, uv).r * ww; w += ww;
+ }
+ gl_FragColor = vec4(vec3(w > 0.0 ? acc / w : 1.0), 1.0);
+}
+`;
+
+const DOF_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv;
+uniform sampler2D tColor; uniform sampler2D tDepth;
+uniform vec2 uRes; uniform float uNear, uFar, uFocus, uAperture, uMaxBlur;
+float linDepth(float d){ float z = d * 2.0 - 1.0; return 2.0 * uNear * uFar / (uFar + uNear - z * (uFar - uNear)); }
+float coc(float z){ return clamp(uAperture * (z - uFocus) / max(z, 0.01), -uMaxBlur, uMaxBlur); }
+void main(){
+ float zc = linDepth(texture2D(tDepth, vUv).r);
+ float cc = coc(zc);
+ vec3 acc = texture2D(tColor, vUv).rgb; float wsum = 1.0;
+ float rad = abs(cc);
+ if (rad > 0.6) {
+ const float GA = 2.39996323;
+ const int N = 40;
+ vec2 px = 1.0 / uRes;
+ for (int i = 1; i <= N; i++) {
+ float r = sqrt(float(i) / float(N));
+ float a = float(i) * GA;
+ vec2 o = vec2(cos(a), sin(a)) * r;
+ // gather radius: allow near-field blur to bleed over sharp areas
+ vec2 uv = vUv + o * px * max(rad, uMaxBlur * 0.0);
+ float zs = linDepth(texture2D(tDepth, uv).r);
+ float cs = abs(coc(zs));
+ float w = (zs < zc) ? 1.0 : smoothstep(0.0, 1.0, cs / max(rad * r, 0.5));
+ vec3 s = texture2D(tColor, uv).rgb;
+ w *= 1.0 + dot(s, vec3(0.3)) * 0.6; // bokeh highlight weight
+ acc += s * w; wsum += w;
+ }
+ }
+ gl_FragColor = vec4(acc / wsum, 1.0);
+}
+`;
+
+const DOWN_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv; uniform sampler2D tSrc; uniform vec2 uTexel; uniform float uThreshold, uFirst;
+vec3 pre(vec3 c){
+ if (uFirst < 0.5) return c;
+ float br = max(c.r, max(c.g, c.b));
+ float soft = clamp(br - uThreshold + 0.5, 0.0, 1.0); soft = soft * soft * 0.5;
+ float contrib = max(soft, br - uThreshold) / max(br, 1e-4);
+ return min(c * contrib, vec3(40.0));
+}
+void main(){
+ vec2 t = uTexel;
+ vec3 a = pre(texture2D(tSrc, vUv + t * vec2(-2, 2)).rgb), b = pre(texture2D(tSrc, vUv + t * vec2(0, 2)).rgb), c = pre(texture2D(tSrc, vUv + t * vec2(2, 2)).rgb);
+ vec3 d = pre(texture2D(tSrc, vUv + t * vec2(-2, 0)).rgb), e = pre(texture2D(tSrc, vUv).rgb), f = pre(texture2D(tSrc, vUv + t * vec2(2, 0)).rgb);
+ vec3 g = pre(texture2D(tSrc, vUv + t * vec2(-2, -2)).rgb), h = pre(texture2D(tSrc, vUv + t * vec2(0, -2)).rgb), i = pre(texture2D(tSrc, vUv + t * vec2(2, -2)).rgb);
+ vec3 j = pre(texture2D(tSrc, vUv + t * vec2(-1, 1)).rgb), k = pre(texture2D(tSrc, vUv + t * vec2(1, 1)).rgb);
+ vec3 l = pre(texture2D(tSrc, vUv + t * vec2(-1, -1)).rgb), m = pre(texture2D(tSrc, vUv + t * vec2(1, -1)).rgb);
+ vec3 col = e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125;
+ gl_FragColor = vec4(col, 1.0);
+}
+`;
+const UP_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv; uniform sampler2D tSrc; uniform sampler2D tAdd; uniform vec2 uTexel; uniform float uMix;
+void main(){
+ vec2 t = uTexel;
+ vec3 s = texture2D(tSrc, vUv + t * vec2(-1, 1)).rgb + texture2D(tSrc, vUv + t * vec2(1, 1)).rgb * 1.0
+ + texture2D(tSrc, vUv + t * vec2(-1, -1)).rgb + texture2D(tSrc, vUv + t * vec2(1, -1)).rgb;
+ s += 2.0 * (texture2D(tSrc, vUv + t * vec2(0, 1)).rgb + texture2D(tSrc, vUv + t * vec2(0, -1)).rgb
+ + texture2D(tSrc, vUv + t * vec2(1, 0)).rgb + texture2D(tSrc, vUv + t * vec2(-1, 0)).rgb);
+ s += 4.0 * texture2D(tSrc, vUv).rgb;
+ s /= 16.0;
+ gl_FragColor = vec4(texture2D(tAdd, vUv).rgb + s * uMix, 1.0);
+}
+`;
+
+const COMB_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv; uniform sampler2D tColor; uniform sampler2D tBloom; uniform float uBloom, uWeight;
+void main(){ vec3 b = texture2D(tBloom, vUv).rgb; b *= vec3(1.10, 1.0, 0.92); // faint red-orange halation
+ gl_FragColor = vec4((texture2D(tColor, vUv).rgb + b * uBloom) * uWeight, 1.0); }
+`;
+
+const FINAL_FRAG = /* glsl */`
+precision highp float;
+varying vec2 vUv;
+uniform sampler2D tColor; uniform sampler2D tBloom;
+uniform vec2 uRes;
+uniform float uExposure, uBloom, uSat, uContrast, uVignette, uGrain, uChroma, uFrame, uFade, uLetterbox;
+uniform vec3 uLift;
+vec3 aces(vec3 x){ // Narkowicz fit
+ return clamp((x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14), 0.0, 1.0);
+}
+float h12(vec2 p){ vec3 p3 = fract(vec3(p.xyx) * .1031); p3 += dot(p3, p3.yzx + 33.33); return fract((p3.x + p3.y) * p3.z); }
+void main(){
+ vec2 c = vUv - 0.5;
+ float r2 = dot(c, c);
+ vec2 off = c * r2 * uChroma * 8.0;
+ vec3 col;
+ col.r = texture2D(tColor, vUv + off).r;
+ col.g = texture2D(tColor, vUv).g;
+ col.b = texture2D(tColor, vUv - off).b;
+ col *= uExposure;
+ // vignette (pre-tonemap, so highlights survive)
+ float vig = 1.0 - uVignette * smoothstep(0.08, 0.72, r2 * 1.9);
+ col *= vig;
+ col = aces(col);
+ // grade
+ float l = dot(col, vec3(0.2126, 0.7152, 0.0722));
+ col = mix(vec3(l), col, uSat);
+ col = (col - 0.18) * uContrast + 0.18;
+ col = max(col, 0.0);
+ col += uLift * (1.0 - col);
+ // gamma (sRGB OETF)
+ col = mix(col * 12.92, 1.055 * pow(col, vec3(1.0 / 2.4)) - 0.055, step(0.0031308, col));
+ // film grain (coarse + fine, stronger in the mids)
+ // film grain: bilinear value noise at ~1.8 px (soft clumps) + a little fine noise, slight chroma variation
+ vec2 gq = gl_FragCoord.xy / 1.8 + vec2(uFrame * 13.7, uFrame * 7.3);
+ vec2 gi = floor(gq), gf = fract(gq); gf = gf * gf * (3.0 - 2.0 * gf);
+ float fo = uFrame * 0.61;
+ float g2 = mix(mix(h12(gi + fo), h12(gi + vec2(1.0, 0.0) + fo), gf.x), mix(h12(gi + vec2(0.0, 1.0) + fo), h12(gi + vec2(1.0, 1.0) + fo), gf.x), gf.y) - 0.5;
+ float g1 = h12(gl_FragCoord.xy + uFrame * 17.13) - 0.5;
+ float g3 = h12(gi * 1.37 + 71.0 + fo) - 0.5;
+ float lum = dot(col, vec3(0.33));
+ float gamt = uGrain * (0.55 + 0.9 * (1.0 - abs(lum * 2.0 - 0.8)));
+ col += (g2 * 1.7 + g1 * 0.35) * gamt + vec3(g3, -g3 * 0.5, -g3) * gamt * 0.35;
+ col *= uFade;
+ if (abs(c.y) > 0.5 - uLetterbox) col = vec3(0.0);
+ gl_FragColor = vec4(col, 1.0);
+}
+`;
+
+export function createPost(renderer, w, h) {
+ const HF = THREE.HalfFloatType;
+ const depthTex = new THREE.DepthTexture(w, h);
+ depthTex.type = THREE.UnsignedIntType;
+ const rtScene = new THREE.WebGLRenderTarget(w, h, { type: HF, samples: 4, depthTexture: depthTex, depthBuffer: true });
+ const mk = (ww, hh) => new THREE.WebGLRenderTarget(ww, hh, { type: HF, depthBuffer: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });
+ const rtFog = mk(w, h), rtDof = mk(w, h), rtComb = mk(w, h);
+ const mk8 = () => new THREE.WebGLRenderTarget(w, h, { depthBuffer: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });
+ const rtAO = mk8(), rtAO2 = mk8();
+ const LEVELS = 6;
+ const down = [], up = [];
+ let bw = w, bh = h;
+ for (let i = 0; i < LEVELS; i++) {
+ bw = Math.max(2, Math.round(bw / 2)); bh = Math.max(2, Math.round(bh / 2));
+ down.push(mk(bw, bh)); up.push(mk(bw, bh));
+ }
+ const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2));
+ quad.frustumCulled = false;
+ const qscene = new THREE.Scene(); qscene.add(quad);
+ const mat = (frag, uniforms) => new THREE.ShaderMaterial({ vertexShader: VERT, fragmentShader: frag, uniforms, depthTest: false, depthWrite: false });
+
+ const glowPos = Array.from({ length: 10 }, () => new THREE.Vector4());
+ const glowCol = Array.from({ length: 10 }, () => new THREE.Color());
+ const fogMat = mat(FOG_FRAG, {
+ tColor: { value: rtScene.texture }, tDepth: { value: depthTex },
+ uInvProj: { value: new THREE.Matrix4() }, uCamWorld: { value: new THREE.Matrix4() },
+ uCamPos: { value: new THREE.Vector3() }, uFogCol: { value: LOOK.fogColor }, uMistCol: { value: LOOK.mistColor },
+ uTime: { value: 0 }, uFrame: { value: 0 },
+ uDensity: { value: LOOK.fogDensity }, uMist: { value: LOOK.mistDensity },
+ uMistH: { value: LOOK.mistHeight }, uMistNoise: { value: LOOK.mistNoise },
+ uZenith: { value: LOOK.zenith }, uHorizon: { value: LOOK.horizon },
+ uSkyGlowDir: { value: LOOK.skyGlowDir }, uSkyGlow: { value: LOOK.skyGlow },
+ uGlowPos: { value: glowPos }, uGlowCol: { value: glowCol }, uGlowN: { value: 0 },
+ tAO: { value: rtAO2.texture }, uAO: { value: 1 },
+ });
+ const aoMat = mat(AO_FRAG, { tDepth: { value: depthTex }, uInvProj: { value: new THREE.Matrix4() }, uRes: { value: new THREE.Vector2(w, h) }, uRadius: { value: 1.8 }, uProjScale: { value: 1 }, uFrame: { value: 0 } });
+ const aoBlurMat = mat(AOBLUR_FRAG, { tAO: { value: rtAO.texture }, tDepth: { value: depthTex }, uRes: { value: new THREE.Vector2(w, h) }, uNear: { value: 0.3 }, uFar: { value: 3000 } });
+ const dofMat = mat(DOF_FRAG, {
+ tColor: { value: rtFog.texture }, tDepth: { value: depthTex },
+ uRes: { value: new THREE.Vector2(w, h) }, uNear: { value: 0.3 }, uFar: { value: 3000 },
+ uFocus: { value: 50 }, uAperture: { value: 0 }, uMaxBlur: { value: 18 },
+ });
+ const downMat = mat(DOWN_FRAG, { tSrc: { value: null }, uTexel: { value: new THREE.Vector2() }, uThreshold: { value: 1 }, uFirst: { value: 0 } });
+ const upMat = mat(UP_FRAG, { tSrc: { value: null }, tAdd: { value: null }, uTexel: { value: new THREE.Vector2() }, uMix: { value: 1 } });
+ const combMat = mat(COMB_FRAG, { tColor: { value: null }, tBloom: { value: null }, uBloom: { value: 0.5 }, uWeight: { value: 1 } });
+ combMat.blending = THREE.CustomBlending; combMat.blendEquation = THREE.AddEquation;
+ combMat.blendSrc = THREE.OneFactor; combMat.blendDst = THREE.ZeroFactor; combMat.transparent = true;
+ const finalMat = mat(FINAL_FRAG, {
+ tColor: { value: null }, tBloom: { value: null }, uRes: { value: new THREE.Vector2(w, h) },
+ uExposure: { value: 1 }, uBloom: { value: 0.5 }, uSat: { value: 1 }, uContrast: { value: 1 },
+ uVignette: { value: 0.4 }, uGrain: { value: 0.05 }, uChroma: { value: 0.001 }, uFrame: { value: 0 },
+ uFade: { value: 1 }, uLetterbox: { value: 0 }, uLift: { value: LOOK.lift },
+ });
+
+ function pass(material, target) {
+ quad.material = material;
+ renderer.setRenderTarget(target);
+ renderer.render(qscene, cam);
+ }
+
+ return {
+ rtScene, depthTex, fogMat, finalMat, glowPos, glowCol,
+ // o: { t, frame, dof:{focus, aperture}|null, fade, exposureMul, fogMul, mistMul }
+ render(scene, camera, o = {}) {
+ renderer.setRenderTarget(rtScene);
+ renderer.clear();
+ renderer.render(scene, camera);
+ // ambient obscurance
+ const aoAmt = LOOK.ao ?? 0.85;
+ if (aoAmt > 0) {
+ aoMat.uniforms.uInvProj.value.copy(camera.projectionMatrixInverse);
+ aoMat.uniforms.uProjScale.value = h * 0.5 * camera.projectionMatrix.elements[5];
+ aoMat.uniforms.uRadius.value = LOOK.aoRadius ?? 1.8;
+ aoMat.uniforms.uFrame.value = o.frame ?? 0;
+ pass(aoMat, rtAO);
+ aoBlurMat.uniforms.uNear.value = camera.near; aoBlurMat.uniforms.uFar.value = camera.far;
+ pass(aoBlurMat, rtAO2);
+ }
+ // fog
+ const fu = fogMat.uniforms;
+ fu.uAO.value = aoAmt;
+ fu.uInvProj.value.copy(camera.projectionMatrixInverse);
+ fu.uCamWorld.value.copy(camera.matrixWorld);
+ fu.uCamPos.value.setFromMatrixPosition(camera.matrixWorld);
+ fu.uTime.value = o.t ?? 0; fu.uFrame.value = o.frame ?? 0;
+ fu.uDensity.value = LOOK.fogDensity * (o.fogMul ?? 1);
+ fu.uMist.value = LOOK.mistDensity * (o.mistMul ?? 1);
+ fu.uMistH.value = LOOK.mistHeight; fu.uMistNoise.value = LOOK.mistNoise;
+ fu.uGlowN.value = o.glowN ?? 0;
+ pass(fogMat, rtFog);
+ let src = rtFog;
+ if (o.dof && o.dof.aperture > 0) {
+ const du = dofMat.uniforms;
+ du.uNear.value = camera.near; du.uFar.value = camera.far;
+ du.uFocus.value = o.dof.focus; du.uAperture.value = o.dof.aperture * (h / 1080);
+ du.uMaxBlur.value = (o.dof.maxBlur ?? 16) * (h / 1080);
+ pass(dofMat, rtDof);
+ src = rtDof;
+ }
+ // bloom down
+ let prev = src;
+ for (let i = 0; i < LEVELS; i++) {
+ downMat.uniforms.tSrc.value = prev.texture;
+ downMat.uniforms.uTexel.value.set(1 / prev.width, 1 / prev.height);
+ downMat.uniforms.uFirst.value = i === 0 ? 1 : 0;
+ downMat.uniforms.uThreshold.value = LOOK.bloomThreshold;
+ pass(downMat, down[i]);
+ prev = down[i];
+ }
+ // bloom up
+ let acc = down[LEVELS - 1];
+ for (let i = LEVELS - 2; i >= 0; i--) {
+ upMat.uniforms.tSrc.value = acc.texture;
+ upMat.uniforms.tAdd.value = down[i].texture;
+ upMat.uniforms.uTexel.value.set(1 / acc.width, 1 / acc.height);
+ upMat.uniforms.uMix.value = 1.15;
+ pass(upMat, up[i]);
+ acc = up[i];
+ }
+ // combine scene + bloom into rtComb; with o.accum = {i, n} sub-frames are averaged (motion blur)
+ const ac = o.accum;
+ combMat.uniforms.tColor.value = src.texture; combMat.uniforms.tBloom.value = acc.texture;
+ combMat.uniforms.uBloom.value = LOOK.bloom / LEVELS * 2.0;
+ combMat.uniforms.uWeight.value = ac ? 1 / ac.n : 1;
+ combMat.blendDst = ac && ac.i > 0 ? THREE.OneFactor : THREE.ZeroFactor;
+ const ac0 = renderer.autoClear; renderer.autoClear = false;
+ pass(combMat, rtComb);
+ renderer.autoClear = ac0;
+ if (ac && ac.i < ac.n - 1) return;
+ const u = finalMat.uniforms;
+ u.tColor.value = rtComb.texture;
+ u.uExposure.value = LOOK.exposure * (o.exposureMul ?? 1);
+ u.uSat.value = LOOK.saturation; u.uContrast.value = LOOK.contrast;
+ u.uVignette.value = LOOK.vignette; u.uGrain.value = LOOK.grain; u.uChroma.value = LOOK.chroma;
+ u.uFrame.value = o.frame ?? 0; u.uFade.value = o.fade ?? 1; u.uLetterbox.value = o.letterbox ?? 0;
+ pass(finalMat, null);
+ },
+ };
+}
diff --git a/src/shots.js b/src/shots.js
new file mode 100644
index 0000000..0f3d322
--- /dev/null
+++ b/src/shots.js
@@ -0,0 +1,128 @@
+// Camera shots. Positions are in the PATH FRAME: origin travels with the walker at constant
+// speed (x = SPEED * t), y = ground, so [0, 18.5, 0] is the building base centre.
+// cam(tl, t) -> { pos:[x,y,z], tgt:[x,y,z], fov, roll?, dof?:{focus,aperture}, shake?:mult }
+// tl = local time inside the shot (s), t = global time.
+import { SPEED } from './gait.js';
+
+const lerp = (a, b, k) => a + (b - a) * k;
+const mix3 = (a, b, k) => [lerp(a[0], b[0], k), lerp(a[1], b[1], k), lerp(a[2], b[2], k)];
+const ease = (k) => { k = Math.min(1, Math.max(0, k)); return k * k * (3 - 2 * k); };
+
+// Still look-dev views matching refs/1..6.webp
+export const SHOTS = {
+ // ref 1: worm's-eye by a foot, block looming overhead and receding into fog
+ ref1: { cam: () => ({ pos: [-46.5, 0.55, 26.5], tgt: [-18, 15.5, 6], fov: 58, dof: { focus: 14, aperture: 2.2 } }) },
+ // ref 2: classic low 3/4 hero view
+ ref2: { cam: () => ({ pos: [-78, 2.0, 58], tgt: [-2, 21, 0], fov: 44 }) },
+ // ref 3: far 3/4 from the other end, heavy fog
+ ref3: { cam: () => ({ pos: [92, 2.6, 86], tgt: [-4, 22, 0], fov: 36 }) },
+ // ref 4: flat side elevation, long lens
+ ref4: { cam: () => ({ pos: [0, 5.0, 205], tgt: [0, 21, 0], fov: 27 }) },
+ // ref 5: straight up into the mechanical belly
+ ref5: { cam: () => ({ pos: [-62, 1.3, 2], tgt: [-18, 19, 0], fov: 62 }) },
+ // ref 6: low over a puddle, block marching past
+ ref6: { cam: () => ({ pos: [70, 0.8, 44], tgt: [2, 19, 0], fov: 50, dof: { focus: 60, aperture: 1.2 } }) },
+ // extra inspection views
+ facade: { cam: () => ({ pos: [-8, 26, 34], tgt: [-8, 27, 0], fov: 40 }) },
+ facadeClose: { cam: () => ({ pos: [-20, 27, 17], tgt: [-14, 27.5, 7], fov: 40 }) },
+ roof: { cam: () => ({ pos: [-60, 52, 40], tgt: [0, 34, 0], fov: 40 }) },
+ leg: { cam: () => ({ pos: [-2, 9, 46], tgt: [11, 13, 14], fov: 38 }) },
+ foot: { cam: () => ({ pos: [20, 2.2, 31], tgt: [12, 3.5, 18], fov: 42 }) },
+ knee: { cam: () => ({ pos: [22, 24, 38], tgt: [12, 22, 20], fov: 36 }) },
+ belly: { cam: () => ({ pos: [-8, 3, 4], tgt: [6, 17, 0], fov: 60 }) },
+ end: { cam: () => ({ pos: [-95, 14, 12], tgt: [-44, 24, 0], fov: 40 }) },
+ back: { cam: () => ({ pos: [60, 4, -70], tgt: [0, 20, 0], fov: 44 }) },
+ grass: { cam: () => ({ pos: [-30, 0.35, 60], tgt: [-10, 6, 20], fov: 50, dof: { focus: 40, aperture: 2.0 } }) },
+};
+
+// ---------------------------------------------------------------- film shots
+const P = (t) => SPEED * t; // walker x at time t
+Object.assign(SHOTS, {
+ // 1. something huge approaches through the fog; rack focus from wet grass to the lights
+ f_open: { cam: (tl, t) => {
+ const k = ease(tl / 5.5), r = ease((tl - 2.3) / 2.4);
+ return { world: true, pos: [150 - 2.0 * k, 0.40 + 0.35 * k, 50], tgt: [P(t) + 22, 13 + 5 * k, 2], fov: 31 - 2.5 * k,
+ dof: { focus: lerp(2.2, 95, r), aperture: 3.2, maxBlur: 22 }, shake: 1.7, post: { fade: ease(tl / 1.3) } };
+ } },
+ // 2. long-lens side elevation, slow truck + push
+ f_side: { cam: (tl) => {
+ const k = tl / 5.5;
+ return { pos: [lerp(-14, 6, k), 4.2, lerp(158, 146, k)], tgt: [lerp(-5, 2, k), 18.2, 0], fov: 29, shake: 0.6 };
+ } },
+ // 3. low 3/4 hero, the block marches past and over us
+ f_hero: { cam: (tl) => {
+ const k = tl / 5.5;
+ return { pos: [lerp(-84, -70, k), lerp(1.7, 2.4, k), lerp(60, 50, k)], tgt: [lerp(-8, 2, k), lerp(18.5, 20.5, k), 0], fov: lerp(42, 46, k), shake: 1.2,
+ dof: { focus: 78, aperture: 0.9 } };
+ } },
+ // 4. worm's-eye: a foot slams down right in front of the lens (leg 2 plants at t=18.752, x=75.6, z=18)
+ f_foot: { cam: (tl) => {
+ const k = ease(tl / 4.0);
+ return { world: true, pos: [86.7 - 1.2 * k, 0.5 + 0.1 * k, 34.0], tgt: [lerp(72.2, 68.2, k), lerp(8.5, 12, k), lerp(20, 13, k)], fov: 56, shake: 2.4,
+ dof: { focus: 15, aperture: 1.6 } };
+ } },
+ // 5. the belly passes overhead
+ f_belly: { cam: (tl, t) => {
+ const k = tl / 5.5;
+ return { world: true, pos: [P(23.2) + 14, 1.25, 1.5], tgt: [P(t) - 14 + 8 * k, 17.0, lerp(-1.5, 1.0, k)], fov: 60, shake: 1.5 };
+ } },
+ // 6. life goes on: drifting up past balconies and laundry
+ f_life: { cam: (tl) => {
+ const k = tl / 5.5, e = ease(k);
+ return { pos: [lerp(-27, -15, k), lerp(21.0, 30.0, e), lerp(21.5, 19.5, k)], tgt: [lerp(-22, -11, k), lerp(22.0, 29.5, e), 7.5], fov: 33, shake: 0.35,
+ dof: { focus: 13.5, aperture: 2.4 } };
+ } },
+ // 7. the machine: knee and pistons of leg 1 (lifts 33.06, slams 34.98)
+ f_knee: { cam: (tl) => {
+ const k = tl / 4.0;
+ return { pos: [lerp(-36, -32, k), lerp(9.5, 12, k), lerp(46, 42, k)], tgt: [-15, lerp(11.5, 13.5, k), 21], fov: 40, shake: 1.2,
+ dof: { focus: 29, aperture: 1.6 } };
+ } },
+ // 8. puddle mirror (hero puddle at world x=130, z=35); leg 2 plants at t=37.95 at x=129, z=18
+ f_puddle: { cam: (tl) => {
+ const k = tl / 5.0;
+ return { world: true, pos: [136.6 - 1.2 * k, 1.25 + 0.25 * k, 43.8], tgt: [lerp(104, 112, k), lerp(8.5, 10.5, k), 0], fov: 56, shake: 1.4,
+ dof: { focus: 46, aperture: 0.9 } };
+ } },
+ // 9. it walks on into the fog; slow crane up, fade out
+ f_away: { cam: (tl, t) => {
+ const k = tl / 4.5, e = ease(k);
+ return { world: true, pos: [P(40.5) - 84 - 8 * k, 5.0 + 24.0 * e, -36 + 4 * k], tgt: [P(t) - 6, 18.5 + 3 * e, 0], fov: 36, shake: 0.8,
+ post: { fade: 1 - ease((tl - 2.9) / 1.55) } };
+ } },
+});
+
+export const TIMELINE = [
+ { shot: 'f_open', start: 0, end: 5.5 },
+ { shot: 'f_side', start: 5.5, end: 11 },
+ { shot: 'f_hero', start: 11, end: 16.5 },
+ { shot: 'f_foot', start: 16.5, end: 20.5 },
+ { shot: 'f_belly', start: 20.5, end: 26 },
+ { shot: 'f_life', start: 26, end: 31.5 },
+ { shot: 'f_knee', start: 31.5, end: 35.5 },
+ { shot: 'f_puddle', start: 35.5, end: 40.5 },
+ { shot: 'f_away', start: 40.5, end: 45 },
+];
+export const DURATION = 45;
+
+export function evalShot(name, t) {
+ let s = SHOTS[name], tl = t;
+ if (s) { const seg = TIMELINE.find((g) => g.shot === name); if (seg) tl = t - seg.start; }
+ if (!s) {
+ // timeline lookup
+ for (const seg of TIMELINE) if (t >= seg.start && t < seg.end) { s = SHOTS[seg.shot]; tl = t - seg.start; name = seg.shot; break; }
+ if (!s && t >= DURATION) { const seg = TIMELINE[TIMELINE.length - 1]; s = SHOTS[seg.shot]; tl = t - seg.start; name = seg.shot; }
+ if (!s) { s = SHOTS.ref2; }
+ }
+ const c = s.cam(tl, t);
+ const px = SPEED * (s.fixed ? (s.fixedT ?? 0) : t);
+ return {
+ name,
+ pos: [c.pos[0] + (c.world ? 0 : px), c.pos[1], c.pos[2]],
+ tgt: [c.tgt[0] + (c.world ? 0 : px), c.tgt[1], c.tgt[2]],
+ fov: c.fov ?? 45, roll: c.roll ?? 0, dof: c.dof ?? null, shake: c.shake ?? 1, handheld: c.handheld ?? (TIMELINE.some((g) => g.shot === name) ? 1 : 0),
+ post: { ...(s.post || {}), ...(c.post || {}) },
+ near: c.near ?? 0.3,
+ };
+}
+export { lerp, mix3, ease };
diff --git a/src/textures.js b/src/textures.js
new file mode 100644
index 0000000..fd0c426
--- /dev/null
+++ b/src/textures.js
@@ -0,0 +1,118 @@
+// Procedural texture helpers (no external assets).
+import * as THREE from 'three';
+
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function () {
+ a |= 0; a = (a + 0x6d2b79f5) | 0;
+ let t = Math.imul(a ^ (a >>> 15), 1 | a);
+ t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+// Periodic (tileable) value noise on a lattice of `period` cells across the unit square.
+function makeLattice(period, rnd) {
+ const g = new Float32Array(period * period);
+ for (let i = 0; i < g.length; i++) g[i] = rnd();
+ return g;
+}
+function sampleLattice(g, period, x, y) {
+ // x,y in [0,1)
+ const fx = x * period, fy = y * period;
+ const ix = Math.floor(fx), iy = Math.floor(fy);
+ let tx = fx - ix, ty = fy - iy;
+ tx = tx * tx * (3 - 2 * tx); ty = ty * ty * (3 - 2 * ty);
+ const x0 = ((ix % period) + period) % period, x1 = (x0 + 1) % period;
+ const y0 = ((iy % period) + period) % period, y1 = (y0 + 1) % period;
+ const a = g[y0 * period + x0], b = g[y0 * period + x1];
+ const c = g[y1 * period + x0], d = g[y1 * period + x1];
+ return a + (b - a) * tx + (c - a) * ty + (a - b - c + d) * tx * ty;
+}
+// Tileable fbm generator: returns function (x,y)->[0,1]
+export function tileFbm(basePeriod, octaves, seed, gain = 0.5) {
+ const rnd = mulberry32(seed);
+ const lat = [];
+ let p = basePeriod;
+ for (let o = 0; o < octaves; o++) { lat.push([makeLattice(p, rnd), p]); p *= 2; }
+ let norm = 0, a = 1;
+ for (let o = 0; o < octaves; o++) { norm += a; a *= gain; }
+ return (x, y) => {
+ let s = 0, amp = 1;
+ for (let o = 0; o < octaves; o++) { s += amp * sampleLattice(lat[o][0], lat[o][1], x, y); amp *= gain; }
+ return s / norm;
+ };
+}
+
+const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+
+// Shared RGBA detail texture used by the weathering shader (triplanar, tileable):
+// R: fine grain / pores G: chips & scratches mask
+// B: soft low-frequency cloud A: independent mid-frequency noise
+let _detail = null;
+export function detailTexture(size = 1024) {
+ if (_detail) return _detail;
+ const data = new Uint8Array(size * size * 4);
+ const fR = tileFbm(40, 4, 11, 0.55);
+ const fG = tileFbm(10, 5, 23, 0.55);
+ const fB = tileFbm(4, 5, 37, 0.5);
+ const fA = tileFbm(16, 4, 51, 0.55);
+ const fP = tileFbm(128, 1, 77);
+ // scratches drawn on a 2D canvas (wrapped), read back into G
+ const cv = document.createElement('canvas'); cv.width = cv.height = size;
+ const c2 = cv.getContext('2d');
+ c2.fillStyle = '#000'; c2.fillRect(0, 0, size, size);
+ const rnd = mulberry32(99);
+ c2.lineCap = 'round';
+ for (let i = 0; i < 260; i++) {
+ const x = rnd() * size, y = rnd() * size;
+ const ang = rnd() < 0.6 ? (rnd() - 0.5) * 0.5 + (rnd() < 0.5 ? 0 : Math.PI / 2) : rnd() * Math.PI;
+ const len = 20 + rnd() * rnd() * 260;
+ const a = 0.25 + rnd() * 0.6;
+ c2.strokeStyle = `rgba(255,255,255,${a})`;
+ c2.lineWidth = 0.6 + rnd() * rnd() * 2.6;
+ for (let ox = -1; ox <= 1; ox++) for (let oy = -1; oy <= 1; oy++) {
+ c2.beginPath();
+ c2.moveTo(x + ox * size, y + oy * size);
+ c2.lineTo(x + ox * size + Math.cos(ang) * len, y + oy * size + Math.sin(ang) * len);
+ c2.stroke();
+ }
+ }
+ const scr = c2.getImageData(0, 0, size, size).data;
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const u = x / size, v = y / size, i = (y * size + x) * 4;
+ let r = (fR(u, v) - 0.5) * 2.1 + 0.5;
+ const pore = fP(u, v);
+ if (pore > 0.93) r -= (pore - 0.93) * 9.0; // dark pores
+ let g = (fG(u, v) - 0.5) * 2.4 + 0.5;
+ g = Math.max(g, scr[i] / 255 * 0.95);
+ const b = (fB(u, v) - 0.5) * 2.2 + 0.5;
+ const a = (fA(u, v) - 0.5) * 2.2 + 0.5;
+ data[i] = clamp01(r) * 255; data[i + 1] = clamp01(g) * 255;
+ data[i + 2] = clamp01(b) * 255; data[i + 3] = clamp01(a) * 255;
+ }
+ }
+ const tex = new THREE.DataTexture(data, size, size, THREE.RGBAFormat, THREE.UnsignedByteType);
+ tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.magFilter = THREE.LinearFilter;
+ tex.minFilter = THREE.LinearMipmapLinearFilter;
+ tex.generateMipmaps = true;
+ tex.anisotropy = 8;
+ tex.colorSpace = THREE.NoColorSpace;
+ tex.needsUpdate = true;
+ _detail = tex;
+ return tex;
+}
+
+// Convenience: build a CanvasTexture by drawing with a 2D context.
+export function canvasTexture(w, h, draw, { srgb = true, repeat = false, aniso = 8 } = {}) {
+ const cv = document.createElement('canvas'); cv.width = w; cv.height = h;
+ const ctx = cv.getContext('2d');
+ draw(ctx, w, h);
+ const tex = new THREE.CanvasTexture(cv);
+ tex.colorSpace = srgb ? THREE.SRGBColorSpace : THREE.NoColorSpace;
+ if (repeat) tex.wrapS = tex.wrapT = THREE.RepeatWrapping;
+ tex.anisotropy = aniso;
+ return tex;
+}
diff --git a/tools/audio.mjs b/tools/audio.mjs
new file mode 100644
index 0000000..5a6e4bd
--- /dev/null
+++ b/tools/audio.mjs
@@ -0,0 +1,467 @@
+// Builds the film soundtrack: music bed + SFX placed from the (closed-form) gait and the shot timeline.
+// All source audio is downloaded material (see audio/CREDITS.md) — nothing is synthesized here.
+// Usage: node tools/audio.mjs [--out out/audio.wav] [--music the_long_dark] [--mstart s] [--sfxrel -1] [--lufs -15]
+// [--nomusic] [--nosfx] [--stems] (writes out/stem_music.wav + out/stem_sfx.wav) [--quiet] (no verification table)
+// Every time comes from src/gait.js (touchdowns / lift-offs) and src/shots.js (camera, shot boundaries) at run time.
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const args = {};
+for (let i = 2; i < process.argv.length; i++) {
+ const a = process.argv[i];
+ if (a.startsWith('--')) { const k = a.slice(2); const n = process.argv[i + 1]; if (n === undefined || n.startsWith('--')) args[k] = true; else { args[k] = n; i++; } }
+}
+const gait = await import(pathToFileURL(path.join(ROOT, 'src/gait.js')));
+const shots = await import(pathToFileURL(path.join(ROOT, 'src/shots.js')));
+const { GAIT, LEGS, NLEGS, SPEED } = gait;
+const SR = 48000, DUR = shots.DURATION, N = Math.round(DUR * SR);
+const L = new Float32Array(N), R = new Float32Array(N);
+
+function mulberry32(a) { return () => { a |= 0; a = (a + 0x6d2b79f5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a); t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
+const rnd = mulberry32(4242);
+const heroHits = []; // [time, strength] of touchdowns close to the camera (music ducks for them)
+
+const WHO = args.who ? new Map() : null; // --who: energy each source file contributes per shot (pre-mix, for balancing)
+const who = (s, d, v) => { let a = WHO.get(s.name); if (!a) WHO.set(s.name, a = new Float64Array(64)); a[shotIdx[d >> 10]] += v * v; };
+let shotIdx = null;
+const cache = new Map();
+function stats(s) {
+ let pk = 0, pkI = 0, env = 0, epk = 0, sq = 0;
+ for (let i = 0; i < s.n; i++) {
+ const m = Math.max(Math.abs(s.l[i]), Math.abs(s.r[i]));
+ sq += m * m;
+ if (m > pk) pk = m;
+ env += (m - env) * 0.0015; // ~14 ms envelope
+ if (env > epk) { epk = env; pkI = i; }
+ }
+ s.peak = pk || 1; s.peakT = pkI / SR; s.rms = Math.sqrt(sq / Math.max(1, s.n)) || 1;
+ let on = 0; while (on < s.n && Math.max(Math.abs(s.l[on]), Math.abs(s.r[on])) < 0.3 * s.peak) on++;
+ s.onT = on / SR; // first sample above 30 % of the peak = the transient
+ return s;
+}
+function load(rel, { ss = 0, t = 0 } = {}) {
+ const key = rel + '|' + ss + '|' + t;
+ if (cache.has(key)) return cache.get(key);
+ const a = ['-v', 'error'];
+ if (ss) a.push('-ss', String(ss));
+ if (t) a.push('-t', String(t));
+ a.push('-i', path.join(ROOT, 'audio', rel), '-f', 'f32le', '-ac', '2', '-ar', String(SR), '-');
+ const r = spawnSync('ffmpeg', a, { maxBuffer: 1 << 30 });
+ if (r.status !== 0) throw new Error('decode failed ' + rel + ': ' + r.stderr);
+ const f = new Float32Array(r.stdout.buffer, r.stdout.byteOffset, Math.floor(r.stdout.length / 4));
+ const n = f.length / 2, l = new Float32Array(n), rr = new Float32Array(n);
+ for (let i = 0; i < n; i++) { l[i] = f[2 * i]; rr[i] = f[2 * i + 1]; }
+ const s = stats({ l, r: rr, n });
+ s.name = path.basename(rel).replace(/\.\w+$/, '');
+ cache.set(key, s);
+ return s;
+}
+const sfx = (name, o) => load('sfx/' + name + '.mp3', o);
+
+// Place a sample. o: { at (s, where 'anchor' seconds into the sample lands), anchor, gain, pan(-1..1), lp (Hz, 0=off),
+// hp (Hz), rate (playback speed), dur (s, truncate), fadeIn, fadeOut (s),
+// norm: default = peak-normalize first; 'rms' = level by RMS (dense, sustained sources such as groans); false = as recorded }
+// Every placed sample is faded in and out, so nothing starts or stops abruptly.
+function place(s, o) {
+ const rate = o.rate ?? 1, g = (o.gain ?? 1) / (o.norm === false ? 1 : o.norm === 'rms' ? 8 * s.rms : s.peak);
+ if (!(g > 0)) return;
+ const pan = Math.max(-1, Math.min(1, o.pan ?? 0));
+ const gl = g * Math.cos((pan + 1) * Math.PI / 4) * 1.414, gr = g * Math.sin((pan + 1) * Math.PI / 4) * 1.414;
+ let len = Math.floor(s.n / rate);
+ if (o.dur) len = Math.min(len, Math.round(o.dur * SR));
+ const start = Math.round(((o.at ?? 0) - (o.anchor ?? 0) / rate) * SR);
+ const fi = Math.max(1, Math.round((o.fadeIn ?? 0.004) * SR)), fo = Math.max(1, Math.min(len, Math.round((o.fadeOut ?? 0.03) * SR)));
+ const aL = o.lp ? 1 - Math.exp(-2 * Math.PI * o.lp / SR) : 1;
+ const aH = o.hp ? 1 - Math.exp(-2 * Math.PI * o.hp / SR) : 0;
+ let yl = 0, yr = 0, yl2 = 0, yr2 = 0, hl = 0, hr = 0, hl2 = 0, hr2 = 0;
+ for (let i = 0; i < len; i++) {
+ const d = start + i;
+ if (d >= N) break;
+ const p = i * rate, i0 = Math.floor(p), fr = p - i0, i1 = Math.min(s.n - 1, i0 + 1);
+ let xl = s.l[i0] + (s.l[i1] - s.l[i0]) * fr, xr = s.r[i0] + (s.r[i1] - s.r[i0]) * fr;
+ if (o.lp) { yl += (xl - yl) * aL; yr += (xr - yr) * aL; yl2 += (yl - yl2) * aL; yr2 += (yr - yr2) * aL; xl = yl2; xr = yr2; }
+ if (o.hp) { hl += (xl - hl) * aH; hr += (xr - hr) * aH; xl -= hl; xr -= hr; hl2 += (xl - hl2) * aH; hr2 += (xr - hr2) * aH; xl -= hl2; xr -= hr2; }
+ if (d < 0) continue;
+ let e = 1;
+ if (i < fi) e = i / fi;
+ if (len - i < fo) e *= (len - i) / fo;
+ const m = (xl + xr) * 0.5; // mono-ish source panning, keep some width
+ const al = (m * 0.7 + xl * 0.3) * gl * e, ar = (m * 0.7 + xr * 0.3) * gr * e;
+ L[d] += al; R[d] += ar;
+ if (WHO) who(s, d, al + ar);
+ }
+}
+// Long bed with a gain envelope function g(t) (skipped where g is 0); loops with a crossfade
+function bed(s, gainFn, { offset = 0, lp = 0, hp = 0, pan = 0, loopXf = 2.0 } = {}) {
+ const aL = lp ? 1 - Math.exp(-2 * Math.PI * lp / SR) : 1, aH = hp ? 1 - Math.exp(-2 * Math.PI * hp / SR) : 0;
+ let yl = 0, yr = 0, yl2 = 0, yr2 = 0, hl = 0, hr = 0, g = 0;
+ const xf = Math.min(Math.round(loopXf * SR), Math.floor(s.n / 4)), usable = s.n - xf;
+ for (let d = 0; d < N; d++) {
+ if ((d & 255) === 0) g = gainFn(d / SR) / s.peak;
+ const p = (d + Math.round(offset * SR)) % usable;
+ let xl = s.l[p], xr = s.r[p];
+ if (p < xf) { const k = p / xf; xl = xl * k + s.l[usable + p] * (1 - k); xr = xr * k + s.r[usable + p] * (1 - k); } // loop crossfade
+ if (lp) { yl += (xl - yl) * aL; yr += (xr - yr) * aL; yl2 += (yl - yl2) * aL; yr2 += (yr - yr2) * aL; xl = yl2; xr = yr2; }
+ if (hp) { hl += (xl - hl) * aH; hr += (xr - hr) * aH; xl -= hl; xr -= hr; }
+ L[d] += xl * g * (1 - Math.max(0, pan)); R[d] += xr * g * (1 + Math.min(0, pan));
+ if (WHO && g) who(s, d, (xl + xr) * g);
+ }
+}
+
+// ---------------------------------------------------------------- camera helpers
+function cam(t) {
+ const c = shots.evalShot('', Math.min(DUR - 0.01, Math.max(0, t)));
+ const fx = c.tgt[0] - c.pos[0], fz = c.tgt[2] - c.pos[2], fl = Math.hypot(fx, fz) || 1;
+ return { name: c.name, pos: c.pos, right: [-fz / fl, fx / fl] }; // right vector in xz (x right-handed: forward x up)
+}
+function spatial(t, x, z, y = 0) {
+ const c = cam(t);
+ const dx = x - c.pos[0], dz = z - c.pos[2], dy = y - c.pos[1];
+ const d = Math.hypot(dx, dy, dz);
+ const pan = Math.max(-0.85, Math.min(0.85, (dx * c.right[0] + dz * c.right[1]) / (d + 8)));
+ return { d, pan: -pan, shot: c.name };
+}
+const smooth = (a, b, x) => { const k = Math.max(0, Math.min(1, (x - a) / (b - a))); return k * k * (3 - 2 * k); };
+const segOf = (name) => shots.TIMELINE.find((s) => s.shot === name) || { start: -1, end: -1 };
+const inShot = (name, t, fade = 0.35) => { const s = segOf(name); return smooth(s.start - fade, s.start + fade, t) * (1 - smooth(s.end - fade, s.end + fade, t)); };
+
+// ---------------------------------------------------------------- SFX
+const clamp = (x, a = 0, b = 1) => Math.max(a, Math.min(b, x));
+shotIdx = Uint8Array.from({ length: (N >> 10) + 2 }, (_, i) => Math.max(0, shots.TIMELINE.findIndex((g) => (i << 10) / SR >= g.start && (i << 10) / SR < g.end)));
+const db = (x) => Math.pow(10, x / 20);
+const marks = []; // every touchdown in the film: { td (gait), at (td + distance delay), near, k, shot }
+// Per-shot perspective: g = how much of the machine reaches the camera, lp = ceiling (Hz, 0 = open), k = extra close-up detail,
+// groan = weight of the structure's stress sounds.
+const PERSP = {
+ f_open: { g: 1.00, lp: 800, k: 0, groan: 0.5 }, // far, through fog: soft, low, late
+ f_side: { g: 0.90, lp: 1100, k: 0, groan: 0.6 }, // 150 m long lens
+ f_hero: { g: 1.25, lp: 0, k: 0, groan: 1.0 },
+ f_foot: { g: 1.00, lp: 0, k: 0, groan: 1.0 }, // a foot lands at the lens: everything
+ f_belly: { g: 0.90, lp: 0, k: 0, groan: 1.5 }, // inside the machine
+ f_life: { g: 0.42, lp: 1500, k: 0, groan: 0.55 }, // up at the balconies: the walk is felt from below
+ f_knee: { g: 1.15, lp: 0, k: 0.4, groan: 1.2 }, // mechanism close-up
+ f_puddle: { g: 1.00, lp: 0, k: 0.3, groan: 1.0 },
+ f_away: { g: 0.90, lp: 2200, k: 0, groan: 0.7 },
+};
+const persp = (name) => PERSP[name] || { g: 1, lp: 0, k: 0, groan: 1 };
+
+if (!args.nosfx) {
+ // ---- sources (offsets below are positions inside the downloaded recordings, not picture times)
+ const steps = ['step1', 'step2', 'step3', 'step4', 'step5'].map((n) => sfx(n));
+ const bass = sfx('bassimpact'), sub = sfx('subdrop'), dboom = sfx('distantboom');
+ const stomps = [2.44, 5.22, 8.88, 11.66, 15.31, 18.10, 21.75].map((ss) => sfx('giantstomp', { ss, t: 1.5 }));
+ const doors = ['metaldoor1', 'metaldoor2', 'metaldoor3'].map((n) => sfx(n));
+ const gravel = sfx('gravelfall'), debris = sfx('debris', { ss: 2, t: 8 }), bigdebris = sfx('bigdebris');
+ const air = sfx('airrelease'), phiss = sfx('pressurehiss'), steam = sfx('steamrelease', { t: 6 });
+ const mdoors = [sfx('mechdoor', { ss: 0.4, t: 2.6 }), sfx('mechdoor', { ss: 3.8, t: 2.7 })];
+ const squelch = sfx('mudsquelch'), squelch2 = sfx('squelch'), splat = sfx('mudsplat'), slimy = sfx('slimy', { ss: 1.3, t: 1.0 });
+ const mudsteps = [12.0, 14.05, 29.85, 40.75].map((ss) => sfx('muddysteps', { ss, t: 0.9 }));
+ const splashBig = sfx('splashstomps', { ss: 14.0, t: 3.0 }), splashSmall = sfx('splashstomps', { ss: 5.5, t: 3.0 });
+ const ripples = sfx('watersplashes', { ss: 19.5, t: 3.5 });
+ const chains = [sfx('chain1', { ss: 2.7, t: 1.8 }), sfx('chain1', { ss: 7.5, t: 1.9 }), sfx('chain1', { ss: 13.6, t: 1.6 }), sfx('chainrattle', { ss: 16.9, t: 2.2 })];
+ const servo = sfx('trunkmotor', { ss: 2.0, t: 3.2 }), clampS = sfx('mechclamp', { ss: 2.2, t: 1.3 });
+ const hydLong = 'sfx/hydraulics_long.mp3';
+ const groans = [sfx('metalgroan'), sfx('longcreak'), sfx('creakslow', { ss: 3, t: 9 }), sfx('gangplank', { ss: 12, t: 9 }), sfx('bendmetal'),
+ sfx('windmillgroan', { ss: 40, t: 7 }), sfx('windmillgroan', { ss: 120, t: 7 })];
+ const creaks = [sfx('bendmetal'), sfx('gaterattle', { ss: 4, t: 2.5 }), sfx('longcreak'), sfx('metalrattle', { ss: 6, t: 2.2 })];
+
+ // ---- one foot touching down
+ function touchdown(td, x, z, ev) {
+ const sp = spatial(td, x, z), near = 1 / (1 + sp.d / 22), P = persp(sp.shot), pan = sp.pan; // near: 1 close .. ~0.1 far
+ // picture sync wins inside 30 m; farther away the sound arrives late like it would (capped so it still reads as the same step)
+ const at = td + Math.min(0.3, Math.max(0, sp.d - 30) / 343);
+ const g = clamp(near * 1.5, 0.15, 1) * P.g;
+ let lp = 600 + 13000 * Math.pow(near, 1.4);
+ if (P.lp) lp = Math.min(lp, P.lp);
+ const kd = clamp((near - 0.2) / 0.3 + P.k); // detail layers
+ const kh = near > 0.32 ? clamp((near - 0.32) / 0.22 + P.k) : 0; // hero layers
+ if (td > 0.3) marks.push({ td, at, near, k: kh, shot: sp.shot, open: !P.lp });
+ // 1) sharp transient: pitched-down mechanical step, no lows of its own
+ const st = steps[ev % steps.length];
+ place(st, { at, anchor: st.onT, gain: 0.62 * g, pan, lp, hp: 70, rate: 0.62 + 0.08 * rnd() });
+ // 2) deep body, kept short so the low end stays tight
+ place(bass, { at: at - 0.010, anchor: bass.onT, gain: 0.60 * g, pan: pan * 0.5, lp: clamp(lp, 500, 2500), hp: 38, rate: 0.6 + 0.1 * rnd(), dur: 1.1, fadeOut: 0.6 });
+ // 3) distance: a soft low boom that takes over as the foot gets farther away
+ place(dboom, { at: at - 0.006, anchor: dboom.onT, gain: 0.36 * g * (1 - near), pan: pan * 0.4, lp: 450 + 900 * near, hp: 42, rate: 0.75, dur: 2.2, fadeOut: 1.2 });
+ if (kd > 0) {
+ const dr = doors[ev % doors.length]; // steel plate clank
+ place(dr, { at: at + 0.015, anchor: dr.onT, gain: 0.34 * g * (0.4 + 0.6 * kd), pan, lp: Math.min(lp, 1800 + 8000 * near), hp: 150, rate: 0.55, dur: 1.4, fadeOut: 0.7 });
+ place(gravel, { at: at + 0.10, gain: 0.42 * g * kd, pan, lp: Math.min(lp, 2500 + 7000 * near), hp: 200, rate: 0.8 });
+ const hs = ev % 2 ? air : phiss; // pneumatic exhaust once the weight is on the foot
+ place(hs, { at: at + 0.42 + 0.15 * rnd(), gain: 0.24 * g * (0.3 + 0.7 * kd), pan, lp: Math.min(lp * 2, 8000), hp: 500, fadeIn: 0.03, fadeOut: 0.9, dur: 2.2 });
+ if (sp.shot === 'f_puddle') place(splashSmall, { at, anchor: splashSmall.onT, gain: 0.2 * g * kd, pan, lp: 6000, hp: 200, fadeOut: 0.8 });
+ }
+ if (kh > 0) {
+ heroHits.push([at, kh * P.g]);
+ const sm = stomps[ev % stomps.length]; // monstrous stomp: weight
+ place(sm, { at: at - 0.010, anchor: sm.onT, gain: 0.42 * g * kh, pan: pan * 0.6, lp: 3000 + 6000 * near, hp: 45, rate: 0.8, dur: 1.3, fadeOut: 0.5 });
+ place(sub, { at: at + 0.01, anchor: sub.onT, gain: 0.16 * g * kh, rate: 0.7, lp: 140, hp: 36, dur: 0.9, fadeOut: 0.5 });
+ place(debris, { at: at + 0.22, gain: 0.36 * g * kh, pan, lp: 7500, hp: 250, dur: 4, fadeOut: 2.0 }); // clods raining back down
+ const ms = mudsteps[ev % mudsteps.length]; // wet ground giving way
+ place(ms, { at, anchor: ms.onT, gain: 0.36 * g * kh, pan, rate: 0.6, lp: 6000, hp: 120, fadeOut: 0.2 });
+ place(squelch, { at, anchor: squelch.onT, gain: 0.34 * g * kh, pan, rate: 0.6, lp: 5000, hp: 150, dur: 1.6, fadeOut: 0.6 });
+ if (kh > 0.6) {
+ place(splat, { at, anchor: splat.onT, gain: 0.34 * g * kh, pan, rate: 0.7, lp: 9000, hp: 200, fadeOut: 0.1 });
+ place(bigdebris, { at: at + 0.08, gain: 0.26 * g * kh, pan, lp: 8000, hp: 180, rate: 0.85, fadeOut: 1.5 });
+ const md = mdoors[ev % 2]; // piston settling
+ place(md, { at: at + 0.6, gain: 0.16 * g * kh, pan, rate: 0.8, lp: 7000, hp: 250, fadeIn: 0.03, fadeOut: 0.8 });
+ }
+ if (sp.shot === 'f_puddle') { // the foot that lands by the puddle
+ place(splashBig, { at, anchor: splashBig.onT, gain: 0.62 * g * kh, pan, lp: 10000, hp: 150, fadeOut: 1.0 });
+ place(ripples, { at: at + 0.3, anchor: ripples.onT, gain: 0.22 * g * kh, pan, hp: 300, fadeIn: 0.02, fadeOut: 1.5 });
+ }
+ }
+ }
+ // ---- one leg swinging forward (lift-off .. touchdown)
+ let ci = 0;
+ function swing(lift, td, x, z) {
+ const sp = spatial(lift, x, z, 6), near = 1 / (1 + sp.d / 22), P = persp(sp.shot), pan = sp.pan;
+ if (near < 0.11) return;
+ const g = clamp(near * 1.6) * P.g, cap = P.lp || 1e5;
+ const h = load(hydLong, { ss: 4 + Math.floor(rnd() * 70), t: 2.6 }); // hydraulic effort (random slice of a long recording)
+ place(h, { at: lift - 0.15, gain: 0.42 * g, pan, lp: Math.min(cap, 2500 + 8000 * near), hp: 150, rate: 0.75, fadeIn: 0.25, fadeOut: 0.7 });
+ const k = clamp((near - 0.26) / 0.25 + P.k);
+ if (near > 0.26) {
+ place(servo, { at: lift + 0.1, gain: 0.17 * g * k, pan, rate: 0.55 + 0.1 * rnd(), lp: Math.min(cap, 5000), hp: 250, fadeIn: 0.3, fadeOut: 0.6, dur: Math.max(0.8, td - lift - 0.2) });
+ const ch = chains[ci++ % chains.length]; // cables and chains swinging with the leg
+ place(ch, { at: lift + 0.5 + 0.6 * rnd(), gain: 0.13 * g * k, pan, rate: 0.8, lp: Math.min(cap * 2, 8000), hp: 500, fadeIn: 0.05, fadeOut: 0.5 });
+ }
+ const k2 = near > 0.36 ? clamp((near - 0.36) / 0.2 + P.k) : 0;
+ if (k2 > 0) {
+ place(clampS, { at: lift - 0.05, anchor: clampS.onT, gain: 0.2 * g * k2, pan, rate: 0.6, lp: 6000, hp: 120, fadeOut: 0.4 }); // joint unlocking
+ place(squelch2, { at: lift + 0.05, gain: 0.34 * g * k2, pan, rate: 0.55, lp: 4500, hp: 120, dur: 2, fadeOut: 0.6 }); // foot peeling out of the mud
+ place(slimy, { at: lift + 0.2, gain: 0.16 * g * k2, pan, rate: 0.7, lp: 5000, hp: 200, fadeOut: 0.3 });
+ place(steam, { at: lift + 0.1, gain: 0.11 * g * k2, pan, hp: 600, fadeIn: 0.1, fadeOut: 2.5 });
+ }
+ }
+ const T = GAIT.T;
+ let ev = 0;
+ for (const leg of LEGS) {
+ for (let n = -1; n < Math.ceil(DUR / T) + 2; n++) {
+ const td = (n - leg.phase) * T; // touchdown time
+ const lift = td + GAIT.duty * T - T; // the lift-off that precedes this touchdown
+ if (td > -0.5 && td < DUR) touchdown(td, SPEED * td + leg.homeX + GAIT.stride * 0.5, leg.homeZ, ev++);
+ if (lift > -1 && lift < DUR) swing(lift, td, SPEED * lift + leg.homeX - GAIT.stride * 0.5, leg.homeZ);
+ }
+ }
+ // ---- the structure taking the load after each group touchdown (two per cycle)
+ let gi = 0;
+ for (let n = -1; n < Math.ceil(DUR / (T / 2)) + 1; n++) {
+ const tg = n * T / 2 - 0.05 * T;
+ if (tg < -1 || tg > DUR) continue;
+ const c = cam(tg), P = persp(c.name);
+ const near = 1 / (1 + Math.hypot(SPEED * tg - c.pos[0], c.pos[2]) / 60);
+ const cap = P.lp ? P.lp * 2 : 1e5;
+ if (near > 0.5) place(sub, { at: tg + 0.1, anchor: sub.peakT * 0.5, gain: 0.09 * near * P.g, rate: 0.7, lp: 150, hp: 36, dur: 1.4, fadeOut: 0.8 });
+ const gr = groans[gi % groans.length]; // long low groan
+ place(gr, { at: tg + 0.55 + 0.5 * rnd(), gain: 0.30 * P.groan * Math.max(0.3, near * 1.3), pan: (rnd() - 0.5) * 0.8, rate: 0.55 + 0.12 * rnd(),
+ lp: Math.min(cap, 2500 + 5000 * near), hp: 90, fadeIn: 0.15, fadeOut: 1.5, dur: 5.5, norm: 'rms' });
+ const cr = creaks[gi % creaks.length]; // shorter, higher stress creak mid-stance
+ place(cr, { at: tg + 1.8 + 0.7 * rnd(), gain: 0.13 * P.groan * Math.max(0.25, near * 1.3), pan: (rnd() - 0.5) * 1.2, rate: 0.75 + 0.2 * rnd(),
+ lp: Math.min(cap, 3000 + 6000 * near), hp: 300, fadeIn: 0.05, fadeOut: 0.8, dur: 3, norm: 'rms' });
+ gi++;
+ }
+ // ---- beds
+ const S = (name, t, f) => inShot(name, t, f);
+ const wind = sfx('windnight', { ss: 20, t: 60 }); // wind over the open field, pulled down under the machine / at the facade
+ bed(wind, (t) => 0.19 * (1 + 0.6 * S('f_open', t, 1.0) - 0.5 * S('f_belly', t) - 0.35 * S('f_knee', t) - 0.25 * S('f_life', t)) * smooth(0, 1.5, t), { hp: 90 });
+ const wind2 = sfx('windsoft', { ss: 5, t: 60 });
+ bed(wind2, (t) => 0.10 * (S('f_open', t) + S('f_side', t) + S('f_away', t, 0.8) + 0.5 * S('f_hero', t) + 0.5 * S('f_puddle', t)), { hp: 150, offset: 7 });
+ const field = sfx('fieldamb', { ss: 10, t: 70 }); // grass moving right at the lens in the ground-level shots
+ bed(field, (t) => 0.16 * (S('f_open', t, 0.8) + S('f_foot', t) + 0.7 * S('f_puddle', t)), { hp: 250 });
+ const gust = sfx('windgust');
+ for (const [name, off] of [['f_side', -0.6], ['f_away', 0.2]]) {
+ const sg = segOf(name);
+ if (sg.start >= 0) place(gust, { at: sg.start + off, gain: 0.2, hp: 120, pan: name === 'f_side' ? -0.3 : 0.3, fadeIn: 0.6, fadeOut: 2.5 });
+ }
+ const rumble = sfx('lowrumble'); // low rumble only where it adds weight
+ bed(rumble, (t) => 0.07 * S('f_belly', t) + 0.035 * S('f_knee', t) + 0.03 * S('f_foot', t), { lp: 220, hp: 40 });
+ const machine = load(hydLong, { ss: 10, t: 60 });
+ bed(machine, (t) => 0.015 + 0.12 * S('f_belly', t) + 0.08 * S('f_knee', t) + 0.03 * S('f_foot', t) + 0.02 * S('f_hero', t) + 0.02 * S('f_puddle', t), { lp: 3500, hp: 150 });
+ const drip = sfx('dripcave', { ss: 20, t: 60 }); // water dripping under the belly, a little around the puddle
+ bed(drip, (t) => 0.30 * S('f_belly', t) + 0.08 * S('f_puddle', t) + 0.05 * S('f_foot', t), { hp: 400, pan: -0.25 });
+ const drip2 = sfx('dripmetal', { t: 45 });
+ bed(drip2, (t) => 0.20 * S('f_belly', t), { hp: 300, pan: 0.35, offset: 20 });
+ const chainBed = sfx('chainrattle', { t: 34 });
+ bed(chainBed, (t) => 0.07 * S('f_belly', t) + 0.03 * S('f_knee', t), { hp: 400, lp: 7000, pan: -0.3, offset: 12 });
+ const ship = sfx('shipcreak', { ss: 30, t: 60 });
+ bed(ship, (t) => 0.04 + 0.05 * S('f_life', t) + 0.06 * S('f_belly', t), { lp: 3000, hp: 180 });
+ const dogs = sfx('dogsfar', { ss: 8, t: 50 });
+ bed(dogs, (t) => 0.09 * (S('f_open', t, 1.0) + 0.7 * S('f_away', t, 1.0) + 0.5 * S('f_side', t, 0.8)), { hp: 300, lp: 3500, pan: 0.3 });
+ // ---- life on the facade: laundry, a radio behind a window, dishes, voices, a dog somewhere (all very low)
+ const cloth = sfx('clothflap');
+ bed(cloth, (t) => 0.09 * S('f_life', t, 0.6), { hp: 300, lp: 6000, pan: -0.2 });
+ // (radio tuning bed removed: the recording could contain off-air broadcast fragments)
+
+ const chatter = sfx('aptchatter');
+ bed(chatter, (t) => 0.05 * S('f_life', t, 0.7), { lp: 1600, hp: 200, pan: 0.25, loopXf: 1.0 });
+ const lf = segOf('f_life'), ll = lf.end - lf.start;
+ if (lf.start >= 0) {
+ const clinks = [[0.14, 'cutleryclinks', 2.0, 0.9], [0.33, 'plates', 0.5, 0.8], [0.52, 'cutleryclinks', 3.2, 1.2], [0.78, 'plates', 7.9, 0.8]];
+ for (const [f, file, ss, t] of clinks) place(sfx(file, { ss, t }), { at: lf.start + f * ll, gain: 0.04, lp: 5000, hp: 600, pan: 0.4, fadeIn: 0.01, fadeOut: 0.2 });
+ place(sfx('dogbark', { ss: 0.5, t: 2.6 }), { at: lf.start + 0.6 * ll, gain: 0.04, lp: 1800, hp: 250, pan: 0.6, fadeIn: 0.02, fadeOut: 0.3 });
+ }
+ // ---- birds startled far away as it comes out of the fog; crows over the field
+ const op = segOf('f_open'), sd = segOf('f_side'), aw = segOf('f_away');
+ if (op.start >= 0) {
+ place(sfx('pigeonflock'), { at: op.start + 0.3 * (op.end - op.start), gain: 0.085, lp: 3500, hp: 400, pan: 0.45, fadeIn: 0.4, fadeOut: 2.0 });
+ place(sfx('crowsingle'), { at: op.start + 0.72 * (op.end - op.start), gain: 0.03, lp: 2500, hp: 400, pan: -0.3, fadeOut: 0.2 });
+ }
+ if (sd.start >= 0) place(sfx('crowcalls', { ss: 8.9, t: 5.2 }), { at: sd.start + 0.8, gain: 0.035, lp: 2600, hp: 400, pan: -0.5, fadeIn: 0.3, fadeOut: 1.5 });
+ if (aw.start >= 0) place(sfx('crowcalls', { ss: 2.8, t: 3.9 }), { at: aw.start + 0.9, gain: 0.035, lp: 2600, hp: 400, pan: 0.4, fadeIn: 0.2, fadeOut: 1.2 });
+}
+
+if (WHO) {
+ console.log('\nsource energy per shot (dB, pre-mix; blank = silent)');
+ console.log('file'.padEnd(16) + shots.TIMELINE.map((g) => g.shot.slice(2, 8).padStart(7)).join(''));
+ const len = shots.TIMELINE.map((g) => (g.end - g.start) * SR);
+ for (const [k, a] of [...WHO].sort((x, y) => Math.max(...y[1]) - Math.max(...x[1])))
+ console.log(k.padEnd(16) + shots.TIMELINE.map((_, i) => a[i] ? (10 * Math.log10(a[i] / len[i])).toFixed(0).padStart(7) : ' ').join(''));
+}
+// SFX bus: 2-pole high-pass at 35 Hz to keep the low end tight
+{
+ const a = 1 - Math.exp(-2 * Math.PI * 35 / SR);
+ let l1 = 0, r1 = 0, l2 = 0, r2 = 0;
+ for (let i = 0; i < N; i++) {
+ l1 += (L[i] - l1) * a; r1 += (R[i] - r1) * a; const xl = L[i] - l1, xr = R[i] - r1;
+ l2 += (xl - l2) * a; r2 += (xr - r2) * a; L[i] = xl - l2; R[i] = xr - r2;
+ }
+}
+// ---------------------------------------------------------------- loudness helpers
+function toPcm(l, r) { const b = Buffer.alloc(N * 8); for (let i = 0; i < N; i++) { b.writeFloatLE(l[i], i * 8); b.writeFloatLE(r[i], i * 8 + 4); } return b; }
+function measure(l, r, full = false) {
+ const res = spawnSync('ffmpeg', ['-hide_banner', '-nostats', '-f', 'f32le', '-ar', String(SR), '-ac', '2', '-i', '-', '-af', 'ebur128=peak=true', '-f', 'null', '-'], { input: toPcm(l, r), maxBuffer: 1 << 30 });
+ const sum = String(res.stderr).split('Summary:')[1] || '';
+ const num = (re) => { const m = re.exec(sum); return m ? +m[1] : -70; };
+ const I = num(/I:\s+(-?[\d.]+) LUFS/);
+ return full ? { I, LRA: num(/LRA:\s+(-?[\d.]+) LU/), TP: num(/Peak:\s+(-?[\d.]+) dBFS/) } : I;
+}
+
+// ---------------------------------------------------------------- music
+// One continuous excerpt, fades only. `at` (s in the track) lands on the first frame of `shot`:
+// The Long Dark: sparse, quiet strings until the full ensemble enters at 313.40 s -> entry on the cut to the hero shot,
+// plateau through the facade shot, faded out as the block walks away.
+const MUSIC = {
+ the_long_dark: { at: 313.40, shot: 'f_hero' },
+ penumbra: { at: 343, shot: 'f_open' },
+};
+const ML = new Float32Array(N), MR = new Float32Array(N);
+let musicI = -70;
+if (!args.nomusic) {
+ const name = args.music || 'the_long_dark', M = MUSIC[name] || { at: 0, shot: 'f_open' };
+ const mstart = Math.max(0, args.mstart !== undefined ? +args.mstart : M.at - Math.max(0, segOf(M.shot).start));
+ const m = load(`music/${name}.mp3`, { ss: mstart, t: DUR + 0.5 });
+ const open = segOf('f_open'), life = segOf('f_life'), away = segOf('f_away');
+ const o1 = open.end > 0 ? open.end : 5.5, l0 = life.start > 0 ? life.start : 0.58 * DUR, l1 = life.end > 0 ? life.end : 0.7 * DUR, a0 = away.start > 0 ? away.start : DUR - 4.5;
+ for (let i = 0; i < Math.min(N, m.n); i++) {
+ const t = i / SR;
+ // fader ride: held back 5 dB in the opening, full level by the facade shot, easing 2.5 dB through the knee and puddle shots,
+ // then a long fade as the block leaves
+ const g = smooth(0, 2.0, t) * db(-5 * (1 - smooth(o1, l0, t)) - 2.5 * smooth(l1, a0, t)) * Math.pow(1 - smooth(a0 + 0.2, DUR - 0.1, t), 1.5) / m.peak;
+ ML[i] = m.l[i] * g; MR[i] = m.r[i] * g;
+ }
+ musicI = measure(ML, MR);
+ console.log(`music ${name} from ${mstart.toFixed(2)} s`);
+ // duck the music a little just before each close footfall so the impact punches through
+ for (const [td, k] of heroHits) {
+ const i0 = Math.max(0, Math.round((td - 0.45) * SR)), i1 = Math.min(N, Math.round((td + 1.3) * SR));
+ for (let i = i0; i < i1; i++) {
+ const t = i / SR - td;
+ const d = t < 0 ? smooth(-0.45, -0.05, t) : 1 - smooth(0.15, 1.3, t);
+ const g = 1 - 0.38 * Math.min(1, k) * d;
+ ML[i] *= g; MR[i] *= g;
+ }
+ }
+}
+// balance: SFX bus sits `sfxrel` LU relative to the music (integrated)
+if (!args.nosfx) {
+ const sfxI = measure(L, R);
+ const rel = +(args.sfxrel ?? -1);
+ const g = args.nomusic ? db(-20 - sfxI) : db(musicI + rel - sfxI);
+ console.log(`sfx I=${sfxI.toFixed(1)} LUFS music I=${musicI.toFixed(1)} LUFS -> sfx gain ${(20 * Math.log10(g)).toFixed(1)} dB`);
+ for (let i = 0; i < N; i++) { L[i] *= g; R[i] *= g; }
+}
+const SL = Float32Array.from(L), SR_ = Float32Array.from(R); // SFX stem
+for (let i = 0; i < N; i++) { L[i] += ML[i]; R[i] += MR[i]; }
+// master fades: clean head, tail out with the picture (which fades over the last 1.5 s)
+const mfade = (t) => smooth(0, 0.5, t) * (1 - smooth(DUR - 1.6, DUR - 0.04, t));
+// static master gain to the target loudness, then a peak limiter that should have very little to do
+for (let i = 0; i < N; i++) { const g = mfade(i / SR); L[i] *= g; R[i] *= g; }
+const mixI = measure(L, R);
+const target = +(args.lufs ?? -15), LIMIT = 0.82;
+const mg = db(target - mixI);
+let pk = 0, over = 0;
+for (let i = 0; i < N; i++) {
+ L[i] *= mg; R[i] *= mg;
+ const g = mfade(i / SR) * mg; SL[i] *= g; SR_[i] *= g; ML[i] *= g; MR[i] *= g;
+ const a = Math.max(Math.abs(L[i]), Math.abs(R[i]));
+ if (a > pk) pk = a;
+ if (a > LIMIT) over++;
+}
+const out = path.resolve(ROOT, args.out || 'out/audio.wav');
+fs.mkdirSync(path.dirname(out), { recursive: true });
+function writeWav(file, l, r, limit) {
+ const af = limit ? ['-af', `alimiter=limit=${LIMIT}:attack=3:release=120:level=disabled`] : [];
+ const r2 = spawnSync('ffmpeg', ['-v', 'error', '-y', '-f', 'f32le', '-ar', String(SR), '-ac', '2', '-i', '-', ...af, '-ar', String(SR), '-c:a', 'pcm_s24le', file], { input: toPcm(l, r), maxBuffer: 1 << 30 });
+ if (r2.status !== 0) throw new Error(String(r2.stderr));
+}
+writeWav(out, L, R, true);
+if (args.stems) { writeWav(path.join(path.dirname(out), 'stem_music.wav'), ML, MR, false); writeWav(path.join(path.dirname(out), 'stem_sfx.wav'), SL, SR_, false); }
+console.log(`wrote ${path.relative(ROOT, out)} mix I=${mixI.toFixed(1)} -> ${target} LUFS (master ${(20 * Math.log10(mg)).toFixed(1)} dB), pre-limiter peak ${pk.toFixed(2)}`
+ + ` = max gain reduction ${Math.max(0, 20 * Math.log10(pk / LIMIT)).toFixed(1)} dB, ${(over / SR * 1000).toFixed(0)} ms of samples over the ceiling`);
+
+// ---------------------------------------------------------------- verification (measured on the written file)
+if (!args.quiet) {
+ const rd = spawnSync('ffmpeg', ['-v', 'error', '-i', out, '-f', 'f32le', '-ac', '2', '-ar', String(SR), '-'], { maxBuffer: 1 << 30 });
+ const f = new Float32Array(rd.stdout.buffer, rd.stdout.byteOffset, Math.floor(rd.stdout.length / 4));
+ const n = Math.min(N, f.length / 2), FL = new Float32Array(N), FR = new Float32Array(N);
+ for (let i = 0; i < n; i++) { FL[i] = f[2 * i]; FR[i] = f[2 * i + 1]; }
+ const fin = measure(FL, FR, true);
+ console.log(`\nfinal file: I ${fin.I.toFixed(1)} LUFS LRA ${fin.LRA.toFixed(1)} LU true peak ${fin.TP.toFixed(1)} dBTP`);
+ // transient time = steepest rise of a 1.5 ms envelope within +-45 ms of the expected time.
+ // click = the same on the signal above 1 kHz (the sharp transient layer; only meaningful where the shot's perspective is open)
+ // body = full band (the low body swells a little later than the click)
+ const mono = (l, r) => { const o = new Float32Array(N); for (let i = 0; i < N; i++) o[i] = (l[i] + r[i]) * 0.5; return o; };
+ const hp1k = (x) => { const a = 1 - Math.exp(-2 * Math.PI * 1000 / SR), o = new Float32Array(N); let l1 = 0, l2 = 0; for (let i = 0; i < N; i++) { l1 += (x[i] - l1) * a; const y = x[i] - l1; l2 += (y - l2) * a; o[i] = y - l2; } return o; };
+ const onset = (x, t) => {
+ const w = Math.round(0.045 * SR), h = Math.round(0.002 * SR), c = Math.round(t * SR), a = 1 - Math.exp(-1 / (0.0015 * SR));
+ const i0 = Math.max(0, c - w - h - Math.round(0.02 * SR)), i1 = Math.min(N, c + w + h + 1), e = new Float32Array(i1 - i0);
+ let env = 0, best = 0, bi = c;
+ for (let i = i0; i < i1; i++) { env += (Math.abs(x[i]) - env) * a; e[i - i0] = env; }
+ for (let i = Math.max(i0 + h, c - w); i < Math.min(i1 - h, c + w); i++) { const d = e[i + h - i0] - e[i - h - i0]; if (d > best) { best = d; bi = i; } }
+ return (bi / SR - t) * 1000;
+ };
+ const sM = mono(SL, SR_), fM = mono(FL, FR), sH = hp1k(sM), fH = hp1k(fM);
+ const all = marks.filter((m) => m.at < DUR - 1.7).sort((a, b) => a.at - b.at);
+ // a foot landing within 130 ms after another one is masked by that one's debris: listed separately
+ const rows = all.map((m, i) => ({ ...m, lone: i === 0 || m.at - all[i - 1].at > 0.13, delay: (m.at - m.td) * 1000,
+ cs: onset(sH, m.at), cf: onset(fH, m.at), bs: onset(sM, m.at), bf: onset(fM, m.at) }));
+ const st = (a) => a.length ? `n=${String(a.length).padStart(2)} mean ${(a.reduce((s, v) => s + v, 0) / a.length).toFixed(1).padStart(5)} ms worst ${a.reduce((s, v) => Math.abs(v) > Math.abs(s) ? v : s, 0).toFixed(1).padStart(6)} ms within +-20 ms: ${a.filter((v) => Math.abs(v) <= 20).length}/${a.length}` : 'n= 0';
+ const sgn = (v) => (v >= 0 ? '+' : '') + v.toFixed(1);
+ const hero = rows.filter((m) => m.k > 0 && m.open), heroL = hero.filter((m) => m.lone);
+ console.log('\nfootfall timing, measured minus expected (expected = gait touchdown + distance delay; delay is 0 within 30 m of the camera)');
+ console.log(` close hits, click >1 kHz, SFX stem ${st(heroL.map((m) => m.cs))}`);
+ console.log(` close hits, click >1 kHz, final mix ${st(heroL.map((m) => m.cf))}`);
+ console.log(` close hits, body full band, final ${st(heroL.map((m) => m.bf))}`);
+ console.log(` all other hits, body, SFX stem ${st(rows.filter((m) => !(m.k > 0 && m.open) && m.lone).map((m) => m.bs))}`);
+ console.log(` masked (<130 ms after another foot) n=${rows.filter((m) => !m.lone).length}, not scored`);
+ console.log(' gait t shot near delay | click stem click mix body mix (ms)');
+ for (const m of hero) console.log(` ${m.td.toFixed(3).padStart(6)} ${m.shot.slice(2).padEnd(7)} ${m.near.toFixed(2)} ${m.delay.toFixed(0).padStart(4)} | ${sgn(m.cs).padStart(9)} ${sgn(m.cf).padStart(10)} ${sgn(m.bf).padStart(9)}${m.lone ? '' : ' (masked)'}`);
+ // per-shot levels (dB RMS): stems, mix, quietest 0.4 s window, band balance
+ const bands = [60, 200, 2000];
+ const rms = (l, r, i0, i1) => { let s = 0; for (let i = i0; i < i1; i++) s += l[i] * l[i] + r[i] * r[i]; return 10 * Math.log10(s / (2 * (i1 - i0)) + 1e-12); };
+ const lowp = (fc) => { const a = 1 - Math.exp(-2 * Math.PI * fc / SR), o = new Float32Array(N); let y1 = 0, y2 = 0, y3 = 0, y4 = 0; for (let i = 0; i < N; i++) { const x = (FL[i] + FR[i]) * 0.5; y1 += (x - y1) * a; y2 += (y1 - y2) * a; y3 += (y2 - y3) * a; y4 += (y3 - y4) * a; o[i] = y4; } return o; };
+ const lps = bands.map(lowp);
+ const sig = [lps[0], ...bands.slice(1).map((_, k) => lps[k + 1].map((v, i) => v - lps[k][i])), fM.map((v, i) => v - lps[bands.length - 1][i])];
+ const r1 = (x, i0, i1) => { let s = 0; for (let i = i0; i < i1; i++) s += x[i] * x[i]; return 10 * Math.log10(s / (i1 - i0) + 1e-12); };
+ const p = (v) => v.toFixed(1).padStart(7);
+ console.log('\nshot time music sfx mix quietest0.4s | <60Hz 60-200 200-2k >2kHz (dB RMS, final file)');
+ for (const sg of shots.TIMELINE) {
+ const i0 = Math.round(sg.start * SR), i1 = Math.min(N, Math.round(sg.end * SR)), w = Math.round(0.4 * SR);
+ let q = 0; for (let i = i0; i + w <= i1; i += w >> 1) q = Math.min(q, rms(FL, FR, i, i + w));
+ console.log(`${sg.shot.padEnd(9)} ${sg.start.toFixed(1).padStart(5)}-${sg.end.toFixed(1).padEnd(5)} ${p(rms(ML, MR, i0, i1))}${p(rms(SL, SR_, i0, i1))}${p(rms(FL, FR, i0, i1))} ${p(q)} |${sig.map((x) => p(r1(x, i0, i1))).join('')}`);
+ }
+}
diff --git a/tools/fsearch.sh b/tools/fsearch.sh
new file mode 100644
index 0000000..e62312c
--- /dev/null
+++ b/tools/fsearch.sh
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+# Search freesound.org (CC0 only) and list id | duration | title | hq preview url.
+# usage: tools/fsearch.sh "query one" "query two" ...
+UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Safari/537.36"
+for q in "$@"; do
+ echo "=== $q"
+ enc=$(printf '%s' "$q" | sed 's/ /+/g')
+ html=$(curl -sL -A "$UA" "https://freesound.org/search/?q=${enc}&f=license%3A%22Creative+Commons+0%22&s=Downloads+%28most+first%29")
+ printf '%s' "$html" | grep -oE 'data-(mp3|title|duration)="[^"]*"' | paste - - - | head -${N:-12} | \
+ sed -E 's/data-mp3="([^"]*)-lq\.mp3"\s*data-title="([^"]*)"\s*data-duration="([^"]*)"/\3s | \2 | \1-hq.mp3/'
+ sleep 7
+done
diff --git a/tools/mux.sh b/tools/mux.sh
new file mode 100644
index 0000000..1a433f7
--- /dev/null
+++ b/tools/mux.sh
@@ -0,0 +1,13 @@
+#!/usr/bin/env bash
+# Encode rendered frames + soundtrack into the final film.
+# usage: bash tools/mux.sh [frames_dir=out/frames] [audio=out/audio.wav] [out=out/walking_block_1080p30.mp4]
+set -e
+cd "$(dirname "$0")/.."
+FR=${1:-out/frames}; AU=${2:-out/audio.wav}; OUT=${3:-out/walking_block_1080p30.mp4}
+ffmpeg -hide_banner -loglevel warning -y -threads 6 \
+ -framerate 30 -start_number 0 -i "$FR/f_%06d.png" -i "$AU" \
+ -c:v libx264 -preset slow -crf 17 -pix_fmt yuv420p -profile:v high -level 4.2 \
+ -vf "scale=in_range=full:out_range=tv:out_color_matrix=bt709:flags=accurate_rnd+full_chroma_int,format=yuv420p" -color_primaries bt709 -color_trc bt709 -colorspace bt709 -color_range tv \
+ -x264-params "keyint=60:min-keyint=30:aq-mode=3:deblock=-1,-1" -tune film \
+ -c:a aac -b:a 256k -ar 48000 -movflags +faststart -shortest "$OUT"
+ffprobe -v error -show_entries format=duration,size,bit_rate:stream=codec_name,width,height,r_frame_rate,nb_frames -of default=nw=1 "$OUT"
diff --git a/tools/render.mjs b/tools/render.mjs
new file mode 100644
index 0000000..130a3e9
--- /dev/null
+++ b/tools/render.mjs
@@ -0,0 +1,83 @@
+// Offline frame renderer: headless Chrome (GPU) -> PNG frames on disk. Resumable.
+// Usage:
+// node tools/render.mjs --w 1920 --h 1080 --fps 30 --from 0 --to 45 --dir out/frames [--mb 1] [--force]
+// --shot NAME render a single shot preset instead of the film timeline
+// --every N render only every Nth frame (previews)
+// Frames are named f_000000.png (index = round(t*fps)). Existing files are skipped unless --force.
+import puppeteer from 'puppeteer-core';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { startServer } from '../server.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const args = {};
+for (let i = 2; i < process.argv.length; i++) {
+ const a = process.argv[i];
+ if (a.startsWith('--')) { const k = a.slice(2); const n = process.argv[i + 1]; if (n === undefined || n.startsWith('--')) args[k] = true; else { args[k] = n; i++; } }
+}
+const W = +(args.w || 1920), H = +(args.h || 1080), FPS = +(args.fps || 30);
+const from = +(args.from || 0), to = +(args.to || 45), every = +(args.every || 1);
+const MB = +(args.mb || 1); // motion-blur sub-samples (1 = off)
+const dir = path.resolve(ROOT, args.dir || 'out/frames');
+fs.mkdirSync(dir, { recursive: true });
+const CHROME = process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+const RESTART_EVERY = +(args.restart || 400); // relaunch the browser periodically to keep memory flat
+
+const f0 = Math.round(from * FPS), f1 = Math.round(to * FPS);
+const todo = [];
+for (let f = f0; f < f1; f += every) {
+ const file = path.join(dir, `f_${String(f).padStart(6, '0')}.png`);
+ if (args.force || !fs.existsSync(file) || fs.statSync(file).size < 1000) todo.push([f, file]);
+}
+console.log(`frames ${f0}..${f1 - 1}: ${todo.length} to render at ${W}x${H}, mb=${MB}`);
+if (!todo.length) process.exit(0);
+
+const { server, port } = await startServer(0);
+async function launch() {
+ const browser = await puppeteer.launch({
+ executablePath: CHROME, headless: 'new', protocolTimeout: 600000,
+ args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-webgl', '--disable-gpu-vsync', '--hide-scrollbars', '--mute-audio', `--window-size=${W},${H}`, '--disable-background-timer-throttling', '--disable-renderer-backgrounding'],
+ defaultViewport: { width: W, height: H, deviceScaleFactor: 1 },
+ });
+ const page = await browser.newPage();
+ page.on('pageerror', (e) => console.log('[pageerror]', e.message));
+ const q = new URLSearchParams({ w: W, h: H, still: 1 });
+ if (args.q) for (const kv of String(args.q).split('&')) { const [k, v] = kv.split('='); q.set(k, v ?? '1'); }
+ await page.goto(`http://127.0.0.1:${port}/?${q}`, { waitUntil: 'load', timeout: 180000 });
+ await page.waitForFunction('window.__app !== undefined', { timeout: 120000 });
+ const res = await page.evaluate(async (shot) => { const r = await window.__app.ready; if (shot) window.__app.setShot(shot); return r.errors; }, args.shot || '');
+ if (res.length) console.log('MODULE ERRORS:\n' + res.join('\n'));
+ return { browser, page };
+}
+
+let { browser, page } = await launch();
+const tStart = Date.now();
+let done = 0;
+try {
+ for (const [f, file] of todo) {
+ if (done > 0 && done % RESTART_EVERY === 0) { await browser.close(); ({ browser, page } = await launch()); }
+ const b64 = await page.evaluate(async (t, mb, fps) => {
+ const app = window.__app;
+ if (mb > 1 && app.renderBlur) app.renderBlur(t, mb, 0.3 / fps); else app.renderAt(t);
+ const cv = document.getElementById('c');
+ const blob = await new Promise((r) => cv.toBlob(r, 'image/png'));
+ const buf = new Uint8Array(await blob.arrayBuffer());
+ let s = ''; const CH = 0x8000;
+ for (let i = 0; i < buf.length; i += CH) s += String.fromCharCode.apply(null, buf.subarray(i, i + CH));
+ return btoa(s);
+ }, f / FPS, MB, FPS);
+ fs.writeFileSync(file, Buffer.from(b64, 'base64'));
+ done++;
+ if (done % 15 === 0 || done === todo.length) {
+ const el = (Date.now() - tStart) / 1000;
+ console.log(`${done}/${todo.length} ${(el / done).toFixed(2)} s/frame eta ${((todo.length - done) * el / done / 60).toFixed(1)} min`);
+ }
+ }
+} catch (e) {
+ console.error('RENDER FAILED at frame', done, e.message);
+ process.exitCode = 1;
+} finally {
+ await browser.close().catch(() => {});
+ server.close();
+}
diff --git a/tools/shot.mjs b/tools/shot.mjs
new file mode 100644
index 0000000..19a2019
--- /dev/null
+++ b/tools/shot.mjs
@@ -0,0 +1,103 @@
+// Capture stills of the scene with headless Chrome (GPU).
+// Usage:
+// node tools/shot.mjs --shots ref1,ref2 --t 3.2 --w 1280 --h 720 --prefix a -> shots/a_ref1.png ...
+// node tools/shot.mjs --shots ref2 --mods env,legs (load only some modules)
+// node tools/shot.mjs --cam "-60,3,40,0,20,0,45" --name mycam (free camera: pos xyz, target xyz, fov; path-frame coords)
+// node tools/shot.mjs --shots ref1,ref2,ref3,ref4,ref5,ref6 --sheet (also writes shots/<prefix>_sheet.jpg contact sheet)
+// --ts 0,1.5,3 capture several times for each shot (suffix _t<time>)
+import puppeteer from 'puppeteer-core';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { startServer } from '../server.mjs';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const args = {};
+for (let i = 2; i < process.argv.length; i++) {
+ const a = process.argv[i];
+ if (a.startsWith('--')) { const k = a.slice(2); const n = process.argv[i + 1]; if (n === undefined || n.startsWith('--')) args[k] = true; else { args[k] = n; i++; } }
+}
+const W = +(args.w || 1280), H = +(args.h || 720);
+const shots = args.cam ? [args.name || 'cam'] : String(args.shots || args.shot || 'ref2').split(',');
+const times = String(args.ts || args.t || '2.0').split(',').map(Number);
+const prefix = args.prefix || 's';
+const outDir = path.resolve(ROOT, args.dir || 'shots');
+fs.mkdirSync(outDir, { recursive: true });
+const CHROME = process.env.CHROME_PATH || 'C:/Program Files/Google/Chrome/Application/chrome.exe';
+
+const { server, port } = await startServer(0);
+const browser = await puppeteer.launch({
+ executablePath: CHROME, headless: 'new',
+ args: ['--use-angle=d3d11', '--enable-gpu', '--ignore-gpu-blocklist', '--enable-webgl', '--disable-gpu-vsync', '--hide-scrollbars', '--mute-audio', `--window-size=${W},${H}`],
+ defaultViewport: { width: W, height: H, deviceScaleFactor: 1 },
+});
+let code = 0;
+try {
+ const page = await browser.newPage();
+ const logs = [];
+ page.on('console', (m) => { const t = m.text(); if (m.type() === 'error' || m.type() === 'warn') logs.push(`[${m.type()}] ${t}`); });
+ page.on('pageerror', (e) => logs.push(`[pageerror] ${e.message}`));
+ const q = new URLSearchParams({ w: W, h: H, still: 1 });
+ if (args.mods) q.set('mods', args.mods);
+ if (args.q) for (const kv of String(args.q).split('&')) { const [k, v] = kv.split('='); q.set(k, v ?? '1'); }
+ await page.goto(`http://127.0.0.1:${port}/?${q}`, { waitUntil: 'load', timeout: 120000 });
+ await page.waitForFunction('window.__app !== undefined', { timeout: 240000 });
+ const t0 = Date.now();
+ const res = await page.evaluate(async () => { const r = await window.__app.ready; return { errors: r.errors, info: window.__app.info() }; });
+ console.log(`ready in ${Date.now() - t0}ms gl=${res.info.gl} calls=${res.info.calls} tris=${res.info.tris}`);
+ console.log('build ms per module: ' + JSON.stringify(res.info.buildMs));
+ if (res.errors.length) { console.log('MODULE ERRORS:\n' + res.errors.join('\n')); code = 2; }
+ const files = [];
+ if (args.board) {
+ // storyboard of the film timeline: N frames per segment
+ const n = +(args.n || 3);
+ const tl = await page.evaluate(async () => (await import('/src/shots.js')).TIMELINE);
+ for (const seg of tl) for (let i = 0; i < n; i++) {
+ const t = seg.start + (seg.end - seg.start) * (n === 1 ? 0.5 : (0.04 + 0.92 * i / (n - 1)));
+ await page.evaluate((t) => { const app = window.__app; app.setShot(''); app.renderAt(t); app.renderAt(t); app.renderer.getContext().finish(); }, t);
+ const file = path.join(outDir, `${prefix}_${seg.shot}_${i}.png`);
+ await (await page.$('#c')).screenshot({ path: file, type: 'png' });
+ files.push(file);
+ }
+ console.log(`storyboard: ${files.length} frames`);
+ shots.length = 0; args.sheet = true; args.cols = args.cols || n;
+ }
+ for (const shot of shots) {
+ for (const t of times) {
+ const ms = await page.evaluate(async (shot, t, cam, mb) => {
+ const app = window.__app;
+ if (cam) { const v = cam.split(',').map(Number); app.setCam(v.slice(0, 3), v.slice(3, 6), v[6] || 45); } else app.setShot(shot);
+ const a = performance.now();
+ app.renderAt(t);
+ if (mb > 1) app.renderBlur(t, mb, 0.01); else app.renderAt(t);
+ app.renderer.getContext().finish();
+ return performance.now() - a;
+ }, shot, t, args.cam || null, +(args.mb || 1));
+ const name = `${prefix}_${shot}${times.length > 1 ? '_t' + t : ''}.png`;
+ const file = path.join(outDir, name);
+ const el = await page.$('#c');
+ await el.screenshot({ path: file, type: 'png' });
+ files.push(file);
+ console.log(`wrote shots/${name} (2 frames ${ms.toFixed(0)}ms)`);
+ }
+ }
+ if (logs.length) console.log('CONSOLE:\n' + [...new Set(logs)].slice(0, 30).join('\n'));
+ if (args.sheet && files.length > 1) {
+ const cols = +(args.cols || (files.length <= 4 ? 2 : 3));
+ const cw = +(args.cw || 640), ch = Math.round(cw * H / W);
+ const rows = Math.ceil(files.length / cols);
+ const sp = await browser.newPage();
+ await sp.setViewport({ width: cols * cw, height: rows * ch, deviceScaleFactor: 1 });
+ const imgs = files.map((f) => `<img src="data:image/png;base64,${fs.readFileSync(f).toString('base64')}" style="width:${cw}px;height:${ch}px;display:block">`).join('');
+ await sp.setContent(`<body style="margin:0;background:#000;display:grid;grid-template-columns:repeat(${cols},${cw}px)">${imgs}</body>`);
+ const sheet = path.join(outDir, `${prefix}_sheet.jpg`);
+ await sp.screenshot({ path: sheet, type: 'jpeg', quality: 88 });
+ console.log(`wrote shots/${prefix}_sheet.jpg`);
+ }
+} catch (e) {
+ console.error('SHOT FAILED:', e.message); code = 1;
+} finally {
+ await browser.close();
+ server.close();
+}
+process.exit(code);